blob: 6ebe9748756099c77d12a27c1d0349df8a880fad [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"
Chandler Carruth3a022472012-12-04 09:13:33 +000016#include "TypeLocBuilder.h"
Steve Naroffaac94152007-08-25 14:02:58 +000017#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000018#include "clang/AST/CXXInheritance.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000019#include "clang/AST/CharUnits.h"
John McCallde6836a2010-08-24 07:21:54 +000020#include "clang/AST/DeclObjC.h"
Richard Smithc406cb72013-01-17 01:17:56 +000021#include "clang/AST/EvaluatedExprVisitor.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000022#include "clang/AST/ExprCXX.h"
Fariborz Jahanian1d446082010-06-16 18:56:04 +000023#include "clang/AST/ExprObjC.h"
Faisal Valia17d19f2013-11-07 05:17:06 +000024#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregorb1dd23f2010-02-24 22:38:50 +000025#include "clang/AST/TypeLoc.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000026#include "clang/Basic/PartialDiagnostic.h"
Sebastian Redlfaf68082008-12-03 20:26:15 +000027#include "clang/Basic/TargetInfo.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000028#include "clang/Lex/Preprocessor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000029#include "clang/Sema/DeclSpec.h"
30#include "clang/Sema/Initialization.h"
31#include "clang/Sema/Lookup.h"
32#include "clang/Sema/ParsedTemplate.h"
33#include "clang/Sema/Scope.h"
34#include "clang/Sema/ScopeInfo.h"
Faisal Valia17d19f2013-11-07 05:17:06 +000035#include "clang/Sema/SemaLambda.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000036#include "clang/Sema/TemplateDeduction.h"
Sebastian Redlb8fc4772012-02-16 12:59:47 +000037#include "llvm/ADT/APInt.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000038#include "llvm/ADT/STLExtras.h"
Chandler Carruth8b0cf1d2011-05-01 07:23:17 +000039#include "llvm/Support/ErrorHandling.h"
Chris Lattner29375652006-12-04 18:06:35 +000040using namespace clang;
John McCall19c1bfd2010-08-25 05:32:35 +000041using namespace sema;
Chris Lattner29375652006-12-04 18:06:35 +000042
Richard Smith7447af42013-03-26 01:15:19 +000043/// \brief Handle the result of the special case name lookup for inheriting
44/// constructor declarations. 'NS::X::X' and 'NS::X<...>::X' are treated as
45/// constructor names in member using declarations, even if 'X' is not the
46/// name of the corresponding type.
47ParsedType Sema::getInheritingConstructorName(CXXScopeSpec &SS,
48 SourceLocation NameLoc,
49 IdentifierInfo &Name) {
50 NestedNameSpecifier *NNS = SS.getScopeRep();
51
52 // Convert the nested-name-specifier into a type.
53 QualType Type;
54 switch (NNS->getKind()) {
55 case NestedNameSpecifier::TypeSpec:
56 case NestedNameSpecifier::TypeSpecWithTemplate:
57 Type = QualType(NNS->getAsType(), 0);
58 break;
59
60 case NestedNameSpecifier::Identifier:
61 // Strip off the last layer of the nested-name-specifier and build a
62 // typename type for it.
63 assert(NNS->getAsIdentifier() == &Name && "not a constructor name");
64 Type = Context.getDependentNameType(ETK_None, NNS->getPrefix(),
65 NNS->getAsIdentifier());
66 break;
67
68 case NestedNameSpecifier::Global:
69 case NestedNameSpecifier::Namespace:
70 case NestedNameSpecifier::NamespaceAlias:
71 llvm_unreachable("Nested name specifier is not a type for inheriting ctor");
72 }
73
74 // This reference to the type is located entirely at the location of the
75 // final identifier in the qualified-id.
76 return CreateParsedType(Type,
77 Context.getTrivialTypeSourceInfo(Type, NameLoc));
78}
79
John McCallba7bf592010-08-24 05:47:05 +000080ParsedType Sema::getDestructorName(SourceLocation TildeLoc,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000081 IdentifierInfo &II,
John McCallba7bf592010-08-24 05:47:05 +000082 SourceLocation NameLoc,
83 Scope *S, CXXScopeSpec &SS,
84 ParsedType ObjectTypePtr,
85 bool EnteringContext) {
Douglas Gregorfe17d252010-02-16 19:09:40 +000086 // Determine where to perform name lookup.
87
88 // FIXME: This area of the standard is very messy, and the current
89 // wording is rather unclear about which scopes we search for the
90 // destructor name; see core issues 399 and 555. Issue 399 in
91 // particular shows where the current description of destructor name
92 // lookup is completely out of line with existing practice, e.g.,
93 // this appears to be ill-formed:
94 //
95 // namespace N {
96 // template <typename T> struct S {
97 // ~S();
98 // };
99 // }
100 //
101 // void f(N::S<int>* s) {
102 // s->N::S<int>::~S();
103 // }
104 //
Douglas Gregor46841e12010-02-23 00:15:22 +0000105 // See also PR6358 and PR6359.
Sebastian Redla771d222010-07-07 23:17:38 +0000106 // For this reason, we're currently only doing the C++03 version of this
107 // code; the C++0x version has to wait until we get a proper spec.
Douglas Gregorfe17d252010-02-16 19:09:40 +0000108 QualType SearchType;
Craig Topperc3ec1492014-05-26 06:22:03 +0000109 DeclContext *LookupCtx = nullptr;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000110 bool isDependent = false;
111 bool LookInScope = false;
112
113 // If we have an object type, it's because we are in a
114 // pseudo-destructor-expression or a member access expression, and
115 // we know what type we're looking for.
116 if (ObjectTypePtr)
117 SearchType = GetTypeFromParser(ObjectTypePtr);
118
119 if (SS.isSet()) {
Aaron Ballman4a979672014-01-03 13:56:08 +0000120 NestedNameSpecifier *NNS = SS.getScopeRep();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000121
Douglas Gregor46841e12010-02-23 00:15:22 +0000122 bool AlreadySearched = false;
123 bool LookAtPrefix = true;
David Majnemere37a6ce2014-05-21 20:19:59 +0000124 // C++11 [basic.lookup.qual]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000125 // If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier,
Sebastian Redla771d222010-07-07 23:17:38 +0000126 // the type-names are looked up as types in the scope designated by the
David Majnemere37a6ce2014-05-21 20:19:59 +0000127 // nested-name-specifier. Similarly, in a qualified-id of the form:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +0000128 //
David Majnemere37a6ce2014-05-21 20:19:59 +0000129 // nested-name-specifier[opt] class-name :: ~ class-name
Sebastian Redla771d222010-07-07 23:17:38 +0000130 //
David Majnemere37a6ce2014-05-21 20:19:59 +0000131 // the second class-name is looked up in the same scope as the first.
Douglas Gregorfe17d252010-02-16 19:09:40 +0000132 //
David Majnemere37a6ce2014-05-21 20:19:59 +0000133 // Here, we determine whether the code below is permitted to look at the
134 // prefix of the nested-name-specifier.
Sebastian Redla771d222010-07-07 23:17:38 +0000135 DeclContext *DC = computeDeclContext(SS, EnteringContext);
136 if (DC && DC->isFileContext()) {
137 AlreadySearched = true;
138 LookupCtx = DC;
139 isDependent = false;
David Majnemere37a6ce2014-05-21 20:19:59 +0000140 } else if (DC && isa<CXXRecordDecl>(DC)) {
Sebastian Redla771d222010-07-07 23:17:38 +0000141 LookAtPrefix = false;
David Majnemere37a6ce2014-05-21 20:19:59 +0000142 LookInScope = true;
143 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000144
Sebastian Redla771d222010-07-07 23:17:38 +0000145 // The second case from the C++03 rules quoted further above.
Craig Topperc3ec1492014-05-26 06:22:03 +0000146 NestedNameSpecifier *Prefix = nullptr;
Douglas Gregor46841e12010-02-23 00:15:22 +0000147 if (AlreadySearched) {
148 // Nothing left to do.
149 } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) {
150 CXXScopeSpec PrefixSS;
Douglas Gregor10176412011-02-25 16:07:42 +0000151 PrefixSS.Adopt(NestedNameSpecifierLoc(Prefix, SS.location_data()));
Douglas Gregor46841e12010-02-23 00:15:22 +0000152 LookupCtx = computeDeclContext(PrefixSS, EnteringContext);
153 isDependent = isDependentScopeSpecifier(PrefixSS);
Douglas Gregor46841e12010-02-23 00:15:22 +0000154 } else if (ObjectTypePtr) {
Douglas Gregorfe17d252010-02-16 19:09:40 +0000155 LookupCtx = computeDeclContext(SearchType);
156 isDependent = SearchType->isDependentType();
157 } else {
158 LookupCtx = computeDeclContext(SS, EnteringContext);
Douglas Gregor46841e12010-02-23 00:15:22 +0000159 isDependent = LookupCtx && LookupCtx->isDependentContext();
Douglas Gregorfe17d252010-02-16 19:09:40 +0000160 }
Douglas Gregorfe17d252010-02-16 19:09:40 +0000161 } else if (ObjectTypePtr) {
162 // C++ [basic.lookup.classref]p3:
163 // If the unqualified-id is ~type-name, the type-name is looked up
164 // in the context of the entire postfix-expression. If the type T
165 // of the object expression is of a class type C, the type-name is
166 // also looked up in the scope of class C. At least one of the
167 // lookups shall find a name that refers to (possibly
168 // cv-qualified) T.
169 LookupCtx = computeDeclContext(SearchType);
170 isDependent = SearchType->isDependentType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000171 assert((isDependent || !SearchType->isIncompleteType()) &&
Douglas Gregorfe17d252010-02-16 19:09:40 +0000172 "Caller should have completed object type");
173
174 LookInScope = true;
175 } else {
176 // Perform lookup into the current scope (only).
177 LookInScope = true;
178 }
179
Craig Topperc3ec1492014-05-26 06:22:03 +0000180 TypeDecl *NonMatchingTypeDecl = nullptr;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000181 LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName);
182 for (unsigned Step = 0; Step != 2; ++Step) {
183 // Look for the name first in the computed lookup context (if we
Douglas Gregor4cf85a72011-03-04 22:32:08 +0000184 // have one) and, if that fails to find a match, in the scope (if
Douglas Gregorfe17d252010-02-16 19:09:40 +0000185 // we're allowed to look there).
186 Found.clear();
187 if (Step == 0 && LookupCtx)
188 LookupQualifiedName(Found, LookupCtx);
Douglas Gregor678f90d2010-02-25 01:56:36 +0000189 else if (Step == 1 && LookInScope && S)
Douglas Gregorfe17d252010-02-16 19:09:40 +0000190 LookupName(Found, S);
191 else
192 continue;
193
194 // FIXME: Should we be suppressing ambiguities here?
195 if (Found.isAmbiguous())
John McCallba7bf592010-08-24 05:47:05 +0000196 return ParsedType();
Douglas Gregorfe17d252010-02-16 19:09:40 +0000197
198 if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
199 QualType T = Context.getTypeDeclType(Type);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000200
201 if (SearchType.isNull() || SearchType->isDependentType() ||
202 Context.hasSameUnqualifiedType(T, SearchType)) {
203 // We found our type!
204
Richard Smithc278c002014-01-22 00:30:17 +0000205 return CreateParsedType(T,
206 Context.getTrivialTypeSourceInfo(T, NameLoc));
Douglas Gregorfe17d252010-02-16 19:09:40 +0000207 }
John Wiegleyb4a9e512011-03-08 08:13:22 +0000208
Douglas Gregor4cf85a72011-03-04 22:32:08 +0000209 if (!SearchType.isNull())
210 NonMatchingTypeDecl = Type;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000211 }
212
213 // If the name that we found is a class template name, and it is
214 // the same name as the template name in the last part of the
215 // nested-name-specifier (if present) or the object type, then
216 // this is the destructor for that class.
217 // FIXME: This is a workaround until we get real drafting for core
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000218 // issue 399, for which there isn't even an obvious direction.
Douglas Gregorfe17d252010-02-16 19:09:40 +0000219 if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) {
220 QualType MemberOfType;
221 if (SS.isSet()) {
222 if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) {
223 // Figure out the type of the context, if it has one.
John McCalle78aac42010-03-10 03:28:59 +0000224 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx))
225 MemberOfType = Context.getTypeDeclType(Record);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000226 }
227 }
228 if (MemberOfType.isNull())
229 MemberOfType = SearchType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000230
Douglas Gregorfe17d252010-02-16 19:09:40 +0000231 if (MemberOfType.isNull())
232 continue;
233
234 // We're referring into a class template specialization. If the
235 // class template we found is the same as the template being
236 // specialized, we found what we are looking for.
237 if (const RecordType *Record = MemberOfType->getAs<RecordType>()) {
238 if (ClassTemplateSpecializationDecl *Spec
239 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
240 if (Spec->getSpecializedTemplate()->getCanonicalDecl() ==
241 Template->getCanonicalDecl())
Richard Smithc278c002014-01-22 00:30:17 +0000242 return CreateParsedType(
243 MemberOfType,
244 Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
Douglas Gregorfe17d252010-02-16 19:09:40 +0000245 }
246
247 continue;
248 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000249
Douglas Gregorfe17d252010-02-16 19:09:40 +0000250 // We're referring to an unresolved class template
251 // specialization. Determine whether we class template we found
252 // is the same as the template being specialized or, if we don't
253 // know which template is being specialized, that it at least
254 // has the same name.
255 if (const TemplateSpecializationType *SpecType
256 = MemberOfType->getAs<TemplateSpecializationType>()) {
257 TemplateName SpecName = SpecType->getTemplateName();
258
259 // The class template we found is the same template being
260 // specialized.
261 if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) {
262 if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl())
Richard Smithc278c002014-01-22 00:30:17 +0000263 return CreateParsedType(
264 MemberOfType,
265 Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
Douglas Gregorfe17d252010-02-16 19:09:40 +0000266
267 continue;
268 }
269
270 // The class template we found has the same name as the
271 // (dependent) template name being specialized.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000272 if (DependentTemplateName *DepTemplate
Douglas Gregorfe17d252010-02-16 19:09:40 +0000273 = SpecName.getAsDependentTemplateName()) {
274 if (DepTemplate->isIdentifier() &&
275 DepTemplate->getIdentifier() == Template->getIdentifier())
Richard Smithc278c002014-01-22 00:30:17 +0000276 return CreateParsedType(
277 MemberOfType,
278 Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
Douglas Gregorfe17d252010-02-16 19:09:40 +0000279
280 continue;
281 }
282 }
283 }
284 }
285
286 if (isDependent) {
287 // We didn't find our type, but that's okay: it's dependent
288 // anyway.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +0000289
290 // FIXME: What if we have no nested-name-specifier?
291 QualType T = CheckTypenameType(ETK_None, SourceLocation(),
292 SS.getWithLocInContext(Context),
293 II, NameLoc);
John McCallba7bf592010-08-24 05:47:05 +0000294 return ParsedType::make(T);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000295 }
296
Douglas Gregor4cf85a72011-03-04 22:32:08 +0000297 if (NonMatchingTypeDecl) {
298 QualType T = Context.getTypeDeclType(NonMatchingTypeDecl);
299 Diag(NameLoc, diag::err_destructor_expr_type_mismatch)
300 << T << SearchType;
301 Diag(NonMatchingTypeDecl->getLocation(), diag::note_destructor_type_here)
302 << T;
303 } else if (ObjectTypePtr)
304 Diag(NameLoc, diag::err_ident_in_dtor_not_a_type)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000305 << &II;
David Blaikie5e026f52013-03-20 17:42:13 +0000306 else {
307 SemaDiagnosticBuilder DtorDiag = Diag(NameLoc,
308 diag::err_destructor_class_name);
309 if (S) {
Ted Kremenekc37877d2013-10-08 17:08:03 +0000310 const DeclContext *Ctx = S->getEntity();
David Blaikie5e026f52013-03-20 17:42:13 +0000311 if (const CXXRecordDecl *Class = dyn_cast_or_null<CXXRecordDecl>(Ctx))
312 DtorDiag << FixItHint::CreateReplacement(SourceRange(NameLoc),
313 Class->getNameAsString());
314 }
315 }
Douglas Gregorfe17d252010-02-16 19:09:40 +0000316
John McCallba7bf592010-08-24 05:47:05 +0000317 return ParsedType();
Douglas Gregorfe17d252010-02-16 19:09:40 +0000318}
319
David Blaikieecd8a942011-12-08 16:13:53 +0000320ParsedType Sema::getDestructorType(const DeclSpec& DS, ParsedType ObjectType) {
David Blaikie08608f62011-12-12 04:13:55 +0000321 if (DS.getTypeSpecType() == DeclSpec::TST_error || !ObjectType)
David Blaikieecd8a942011-12-08 16:13:53 +0000322 return ParsedType();
323 assert(DS.getTypeSpecType() == DeclSpec::TST_decltype
324 && "only get destructor types from declspecs");
325 QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
326 QualType SearchType = GetTypeFromParser(ObjectType);
327 if (SearchType->isDependentType() || Context.hasSameUnqualifiedType(SearchType, T)) {
328 return ParsedType::make(T);
329 }
330
331 Diag(DS.getTypeSpecTypeLoc(), diag::err_destructor_expr_type_mismatch)
332 << T << SearchType;
333 return ParsedType();
334}
335
Richard Smithd091dc12013-12-05 00:58:33 +0000336bool Sema::checkLiteralOperatorId(const CXXScopeSpec &SS,
337 const UnqualifiedId &Name) {
338 assert(Name.getKind() == UnqualifiedId::IK_LiteralOperatorId);
339
340 if (!SS.isValid())
341 return false;
342
343 switch (SS.getScopeRep()->getKind()) {
344 case NestedNameSpecifier::Identifier:
345 case NestedNameSpecifier::TypeSpec:
346 case NestedNameSpecifier::TypeSpecWithTemplate:
347 // Per C++11 [over.literal]p2, literal operators can only be declared at
348 // namespace scope. Therefore, this unqualified-id cannot name anything.
349 // Reject it early, because we have no AST representation for this in the
350 // case where the scope is dependent.
351 Diag(Name.getLocStart(), diag::err_literal_operator_id_outside_namespace)
352 << SS.getScopeRep();
353 return true;
354
355 case NestedNameSpecifier::Global:
356 case NestedNameSpecifier::Namespace:
357 case NestedNameSpecifier::NamespaceAlias:
358 return false;
359 }
360
361 llvm_unreachable("unknown nested name specifier kind");
362}
363
Douglas Gregor9da64192010-04-26 22:37:10 +0000364/// \brief Build a C++ typeid expression with a type operand.
John McCalldadc5752010-08-24 06:29:42 +0000365ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000366 SourceLocation TypeidLoc,
367 TypeSourceInfo *Operand,
368 SourceLocation RParenLoc) {
Douglas Gregor9da64192010-04-26 22:37:10 +0000369 // C++ [expr.typeid]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000370 // The top-level cv-qualifiers of the lvalue expression or the type-id
Douglas Gregor9da64192010-04-26 22:37:10 +0000371 // that is the operand of typeid are always ignored.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000372 // If the type of the type-id is a class type or a reference to a class
Douglas Gregor9da64192010-04-26 22:37:10 +0000373 // type, the class shall be completely-defined.
Douglas Gregor876cec22010-06-02 06:16:02 +0000374 Qualifiers Quals;
375 QualType T
376 = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
377 Quals);
Douglas Gregor9da64192010-04-26 22:37:10 +0000378 if (T->getAs<RecordType>() &&
379 RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
380 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000381
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000382 return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), Operand,
383 SourceRange(TypeidLoc, RParenLoc));
Douglas Gregor9da64192010-04-26 22:37:10 +0000384}
385
386/// \brief Build a C++ typeid expression with an expression operand.
John McCalldadc5752010-08-24 06:29:42 +0000387ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000388 SourceLocation TypeidLoc,
389 Expr *E,
390 SourceLocation RParenLoc) {
Douglas Gregor9da64192010-04-26 22:37:10 +0000391 if (E && !E->isTypeDependent()) {
John McCall50a2c2c2011-10-11 23:14:30 +0000392 if (E->getType()->isPlaceholderType()) {
393 ExprResult result = CheckPlaceholderExpr(E);
394 if (result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000395 E = result.get();
John McCall50a2c2c2011-10-11 23:14:30 +0000396 }
397
Douglas Gregor9da64192010-04-26 22:37:10 +0000398 QualType T = E->getType();
399 if (const RecordType *RecordT = T->getAs<RecordType>()) {
400 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
401 // C++ [expr.typeid]p3:
402 // [...] If the type of the expression is a class type, the class
403 // shall be completely-defined.
404 if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
405 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000406
Douglas Gregor9da64192010-04-26 22:37:10 +0000407 // C++ [expr.typeid]p3:
Sebastian Redlc57d34b2010-07-20 04:20:21 +0000408 // When typeid is applied to an expression other than an glvalue of a
Douglas Gregor9da64192010-04-26 22:37:10 +0000409 // polymorphic class type [...] [the] expression is an unevaluated
410 // operand. [...]
Richard Smithef8bf432012-08-13 20:08:14 +0000411 if (RecordD->isPolymorphic() && E->isGLValue()) {
Eli Friedman456f0182012-01-20 01:26:23 +0000412 // The subexpression is potentially evaluated; switch the context
413 // and recheck the subexpression.
Benjamin Kramerd81108f2012-11-14 15:08:31 +0000414 ExprResult Result = TransformToPotentiallyEvaluated(E);
Eli Friedman456f0182012-01-20 01:26:23 +0000415 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000416 E = Result.get();
Douglas Gregor88d292c2010-05-13 16:44:06 +0000417
418 // We require a vtable to query the type at run time.
419 MarkVTableUsed(TypeidLoc, RecordD);
420 }
Douglas Gregor9da64192010-04-26 22:37:10 +0000421 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000422
Douglas Gregor9da64192010-04-26 22:37:10 +0000423 // C++ [expr.typeid]p4:
424 // [...] If the type of the type-id is a reference to a possibly
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000425 // cv-qualified type, the result of the typeid expression refers to a
426 // std::type_info object representing the cv-unqualified referenced
Douglas Gregor9da64192010-04-26 22:37:10 +0000427 // type.
Douglas Gregor876cec22010-06-02 06:16:02 +0000428 Qualifiers Quals;
429 QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
430 if (!Context.hasSameType(T, UnqualT)) {
431 T = UnqualT;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000432 E = ImpCastExprToType(E, UnqualT, CK_NoOp, E->getValueKind()).get();
Douglas Gregor9da64192010-04-26 22:37:10 +0000433 }
434 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000435
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000436 return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), E,
437 SourceRange(TypeidLoc, RParenLoc));
Douglas Gregor9da64192010-04-26 22:37:10 +0000438}
439
440/// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
John McCalldadc5752010-08-24 06:29:42 +0000441ExprResult
Sebastian Redlc4704762008-11-11 11:37:55 +0000442Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
443 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Douglas Gregor9da64192010-04-26 22:37:10 +0000444 // Find the std::type_info type.
Sebastian Redl7ac97412011-03-31 19:29:24 +0000445 if (!getStdNamespace())
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000446 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000447
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000448 if (!CXXTypeInfoDecl) {
449 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
450 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
451 LookupQualifiedName(R, getStdNamespace());
452 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
Nico Weber5f968832012-06-19 23:58:27 +0000453 // Microsoft's typeinfo doesn't have type_info in std but in the global
454 // namespace if _HAS_EXCEPTIONS is defined to 0. See PR13153.
Alp Tokerbfa39342014-01-14 12:51:41 +0000455 if (!CXXTypeInfoDecl && LangOpts.MSVCCompat) {
Nico Weber5f968832012-06-19 23:58:27 +0000456 LookupQualifiedName(R, Context.getTranslationUnitDecl());
457 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
458 }
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000459 if (!CXXTypeInfoDecl)
460 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
461 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000462
Nico Weber1b7f39d2012-05-20 01:27:21 +0000463 if (!getLangOpts().RTTI) {
464 return ExprError(Diag(OpLoc, diag::err_no_typeid_with_fno_rtti));
465 }
466
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000467 QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000468
Douglas Gregor9da64192010-04-26 22:37:10 +0000469 if (isType) {
470 // The operand is a type; handle it as such.
Craig Topperc3ec1492014-05-26 06:22:03 +0000471 TypeSourceInfo *TInfo = nullptr;
John McCallba7bf592010-08-24 05:47:05 +0000472 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
473 &TInfo);
Douglas Gregor9da64192010-04-26 22:37:10 +0000474 if (T.isNull())
475 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000476
Douglas Gregor9da64192010-04-26 22:37:10 +0000477 if (!TInfo)
478 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
Sebastian Redlc4704762008-11-11 11:37:55 +0000479
Douglas Gregor9da64192010-04-26 22:37:10 +0000480 return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
Douglas Gregor0b6a6242009-06-22 20:57:11 +0000481 }
Mike Stump11289f42009-09-09 15:08:12 +0000482
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000483 // The operand is an expression.
John McCallb268a282010-08-23 23:25:46 +0000484 return BuildCXXTypeId(TypeInfoType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
Sebastian Redlc4704762008-11-11 11:37:55 +0000485}
486
Francois Pichet9f4f2072010-09-08 12:20:18 +0000487/// \brief Build a Microsoft __uuidof expression with a type operand.
488ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
489 SourceLocation TypeidLoc,
490 TypeSourceInfo *Operand,
491 SourceLocation RParenLoc) {
Francois Pichetb7577652010-12-27 01:32:00 +0000492 if (!Operand->getType()->isDependentType()) {
David Majnemer59c0ec22013-09-07 06:59:46 +0000493 bool HasMultipleGUIDs = false;
494 if (!CXXUuidofExpr::GetUuidAttrOfType(Operand->getType(),
495 &HasMultipleGUIDs)) {
496 if (HasMultipleGUIDs)
497 return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
498 else
499 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
500 }
Francois Pichetb7577652010-12-27 01:32:00 +0000501 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000502
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000503 return new (Context) CXXUuidofExpr(TypeInfoType.withConst(), Operand,
504 SourceRange(TypeidLoc, RParenLoc));
Francois Pichet9f4f2072010-09-08 12:20:18 +0000505}
506
507/// \brief Build a Microsoft __uuidof expression with an expression operand.
508ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
509 SourceLocation TypeidLoc,
510 Expr *E,
511 SourceLocation RParenLoc) {
Francois Pichetb7577652010-12-27 01:32:00 +0000512 if (!E->getType()->isDependentType()) {
David Majnemer59c0ec22013-09-07 06:59:46 +0000513 bool HasMultipleGUIDs = false;
514 if (!CXXUuidofExpr::GetUuidAttrOfType(E->getType(), &HasMultipleGUIDs) &&
515 !E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
516 if (HasMultipleGUIDs)
517 return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
518 else
519 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
520 }
Francois Pichetb7577652010-12-27 01:32:00 +0000521 }
David Majnemer59c0ec22013-09-07 06:59:46 +0000522
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000523 return new (Context) CXXUuidofExpr(TypeInfoType.withConst(), E,
524 SourceRange(TypeidLoc, RParenLoc));
Francois Pichet9f4f2072010-09-08 12:20:18 +0000525}
526
527/// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
528ExprResult
529Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc,
530 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000531 // If MSVCGuidDecl has not been cached, do the lookup.
Francois Pichet9f4f2072010-09-08 12:20:18 +0000532 if (!MSVCGuidDecl) {
533 IdentifierInfo *GuidII = &PP.getIdentifierTable().get("_GUID");
534 LookupResult R(*this, GuidII, SourceLocation(), LookupTagName);
535 LookupQualifiedName(R, Context.getTranslationUnitDecl());
536 MSVCGuidDecl = R.getAsSingle<RecordDecl>();
537 if (!MSVCGuidDecl)
538 return ExprError(Diag(OpLoc, diag::err_need_header_before_ms_uuidof));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000539 }
540
Francois Pichet9f4f2072010-09-08 12:20:18 +0000541 QualType GuidType = Context.getTypeDeclType(MSVCGuidDecl);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000542
Francois Pichet9f4f2072010-09-08 12:20:18 +0000543 if (isType) {
544 // The operand is a type; handle it as such.
Craig Topperc3ec1492014-05-26 06:22:03 +0000545 TypeSourceInfo *TInfo = nullptr;
Francois Pichet9f4f2072010-09-08 12:20:18 +0000546 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
547 &TInfo);
548 if (T.isNull())
549 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000550
Francois Pichet9f4f2072010-09-08 12:20:18 +0000551 if (!TInfo)
552 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
553
554 return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);
555 }
556
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000557 // The operand is an expression.
Francois Pichet9f4f2072010-09-08 12:20:18 +0000558 return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
559}
560
Steve Naroff66356bd2007-09-16 14:56:35 +0000561/// ActOnCXXBoolLiteral - Parse {true,false} literals.
John McCalldadc5752010-08-24 06:29:42 +0000562ExprResult
Steve Naroff66356bd2007-09-16 14:56:35 +0000563Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor08d918a2008-10-24 15:36:09 +0000564 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Bill Wendlingbf313b02007-02-13 20:09:46 +0000565 "Unknown C++ Boolean value!");
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000566 return new (Context)
567 CXXBoolLiteralExpr(Kind == tok::kw_true, Context.BoolTy, OpLoc);
Bill Wendling4073ed52007-02-13 01:51:42 +0000568}
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000569
Sebastian Redl576fd422009-05-10 18:38:11 +0000570/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
John McCalldadc5752010-08-24 06:29:42 +0000571ExprResult
Sebastian Redl576fd422009-05-10 18:38:11 +0000572Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000573 return new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
Sebastian Redl576fd422009-05-10 18:38:11 +0000574}
575
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000576/// ActOnCXXThrow - Parse throw expressions.
John McCalldadc5752010-08-24 06:29:42 +0000577ExprResult
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000578Sema::ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *Ex) {
579 bool IsThrownVarInScope = false;
580 if (Ex) {
581 // C++0x [class.copymove]p31:
582 // When certain criteria are met, an implementation is allowed to omit the
583 // copy/move construction of a class object [...]
584 //
585 // - in a throw-expression, when the operand is the name of a
586 // non-volatile automatic object (other than a function or catch-
587 // clause parameter) whose scope does not extend beyond the end of the
588 // innermost enclosing try-block (if there is one), the copy/move
589 // operation from the operand to the exception object (15.1) can be
590 // omitted by constructing the automatic object directly into the
591 // exception object
592 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Ex->IgnoreParens()))
593 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
594 if (Var->hasLocalStorage() && !Var->getType().isVolatileQualified()) {
595 for( ; S; S = S->getParent()) {
596 if (S->isDeclScope(Var)) {
597 IsThrownVarInScope = true;
598 break;
599 }
600
601 if (S->getFlags() &
602 (Scope::FnScope | Scope::ClassScope | Scope::BlockScope |
603 Scope::FunctionPrototypeScope | Scope::ObjCMethodScope |
604 Scope::TryScope))
605 break;
606 }
607 }
608 }
609 }
610
611 return BuildCXXThrow(OpLoc, Ex, IsThrownVarInScope);
612}
613
614ExprResult Sema::BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
615 bool IsThrownVarInScope) {
Anders Carlssond99dbcc2011-02-23 03:46:46 +0000616 // Don't report an error if 'throw' is used in system headers.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000617 if (!getLangOpts().CXXExceptions &&
Anders Carlssond99dbcc2011-02-23 03:46:46 +0000618 !getSourceManager().isInSystemHeader(OpLoc))
Anders Carlssonb94ad3e2011-02-19 21:53:09 +0000619 Diag(OpLoc, diag::err_exceptions_disabled) << "throw";
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000620
John Wiegley01296292011-04-08 18:41:53 +0000621 if (Ex && !Ex->isTypeDependent()) {
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000622 ExprResult ExRes = CheckCXXThrowOperand(OpLoc, Ex, IsThrownVarInScope);
John Wiegley01296292011-04-08 18:41:53 +0000623 if (ExRes.isInvalid())
624 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000625 Ex = ExRes.get();
John Wiegley01296292011-04-08 18:41:53 +0000626 }
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000627
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000628 return new (Context)
629 CXXThrowExpr(Ex, Context.VoidTy, OpLoc, IsThrownVarInScope);
Sebastian Redl4de47b42009-04-27 20:27:31 +0000630}
631
632/// CheckCXXThrowOperand - Validate the operand of a throw.
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000633ExprResult Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *E,
634 bool IsThrownVarInScope) {
Sebastian Redl4de47b42009-04-27 20:27:31 +0000635 // C++ [except.throw]p3:
Douglas Gregor247894b2009-12-23 22:04:40 +0000636 // A throw-expression initializes a temporary object, called the exception
637 // object, the type of which is determined by removing any top-level
638 // cv-qualifiers from the static type of the operand of throw and adjusting
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000639 // the type from "array of T" or "function returning T" to "pointer to T"
Douglas Gregor247894b2009-12-23 22:04:40 +0000640 // or "pointer to function returning T", [...]
641 if (E->getType().hasQualifiers())
John Wiegley01296292011-04-08 18:41:53 +0000642 E = ImpCastExprToType(E, E->getType().getUnqualifiedType(), CK_NoOp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000643 E->getValueKind()).get();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000644
John Wiegley01296292011-04-08 18:41:53 +0000645 ExprResult Res = DefaultFunctionArrayConversion(E);
646 if (Res.isInvalid())
647 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000648 E = Res.get();
Sebastian Redl4de47b42009-04-27 20:27:31 +0000649
650 // If the type of the exception would be an incomplete type or a pointer
651 // to an incomplete type other than (cv) void the program is ill-formed.
652 QualType Ty = E->getType();
John McCall2e6567a2010-04-22 01:10:34 +0000653 bool isPointer = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000654 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl4de47b42009-04-27 20:27:31 +0000655 Ty = Ptr->getPointeeType();
John McCall2e6567a2010-04-22 01:10:34 +0000656 isPointer = true;
Sebastian Redl4de47b42009-04-27 20:27:31 +0000657 }
658 if (!isPointer || !Ty->isVoidType()) {
659 if (RequireCompleteType(ThrowLoc, Ty,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +0000660 isPointer? diag::err_throw_incomplete_ptr
661 : diag::err_throw_incomplete,
662 E->getSourceRange()))
John Wiegley01296292011-04-08 18:41:53 +0000663 return ExprError();
Rafael Espindola70e040d2010-03-02 21:28:26 +0000664
Douglas Gregore8154332010-04-15 18:05:39 +0000665 if (RequireNonAbstractType(ThrowLoc, E->getType(),
Douglas Gregorae298422012-05-04 17:09:59 +0000666 diag::err_throw_abstract_type, E))
John Wiegley01296292011-04-08 18:41:53 +0000667 return ExprError();
Sebastian Redl4de47b42009-04-27 20:27:31 +0000668 }
669
John McCall2e6567a2010-04-22 01:10:34 +0000670 // Initialize the exception result. This implicitly weeds out
671 // abstract types or types with inaccessible copy constructors.
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000672
673 // C++0x [class.copymove]p31:
674 // When certain criteria are met, an implementation is allowed to omit the
675 // copy/move construction of a class object [...]
676 //
677 // - in a throw-expression, when the operand is the name of a
678 // non-volatile automatic object (other than a function or catch-clause
679 // parameter) whose scope does not extend beyond the end of the
680 // innermost enclosing try-block (if there is one), the copy/move
681 // operation from the operand to the exception object (15.1) can be
682 // omitted by constructing the automatic object directly into the
683 // exception object
Craig Topperc3ec1492014-05-26 06:22:03 +0000684 const VarDecl *NRVOVariable = nullptr;
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000685 if (IsThrownVarInScope)
686 NRVOVariable = getCopyElisionCandidate(QualType(), E, false);
Craig Topperc3ec1492014-05-26 06:22:03 +0000687
John McCall2e6567a2010-04-22 01:10:34 +0000688 InitializedEntity Entity =
Douglas Gregorc74edc22011-01-21 22:46:35 +0000689 InitializedEntity::InitializeException(ThrowLoc, E->getType(),
Craig Topperc3ec1492014-05-26 06:22:03 +0000690 /*NRVO=*/NRVOVariable != nullptr);
John Wiegley01296292011-04-08 18:41:53 +0000691 Res = PerformMoveOrCopyInitialization(Entity, NRVOVariable,
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000692 QualType(), E,
693 IsThrownVarInScope);
John McCall2e6567a2010-04-22 01:10:34 +0000694 if (Res.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +0000695 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000696 E = Res.get();
Douglas Gregor88d292c2010-05-13 16:44:06 +0000697
Eli Friedman91a3d272010-06-03 20:39:03 +0000698 // If the exception has class type, we need additional handling.
699 const RecordType *RecordTy = Ty->getAs<RecordType>();
700 if (!RecordTy)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000701 return E;
Eli Friedman91a3d272010-06-03 20:39:03 +0000702 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
703
Douglas Gregor88d292c2010-05-13 16:44:06 +0000704 // If we are throwing a polymorphic class type or pointer thereof,
705 // exception handling will make use of the vtable.
Eli Friedman91a3d272010-06-03 20:39:03 +0000706 MarkVTableUsed(ThrowLoc, RD);
707
Eli Friedman36ebbec2010-10-12 20:32:36 +0000708 // If a pointer is thrown, the referenced object will not be destroyed.
709 if (isPointer)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000710 return E;
Eli Friedman36ebbec2010-10-12 20:32:36 +0000711
Richard Smitheec915d62012-02-18 04:13:32 +0000712 // If the class has a destructor, we must be able to call it.
713 if (RD->hasIrrelevantDestructor())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000714 return E;
Eli Friedman91a3d272010-06-03 20:39:03 +0000715
Sebastian Redl249dee52012-03-05 19:35:43 +0000716 CXXDestructorDecl *Destructor = LookupDestructor(RD);
Eli Friedman91a3d272010-06-03 20:39:03 +0000717 if (!Destructor)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000718 return E;
Eli Friedman91a3d272010-06-03 20:39:03 +0000719
Eli Friedmanfa0df832012-02-02 03:46:19 +0000720 MarkFunctionReferenced(E->getExprLoc(), Destructor);
Eli Friedman91a3d272010-06-03 20:39:03 +0000721 CheckDestructorAccess(E->getExprLoc(), Destructor,
Douglas Gregor747eb782010-07-08 06:14:04 +0000722 PDiag(diag::err_access_dtor_exception) << Ty);
Richard Smith22262ab2013-05-04 06:44:46 +0000723 if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
724 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000725 return E;
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000726}
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000727
Eli Friedman73a04092012-01-07 04:59:52 +0000728QualType Sema::getCurrentThisType() {
729 DeclContext *DC = getFunctionLevelDeclContext();
Douglas Gregor3024f072012-04-16 07:05:22 +0000730 QualType ThisTy = CXXThisTypeOverride;
Richard Smith938f40b2011-06-11 17:19:42 +0000731 if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC)) {
732 if (method && method->isInstance())
733 ThisTy = method->getThisType(Context);
Richard Smith938f40b2011-06-11 17:19:42 +0000734 }
Douglas Gregor3024f072012-04-16 07:05:22 +0000735
Richard Smith938f40b2011-06-11 17:19:42 +0000736 return ThisTy;
John McCallf3a88602011-02-03 08:15:49 +0000737}
738
Douglas Gregor3024f072012-04-16 07:05:22 +0000739Sema::CXXThisScopeRAII::CXXThisScopeRAII(Sema &S,
740 Decl *ContextDecl,
741 unsigned CXXThisTypeQuals,
742 bool Enabled)
743 : S(S), OldCXXThisTypeOverride(S.CXXThisTypeOverride), Enabled(false)
744{
745 if (!Enabled || !ContextDecl)
746 return;
Craig Topperc3ec1492014-05-26 06:22:03 +0000747
748 CXXRecordDecl *Record = nullptr;
Douglas Gregor3024f072012-04-16 07:05:22 +0000749 if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(ContextDecl))
750 Record = Template->getTemplatedDecl();
751 else
752 Record = cast<CXXRecordDecl>(ContextDecl);
753
754 S.CXXThisTypeOverride
755 = S.Context.getPointerType(
756 S.Context.getRecordType(Record).withCVRQualifiers(CXXThisTypeQuals));
757
758 this->Enabled = true;
759}
760
761
762Sema::CXXThisScopeRAII::~CXXThisScopeRAII() {
763 if (Enabled) {
764 S.CXXThisTypeOverride = OldCXXThisTypeOverride;
765 }
766}
767
Ben Langmuire7d7c4c2013-04-29 13:32:41 +0000768static Expr *captureThis(ASTContext &Context, RecordDecl *RD,
769 QualType ThisTy, SourceLocation Loc) {
770 FieldDecl *Field
Craig Topperc3ec1492014-05-26 06:22:03 +0000771 = FieldDecl::Create(Context, RD, Loc, Loc, nullptr, ThisTy,
Ben Langmuire7d7c4c2013-04-29 13:32:41 +0000772 Context.getTrivialTypeSourceInfo(ThisTy, Loc),
Craig Topperc3ec1492014-05-26 06:22:03 +0000773 nullptr, false, ICIS_NoInit);
Ben Langmuire7d7c4c2013-04-29 13:32:41 +0000774 Field->setImplicit(true);
775 Field->setAccess(AS_private);
776 RD->addDecl(Field);
777 return new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit*/true);
778}
779
Faisal Valia17d19f2013-11-07 05:17:06 +0000780bool Sema::CheckCXXThisCapture(SourceLocation Loc, bool Explicit,
781 bool BuildAndDiagnose, const unsigned *const FunctionScopeIndexToStopAt) {
Eli Friedman73a04092012-01-07 04:59:52 +0000782 // We don't need to capture this in an unevaluated context.
John McCallf413f5e2013-05-03 00:10:13 +0000783 if (isUnevaluatedContext() && !Explicit)
Faisal Valia17d19f2013-11-07 05:17:06 +0000784 return true;
Eli Friedman73a04092012-01-07 04:59:52 +0000785
Faisal Valia17d19f2013-11-07 05:17:06 +0000786 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt ?
787 *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
788 // Otherwise, check that we can capture 'this'.
Eli Friedman73a04092012-01-07 04:59:52 +0000789 unsigned NumClosures = 0;
Faisal Valia17d19f2013-11-07 05:17:06 +0000790 for (unsigned idx = MaxFunctionScopesIndex; idx != 0; idx--) {
Eli Friedman20139d32012-01-11 02:36:31 +0000791 if (CapturingScopeInfo *CSI =
792 dyn_cast<CapturingScopeInfo>(FunctionScopes[idx])) {
793 if (CSI->CXXThisCaptureIndex != 0) {
794 // 'this' is already being captured; there isn't anything more to do.
Eli Friedman73a04092012-01-07 04:59:52 +0000795 break;
796 }
Faisal Valia17d19f2013-11-07 05:17:06 +0000797 LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI);
798 if (LSI && isGenericLambdaCallOperatorSpecialization(LSI->CallOperator)) {
799 // This context can't implicitly capture 'this'; fail out.
800 if (BuildAndDiagnose)
801 Diag(Loc, diag::err_this_capture) << Explicit;
802 return true;
803 }
Eli Friedman20139d32012-01-11 02:36:31 +0000804 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByref ||
Douglas Gregora1bffa22012-02-10 17:46:20 +0000805 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval ||
Douglas Gregorcdd11d42012-02-01 17:04:21 +0000806 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_Block ||
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +0000807 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_CapturedRegion ||
Douglas Gregorcdd11d42012-02-01 17:04:21 +0000808 Explicit) {
809 // This closure can capture 'this'; continue looking upwards.
Eli Friedman73a04092012-01-07 04:59:52 +0000810 NumClosures++;
Douglas Gregorcdd11d42012-02-01 17:04:21 +0000811 Explicit = false;
Eli Friedman73a04092012-01-07 04:59:52 +0000812 continue;
813 }
Eli Friedman20139d32012-01-11 02:36:31 +0000814 // This context can't implicitly capture 'this'; fail out.
Faisal Valia17d19f2013-11-07 05:17:06 +0000815 if (BuildAndDiagnose)
816 Diag(Loc, diag::err_this_capture) << Explicit;
817 return true;
Eli Friedman73a04092012-01-07 04:59:52 +0000818 }
Eli Friedman73a04092012-01-07 04:59:52 +0000819 break;
820 }
Faisal Valia17d19f2013-11-07 05:17:06 +0000821 if (!BuildAndDiagnose) return false;
Eli Friedman73a04092012-01-07 04:59:52 +0000822 // Mark that we're implicitly capturing 'this' in all the scopes we skipped.
823 // FIXME: We need to delay this marking in PotentiallyPotentiallyEvaluated
824 // contexts.
Faisal Valia17d19f2013-11-07 05:17:06 +0000825 for (unsigned idx = MaxFunctionScopesIndex; NumClosures;
826 --idx, --NumClosures) {
Eli Friedman20139d32012-01-11 02:36:31 +0000827 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[idx]);
Craig Topperc3ec1492014-05-26 06:22:03 +0000828 Expr *ThisExpr = nullptr;
Douglas Gregorfdf598e2012-02-18 09:37:24 +0000829 QualType ThisTy = getCurrentThisType();
Ben Langmuire7d7c4c2013-04-29 13:32:41 +0000830 if (LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI))
Eli Friedmanc9751062012-02-11 02:51:16 +0000831 // For lambda expressions, build a field and an initializing expression.
Ben Langmuire7d7c4c2013-04-29 13:32:41 +0000832 ThisExpr = captureThis(Context, LSI->Lambda, ThisTy, Loc);
833 else if (CapturedRegionScopeInfo *RSI
834 = dyn_cast<CapturedRegionScopeInfo>(FunctionScopes[idx]))
835 ThisExpr = captureThis(Context, RSI->TheRecordDecl, ThisTy, Loc);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +0000836
Eli Friedman20139d32012-01-11 02:36:31 +0000837 bool isNested = NumClosures > 1;
Douglas Gregorfdf598e2012-02-18 09:37:24 +0000838 CSI->addThisCapture(isNested, Loc, ThisTy, ThisExpr);
Eli Friedman73a04092012-01-07 04:59:52 +0000839 }
Faisal Valia17d19f2013-11-07 05:17:06 +0000840 return false;
Eli Friedman73a04092012-01-07 04:59:52 +0000841}
842
Richard Smith938f40b2011-06-11 17:19:42 +0000843ExprResult Sema::ActOnCXXThis(SourceLocation Loc) {
John McCallf3a88602011-02-03 08:15:49 +0000844 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
845 /// is a non-lvalue expression whose value is the address of the object for
846 /// which the function is called.
847
Douglas Gregor09deffa2011-10-18 16:47:30 +0000848 QualType ThisTy = getCurrentThisType();
Richard Smith938f40b2011-06-11 17:19:42 +0000849 if (ThisTy.isNull()) return Diag(Loc, diag::err_invalid_this_use);
John McCallf3a88602011-02-03 08:15:49 +0000850
Eli Friedman73a04092012-01-07 04:59:52 +0000851 CheckCXXThisCapture(Loc);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000852 return new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit=*/false);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000853}
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000854
Douglas Gregor3024f072012-04-16 07:05:22 +0000855bool Sema::isThisOutsideMemberFunctionBody(QualType BaseType) {
856 // If we're outside the body of a member function, then we'll have a specified
857 // type for 'this'.
858 if (CXXThisTypeOverride.isNull())
859 return false;
860
861 // Determine whether we're looking into a class that's currently being
862 // defined.
863 CXXRecordDecl *Class = BaseType->getAsCXXRecordDecl();
864 return Class && Class->isBeingDefined();
865}
866
John McCalldadc5752010-08-24 06:29:42 +0000867ExprResult
Douglas Gregor2b88c112010-09-08 00:15:04 +0000868Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000869 SourceLocation LParenLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000870 MultiExprArg exprs,
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000871 SourceLocation RParenLoc) {
Douglas Gregor7df89f52010-02-05 19:11:37 +0000872 if (!TypeRep)
873 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000874
John McCall97513962010-01-15 18:39:57 +0000875 TypeSourceInfo *TInfo;
876 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
877 if (!TInfo)
878 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
Douglas Gregor2b88c112010-09-08 00:15:04 +0000879
880 return BuildCXXTypeConstructExpr(TInfo, LParenLoc, exprs, RParenLoc);
881}
882
883/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
884/// Can be interpreted either as function-style casting ("int(x)")
885/// or class type construction ("ClassType(x,y,z)")
886/// or creation of a value-initialized type ("int()").
887ExprResult
888Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
889 SourceLocation LParenLoc,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +0000890 MultiExprArg Exprs,
Douglas Gregor2b88c112010-09-08 00:15:04 +0000891 SourceLocation RParenLoc) {
892 QualType Ty = TInfo->getType();
Douglas Gregor2b88c112010-09-08 00:15:04 +0000893 SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000894
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +0000895 if (Ty->isDependentType() || CallExpr::hasAnyTypeDependentArguments(Exprs)) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000896 return CXXUnresolvedConstructExpr::Create(Context, TInfo, LParenLoc, Exprs,
897 RParenLoc);
Douglas Gregor0950e412009-03-13 21:01:28 +0000898 }
899
Sebastian Redld74dd492012-02-12 18:41:05 +0000900 bool ListInitialization = LParenLoc.isInvalid();
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +0000901 assert((!ListInitialization || (Exprs.size() == 1 && isa<InitListExpr>(Exprs[0])))
Sebastian Redld74dd492012-02-12 18:41:05 +0000902 && "List initialization must have initializer list as expression.");
903 SourceRange FullRange = SourceRange(TyBeginLoc,
904 ListInitialization ? Exprs[0]->getSourceRange().getEnd() : RParenLoc);
905
Douglas Gregordd04d332009-01-16 18:33:17 +0000906 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000907 // If the expression list is a single expression, the type conversion
908 // expression is equivalent (in definedness, and if defined in meaning) to the
909 // corresponding cast expression.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +0000910 if (Exprs.size() == 1 && !ListInitialization) {
John McCallb50451a2011-10-05 07:41:44 +0000911 Expr *Arg = Exprs[0];
John McCallb50451a2011-10-05 07:41:44 +0000912 return BuildCXXFunctionalCastExpr(TInfo, LParenLoc, Arg, RParenLoc);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000913 }
914
Eli Friedman576cbd02012-02-29 00:00:28 +0000915 QualType ElemTy = Ty;
916 if (Ty->isArrayType()) {
917 if (!ListInitialization)
918 return ExprError(Diag(TyBeginLoc,
919 diag::err_value_init_for_array_type) << FullRange);
920 ElemTy = Context.getBaseElementType(Ty);
921 }
922
923 if (!Ty->isVoidType() &&
924 RequireCompleteType(TyBeginLoc, ElemTy,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +0000925 diag::err_invalid_incomplete_type_use, FullRange))
Eli Friedman576cbd02012-02-29 00:00:28 +0000926 return ExprError();
927
928 if (RequireNonAbstractType(TyBeginLoc, Ty,
929 diag::err_allocation_of_abstract_type))
930 return ExprError();
931
Douglas Gregor8ec51732010-09-08 21:40:08 +0000932 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +0000933 InitializationKind Kind =
934 Exprs.size() ? ListInitialization
935 ? InitializationKind::CreateDirectList(TyBeginLoc)
936 : InitializationKind::CreateDirect(TyBeginLoc, LParenLoc, RParenLoc)
937 : InitializationKind::CreateValue(TyBeginLoc, LParenLoc, RParenLoc);
938 InitializationSequence InitSeq(*this, Entity, Kind, Exprs);
939 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Exprs);
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000940
Richard Smith90061902013-09-23 02:20:00 +0000941 if (Result.isInvalid() || !ListInitialization)
942 return Result;
943
944 Expr *Inner = Result.get();
945 if (CXXBindTemporaryExpr *BTE = dyn_cast_or_null<CXXBindTemporaryExpr>(Inner))
946 Inner = BTE->getSubExpr();
947 if (isa<InitListExpr>(Inner)) {
Sebastian Redl2b80af42012-02-13 19:55:43 +0000948 // If the list-initialization doesn't involve a constructor call, we'll get
949 // the initializer-list (with corrected type) back, but that's not what we
950 // want, since it will be treated as an initializer list in further
951 // processing. Explicitly insert a cast here.
Richard Smith90061902013-09-23 02:20:00 +0000952 QualType ResultType = Result.get()->getType();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000953 Result = CXXFunctionalCastExpr::Create(
Richard Smith90061902013-09-23 02:20:00 +0000954 Context, ResultType, Expr::getValueKindForType(TInfo->getType()), TInfo,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000955 CK_NoOp, Result.get(), /*Path=*/nullptr, LParenLoc, RParenLoc);
Sebastian Redl2b80af42012-02-13 19:55:43 +0000956 }
957
Douglas Gregor8ec51732010-09-08 21:40:08 +0000958 // FIXME: Improve AST representation?
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000959 return Result;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000960}
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +0000961
John McCall284c48f2011-01-27 09:37:56 +0000962/// doesUsualArrayDeleteWantSize - Answers whether the usual
963/// operator delete[] for the given type has a size_t parameter.
964static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc,
965 QualType allocType) {
966 const RecordType *record =
967 allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
968 if (!record) return false;
969
970 // Try to find an operator delete[] in class scope.
971
972 DeclarationName deleteName =
973 S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
974 LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
975 S.LookupQualifiedName(ops, record->getDecl());
976
977 // We're just doing this for information.
978 ops.suppressDiagnostics();
979
980 // Very likely: there's no operator delete[].
981 if (ops.empty()) return false;
982
983 // If it's ambiguous, it should be illegal to call operator delete[]
984 // on this thing, so it doesn't matter if we allocate extra space or not.
985 if (ops.isAmbiguous()) return false;
986
987 LookupResult::Filter filter = ops.makeFilter();
988 while (filter.hasNext()) {
989 NamedDecl *del = filter.next()->getUnderlyingDecl();
990
991 // C++0x [basic.stc.dynamic.deallocation]p2:
992 // A template instance is never a usual deallocation function,
993 // regardless of its signature.
994 if (isa<FunctionTemplateDecl>(del)) {
995 filter.erase();
996 continue;
997 }
998
999 // C++0x [basic.stc.dynamic.deallocation]p2:
1000 // If class T does not declare [an operator delete[] with one
1001 // parameter] but does declare a member deallocation function
1002 // named operator delete[] with exactly two parameters, the
1003 // second of which has type std::size_t, then this function
1004 // is a usual deallocation function.
1005 if (!cast<CXXMethodDecl>(del)->isUsualDeallocationFunction()) {
1006 filter.erase();
1007 continue;
1008 }
1009 }
1010 filter.done();
1011
1012 if (!ops.isSingleResult()) return false;
1013
1014 const FunctionDecl *del = cast<FunctionDecl>(ops.getFoundDecl());
1015 return (del->getNumParams() == 2);
1016}
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001017
Sebastian Redld74dd492012-02-12 18:41:05 +00001018/// \brief Parsed a C++ 'new' expression (C++ 5.3.4).
James Dennettf14a6e52012-06-15 22:23:43 +00001019///
Sebastian Redld74dd492012-02-12 18:41:05 +00001020/// E.g.:
Sebastian Redlbd150f42008-11-21 19:14:01 +00001021/// @code new (memory) int[size][4] @endcode
1022/// or
1023/// @code ::new Foo(23, "hello") @endcode
Sebastian Redld74dd492012-02-12 18:41:05 +00001024///
1025/// \param StartLoc The first location of the expression.
1026/// \param UseGlobal True if 'new' was prefixed with '::'.
1027/// \param PlacementLParen Opening paren of the placement arguments.
1028/// \param PlacementArgs Placement new arguments.
1029/// \param PlacementRParen Closing paren of the placement arguments.
1030/// \param TypeIdParens If the type is in parens, the source range.
1031/// \param D The type to be allocated, as well as array dimensions.
James Dennettf14a6e52012-06-15 22:23:43 +00001032/// \param Initializer The initializing expression or initializer-list, or null
1033/// if there is none.
John McCalldadc5752010-08-24 06:29:42 +00001034ExprResult
Sebastian Redlbd150f42008-11-21 19:14:01 +00001035Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001036 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001037 SourceLocation PlacementRParen, SourceRange TypeIdParens,
Sebastian Redl6047f072012-02-16 12:22:20 +00001038 Declarator &D, Expr *Initializer) {
Richard Smith74aeef52013-04-26 16:15:35 +00001039 bool TypeContainsAuto = D.getDeclSpec().containsPlaceholderType();
Richard Smith30482bc2011-02-20 03:19:35 +00001040
Craig Topperc3ec1492014-05-26 06:22:03 +00001041 Expr *ArraySize = nullptr;
Sebastian Redl351bb782008-12-02 14:43:59 +00001042 // If the specified type is an array, unwrap it and save the expression.
1043 if (D.getNumTypeObjects() > 0 &&
1044 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
James Dennettf14a6e52012-06-15 22:23:43 +00001045 DeclaratorChunk &Chunk = D.getTypeObject(0);
Richard Smith30482bc2011-02-20 03:19:35 +00001046 if (TypeContainsAuto)
1047 return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
1048 << D.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00001049 if (Chunk.Arr.hasStatic)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001050 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
1051 << D.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00001052 if (!Chunk.Arr.NumElts)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001053 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
1054 << D.getSourceRange());
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001055
Sebastian Redl351bb782008-12-02 14:43:59 +00001056 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001057 D.DropFirstTypeObject();
Sebastian Redl351bb782008-12-02 14:43:59 +00001058 }
1059
Douglas Gregor73341c42009-09-11 00:18:58 +00001060 // Every dimension shall be of constant size.
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001061 if (ArraySize) {
1062 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor73341c42009-09-11 00:18:58 +00001063 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
1064 break;
1065
1066 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
1067 if (Expr *NumElts = (Expr *)Array.NumElts) {
Richard Smithf4c51d92012-02-04 09:53:13 +00001068 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent()) {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001069 if (getLangOpts().CPlusPlus1y) {
1070 // C++1y [expr.new]p6: Every constant-expression in a noptr-new-declarator
1071 // shall be a converted constant expression (5.19) of type std::size_t
1072 // and shall evaluate to a strictly positive value.
1073 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
1074 assert(IntWidth && "Builtin type of size 0?");
1075 llvm::APSInt Value(IntWidth);
1076 Array.NumElts
1077 = CheckConvertedConstantExpression(NumElts, Context.getSizeType(), Value,
1078 CCEK_NewExpr)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001079 .get();
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001080 } else {
1081 Array.NumElts
Craig Topperc3ec1492014-05-26 06:22:03 +00001082 = VerifyIntegerConstantExpression(NumElts, nullptr,
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001083 diag::err_new_array_nonconst)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001084 .get();
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001085 }
Richard Smithf4c51d92012-02-04 09:53:13 +00001086 if (!Array.NumElts)
1087 return ExprError();
Douglas Gregor73341c42009-09-11 00:18:58 +00001088 }
1089 }
1090 }
1091 }
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001092
Craig Topperc3ec1492014-05-26 06:22:03 +00001093 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/nullptr);
John McCall8cb7bdf2010-06-04 23:28:52 +00001094 QualType AllocType = TInfo->getType();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001095 if (D.isInvalidType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001096 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001097
Sebastian Redl6047f072012-02-16 12:22:20 +00001098 SourceRange DirectInitRange;
1099 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer))
1100 DirectInitRange = List->getSourceRange();
1101
David Blaikie7b97aef2012-11-07 00:12:38 +00001102 return BuildCXXNew(SourceRange(StartLoc, D.getLocEnd()), UseGlobal,
Douglas Gregord0fefba2009-05-21 00:00:09 +00001103 PlacementLParen,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001104 PlacementArgs,
Douglas Gregord0fefba2009-05-21 00:00:09 +00001105 PlacementRParen,
Douglas Gregorf2753b32010-07-13 15:54:32 +00001106 TypeIdParens,
Mike Stump11289f42009-09-09 15:08:12 +00001107 AllocType,
Douglas Gregor0744ef62010-09-07 21:49:58 +00001108 TInfo,
John McCallb268a282010-08-23 23:25:46 +00001109 ArraySize,
Sebastian Redl6047f072012-02-16 12:22:20 +00001110 DirectInitRange,
1111 Initializer,
Richard Smith30482bc2011-02-20 03:19:35 +00001112 TypeContainsAuto);
Douglas Gregord0fefba2009-05-21 00:00:09 +00001113}
1114
Sebastian Redlb8fc4772012-02-16 12:59:47 +00001115static bool isLegalArrayNewInitializer(CXXNewExpr::InitializationStyle Style,
1116 Expr *Init) {
Sebastian Redl6047f072012-02-16 12:22:20 +00001117 if (!Init)
1118 return true;
Sebastian Redleb54f082012-02-17 08:42:32 +00001119 if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init))
1120 return PLE->getNumExprs() == 0;
Sebastian Redl6047f072012-02-16 12:22:20 +00001121 if (isa<ImplicitValueInitExpr>(Init))
1122 return true;
1123 else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init))
1124 return !CCE->isListInitialization() &&
1125 CCE->getConstructor()->isDefaultConstructor();
Sebastian Redlb8fc4772012-02-16 12:59:47 +00001126 else if (Style == CXXNewExpr::ListInit) {
1127 assert(isa<InitListExpr>(Init) &&
1128 "Shouldn't create list CXXConstructExprs for arrays.");
1129 return true;
1130 }
Sebastian Redl6047f072012-02-16 12:22:20 +00001131 return false;
1132}
1133
John McCalldadc5752010-08-24 06:29:42 +00001134ExprResult
David Blaikie7b97aef2012-11-07 00:12:38 +00001135Sema::BuildCXXNew(SourceRange Range, bool UseGlobal,
Douglas Gregord0fefba2009-05-21 00:00:09 +00001136 SourceLocation PlacementLParen,
1137 MultiExprArg PlacementArgs,
1138 SourceLocation PlacementRParen,
Douglas Gregorf2753b32010-07-13 15:54:32 +00001139 SourceRange TypeIdParens,
Douglas Gregord0fefba2009-05-21 00:00:09 +00001140 QualType AllocType,
Douglas Gregor0744ef62010-09-07 21:49:58 +00001141 TypeSourceInfo *AllocTypeInfo,
John McCallb268a282010-08-23 23:25:46 +00001142 Expr *ArraySize,
Sebastian Redl6047f072012-02-16 12:22:20 +00001143 SourceRange DirectInitRange,
1144 Expr *Initializer,
Richard Smith30482bc2011-02-20 03:19:35 +00001145 bool TypeMayContainAuto) {
Douglas Gregor0744ef62010-09-07 21:49:58 +00001146 SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
David Blaikie7b97aef2012-11-07 00:12:38 +00001147 SourceLocation StartLoc = Range.getBegin();
Sebastian Redl351bb782008-12-02 14:43:59 +00001148
Sebastian Redl6047f072012-02-16 12:22:20 +00001149 CXXNewExpr::InitializationStyle initStyle;
1150 if (DirectInitRange.isValid()) {
1151 assert(Initializer && "Have parens but no initializer.");
1152 initStyle = CXXNewExpr::CallInit;
1153 } else if (Initializer && isa<InitListExpr>(Initializer))
1154 initStyle = CXXNewExpr::ListInit;
1155 else {
1156 assert((!Initializer || isa<ImplicitValueInitExpr>(Initializer) ||
1157 isa<CXXConstructExpr>(Initializer)) &&
1158 "Initializer expression that cannot have been implicitly created.");
1159 initStyle = CXXNewExpr::NoInit;
1160 }
1161
1162 Expr **Inits = &Initializer;
1163 unsigned NumInits = Initializer ? 1 : 0;
Richard Smithdd2ca572012-11-26 08:32:48 +00001164 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer)) {
1165 assert(initStyle == CXXNewExpr::CallInit && "paren init for non-call init");
1166 Inits = List->getExprs();
1167 NumInits = List->getNumExprs();
Sebastian Redl6047f072012-02-16 12:22:20 +00001168 }
1169
Richard Smithdd2ca572012-11-26 08:32:48 +00001170 // Determine whether we've already built the initializer.
1171 bool HaveCompleteInit = false;
1172 if (Initializer && isa<CXXConstructExpr>(Initializer) &&
1173 !isa<CXXTemporaryObjectExpr>(Initializer))
1174 HaveCompleteInit = true;
1175 else if (Initializer && isa<ImplicitValueInitExpr>(Initializer))
1176 HaveCompleteInit = true;
1177
Richard Smith66204ec2014-03-12 17:42:45 +00001178 // C++11 [dcl.spec.auto]p6. Deduce the type which 'auto' stands in for.
Richard Smith27d807c2013-04-30 13:56:41 +00001179 if (TypeMayContainAuto && AllocType->isUndeducedType()) {
Sebastian Redl6047f072012-02-16 12:22:20 +00001180 if (initStyle == CXXNewExpr::NoInit || NumInits == 0)
Richard Smith30482bc2011-02-20 03:19:35 +00001181 return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
1182 << AllocType << TypeRange);
Richard Smith66204ec2014-03-12 17:42:45 +00001183 if (initStyle == CXXNewExpr::ListInit ||
1184 (NumInits == 1 && isa<InitListExpr>(Inits[0])))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001185 return ExprError(Diag(Inits[0]->getLocStart(),
Richard Smith66204ec2014-03-12 17:42:45 +00001186 diag::err_auto_new_list_init)
Sebastian Redl6047f072012-02-16 12:22:20 +00001187 << AllocType << TypeRange);
1188 if (NumInits > 1) {
1189 Expr *FirstBad = Inits[1];
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001190 return ExprError(Diag(FirstBad->getLocStart(),
Richard Smith30482bc2011-02-20 03:19:35 +00001191 diag::err_auto_new_ctor_multiple_expressions)
1192 << AllocType << TypeRange);
1193 }
Sebastian Redl6047f072012-02-16 12:22:20 +00001194 Expr *Deduce = Inits[0];
Richard Smith061f1e22013-04-30 21:23:01 +00001195 QualType DeducedType;
Richard Smith74801c82012-07-08 04:13:07 +00001196 if (DeduceAutoType(AllocTypeInfo, Deduce, DeducedType) == DAR_Failed)
Richard Smith30482bc2011-02-20 03:19:35 +00001197 return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
Sebastian Redld74dd492012-02-12 18:41:05 +00001198 << AllocType << Deduce->getType()
1199 << TypeRange << Deduce->getSourceRange());
Richard Smith061f1e22013-04-30 21:23:01 +00001200 if (DeducedType.isNull())
Richard Smith9647d3c2011-03-17 16:11:59 +00001201 return ExprError();
Richard Smith061f1e22013-04-30 21:23:01 +00001202 AllocType = DeducedType;
Richard Smith30482bc2011-02-20 03:19:35 +00001203 }
Sebastian Redld74dd492012-02-12 18:41:05 +00001204
Douglas Gregorcda95f42010-05-16 16:01:03 +00001205 // Per C++0x [expr.new]p5, the type being constructed may be a
1206 // typedef of an array type.
John McCallb268a282010-08-23 23:25:46 +00001207 if (!ArraySize) {
Douglas Gregorcda95f42010-05-16 16:01:03 +00001208 if (const ConstantArrayType *Array
1209 = Context.getAsConstantArrayType(AllocType)) {
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00001210 ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
1211 Context.getSizeType(),
1212 TypeRange.getEnd());
Douglas Gregorcda95f42010-05-16 16:01:03 +00001213 AllocType = Array->getElementType();
1214 }
1215 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00001216
Douglas Gregor3999e152010-10-06 16:00:31 +00001217 if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
1218 return ExprError();
1219
Craig Topperc3ec1492014-05-26 06:22:03 +00001220 if (initStyle == CXXNewExpr::ListInit &&
1221 isStdInitializerList(AllocType, nullptr)) {
Sebastian Redld74dd492012-02-12 18:41:05 +00001222 Diag(AllocTypeInfo->getTypeLoc().getBeginLoc(),
1223 diag::warn_dangling_std_initializer_list)
Sebastian Redl73cfbeb2012-02-19 16:31:05 +00001224 << /*at end of FE*/0 << Inits[0]->getSourceRange();
Sebastian Redld74dd492012-02-12 18:41:05 +00001225 }
1226
John McCall31168b02011-06-15 23:02:42 +00001227 // In ARC, infer 'retaining' for the allocated
David Blaikiebbafb8a2012-03-11 07:00:24 +00001228 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001229 AllocType.getObjCLifetime() == Qualifiers::OCL_None &&
1230 AllocType->isObjCLifetimeType()) {
1231 AllocType = Context.getLifetimeQualifiedType(AllocType,
1232 AllocType->getObjCARCImplicitLifetime());
1233 }
Sebastian Redl351bb782008-12-02 14:43:59 +00001234
John McCall31168b02011-06-15 23:02:42 +00001235 QualType ResultType = Context.getPointerType(AllocType);
1236
John McCall5e77d762013-04-16 07:28:30 +00001237 if (ArraySize && ArraySize->getType()->isNonOverloadPlaceholderType()) {
1238 ExprResult result = CheckPlaceholderExpr(ArraySize);
1239 if (result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001240 ArraySize = result.get();
John McCall5e77d762013-04-16 07:28:30 +00001241 }
Richard Smith8dd34252012-02-04 07:07:42 +00001242 // C++98 5.3.4p6: "The expression in a direct-new-declarator shall have
1243 // integral or enumeration type with a non-negative value."
1244 // C++11 [expr.new]p6: The expression [...] shall be of integral or unscoped
1245 // enumeration type, or a class type for which a single non-explicit
1246 // conversion function to integral or unscoped enumeration type exists.
Richard Smithccc11812013-05-21 19:05:48 +00001247 // C++1y [expr.new]p6: The expression [...] is implicitly converted to
Larisse Voufobf4aa572013-06-18 03:08:53 +00001248 // std::size_t.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001249 if (ArraySize && !ArraySize->isTypeDependent()) {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001250 ExprResult ConvertedSize;
1251 if (getLangOpts().CPlusPlus1y) {
Alp Toker965f8822013-11-27 05:22:15 +00001252 assert(Context.getTargetInfo().getIntWidth() && "Builtin type of size 0?");
1253
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001254 ConvertedSize = PerformImplicitConversion(ArraySize, Context.getSizeType(),
1255 AA_Converting);
Richard Smithccc11812013-05-21 19:05:48 +00001256
Larisse Voufobf4aa572013-06-18 03:08:53 +00001257 if (!ConvertedSize.isInvalid() &&
1258 ArraySize->getType()->getAs<RecordType>())
Larisse Voufo9f380c52013-06-18 01:27:47 +00001259 // Diagnose the compatibility of this conversion.
1260 Diag(StartLoc, diag::warn_cxx98_compat_array_size_conversion)
1261 << ArraySize->getType() << 0 << "'size_t'";
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001262 } else {
1263 class SizeConvertDiagnoser : public ICEConvertDiagnoser {
1264 protected:
1265 Expr *ArraySize;
1266
1267 public:
1268 SizeConvertDiagnoser(Expr *ArraySize)
1269 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, false, false),
1270 ArraySize(ArraySize) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00001271
1272 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
1273 QualType T) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001274 return S.Diag(Loc, diag::err_array_size_not_integral)
1275 << S.getLangOpts().CPlusPlus11 << T;
1276 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001277
1278 SemaDiagnosticBuilder diagnoseIncomplete(
1279 Sema &S, SourceLocation Loc, QualType T) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001280 return S.Diag(Loc, diag::err_array_size_incomplete_type)
1281 << T << ArraySize->getSourceRange();
1282 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001283
1284 SemaDiagnosticBuilder diagnoseExplicitConv(
1285 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001286 return S.Diag(Loc, diag::err_array_size_explicit_conversion) << T << ConvTy;
1287 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001288
1289 SemaDiagnosticBuilder noteExplicitConv(
1290 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001291 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
1292 << ConvTy->isEnumeralType() << ConvTy;
1293 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001294
1295 SemaDiagnosticBuilder diagnoseAmbiguous(
1296 Sema &S, SourceLocation Loc, QualType T) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001297 return S.Diag(Loc, diag::err_array_size_ambiguous_conversion) << T;
1298 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001299
1300 SemaDiagnosticBuilder noteAmbiguous(
1301 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001302 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
1303 << ConvTy->isEnumeralType() << ConvTy;
1304 }
Richard Smithccc11812013-05-21 19:05:48 +00001305
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001306 virtual SemaDiagnosticBuilder diagnoseConversion(
Craig Toppere14c0f82014-03-12 04:55:44 +00001307 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001308 return S.Diag(Loc,
1309 S.getLangOpts().CPlusPlus11
1310 ? diag::warn_cxx98_compat_array_size_conversion
1311 : diag::ext_array_size_conversion)
1312 << T << ConvTy->isEnumeralType() << ConvTy;
1313 }
1314 } SizeDiagnoser(ArraySize);
Richard Smithccc11812013-05-21 19:05:48 +00001315
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001316 ConvertedSize = PerformContextualImplicitConversion(StartLoc, ArraySize,
1317 SizeDiagnoser);
1318 }
Douglas Gregor4799d032010-06-30 00:20:43 +00001319 if (ConvertedSize.isInvalid())
1320 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001321
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001322 ArraySize = ConvertedSize.get();
John McCall9b80c212012-01-11 00:14:46 +00001323 QualType SizeType = ArraySize->getType();
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001324
Douglas Gregor0bf31402010-10-08 23:50:27 +00001325 if (!SizeType->isIntegralOrUnscopedEnumerationType())
Douglas Gregor4799d032010-06-30 00:20:43 +00001326 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001327
Richard Smithbcc9bcb2012-02-04 05:35:53 +00001328 // C++98 [expr.new]p7:
1329 // The expression in a direct-new-declarator shall have integral type
1330 // with a non-negative value.
1331 //
1332 // Let's see if this is a constant < 0. If so, we reject it out of
1333 // hand. Otherwise, if it's not a constant, we must have an unparenthesized
1334 // array type.
1335 //
1336 // Note: such a construct has well-defined semantics in C++11: it throws
1337 // std::bad_array_new_length.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001338 if (!ArraySize->isValueDependent()) {
1339 llvm::APSInt Value;
Richard Smithf4c51d92012-02-04 09:53:13 +00001340 // We've already performed any required implicit conversion to integer or
1341 // unscoped enumeration type.
Richard Smithbcc9bcb2012-02-04 05:35:53 +00001342 if (ArraySize->isIntegerConstantExpr(Value, Context)) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001343 if (Value < llvm::APSInt(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001344 llvm::APInt::getNullValue(Value.getBitWidth()),
Richard Smithbcc9bcb2012-02-04 05:35:53 +00001345 Value.isUnsigned())) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001346 if (getLangOpts().CPlusPlus11)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001347 Diag(ArraySize->getLocStart(),
Richard Smithbcc9bcb2012-02-04 05:35:53 +00001348 diag::warn_typecheck_negative_array_new_size)
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00001349 << ArraySize->getSourceRange();
Richard Smithbcc9bcb2012-02-04 05:35:53 +00001350 else
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001351 return ExprError(Diag(ArraySize->getLocStart(),
Richard Smithbcc9bcb2012-02-04 05:35:53 +00001352 diag::err_typecheck_negative_array_size)
1353 << ArraySize->getSourceRange());
1354 } else if (!AllocType->isDependentType()) {
1355 unsigned ActiveSizeBits =
1356 ConstantArrayType::getNumAddressingBits(Context, AllocType, Value);
1357 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001358 if (getLangOpts().CPlusPlus11)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001359 Diag(ArraySize->getLocStart(),
Richard Smithbcc9bcb2012-02-04 05:35:53 +00001360 diag::warn_array_new_too_large)
1361 << Value.toString(10)
1362 << ArraySize->getSourceRange();
1363 else
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001364 return ExprError(Diag(ArraySize->getLocStart(),
Richard Smithbcc9bcb2012-02-04 05:35:53 +00001365 diag::err_array_too_large)
1366 << Value.toString(10)
1367 << ArraySize->getSourceRange());
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00001368 }
1369 }
Douglas Gregorf2753b32010-07-13 15:54:32 +00001370 } else if (TypeIdParens.isValid()) {
1371 // Can't have dynamic array size when the type-id is in parentheses.
1372 Diag(ArraySize->getLocStart(), diag::ext_new_paren_array_nonconst)
1373 << ArraySize->getSourceRange()
1374 << FixItHint::CreateRemoval(TypeIdParens.getBegin())
1375 << FixItHint::CreateRemoval(TypeIdParens.getEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001376
Douglas Gregorf2753b32010-07-13 15:54:32 +00001377 TypeIdParens = SourceRange();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001378 }
Sebastian Redl351bb782008-12-02 14:43:59 +00001379 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001380
John McCall036f2f62011-05-15 07:14:44 +00001381 // Note that we do *not* convert the argument in any way. It can
1382 // be signed, larger than size_t, whatever.
Sebastian Redl351bb782008-12-02 14:43:59 +00001383 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00001384
Craig Topperc3ec1492014-05-26 06:22:03 +00001385 FunctionDecl *OperatorNew = nullptr;
1386 FunctionDecl *OperatorDelete = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001387
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001388 if (!AllocType->isDependentType() &&
Dmitri Gribenkobe022102013-05-10 13:22:23 +00001389 !Expr::hasAnyTypeDependentArguments(PlacementArgs) &&
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001390 FindAllocationFunctions(StartLoc,
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00001391 SourceRange(PlacementLParen, PlacementRParen),
Dmitri Gribenkobe022102013-05-10 13:22:23 +00001392 UseGlobal, AllocType, ArraySize, PlacementArgs,
1393 OperatorNew, OperatorDelete))
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001394 return ExprError();
John McCall284c48f2011-01-27 09:37:56 +00001395
1396 // If this is an array allocation, compute whether the usual array
1397 // deallocation function for the type has a size_t parameter.
1398 bool UsualArrayDeleteWantsSize = false;
1399 if (ArraySize && !AllocType->isDependentType())
1400 UsualArrayDeleteWantsSize
1401 = doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
1402
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001403 SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +00001404 if (OperatorNew) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001405 const FunctionProtoType *Proto =
Richard Smithd6f9e732014-05-13 19:56:21 +00001406 OperatorNew->getType()->getAs<FunctionProtoType>();
1407 VariadicCallType CallType = Proto->isVariadic() ? VariadicFunction
1408 : VariadicDoesNotApply;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001409
Richard Smithd6f9e732014-05-13 19:56:21 +00001410 // We've already converted the placement args, just fill in any default
1411 // arguments. Skip the first parameter because we don't have a corresponding
1412 // argument.
Dmitri Gribenkobe022102013-05-10 13:22:23 +00001413 if (GatherArgumentsForCall(PlacementLParen, OperatorNew, Proto, 1,
1414 PlacementArgs, AllPlaceArgs, CallType))
Fariborz Jahanian835026e2009-11-24 18:29:37 +00001415 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001416
Dmitri Gribenkobe022102013-05-10 13:22:23 +00001417 if (!AllPlaceArgs.empty())
1418 PlacementArgs = AllPlaceArgs;
Eli Friedmanff4b4072012-02-18 04:48:30 +00001419
Richard Smithd6f9e732014-05-13 19:56:21 +00001420 // FIXME: This is wrong: PlacementArgs misses out the first (size) argument.
Dmitri Gribenkobe022102013-05-10 13:22:23 +00001421 DiagnoseSentinelCalls(OperatorNew, PlacementLParen, PlacementArgs);
Eli Friedmanff4b4072012-02-18 04:48:30 +00001422
1423 // FIXME: Missing call to CheckFunctionCall or equivalent
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +00001424 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001425
Nick Lewycky411fc652012-01-24 21:15:41 +00001426 // Warn if the type is over-aligned and is being allocated by global operator
1427 // new.
Dmitri Gribenkobe022102013-05-10 13:22:23 +00001428 if (PlacementArgs.empty() && OperatorNew &&
Nick Lewycky411fc652012-01-24 21:15:41 +00001429 (OperatorNew->isImplicit() ||
1430 getSourceManager().isInSystemHeader(OperatorNew->getLocStart()))) {
1431 if (unsigned Align = Context.getPreferredTypeAlign(AllocType.getTypePtr())){
1432 unsigned SuitableAlign = Context.getTargetInfo().getSuitableAlign();
1433 if (Align > SuitableAlign)
1434 Diag(StartLoc, diag::warn_overaligned_type)
1435 << AllocType
1436 << unsigned(Align / Context.getCharWidth())
1437 << unsigned(SuitableAlign / Context.getCharWidth());
1438 }
1439 }
1440
Sebastian Redlb8fc4772012-02-16 12:59:47 +00001441 QualType InitType = AllocType;
Sebastian Redl6047f072012-02-16 12:22:20 +00001442 // Array 'new' can't have any initializers except empty parentheses.
Sebastian Redlb8fc4772012-02-16 12:59:47 +00001443 // Initializer lists are also allowed, in C++11. Rely on the parser for the
1444 // dialect distinction.
1445 if (ResultType->isArrayType() || ArraySize) {
1446 if (!isLegalArrayNewInitializer(initStyle, Initializer)) {
1447 SourceRange InitRange(Inits[0]->getLocStart(),
1448 Inits[NumInits - 1]->getLocEnd());
1449 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
1450 return ExprError();
1451 }
1452 if (InitListExpr *ILE = dyn_cast_or_null<InitListExpr>(Initializer)) {
1453 // We do the initialization typechecking against the array type
1454 // corresponding to the number of initializers + 1 (to also check
1455 // default-initialization).
1456 unsigned NumElements = ILE->getNumInits() + 1;
1457 InitType = Context.getConstantArrayType(AllocType,
1458 llvm::APInt(Context.getTypeSize(Context.getSizeType()), NumElements),
1459 ArrayType::Normal, 0);
1460 }
Anders Carlssonc6bb0e12010-05-03 15:45:23 +00001461 }
1462
Richard Smithdd2ca572012-11-26 08:32:48 +00001463 // If we can perform the initialization, and we've not already done so,
1464 // do it now.
Douglas Gregor85dabae2009-12-16 01:38:02 +00001465 if (!AllocType->isDependentType() &&
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00001466 !Expr::hasAnyTypeDependentArguments(
Richard Smithdd2ca572012-11-26 08:32:48 +00001467 llvm::makeArrayRef(Inits, NumInits)) &&
1468 !HaveCompleteInit) {
Sebastian Redld74dd492012-02-12 18:41:05 +00001469 // C++11 [expr.new]p15:
Douglas Gregor85dabae2009-12-16 01:38:02 +00001470 // A new-expression that creates an object of type T initializes that
1471 // object as follows:
1472 InitializationKind Kind
1473 // - If the new-initializer is omitted, the object is default-
1474 // initialized (8.5); if no initialization is performed,
1475 // the object has indeterminate value
Sebastian Redl6047f072012-02-16 12:22:20 +00001476 = initStyle == CXXNewExpr::NoInit
1477 ? InitializationKind::CreateDefault(TypeRange.getBegin())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001478 // - Otherwise, the new-initializer is interpreted according to the
Douglas Gregor85dabae2009-12-16 01:38:02 +00001479 // initialization rules of 8.5 for direct-initialization.
Sebastian Redl6047f072012-02-16 12:22:20 +00001480 : initStyle == CXXNewExpr::ListInit
1481 ? InitializationKind::CreateDirectList(TypeRange.getBegin())
1482 : InitializationKind::CreateDirect(TypeRange.getBegin(),
1483 DirectInitRange.getBegin(),
1484 DirectInitRange.getEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001485
Douglas Gregor85dabae2009-12-16 01:38:02 +00001486 InitializedEntity Entity
Sebastian Redlb8fc4772012-02-16 12:59:47 +00001487 = InitializedEntity::InitializeNew(StartLoc, InitType);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001488 InitializationSequence InitSeq(*this, Entity, Kind, MultiExprArg(Inits, NumInits));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001489 ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
Sebastian Redl6047f072012-02-16 12:22:20 +00001490 MultiExprArg(Inits, NumInits));
Douglas Gregor85dabae2009-12-16 01:38:02 +00001491 if (FullInit.isInvalid())
1492 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001493
Sebastian Redl6047f072012-02-16 12:22:20 +00001494 // FullInit is our initializer; strip off CXXBindTemporaryExprs, because
1495 // we don't want the initialized object to be destructed.
1496 if (CXXBindTemporaryExpr *Binder =
1497 dyn_cast_or_null<CXXBindTemporaryExpr>(FullInit.get()))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001498 FullInit = Binder->getSubExpr();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001499
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001500 Initializer = FullInit.get();
Sebastian Redlbd150f42008-11-21 19:14:01 +00001501 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001502
Douglas Gregor6642ca22010-02-26 05:06:18 +00001503 // Mark the new and delete operators as referenced.
Nick Lewyckya096b142013-02-12 08:08:54 +00001504 if (OperatorNew) {
Richard Smith22262ab2013-05-04 06:44:46 +00001505 if (DiagnoseUseOfDecl(OperatorNew, StartLoc))
1506 return ExprError();
Eli Friedmanfa0df832012-02-02 03:46:19 +00001507 MarkFunctionReferenced(StartLoc, OperatorNew);
Nick Lewyckya096b142013-02-12 08:08:54 +00001508 }
1509 if (OperatorDelete) {
Richard Smith22262ab2013-05-04 06:44:46 +00001510 if (DiagnoseUseOfDecl(OperatorDelete, StartLoc))
1511 return ExprError();
Eli Friedmanfa0df832012-02-02 03:46:19 +00001512 MarkFunctionReferenced(StartLoc, OperatorDelete);
Nick Lewyckya096b142013-02-12 08:08:54 +00001513 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00001514
John McCall928a2572011-07-13 20:12:57 +00001515 // C++0x [expr.new]p17:
1516 // If the new expression creates an array of objects of class type,
1517 // access and ambiguity control are done for the destructor.
David Blaikie631a4862012-03-10 23:40:02 +00001518 QualType BaseAllocType = Context.getBaseElementType(AllocType);
1519 if (ArraySize && !BaseAllocType->isDependentType()) {
1520 if (const RecordType *BaseRecordType = BaseAllocType->getAs<RecordType>()) {
1521 if (CXXDestructorDecl *dtor = LookupDestructor(
1522 cast<CXXRecordDecl>(BaseRecordType->getDecl()))) {
1523 MarkFunctionReferenced(StartLoc, dtor);
1524 CheckDestructorAccess(StartLoc, dtor,
1525 PDiag(diag::err_access_dtor)
1526 << BaseAllocType);
Richard Smith22262ab2013-05-04 06:44:46 +00001527 if (DiagnoseUseOfDecl(dtor, StartLoc))
1528 return ExprError();
David Blaikie631a4862012-03-10 23:40:02 +00001529 }
John McCall928a2572011-07-13 20:12:57 +00001530 }
1531 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001532
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001533 return new (Context)
1534 CXXNewExpr(Context, UseGlobal, OperatorNew, OperatorDelete,
1535 UsualArrayDeleteWantsSize, PlacementArgs, TypeIdParens,
1536 ArraySize, initStyle, Initializer, ResultType, AllocTypeInfo,
1537 Range, DirectInitRange);
Sebastian Redlbd150f42008-11-21 19:14:01 +00001538}
1539
Sebastian Redl6047f072012-02-16 12:22:20 +00001540/// \brief Checks that a type is suitable as the allocated type
Sebastian Redlbd150f42008-11-21 19:14:01 +00001541/// in a new-expression.
Douglas Gregord0fefba2009-05-21 00:00:09 +00001542bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00001543 SourceRange R) {
Sebastian Redlbd150f42008-11-21 19:14:01 +00001544 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
1545 // abstract class type or array thereof.
Douglas Gregorac1fb652009-03-24 19:52:54 +00001546 if (AllocType->isFunctionType())
Douglas Gregord0fefba2009-05-21 00:00:09 +00001547 return Diag(Loc, diag::err_bad_new_type)
1548 << AllocType << 0 << R;
Douglas Gregorac1fb652009-03-24 19:52:54 +00001549 else if (AllocType->isReferenceType())
Douglas Gregord0fefba2009-05-21 00:00:09 +00001550 return Diag(Loc, diag::err_bad_new_type)
1551 << AllocType << 1 << R;
Douglas Gregorac1fb652009-03-24 19:52:54 +00001552 else if (!AllocType->isDependentType() &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001553 RequireCompleteType(Loc, AllocType, diag::err_new_incomplete_type,R))
Sebastian Redlbd150f42008-11-21 19:14:01 +00001554 return true;
Douglas Gregord0fefba2009-05-21 00:00:09 +00001555 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregorac1fb652009-03-24 19:52:54 +00001556 diag::err_allocation_of_abstract_type))
1557 return true;
Douglas Gregor3999e152010-10-06 16:00:31 +00001558 else if (AllocType->isVariablyModifiedType())
1559 return Diag(Loc, diag::err_variably_modified_new_type)
1560 << AllocType;
Douglas Gregor39d1a092011-04-15 19:46:20 +00001561 else if (unsigned AddressSpace = AllocType.getAddressSpace())
1562 return Diag(Loc, diag::err_address_space_qualified_new)
1563 << AllocType.getUnqualifiedType() << AddressSpace;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001564 else if (getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +00001565 if (const ArrayType *AT = Context.getAsArrayType(AllocType)) {
1566 QualType BaseAllocType = Context.getBaseElementType(AT);
1567 if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None &&
1568 BaseAllocType->isObjCLifetimeType())
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00001569 return Diag(Loc, diag::err_arc_new_array_without_ownership)
John McCall31168b02011-06-15 23:02:42 +00001570 << BaseAllocType;
1571 }
1572 }
Douglas Gregor39d1a092011-04-15 19:46:20 +00001573
Sebastian Redlbd150f42008-11-21 19:14:01 +00001574 return false;
1575}
1576
Douglas Gregor6642ca22010-02-26 05:06:18 +00001577/// \brief Determine whether the given function is a non-placement
1578/// deallocation function.
Richard Smith1cdec012013-09-29 04:40:38 +00001579static bool isNonPlacementDeallocationFunction(Sema &S, FunctionDecl *FD) {
Douglas Gregor6642ca22010-02-26 05:06:18 +00001580 if (FD->isInvalidDecl())
1581 return false;
1582
1583 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
1584 return Method->isUsualDeallocationFunction();
1585
Richard Smith1cdec012013-09-29 04:40:38 +00001586 if (FD->getOverloadedOperator() != OO_Delete &&
1587 FD->getOverloadedOperator() != OO_Array_Delete)
1588 return false;
1589
1590 if (FD->getNumParams() == 1)
1591 return true;
1592
1593 return S.getLangOpts().SizedDeallocation && FD->getNumParams() == 2 &&
1594 S.Context.hasSameUnqualifiedType(FD->getParamDecl(1)->getType(),
1595 S.Context.getSizeType());
Douglas Gregor6642ca22010-02-26 05:06:18 +00001596}
1597
Sebastian Redlfaf68082008-12-03 20:26:15 +00001598/// FindAllocationFunctions - Finds the overloads of operator new and delete
1599/// that are appropriate for the allocation.
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00001600bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
1601 bool UseGlobal, QualType AllocType,
Dmitri Gribenkobe022102013-05-10 13:22:23 +00001602 bool IsArray, MultiExprArg PlaceArgs,
Sebastian Redlfaf68082008-12-03 20:26:15 +00001603 FunctionDecl *&OperatorNew,
Mike Stump11289f42009-09-09 15:08:12 +00001604 FunctionDecl *&OperatorDelete) {
Sebastian Redlfaf68082008-12-03 20:26:15 +00001605 // --- Choosing an allocation function ---
1606 // C++ 5.3.4p8 - 14 & 18
1607 // 1) If UseGlobal is true, only look in the global scope. Else, also look
1608 // in the scope of the allocated class.
1609 // 2) If an array size is given, look for operator new[], else look for
1610 // operator new.
1611 // 3) The first argument is always size_t. Append the arguments from the
1612 // placement form.
Sebastian Redlfaf68082008-12-03 20:26:15 +00001613
Dmitri Gribenkobe022102013-05-10 13:22:23 +00001614 SmallVector<Expr*, 8> AllocArgs(1 + PlaceArgs.size());
Sebastian Redlfaf68082008-12-03 20:26:15 +00001615 // We don't care about the actual value of this argument.
1616 // FIXME: Should the Sema create the expression and embed it in the syntax
1617 // tree? Or should the consumer just recalculate the value?
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00001618 IntegerLiteral Size(Context, llvm::APInt::getNullValue(
Douglas Gregore8bbc122011-09-02 00:18:52 +00001619 Context.getTargetInfo().getPointerWidth(0)),
Anders Carlssona471db02009-08-16 20:29:29 +00001620 Context.getSizeType(),
1621 SourceLocation());
1622 AllocArgs[0] = &Size;
Dmitri Gribenkobe022102013-05-10 13:22:23 +00001623 std::copy(PlaceArgs.begin(), PlaceArgs.end(), AllocArgs.begin() + 1);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001624
Douglas Gregor6642ca22010-02-26 05:06:18 +00001625 // C++ [expr.new]p8:
1626 // If the allocated type is a non-array type, the allocation
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001627 // function's name is operator new and the deallocation function's
Douglas Gregor6642ca22010-02-26 05:06:18 +00001628 // name is operator delete. If the allocated type is an array
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001629 // type, the allocation function's name is operator new[] and the
1630 // deallocation function's name is operator delete[].
Sebastian Redlfaf68082008-12-03 20:26:15 +00001631 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
1632 IsArray ? OO_Array_New : OO_New);
Douglas Gregor6642ca22010-02-26 05:06:18 +00001633 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1634 IsArray ? OO_Array_Delete : OO_Delete);
1635
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00001636 QualType AllocElemType = Context.getBaseElementType(AllocType);
1637
1638 if (AllocElemType->isRecordType() && !UseGlobal) {
Mike Stump11289f42009-09-09 15:08:12 +00001639 CXXRecordDecl *Record
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00001640 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Dmitri Gribenko08c86682013-05-10 00:20:06 +00001641 if (FindAllocationOverload(StartLoc, Range, NewName, AllocArgs, Record,
1642 /*AllowMissing=*/true, OperatorNew))
Sebastian Redlfaf68082008-12-03 20:26:15 +00001643 return true;
Sebastian Redlfaf68082008-12-03 20:26:15 +00001644 }
Aaron Ballman324fbee2013-05-30 01:55:39 +00001645
Sebastian Redlfaf68082008-12-03 20:26:15 +00001646 if (!OperatorNew) {
1647 // Didn't find a member overload. Look for a global one.
1648 DeclareGlobalNewDelete();
Sebastian Redl33a31012008-12-04 22:20:51 +00001649 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Alp Tokerbfa39342014-01-14 12:51:41 +00001650 bool FallbackEnabled = IsArray && Context.getLangOpts().MSVCCompat;
Dmitri Gribenko08c86682013-05-10 00:20:06 +00001651 if (FindAllocationOverload(StartLoc, Range, NewName, AllocArgs, TUDecl,
Aaron Ballman324fbee2013-05-30 01:55:39 +00001652 /*AllowMissing=*/FallbackEnabled, OperatorNew,
1653 /*Diagnose=*/!FallbackEnabled)) {
1654 if (!FallbackEnabled)
1655 return true;
1656
1657 // MSVC will fall back on trying to find a matching global operator new
1658 // if operator new[] cannot be found. Also, MSVC will leak by not
1659 // generating a call to operator delete or operator delete[], but we
1660 // will not replicate that bug.
1661 NewName = Context.DeclarationNames.getCXXOperatorName(OO_New);
1662 DeleteName = Context.DeclarationNames.getCXXOperatorName(OO_Delete);
1663 if (FindAllocationOverload(StartLoc, Range, NewName, AllocArgs, TUDecl,
Dmitri Gribenko08c86682013-05-10 00:20:06 +00001664 /*AllowMissing=*/false, OperatorNew))
Sebastian Redlfaf68082008-12-03 20:26:15 +00001665 return true;
Aaron Ballman324fbee2013-05-30 01:55:39 +00001666 }
Sebastian Redlfaf68082008-12-03 20:26:15 +00001667 }
1668
John McCall0f55a032010-04-20 02:18:25 +00001669 // We don't need an operator delete if we're running under
1670 // -fno-exceptions.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001671 if (!getLangOpts().Exceptions) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001672 OperatorDelete = nullptr;
John McCall0f55a032010-04-20 02:18:25 +00001673 return false;
1674 }
1675
Douglas Gregor6642ca22010-02-26 05:06:18 +00001676 // C++ [expr.new]p19:
1677 //
1678 // If the new-expression begins with a unary :: operator, the
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001679 // deallocation function's name is looked up in the global
Douglas Gregor6642ca22010-02-26 05:06:18 +00001680 // scope. Otherwise, if the allocated type is a class type T or an
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001681 // array thereof, the deallocation function's name is looked up in
Douglas Gregor6642ca22010-02-26 05:06:18 +00001682 // the scope of T. If this lookup fails to find the name, or if
1683 // the allocated type is not a class type or array thereof, the
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001684 // deallocation function's name is looked up in the global scope.
Douglas Gregor6642ca22010-02-26 05:06:18 +00001685 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00001686 if (AllocElemType->isRecordType() && !UseGlobal) {
Douglas Gregor6642ca22010-02-26 05:06:18 +00001687 CXXRecordDecl *RD
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00001688 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Douglas Gregor6642ca22010-02-26 05:06:18 +00001689 LookupQualifiedName(FoundDelete, RD);
1690 }
John McCallfb6f5262010-03-18 08:19:33 +00001691 if (FoundDelete.isAmbiguous())
1692 return true; // FIXME: clean up expressions?
Douglas Gregor6642ca22010-02-26 05:06:18 +00001693
1694 if (FoundDelete.empty()) {
1695 DeclareGlobalNewDelete();
1696 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
1697 }
1698
1699 FoundDelete.suppressDiagnostics();
John McCalla0296f72010-03-19 07:35:19 +00001700
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001701 SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
John McCalla0296f72010-03-19 07:35:19 +00001702
John McCalld3be2c82010-09-14 21:34:24 +00001703 // Whether we're looking for a placement operator delete is dictated
1704 // by whether we selected a placement operator new, not by whether
1705 // we had explicit placement arguments. This matters for things like
1706 // struct A { void *operator new(size_t, int = 0); ... };
1707 // A *a = new A()
Dmitri Gribenkobe022102013-05-10 13:22:23 +00001708 bool isPlacementNew = (!PlaceArgs.empty() || OperatorNew->param_size() != 1);
John McCalld3be2c82010-09-14 21:34:24 +00001709
1710 if (isPlacementNew) {
Douglas Gregor6642ca22010-02-26 05:06:18 +00001711 // C++ [expr.new]p20:
1712 // A declaration of a placement deallocation function matches the
1713 // declaration of a placement allocation function if it has the
1714 // same number of parameters and, after parameter transformations
1715 // (8.3.5), all parameter types except the first are
1716 // identical. [...]
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001717 //
Douglas Gregor6642ca22010-02-26 05:06:18 +00001718 // To perform this comparison, we compute the function type that
1719 // the deallocation function should have, and use that type both
1720 // for template argument deduction and for comparison purposes.
John McCalldb40c7f2010-12-14 08:05:40 +00001721 //
1722 // FIXME: this comparison should ignore CC and the like.
Douglas Gregor6642ca22010-02-26 05:06:18 +00001723 QualType ExpectedFunctionType;
1724 {
1725 const FunctionProtoType *Proto
1726 = OperatorNew->getType()->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00001727
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001728 SmallVector<QualType, 4> ArgTypes;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001729 ArgTypes.push_back(Context.VoidPtrTy);
Alp Toker9cacbab2014-01-20 20:26:09 +00001730 for (unsigned I = 1, N = Proto->getNumParams(); I < N; ++I)
1731 ArgTypes.push_back(Proto->getParamType(I));
Douglas Gregor6642ca22010-02-26 05:06:18 +00001732
John McCalldb40c7f2010-12-14 08:05:40 +00001733 FunctionProtoType::ExtProtoInfo EPI;
1734 EPI.Variadic = Proto->isVariadic();
1735
Douglas Gregor6642ca22010-02-26 05:06:18 +00001736 ExpectedFunctionType
Jordan Rose5c382722013-03-08 21:51:21 +00001737 = Context.getFunctionType(Context.VoidTy, ArgTypes, EPI);
Douglas Gregor6642ca22010-02-26 05:06:18 +00001738 }
1739
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001740 for (LookupResult::iterator D = FoundDelete.begin(),
Douglas Gregor6642ca22010-02-26 05:06:18 +00001741 DEnd = FoundDelete.end();
1742 D != DEnd; ++D) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001743 FunctionDecl *Fn = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001744 if (FunctionTemplateDecl *FnTmpl
Douglas Gregor6642ca22010-02-26 05:06:18 +00001745 = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
1746 // Perform template argument deduction to try to match the
1747 // expected function type.
Craig Toppere6706e42012-09-19 02:26:47 +00001748 TemplateDeductionInfo Info(StartLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00001749 if (DeduceTemplateArguments(FnTmpl, nullptr, ExpectedFunctionType, Fn,
1750 Info))
Douglas Gregor6642ca22010-02-26 05:06:18 +00001751 continue;
1752 } else
1753 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
1754
1755 if (Context.hasSameType(Fn->getType(), ExpectedFunctionType))
John McCalla0296f72010-03-19 07:35:19 +00001756 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6642ca22010-02-26 05:06:18 +00001757 }
1758 } else {
1759 // C++ [expr.new]p20:
1760 // [...] Any non-placement deallocation function matches a
1761 // non-placement allocation function. [...]
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001762 for (LookupResult::iterator D = FoundDelete.begin(),
Douglas Gregor6642ca22010-02-26 05:06:18 +00001763 DEnd = FoundDelete.end();
1764 D != DEnd; ++D) {
1765 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>((*D)->getUnderlyingDecl()))
Richard Smith1cdec012013-09-29 04:40:38 +00001766 if (isNonPlacementDeallocationFunction(*this, Fn))
John McCalla0296f72010-03-19 07:35:19 +00001767 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6642ca22010-02-26 05:06:18 +00001768 }
Richard Smith1cdec012013-09-29 04:40:38 +00001769
1770 // C++1y [expr.new]p22:
1771 // For a non-placement allocation function, the normal deallocation
1772 // function lookup is used
1773 // C++1y [expr.delete]p?:
1774 // If [...] deallocation function lookup finds both a usual deallocation
1775 // function with only a pointer parameter and a usual deallocation
1776 // function with both a pointer parameter and a size parameter, then the
1777 // selected deallocation function shall be the one with two parameters.
1778 // Otherwise, the selected deallocation function shall be the function
1779 // with one parameter.
1780 if (getLangOpts().SizedDeallocation && Matches.size() == 2) {
1781 if (Matches[0].second->getNumParams() == 1)
1782 Matches.erase(Matches.begin());
1783 else
1784 Matches.erase(Matches.begin() + 1);
1785 assert(Matches[0].second->getNumParams() == 2 &&
Richard Smith2eaf2062014-02-03 07:04:10 +00001786 "found an unexpected usual deallocation function");
Richard Smith1cdec012013-09-29 04:40:38 +00001787 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00001788 }
1789
1790 // C++ [expr.new]p20:
1791 // [...] If the lookup finds a single matching deallocation
1792 // function, that function will be called; otherwise, no
1793 // deallocation function will be called.
1794 if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00001795 OperatorDelete = Matches[0].second;
Douglas Gregor6642ca22010-02-26 05:06:18 +00001796
1797 // C++0x [expr.new]p20:
1798 // If the lookup finds the two-parameter form of a usual
1799 // deallocation function (3.7.4.2) and that function, considered
1800 // as a placement deallocation function, would have been
1801 // selected as a match for the allocation function, the program
1802 // is ill-formed.
Dmitri Gribenkobe022102013-05-10 13:22:23 +00001803 if (!PlaceArgs.empty() && getLangOpts().CPlusPlus11 &&
Richard Smith1cdec012013-09-29 04:40:38 +00001804 isNonPlacementDeallocationFunction(*this, OperatorDelete)) {
Douglas Gregor6642ca22010-02-26 05:06:18 +00001805 Diag(StartLoc, diag::err_placement_new_non_placement_delete)
Dmitri Gribenkobe022102013-05-10 13:22:23 +00001806 << SourceRange(PlaceArgs.front()->getLocStart(),
1807 PlaceArgs.back()->getLocEnd());
Richard Smith1cdec012013-09-29 04:40:38 +00001808 if (!OperatorDelete->isImplicit())
1809 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
1810 << DeleteName;
John McCallfb6f5262010-03-18 08:19:33 +00001811 } else {
1812 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
John McCalla0296f72010-03-19 07:35:19 +00001813 Matches[0].first);
Douglas Gregor6642ca22010-02-26 05:06:18 +00001814 }
1815 }
1816
Sebastian Redlfaf68082008-12-03 20:26:15 +00001817 return false;
1818}
1819
Richard Smithd6f9e732014-05-13 19:56:21 +00001820/// \brief Find an fitting overload for the allocation function
1821/// in the specified scope.
1822///
1823/// \param StartLoc The location of the 'new' token.
NAKAMURA Takumi5182b5a2014-05-14 08:07:56 +00001824/// \param Range The range of the placement arguments.
Richard Smithd6f9e732014-05-13 19:56:21 +00001825/// \param Name The name of the function ('operator new' or 'operator new[]').
1826/// \param Args The placement arguments specified.
1827/// \param Ctx The scope in which we should search; either a class scope or the
1828/// translation unit.
1829/// \param AllowMissing If \c true, report an error if we can't find any
1830/// allocation functions. Otherwise, succeed but don't fill in \p
1831/// Operator.
1832/// \param Operator Filled in with the found allocation function. Unchanged if
1833/// no allocation function was found.
1834/// \param Diagnose If \c true, issue errors if the allocation function is not
1835/// usable.
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00001836bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
Dmitri Gribenko08c86682013-05-10 00:20:06 +00001837 DeclarationName Name, MultiExprArg Args,
1838 DeclContext *Ctx,
Alexis Hunt1f69a022011-05-12 22:46:29 +00001839 bool AllowMissing, FunctionDecl *&Operator,
1840 bool Diagnose) {
John McCall27b18f82009-11-17 02:14:36 +00001841 LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
1842 LookupQualifiedName(R, Ctx);
John McCall9f3059a2009-10-09 21:13:30 +00001843 if (R.empty()) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00001844 if (AllowMissing || !Diagnose)
Sebastian Redl33a31012008-12-04 22:20:51 +00001845 return false;
Sebastian Redl33a31012008-12-04 22:20:51 +00001846 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner45d9d602009-02-17 07:29:20 +00001847 << Name << Range;
Sebastian Redl33a31012008-12-04 22:20:51 +00001848 }
1849
John McCallfb6f5262010-03-18 08:19:33 +00001850 if (R.isAmbiguous())
1851 return true;
1852
1853 R.suppressDiagnostics();
John McCall9f3059a2009-10-09 21:13:30 +00001854
Richard Smith100b24a2014-04-17 01:52:14 +00001855 OverloadCandidateSet Candidates(StartLoc, OverloadCandidateSet::CSK_Normal);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001856 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
Douglas Gregor80a6cc52009-09-30 00:03:47 +00001857 Alloc != AllocEnd; ++Alloc) {
Douglas Gregor55297ac2008-12-23 00:26:44 +00001858 // Even member operator new/delete are implicitly treated as
1859 // static, so don't use AddMemberCandidate.
John McCalla0296f72010-03-19 07:35:19 +00001860 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
Chandler Carruth93538422010-02-03 11:02:14 +00001861
John McCalla0296f72010-03-19 07:35:19 +00001862 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
1863 AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
Craig Topperc3ec1492014-05-26 06:22:03 +00001864 /*ExplicitTemplateArgs=*/nullptr,
Dmitri Gribenko08c86682013-05-10 00:20:06 +00001865 Args, Candidates,
Chandler Carruth93538422010-02-03 11:02:14 +00001866 /*SuppressUserConversions=*/false);
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001867 continue;
Chandler Carruth93538422010-02-03 11:02:14 +00001868 }
1869
John McCalla0296f72010-03-19 07:35:19 +00001870 FunctionDecl *Fn = cast<FunctionDecl>(D);
Dmitri Gribenko08c86682013-05-10 00:20:06 +00001871 AddOverloadCandidate(Fn, Alloc.getPair(), Args, Candidates,
Chandler Carruth93538422010-02-03 11:02:14 +00001872 /*SuppressUserConversions=*/false);
Sebastian Redl33a31012008-12-04 22:20:51 +00001873 }
1874
1875 // Do the resolution.
1876 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00001877 switch (Candidates.BestViableFunction(*this, StartLoc, Best)) {
Sebastian Redl33a31012008-12-04 22:20:51 +00001878 case OR_Success: {
1879 // Got one!
1880 FunctionDecl *FnDecl = Best->Function;
Richard Smith921bd202012-02-26 09:11:52 +00001881 if (CheckAllocationAccess(StartLoc, Range, R.getNamingClass(),
1882 Best->FoundDecl, Diagnose) == AR_inaccessible)
1883 return true;
1884
Richard Smithd6f9e732014-05-13 19:56:21 +00001885 Operator = FnDecl;
Sebastian Redl33a31012008-12-04 22:20:51 +00001886 return false;
1887 }
1888
1889 case OR_No_Viable_Function:
Chandler Carruthe6c88182011-06-08 10:26:03 +00001890 if (Diagnose) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00001891 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
1892 << Name << Range;
Dmitri Gribenko08c86682013-05-10 00:20:06 +00001893 Candidates.NoteCandidates(*this, OCD_AllCandidates, Args);
Chandler Carruthe6c88182011-06-08 10:26:03 +00001894 }
Sebastian Redl33a31012008-12-04 22:20:51 +00001895 return true;
1896
1897 case OR_Ambiguous:
Chandler Carruthe6c88182011-06-08 10:26:03 +00001898 if (Diagnose) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00001899 Diag(StartLoc, diag::err_ovl_ambiguous_call)
1900 << Name << Range;
Dmitri Gribenko08c86682013-05-10 00:20:06 +00001901 Candidates.NoteCandidates(*this, OCD_ViableCandidates, Args);
Chandler Carruthe6c88182011-06-08 10:26:03 +00001902 }
Sebastian Redl33a31012008-12-04 22:20:51 +00001903 return true;
Douglas Gregor171c45a2009-02-18 21:56:37 +00001904
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001905 case OR_Deleted: {
Chandler Carruthe6c88182011-06-08 10:26:03 +00001906 if (Diagnose) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00001907 Diag(StartLoc, diag::err_ovl_deleted_call)
1908 << Best->Function->isDeleted()
1909 << Name
1910 << getDeletedOrUnavailableSuffix(Best->Function)
1911 << Range;
Dmitri Gribenko08c86682013-05-10 00:20:06 +00001912 Candidates.NoteCandidates(*this, OCD_AllCandidates, Args);
Chandler Carruthe6c88182011-06-08 10:26:03 +00001913 }
Douglas Gregor171c45a2009-02-18 21:56:37 +00001914 return true;
Sebastian Redl33a31012008-12-04 22:20:51 +00001915 }
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001916 }
David Blaikie83d382b2011-09-23 05:06:16 +00001917 llvm_unreachable("Unreachable, bad result from BestViableFunction");
Sebastian Redl33a31012008-12-04 22:20:51 +00001918}
1919
1920
Sebastian Redlfaf68082008-12-03 20:26:15 +00001921/// DeclareGlobalNewDelete - Declare the global forms of operator new and
1922/// delete. These are:
1923/// @code
Sebastian Redl37588092011-03-14 18:08:30 +00001924/// // C++03:
Sebastian Redlfaf68082008-12-03 20:26:15 +00001925/// void* operator new(std::size_t) throw(std::bad_alloc);
1926/// void* operator new[](std::size_t) throw(std::bad_alloc);
1927/// void operator delete(void *) throw();
1928/// void operator delete[](void *) throw();
Richard Smith1cdec012013-09-29 04:40:38 +00001929/// // C++11:
Sebastian Redl37588092011-03-14 18:08:30 +00001930/// void* operator new(std::size_t);
1931/// void* operator new[](std::size_t);
Richard Smith1cdec012013-09-29 04:40:38 +00001932/// void operator delete(void *) noexcept;
1933/// void operator delete[](void *) noexcept;
1934/// // C++1y:
1935/// void* operator new(std::size_t);
1936/// void* operator new[](std::size_t);
1937/// void operator delete(void *) noexcept;
1938/// void operator delete[](void *) noexcept;
1939/// void operator delete(void *, std::size_t) noexcept;
1940/// void operator delete[](void *, std::size_t) noexcept;
Sebastian Redlfaf68082008-12-03 20:26:15 +00001941/// @endcode
1942/// Note that the placement and nothrow forms of new are *not* implicitly
1943/// declared. Their use requires including \<new\>.
Mike Stump11289f42009-09-09 15:08:12 +00001944void Sema::DeclareGlobalNewDelete() {
Sebastian Redlfaf68082008-12-03 20:26:15 +00001945 if (GlobalNewDeleteDeclared)
1946 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001947
Douglas Gregor87f54062009-09-15 22:30:29 +00001948 // C++ [basic.std.dynamic]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001949 // [...] The following allocation and deallocation functions (18.4) are
1950 // implicitly declared in global scope in each translation unit of a
Douglas Gregor87f54062009-09-15 22:30:29 +00001951 // program
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001952 //
Sebastian Redl37588092011-03-14 18:08:30 +00001953 // C++03:
Douglas Gregor87f54062009-09-15 22:30:29 +00001954 // void* operator new(std::size_t) throw(std::bad_alloc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001955 // void* operator new[](std::size_t) throw(std::bad_alloc);
1956 // void operator delete(void*) throw();
Douglas Gregor87f54062009-09-15 22:30:29 +00001957 // void operator delete[](void*) throw();
Richard Smith1cdec012013-09-29 04:40:38 +00001958 // C++11:
Sebastian Redl37588092011-03-14 18:08:30 +00001959 // void* operator new(std::size_t);
1960 // void* operator new[](std::size_t);
Richard Smith1cdec012013-09-29 04:40:38 +00001961 // void operator delete(void*) noexcept;
1962 // void operator delete[](void*) noexcept;
1963 // C++1y:
1964 // void* operator new(std::size_t);
1965 // void* operator new[](std::size_t);
1966 // void operator delete(void*) noexcept;
1967 // void operator delete[](void*) noexcept;
1968 // void operator delete(void*, std::size_t) noexcept;
1969 // void operator delete[](void*, std::size_t) noexcept;
Douglas Gregor87f54062009-09-15 22:30:29 +00001970 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001971 // These implicit declarations introduce only the function names operator
Douglas Gregor87f54062009-09-15 22:30:29 +00001972 // new, operator new[], operator delete, operator delete[].
1973 //
1974 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
1975 // "std" or "bad_alloc" as necessary to form the exception specification.
1976 // However, we do not make these implicit declarations visible to name
1977 // lookup.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001978 if (!StdBadAlloc && !getLangOpts().CPlusPlus11) {
Douglas Gregor87f54062009-09-15 22:30:29 +00001979 // The "std::bad_alloc" class has not yet been declared, so build it
1980 // implicitly.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001981 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
1982 getOrCreateStdNamespace(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00001983 SourceLocation(), SourceLocation(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001984 &PP.getIdentifierTable().get("bad_alloc"),
Craig Topperc3ec1492014-05-26 06:22:03 +00001985 nullptr);
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00001986 getStdBadAlloc()->setImplicit(true);
Douglas Gregor87f54062009-09-15 22:30:29 +00001987 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001988
Sebastian Redlfaf68082008-12-03 20:26:15 +00001989 GlobalNewDeleteDeclared = true;
1990
1991 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
1992 QualType SizeT = Context.getSizeType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00001993 bool AssumeSaneOperatorNew = getLangOpts().AssumeSaneOperatorNew;
Sebastian Redlfaf68082008-12-03 20:26:15 +00001994
Sebastian Redlfaf68082008-12-03 20:26:15 +00001995 DeclareGlobalAllocationFunction(
1996 Context.DeclarationNames.getCXXOperatorName(OO_New),
Richard Smith1cdec012013-09-29 04:40:38 +00001997 VoidPtr, SizeT, QualType(), AssumeSaneOperatorNew);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001998 DeclareGlobalAllocationFunction(
1999 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
Richard Smith1cdec012013-09-29 04:40:38 +00002000 VoidPtr, SizeT, QualType(), AssumeSaneOperatorNew);
Sebastian Redlfaf68082008-12-03 20:26:15 +00002001 DeclareGlobalAllocationFunction(
2002 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
2003 Context.VoidTy, VoidPtr);
2004 DeclareGlobalAllocationFunction(
2005 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
2006 Context.VoidTy, VoidPtr);
Richard Smith1cdec012013-09-29 04:40:38 +00002007 if (getLangOpts().SizedDeallocation) {
2008 DeclareGlobalAllocationFunction(
2009 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
2010 Context.VoidTy, VoidPtr, Context.getSizeType());
2011 DeclareGlobalAllocationFunction(
2012 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
2013 Context.VoidTy, VoidPtr, Context.getSizeType());
2014 }
Sebastian Redlfaf68082008-12-03 20:26:15 +00002015}
2016
2017/// DeclareGlobalAllocationFunction - Declares a single implicit global
2018/// allocation function if it doesn't already exist.
2019void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Richard Smith1cdec012013-09-29 04:40:38 +00002020 QualType Return,
2021 QualType Param1, QualType Param2,
Nuno Lopes13c88c72009-12-16 16:59:22 +00002022 bool AddMallocAttr) {
Sebastian Redlfaf68082008-12-03 20:26:15 +00002023 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
Richard Smith1cdec012013-09-29 04:40:38 +00002024 unsigned NumParams = Param2.isNull() ? 1 : 2;
Sebastian Redlfaf68082008-12-03 20:26:15 +00002025
2026 // Check if this function is already declared.
Serge Pavlovd5489072013-09-14 12:00:01 +00002027 DeclContext::lookup_result R = GlobalCtx->lookup(Name);
2028 for (DeclContext::lookup_iterator Alloc = R.begin(), AllocEnd = R.end();
2029 Alloc != AllocEnd; ++Alloc) {
2030 // Only look at non-template functions, as it is the predefined,
2031 // non-templated allocation function we are trying to declare here.
2032 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
Richard Smith1cdec012013-09-29 04:40:38 +00002033 if (Func->getNumParams() == NumParams) {
2034 QualType InitialParam1Type =
2035 Context.getCanonicalType(Func->getParamDecl(0)
2036 ->getType().getUnqualifiedType());
2037 QualType InitialParam2Type =
2038 NumParams == 2
2039 ? Context.getCanonicalType(Func->getParamDecl(1)
2040 ->getType().getUnqualifiedType())
2041 : QualType();
Chandler Carruth93538422010-02-03 11:02:14 +00002042 // FIXME: Do we need to check for default arguments here?
Richard Smith1cdec012013-09-29 04:40:38 +00002043 if (InitialParam1Type == Param1 &&
2044 (NumParams == 1 || InitialParam2Type == Param2)) {
Richard Smith42713d72013-07-14 02:01:48 +00002045 if (AddMallocAttr && !Func->hasAttr<MallocAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +00002046 Func->addAttr(MallocAttr::CreateImplicit(Context));
Serge Pavlovd5489072013-09-14 12:00:01 +00002047 // Make the function visible to name lookup, even if we found it in
2048 // an unimported module. It either is an implicitly-declared global
Richard Smith42713d72013-07-14 02:01:48 +00002049 // allocation function, or is suppressing that function.
2050 Func->setHidden(false);
Chandler Carruth93538422010-02-03 11:02:14 +00002051 return;
Douglas Gregorc1a42fd2010-08-18 15:06:25 +00002052 }
Chandler Carruth93538422010-02-03 11:02:14 +00002053 }
Sebastian Redlfaf68082008-12-03 20:26:15 +00002054 }
2055 }
2056
Richard Smithc015bc22014-02-07 22:39:53 +00002057 FunctionProtoType::ExtProtoInfo EPI;
2058
Richard Smithf8b417c2014-02-08 00:42:45 +00002059 QualType BadAllocType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002060 bool HasBadAllocExceptionSpec
Douglas Gregor87f54062009-09-15 22:30:29 +00002061 = (Name.getCXXOverloadedOperator() == OO_New ||
2062 Name.getCXXOverloadedOperator() == OO_Array_New);
John McCalldb40c7f2010-12-14 08:05:40 +00002063 if (HasBadAllocExceptionSpec) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002064 if (!getLangOpts().CPlusPlus11) {
Richard Smithf8b417c2014-02-08 00:42:45 +00002065 BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
Richard Smithc015bc22014-02-07 22:39:53 +00002066 assert(StdBadAlloc && "Must have std::bad_alloc declared");
Sebastian Redl37588092011-03-14 18:08:30 +00002067 EPI.ExceptionSpecType = EST_Dynamic;
2068 EPI.NumExceptions = 1;
2069 EPI.Exceptions = &BadAllocType;
2070 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002071 } else {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002072 EPI.ExceptionSpecType = getLangOpts().CPlusPlus11 ?
Sebastian Redl37588092011-03-14 18:08:30 +00002073 EST_BasicNoexcept : EST_DynamicNone;
John McCalldb40c7f2010-12-14 08:05:40 +00002074 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002075
Richard Smith1cdec012013-09-29 04:40:38 +00002076 QualType Params[] = { Param1, Param2 };
2077
2078 QualType FnType = Context.getFunctionType(
2079 Return, ArrayRef<QualType>(Params, NumParams), EPI);
Sebastian Redlfaf68082008-12-03 20:26:15 +00002080 FunctionDecl *Alloc =
Abramo Bagnaradff19302011-03-08 08:55:46 +00002081 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(),
2082 SourceLocation(), Name,
Craig Topperc3ec1492014-05-26 06:22:03 +00002083 FnType, /*TInfo=*/nullptr, SC_None, false, true);
Sebastian Redlfaf68082008-12-03 20:26:15 +00002084 Alloc->setImplicit();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002085
Nuno Lopes13c88c72009-12-16 16:59:22 +00002086 if (AddMallocAttr)
Aaron Ballman36a53502014-01-16 13:03:14 +00002087 Alloc->addAttr(MallocAttr::CreateImplicit(Context));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002088
Richard Smith1cdec012013-09-29 04:40:38 +00002089 ParmVarDecl *ParamDecls[2];
Richard Smithbdd14642014-02-04 01:14:30 +00002090 for (unsigned I = 0; I != NumParams; ++I) {
Richard Smith1cdec012013-09-29 04:40:38 +00002091 ParamDecls[I] = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +00002092 SourceLocation(), nullptr,
2093 Params[I], /*TInfo=*/nullptr,
2094 SC_None, nullptr);
Richard Smithbdd14642014-02-04 01:14:30 +00002095 ParamDecls[I]->setImplicit();
2096 }
Richard Smith1cdec012013-09-29 04:40:38 +00002097 Alloc->setParams(ArrayRef<ParmVarDecl*>(ParamDecls, NumParams));
Sebastian Redlfaf68082008-12-03 20:26:15 +00002098
John McCallcc14d1f2010-08-24 08:50:51 +00002099 Context.getTranslationUnitDecl()->addDecl(Alloc);
Richard Smithdebcd502014-05-16 02:14:42 +00002100 IdResolver.tryAddTopLevelDecl(Alloc, Name);
Sebastian Redlfaf68082008-12-03 20:26:15 +00002101}
2102
Richard Smith1cdec012013-09-29 04:40:38 +00002103FunctionDecl *Sema::FindUsualDeallocationFunction(SourceLocation StartLoc,
2104 bool CanProvideSize,
2105 DeclarationName Name) {
2106 DeclareGlobalNewDelete();
2107
2108 LookupResult FoundDelete(*this, Name, StartLoc, LookupOrdinaryName);
2109 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
2110
2111 // C++ [expr.new]p20:
2112 // [...] Any non-placement deallocation function matches a
2113 // non-placement allocation function. [...]
2114 llvm::SmallVector<FunctionDecl*, 2> Matches;
2115 for (LookupResult::iterator D = FoundDelete.begin(),
2116 DEnd = FoundDelete.end();
2117 D != DEnd; ++D) {
2118 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>(*D))
2119 if (isNonPlacementDeallocationFunction(*this, Fn))
2120 Matches.push_back(Fn);
2121 }
2122
2123 // C++1y [expr.delete]p?:
2124 // If the type is complete and deallocation function lookup finds both a
2125 // usual deallocation function with only a pointer parameter and a usual
2126 // deallocation function with both a pointer parameter and a size
2127 // parameter, then the selected deallocation function shall be the one
2128 // with two parameters. Otherwise, the selected deallocation function
2129 // shall be the function with one parameter.
2130 if (getLangOpts().SizedDeallocation && Matches.size() == 2) {
2131 unsigned NumArgs = CanProvideSize ? 2 : 1;
2132 if (Matches[0]->getNumParams() != NumArgs)
2133 Matches.erase(Matches.begin());
2134 else
2135 Matches.erase(Matches.begin() + 1);
2136 assert(Matches[0]->getNumParams() == NumArgs &&
Richard Smith2eaf2062014-02-03 07:04:10 +00002137 "found an unexpected usual deallocation function");
Richard Smith1cdec012013-09-29 04:40:38 +00002138 }
2139
2140 assert(Matches.size() == 1 &&
2141 "unexpectedly have multiple usual deallocation functions");
2142 return Matches.front();
2143}
2144
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002145bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
2146 DeclarationName Name,
Alexis Hunt1f69a022011-05-12 22:46:29 +00002147 FunctionDecl* &Operator, bool Diagnose) {
John McCall27b18f82009-11-17 02:14:36 +00002148 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002149 // Try to find operator delete/operator delete[] in class scope.
John McCall27b18f82009-11-17 02:14:36 +00002150 LookupQualifiedName(Found, RD);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002151
John McCall27b18f82009-11-17 02:14:36 +00002152 if (Found.isAmbiguous())
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002153 return true;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002154
Chandler Carruthb6f99172010-06-28 00:30:51 +00002155 Found.suppressDiagnostics();
2156
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002157 SmallVector<DeclAccessPair,4> Matches;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002158 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
2159 F != FEnd; ++F) {
Chandler Carruth9b418232010-08-08 07:04:00 +00002160 NamedDecl *ND = (*F)->getUnderlyingDecl();
2161
2162 // Ignore template operator delete members from the check for a usual
2163 // deallocation function.
2164 if (isa<FunctionTemplateDecl>(ND))
2165 continue;
2166
2167 if (cast<CXXMethodDecl>(ND)->isUsualDeallocationFunction())
John McCall66a87592010-08-04 00:31:26 +00002168 Matches.push_back(F.getPair());
2169 }
2170
2171 // There's exactly one suitable operator; pick it.
2172 if (Matches.size() == 1) {
2173 Operator = cast<CXXMethodDecl>(Matches[0]->getUnderlyingDecl());
Alexis Hunt1f69a022011-05-12 22:46:29 +00002174
2175 if (Operator->isDeleted()) {
2176 if (Diagnose) {
2177 Diag(StartLoc, diag::err_deleted_function_use);
Richard Smith852265f2012-03-30 20:53:28 +00002178 NoteDeletedFunction(Operator);
Alexis Hunt1f69a022011-05-12 22:46:29 +00002179 }
2180 return true;
2181 }
2182
Richard Smith921bd202012-02-26 09:11:52 +00002183 if (CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
2184 Matches[0], Diagnose) == AR_inaccessible)
2185 return true;
2186
John McCall66a87592010-08-04 00:31:26 +00002187 return false;
2188
2189 // We found multiple suitable operators; complain about the ambiguity.
2190 } else if (!Matches.empty()) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00002191 if (Diagnose) {
Alexis Huntf91729462011-05-12 22:46:25 +00002192 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
2193 << Name << RD;
John McCall66a87592010-08-04 00:31:26 +00002194
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002195 for (SmallVectorImpl<DeclAccessPair>::iterator
Alexis Huntf91729462011-05-12 22:46:25 +00002196 F = Matches.begin(), FEnd = Matches.end(); F != FEnd; ++F)
2197 Diag((*F)->getUnderlyingDecl()->getLocation(),
2198 diag::note_member_declared_here) << Name;
2199 }
John McCall66a87592010-08-04 00:31:26 +00002200 return true;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002201 }
2202
2203 // We did find operator delete/operator delete[] declarations, but
2204 // none of them were suitable.
2205 if (!Found.empty()) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00002206 if (Diagnose) {
Alexis Huntf91729462011-05-12 22:46:25 +00002207 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
2208 << Name << RD;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002209
Alexis Huntf91729462011-05-12 22:46:25 +00002210 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
2211 F != FEnd; ++F)
2212 Diag((*F)->getUnderlyingDecl()->getLocation(),
2213 diag::note_member_declared_here) << Name;
2214 }
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002215 return true;
2216 }
2217
Craig Topperc3ec1492014-05-26 06:22:03 +00002218 Operator = nullptr;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002219 return false;
2220}
2221
Sebastian Redlbd150f42008-11-21 19:14:01 +00002222/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
2223/// @code ::delete ptr; @endcode
2224/// or
2225/// @code delete [] ptr; @endcode
John McCalldadc5752010-08-24 06:29:42 +00002226ExprResult
Sebastian Redlbd150f42008-11-21 19:14:01 +00002227Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
John Wiegley01296292011-04-08 18:41:53 +00002228 bool ArrayForm, Expr *ExE) {
Douglas Gregor0fea62d2009-09-09 23:39:55 +00002229 // C++ [expr.delete]p1:
2230 // The operand shall have a pointer type, or a class type having a single
Richard Smithccc11812013-05-21 19:05:48 +00002231 // non-explicit conversion function to a pointer type. The result has type
2232 // void.
Douglas Gregor0fea62d2009-09-09 23:39:55 +00002233 //
Sebastian Redlbd150f42008-11-21 19:14:01 +00002234 // DR599 amends "pointer type" to "pointer to object type" in both cases.
2235
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002236 ExprResult Ex = ExE;
Craig Topperc3ec1492014-05-26 06:22:03 +00002237 FunctionDecl *OperatorDelete = nullptr;
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00002238 bool ArrayFormAsWritten = ArrayForm;
John McCall284c48f2011-01-27 09:37:56 +00002239 bool UsualArrayDeleteWantsSize = false;
Mike Stump11289f42009-09-09 15:08:12 +00002240
John Wiegley01296292011-04-08 18:41:53 +00002241 if (!Ex.get()->isTypeDependent()) {
John McCallef429022012-03-09 04:08:29 +00002242 // Perform lvalue-to-rvalue cast, if needed.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002243 Ex = DefaultLvalueConversion(Ex.get());
Eli Friedman89a4a2c2012-12-13 00:37:17 +00002244 if (Ex.isInvalid())
2245 return ExprError();
John McCallef429022012-03-09 04:08:29 +00002246
John Wiegley01296292011-04-08 18:41:53 +00002247 QualType Type = Ex.get()->getType();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002248
Richard Smithccc11812013-05-21 19:05:48 +00002249 class DeleteConverter : public ContextualImplicitConverter {
2250 public:
2251 DeleteConverter() : ContextualImplicitConverter(false, true) {}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002252
Craig Toppere14c0f82014-03-12 04:55:44 +00002253 bool match(QualType ConvType) override {
Richard Smithccc11812013-05-21 19:05:48 +00002254 // FIXME: If we have an operator T* and an operator void*, we must pick
2255 // the operator T*.
Douglas Gregor0fea62d2009-09-09 23:39:55 +00002256 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
Eli Friedmana170cd62010-08-05 02:49:48 +00002257 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
Richard Smithccc11812013-05-21 19:05:48 +00002258 return true;
2259 return false;
Douglas Gregor0fea62d2009-09-09 23:39:55 +00002260 }
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002261
Richard Smithccc11812013-05-21 19:05:48 +00002262 SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00002263 QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00002264 return S.Diag(Loc, diag::err_delete_operand) << T;
2265 }
2266
2267 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00002268 QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00002269 return S.Diag(Loc, diag::err_delete_incomplete_class_type) << T;
2270 }
2271
2272 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00002273 QualType T,
2274 QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +00002275 return S.Diag(Loc, diag::err_delete_explicit_conversion) << T << ConvTy;
2276 }
2277
2278 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
Craig Toppere14c0f82014-03-12 04:55:44 +00002279 QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +00002280 return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
2281 << ConvTy;
2282 }
2283
2284 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00002285 QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00002286 return S.Diag(Loc, diag::err_ambiguous_delete_operand) << T;
2287 }
2288
2289 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
Craig Toppere14c0f82014-03-12 04:55:44 +00002290 QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +00002291 return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
2292 << ConvTy;
2293 }
2294
2295 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00002296 QualType T,
2297 QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +00002298 llvm_unreachable("conversion functions are permitted");
2299 }
2300 } Converter;
2301
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002302 Ex = PerformContextualImplicitConversion(StartLoc, Ex.get(), Converter);
Richard Smithccc11812013-05-21 19:05:48 +00002303 if (Ex.isInvalid())
2304 return ExprError();
2305 Type = Ex.get()->getType();
2306 if (!Converter.match(Type))
2307 // FIXME: PerformContextualImplicitConversion should return ExprError
2308 // itself in this case.
2309 return ExprError();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002310
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002311 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Eli Friedmanae4280f2011-07-26 22:25:31 +00002312 QualType PointeeElem = Context.getBaseElementType(Pointee);
2313
2314 if (unsigned AddressSpace = Pointee.getAddressSpace())
2315 return Diag(Ex.get()->getLocStart(),
2316 diag::err_address_space_qualified_delete)
2317 << Pointee.getUnqualifiedType() << AddressSpace;
2318
Craig Topperc3ec1492014-05-26 06:22:03 +00002319 CXXRecordDecl *PointeeRD = nullptr;
Douglas Gregorbb3348e2010-05-24 17:01:56 +00002320 if (Pointee->isVoidType() && !isSFINAEContext()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002321 // The C++ standard bans deleting a pointer to a non-object type, which
Douglas Gregorbb3348e2010-05-24 17:01:56 +00002322 // effectively bans deletion of "void*". However, most compilers support
2323 // this, so we treat it as a warning unless we're in a SFINAE context.
2324 Diag(StartLoc, diag::ext_delete_void_ptr_operand)
John Wiegley01296292011-04-08 18:41:53 +00002325 << Type << Ex.get()->getSourceRange();
Eli Friedmanae4280f2011-07-26 22:25:31 +00002326 } else if (Pointee->isFunctionType() || Pointee->isVoidType()) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00002327 return ExprError(Diag(StartLoc, diag::err_delete_operand)
John Wiegley01296292011-04-08 18:41:53 +00002328 << Type << Ex.get()->getSourceRange());
Eli Friedmanae4280f2011-07-26 22:25:31 +00002329 } else if (!Pointee->isDependentType()) {
2330 if (!RequireCompleteType(StartLoc, Pointee,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002331 diag::warn_delete_incomplete, Ex.get())) {
Eli Friedmanae4280f2011-07-26 22:25:31 +00002332 if (const RecordType *RT = PointeeElem->getAs<RecordType>())
2333 PointeeRD = cast<CXXRecordDecl>(RT->getDecl());
2334 }
2335 }
2336
Douglas Gregor98496dc2009-09-29 21:38:53 +00002337 // C++ [expr.delete]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002338 // [Note: a pointer to a const type can be the operand of a
2339 // delete-expression; it is not necessary to cast away the constness
2340 // (5.2.11) of the pointer expression before it is used as the operand
Douglas Gregor98496dc2009-09-29 21:38:53 +00002341 // of the delete-expression. ]
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00002342
2343 if (Pointee->isArrayType() && !ArrayForm) {
2344 Diag(StartLoc, diag::warn_delete_array_type)
John Wiegley01296292011-04-08 18:41:53 +00002345 << Type << Ex.get()->getSourceRange()
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00002346 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(StartLoc), "[]");
2347 ArrayForm = true;
2348 }
2349
Anders Carlssona471db02009-08-16 20:29:29 +00002350 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
2351 ArrayForm ? OO_Array_Delete : OO_Delete);
2352
Eli Friedmanae4280f2011-07-26 22:25:31 +00002353 if (PointeeRD) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002354 if (!UseGlobal &&
Eli Friedmanae4280f2011-07-26 22:25:31 +00002355 FindDeallocationFunction(StartLoc, PointeeRD, DeleteName,
2356 OperatorDelete))
Anders Carlsson654e5c72009-11-14 03:17:38 +00002357 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002358
John McCall284c48f2011-01-27 09:37:56 +00002359 // If we're allocating an array of records, check whether the
2360 // usual operator delete[] has a size_t parameter.
2361 if (ArrayForm) {
2362 // If the user specifically asked to use the global allocator,
2363 // we'll need to do the lookup into the class.
2364 if (UseGlobal)
2365 UsualArrayDeleteWantsSize =
2366 doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
2367
2368 // Otherwise, the usual operator delete[] should be the
2369 // function we just found.
Richard Smithf03bd302013-12-05 08:30:59 +00002370 else if (OperatorDelete && isa<CXXMethodDecl>(OperatorDelete))
John McCall284c48f2011-01-27 09:37:56 +00002371 UsualArrayDeleteWantsSize = (OperatorDelete->getNumParams() == 2);
2372 }
2373
Richard Smitheec915d62012-02-18 04:13:32 +00002374 if (!PointeeRD->hasIrrelevantDestructor())
Eli Friedmanae4280f2011-07-26 22:25:31 +00002375 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00002376 MarkFunctionReferenced(StartLoc,
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002377 const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith22262ab2013-05-04 06:44:46 +00002378 if (DiagnoseUseOfDecl(Dtor, StartLoc))
2379 return ExprError();
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002380 }
Argyrios Kyrtzidis8bd42852011-05-24 19:53:26 +00002381
2382 // C++ [expr.delete]p3:
2383 // In the first alternative (delete object), if the static type of the
2384 // object to be deleted is different from its dynamic type, the static
2385 // type shall be a base class of the dynamic type of the object to be
2386 // deleted and the static type shall have a virtual destructor or the
2387 // behavior is undefined.
2388 //
2389 // Note: a final class cannot be derived from, no issue there
Eli Friedman1b71a222011-07-26 23:27:24 +00002390 if (PointeeRD->isPolymorphic() && !PointeeRD->hasAttr<FinalAttr>()) {
Eli Friedmanae4280f2011-07-26 22:25:31 +00002391 CXXDestructorDecl *dtor = PointeeRD->getDestructor();
Eli Friedman1b71a222011-07-26 23:27:24 +00002392 if (dtor && !dtor->isVirtual()) {
2393 if (PointeeRD->isAbstract()) {
2394 // If the class is abstract, we warn by default, because we're
2395 // sure the code has undefined behavior.
2396 Diag(StartLoc, diag::warn_delete_abstract_non_virtual_dtor)
2397 << PointeeElem;
2398 } else if (!ArrayForm) {
2399 // Otherwise, if this is not an array delete, it's a bit suspect,
2400 // but not necessarily wrong.
2401 Diag(StartLoc, diag::warn_delete_non_virtual_dtor) << PointeeElem;
2402 }
2403 }
Argyrios Kyrtzidis8bd42852011-05-24 19:53:26 +00002404 }
John McCall31168b02011-06-15 23:02:42 +00002405
Anders Carlssona471db02009-08-16 20:29:29 +00002406 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002407
Richard Smith1cdec012013-09-29 04:40:38 +00002408 if (!OperatorDelete)
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002409 // Look for a global declaration.
Richard Smith1cdec012013-09-29 04:40:38 +00002410 OperatorDelete = FindUsualDeallocationFunction(
2411 StartLoc, !RequireCompleteType(StartLoc, Pointee, 0) &&
2412 (!ArrayForm || UsualArrayDeleteWantsSize ||
2413 Pointee.isDestructedType()),
2414 DeleteName);
Mike Stump11289f42009-09-09 15:08:12 +00002415
Eli Friedmanfa0df832012-02-02 03:46:19 +00002416 MarkFunctionReferenced(StartLoc, OperatorDelete);
John McCall284c48f2011-01-27 09:37:56 +00002417
Douglas Gregorfa778132011-02-01 15:50:11 +00002418 // Check access and ambiguity of operator delete and destructor.
Eli Friedmanae4280f2011-07-26 22:25:31 +00002419 if (PointeeRD) {
2420 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
John Wiegley01296292011-04-08 18:41:53 +00002421 CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor,
Douglas Gregorfa778132011-02-01 15:50:11 +00002422 PDiag(diag::err_access_dtor) << PointeeElem);
2423 }
2424 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002425 }
2426
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002427 return new (Context) CXXDeleteExpr(
2428 Context.VoidTy, UseGlobal, ArrayForm, ArrayFormAsWritten,
2429 UsualArrayDeleteWantsSize, OperatorDelete, Ex.get(), StartLoc);
Sebastian Redlbd150f42008-11-21 19:14:01 +00002430}
2431
Douglas Gregor633caca2009-11-23 23:44:04 +00002432/// \brief Check the use of the given variable as a C++ condition in an if,
2433/// while, do-while, or switch statement.
John McCalldadc5752010-08-24 06:29:42 +00002434ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
John McCall7decc9e2010-11-18 06:31:45 +00002435 SourceLocation StmtLoc,
2436 bool ConvertToBoolean) {
Richard Smith27d807c2013-04-30 13:56:41 +00002437 if (ConditionVar->isInvalidDecl())
2438 return ExprError();
2439
Douglas Gregor633caca2009-11-23 23:44:04 +00002440 QualType T = ConditionVar->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002441
Douglas Gregor633caca2009-11-23 23:44:04 +00002442 // C++ [stmt.select]p2:
2443 // The declarator shall not specify a function or an array.
2444 if (T->isFunctionType())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002445 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor633caca2009-11-23 23:44:04 +00002446 diag::err_invalid_use_of_function_type)
2447 << ConditionVar->getSourceRange());
2448 else if (T->isArrayType())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002449 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor633caca2009-11-23 23:44:04 +00002450 diag::err_invalid_use_of_array_type)
2451 << ConditionVar->getSourceRange());
Douglas Gregor0156d1c2009-11-24 16:07:02 +00002452
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002453 ExprResult Condition = DeclRefExpr::Create(
2454 Context, NestedNameSpecifierLoc(), SourceLocation(), ConditionVar,
2455 /*enclosing*/ false, ConditionVar->getLocation(),
2456 ConditionVar->getType().getNonReferenceType(), VK_LValue);
Eli Friedman2dfa7932012-01-16 21:00:51 +00002457
Eli Friedmanfa0df832012-02-02 03:46:19 +00002458 MarkDeclRefReferenced(cast<DeclRefExpr>(Condition.get()));
Eli Friedman2dfa7932012-01-16 21:00:51 +00002459
John Wiegley01296292011-04-08 18:41:53 +00002460 if (ConvertToBoolean) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002461 Condition = CheckBooleanCondition(Condition.get(), StmtLoc);
John Wiegley01296292011-04-08 18:41:53 +00002462 if (Condition.isInvalid())
2463 return ExprError();
2464 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002465
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002466 return Condition;
Douglas Gregor633caca2009-11-23 23:44:04 +00002467}
2468
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00002469/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
John Wiegley01296292011-04-08 18:41:53 +00002470ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr) {
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00002471 // C++ 6.4p4:
2472 // The value of a condition that is an initialized declaration in a statement
2473 // other than a switch statement is the value of the declared variable
2474 // implicitly converted to type bool. If that conversion is ill-formed, the
2475 // program is ill-formed.
2476 // The value of a condition that is an expression is the value of the
2477 // expression, implicitly converted to bool.
2478 //
Douglas Gregor5fb53972009-01-14 15:45:31 +00002479 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00002480}
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00002481
2482/// Helper function to determine whether this is the (deprecated) C++
2483/// conversion from a string literal to a pointer to non-const char or
2484/// non-const wchar_t (for narrow and wide string literals,
2485/// respectively).
Mike Stump11289f42009-09-09 15:08:12 +00002486bool
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00002487Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
2488 // Look inside the implicit cast, if it exists.
2489 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
2490 From = Cast->getSubExpr();
2491
2492 // A string literal (2.13.4) that is not a wide string literal can
2493 // be converted to an rvalue of type "pointer to char"; a wide
2494 // string literal can be converted to an rvalue of type "pointer
2495 // to wchar_t" (C++ 4.2p2).
Douglas Gregor689999d2010-06-22 23:47:37 +00002496 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002497 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump11289f42009-09-09 15:08:12 +00002498 if (const BuiltinType *ToPointeeType
John McCall9dd450b2009-09-21 23:43:11 +00002499 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00002500 // This conversion is considered only when there is an
2501 // explicit appropriate pointer target type (C++ 4.2p2).
Douglas Gregorfb65e592011-07-27 05:40:30 +00002502 if (!ToPtrType->getPointeeType().hasQualifiers()) {
2503 switch (StrLit->getKind()) {
2504 case StringLiteral::UTF8:
2505 case StringLiteral::UTF16:
2506 case StringLiteral::UTF32:
2507 // We don't allow UTF literals to be implicitly converted
2508 break;
2509 case StringLiteral::Ascii:
2510 return (ToPointeeType->getKind() == BuiltinType::Char_U ||
2511 ToPointeeType->getKind() == BuiltinType::Char_S);
2512 case StringLiteral::Wide:
2513 return ToPointeeType->isWideCharType();
2514 }
2515 }
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00002516 }
2517
2518 return false;
2519}
Douglas Gregor39c16d42008-10-24 04:54:22 +00002520
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002521static ExprResult BuildCXXCastArgument(Sema &S,
John McCalle3027922010-08-25 11:45:40 +00002522 SourceLocation CastLoc,
2523 QualType Ty,
2524 CastKind Kind,
2525 CXXMethodDecl *Method,
John McCall30909032011-09-21 08:36:56 +00002526 DeclAccessPair FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00002527 bool HadMultipleCandidates,
John McCalle3027922010-08-25 11:45:40 +00002528 Expr *From) {
Douglas Gregora4253922010-04-16 22:17:36 +00002529 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00002530 default: llvm_unreachable("Unhandled cast kind!");
John McCalle3027922010-08-25 11:45:40 +00002531 case CK_ConstructorConversion: {
Douglas Gregorc7a31072011-10-10 22:41:00 +00002532 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method);
Benjamin Kramerf0623432012-08-23 22:51:59 +00002533 SmallVector<Expr*, 8> ConstructorArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002534
Richard Smith72d74052013-07-20 19:41:36 +00002535 if (S.RequireNonAbstractType(CastLoc, Ty,
2536 diag::err_allocation_of_abstract_type))
2537 return ExprError();
2538
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002539 if (S.CompleteConstructorCall(Constructor, From, CastLoc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00002540 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002541
John McCall5dadb652012-04-07 03:04:20 +00002542 S.CheckConstructorAccess(CastLoc, Constructor,
2543 InitializedEntity::InitializeTemporary(Ty),
2544 Constructor->getAccess());
Richard Smithd59b8322012-12-19 01:39:02 +00002545
Douglas Gregorc7a31072011-10-10 22:41:00 +00002546 ExprResult Result
2547 = S.BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
Richard Smithd59b8322012-12-19 01:39:02 +00002548 ConstructorArgs, HadMultipleCandidates,
2549 /*ListInit*/ false, /*ZeroInit*/ false,
Douglas Gregorc7a31072011-10-10 22:41:00 +00002550 CXXConstructExpr::CK_Complete, SourceRange());
Douglas Gregora4253922010-04-16 22:17:36 +00002551 if (Result.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00002552 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002553
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002554 return S.MaybeBindToTemporary(Result.getAs<Expr>());
Douglas Gregora4253922010-04-16 22:17:36 +00002555 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002556
John McCalle3027922010-08-25 11:45:40 +00002557 case CK_UserDefinedConversion: {
Douglas Gregora4253922010-04-16 22:17:36 +00002558 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002559
Douglas Gregora4253922010-04-16 22:17:36 +00002560 // Create an implicit call expr that calls it.
Eli Friedman2fb85122012-03-01 01:30:04 +00002561 CXXConversionDecl *Conv = cast<CXXConversionDecl>(Method);
2562 ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Conv,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00002563 HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +00002564 if (Result.isInvalid())
2565 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00002566 // Record usage of conversion in an implicit cast.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002567 Result = ImplicitCastExpr::Create(S.Context, Result.get()->getType(),
2568 CK_UserDefinedConversion, Result.get(),
2569 nullptr, Result.get()->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002570
Craig Topperc3ec1492014-05-26 06:22:03 +00002571 S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ nullptr, FoundDecl);
John McCall30909032011-09-21 08:36:56 +00002572
Douglas Gregor668443e2011-01-20 00:18:04 +00002573 return S.MaybeBindToTemporary(Result.get());
Douglas Gregora4253922010-04-16 22:17:36 +00002574 }
2575 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002576}
Douglas Gregora4253922010-04-16 22:17:36 +00002577
Douglas Gregor5fb53972009-01-14 15:45:31 +00002578/// PerformImplicitConversion - Perform an implicit conversion of the
2579/// expression From to the type ToType using the pre-computed implicit
John Wiegley01296292011-04-08 18:41:53 +00002580/// conversion sequence ICS. Returns the converted
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00002581/// expression. Action is the kind of conversion we're performing,
Douglas Gregor5fb53972009-01-14 15:45:31 +00002582/// used in the error message.
John Wiegley01296292011-04-08 18:41:53 +00002583ExprResult
2584Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor5fb53972009-01-14 15:45:31 +00002585 const ImplicitConversionSequence &ICS,
John McCall31168b02011-06-15 23:02:42 +00002586 AssignmentAction Action,
2587 CheckedConversionKind CCK) {
John McCall0d1da222010-01-12 00:44:57 +00002588 switch (ICS.getKind()) {
John Wiegley01296292011-04-08 18:41:53 +00002589 case ImplicitConversionSequence::StandardConversion: {
Richard Smith507840d2011-11-29 22:48:16 +00002590 ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard,
2591 Action, CCK);
John Wiegley01296292011-04-08 18:41:53 +00002592 if (Res.isInvalid())
2593 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002594 From = Res.get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00002595 break;
John Wiegley01296292011-04-08 18:41:53 +00002596 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00002597
Anders Carlsson110b07b2009-09-15 06:28:28 +00002598 case ImplicitConversionSequence::UserDefinedConversion: {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002599
Fariborz Jahanian2fee79a2009-08-28 22:04:50 +00002600 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
John McCall8cb679e2010-11-15 09:13:47 +00002601 CastKind CastKind;
Anders Carlsson110b07b2009-09-15 06:28:28 +00002602 QualType BeforeToType;
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00002603 assert(FD && "FIXME: aggregate initialization from init list");
Anders Carlsson110b07b2009-09-15 06:28:28 +00002604 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
John McCalle3027922010-08-25 11:45:40 +00002605 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002606
Anders Carlsson110b07b2009-09-15 06:28:28 +00002607 // If the user-defined conversion is specified by a conversion function,
2608 // the initial standard conversion sequence converts the source type to
2609 // the implicit object parameter of the conversion function.
2610 BeforeToType = Context.getTagDeclType(Conv->getParent());
John McCalla03edda2010-12-04 09:57:16 +00002611 } else {
2612 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
John McCalle3027922010-08-25 11:45:40 +00002613 CastKind = CK_ConstructorConversion;
Fariborz Jahanian55824512009-11-06 00:23:08 +00002614 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregor3153da72009-11-20 02:31:03 +00002615 if (!ICS.UserDefined.EllipsisConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002616 // If the user-defined conversion is specified by a constructor, the
Fariborz Jahanian55824512009-11-06 00:23:08 +00002617 // initial standard conversion sequence converts the source type to the
2618 // type required by the argument of the constructor
Douglas Gregor3153da72009-11-20 02:31:03 +00002619 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
2620 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002621 }
Richard Smith72d74052013-07-20 19:41:36 +00002622 // Watch out for ellipsis conversion.
Fariborz Jahanianeec642f2009-11-06 00:55:14 +00002623 if (!ICS.UserDefined.EllipsisConversion) {
John Wiegley01296292011-04-08 18:41:53 +00002624 ExprResult Res =
Richard Smith507840d2011-11-29 22:48:16 +00002625 PerformImplicitConversion(From, BeforeToType,
2626 ICS.UserDefined.Before, AA_Converting,
2627 CCK);
John Wiegley01296292011-04-08 18:41:53 +00002628 if (Res.isInvalid())
2629 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002630 From = Res.get();
Fariborz Jahanian55824512009-11-06 00:23:08 +00002631 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002632
2633 ExprResult CastArg
Douglas Gregora4253922010-04-16 22:17:36 +00002634 = BuildCXXCastArgument(*this,
2635 From->getLocStart(),
Anders Carlssone9766d52009-09-09 21:33:21 +00002636 ToType.getNonReferenceType(),
Douglas Gregor2bbfba02011-01-20 01:32:05 +00002637 CastKind, cast<CXXMethodDecl>(FD),
2638 ICS.UserDefined.FoundConversionFunction,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00002639 ICS.UserDefined.HadMultipleCandidates,
John McCallb268a282010-08-23 23:25:46 +00002640 From);
Anders Carlssone9766d52009-09-09 21:33:21 +00002641
2642 if (CastArg.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00002643 return ExprError();
Eli Friedmane96f1d32009-11-27 04:41:50 +00002644
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002645 From = CastArg.get();
Eli Friedmane96f1d32009-11-27 04:41:50 +00002646
Richard Smith507840d2011-11-29 22:48:16 +00002647 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
2648 AA_Converting, CCK);
Fariborz Jahanianda21efb2009-10-16 19:20:59 +00002649 }
John McCall0d1da222010-01-12 00:44:57 +00002650
2651 case ImplicitConversionSequence::AmbiguousConversion:
John McCall5c32be02010-08-24 20:38:10 +00002652 ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
John McCall0d1da222010-01-12 00:44:57 +00002653 PDiag(diag::err_typecheck_ambiguous_condition)
2654 << From->getSourceRange());
John Wiegley01296292011-04-08 18:41:53 +00002655 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002656
Douglas Gregor39c16d42008-10-24 04:54:22 +00002657 case ImplicitConversionSequence::EllipsisConversion:
David Blaikie83d382b2011-09-23 05:06:16 +00002658 llvm_unreachable("Cannot perform an ellipsis conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00002659
2660 case ImplicitConversionSequence::BadConversion:
John Wiegley01296292011-04-08 18:41:53 +00002661 return ExprError();
Douglas Gregor39c16d42008-10-24 04:54:22 +00002662 }
2663
2664 // Everything went well.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002665 return From;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002666}
2667
Richard Smith507840d2011-11-29 22:48:16 +00002668/// PerformImplicitConversion - Perform an implicit conversion of the
Douglas Gregor39c16d42008-10-24 04:54:22 +00002669/// expression From to the type ToType by following the standard
John Wiegley01296292011-04-08 18:41:53 +00002670/// conversion sequence SCS. Returns the converted
Douglas Gregor47d3f272008-12-19 17:40:08 +00002671/// expression. Flavor is the context in which we're performing this
2672/// conversion, for use in error messages.
John Wiegley01296292011-04-08 18:41:53 +00002673ExprResult
Richard Smith507840d2011-11-29 22:48:16 +00002674Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor47d3f272008-12-19 17:40:08 +00002675 const StandardConversionSequence& SCS,
John McCall31168b02011-06-15 23:02:42 +00002676 AssignmentAction Action,
2677 CheckedConversionKind CCK) {
2678 bool CStyle = (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast);
2679
Mike Stump87c57ac2009-05-16 07:39:55 +00002680 // Overall FIXME: we are recomputing too many types here and doing far too
2681 // much extra work. What this means is that we need to keep track of more
2682 // information that is computed when we try the implicit conversion initially,
2683 // so that we don't need to recompute anything here.
Douglas Gregor39c16d42008-10-24 04:54:22 +00002684 QualType FromType = From->getType();
John McCall31168b02011-06-15 23:02:42 +00002685
Douglas Gregor2fe98832008-11-03 19:09:14 +00002686 if (SCS.CopyConstructor) {
Anders Carlsson549c5bd2009-05-19 04:45:15 +00002687 // FIXME: When can ToType be a reference type?
2688 assert(!ToType->isReferenceType());
Fariborz Jahanian49850df2009-09-25 18:59:21 +00002689 if (SCS.Second == ICK_Derived_To_Base) {
Benjamin Kramerf0623432012-08-23 22:51:59 +00002690 SmallVector<Expr*, 8> ConstructorArgs;
Fariborz Jahanian49850df2009-09-25 18:59:21 +00002691 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002692 From, /*FIXME:ConstructLoc*/SourceLocation(),
Fariborz Jahanian49850df2009-09-25 18:59:21 +00002693 ConstructorArgs))
John Wiegley01296292011-04-08 18:41:53 +00002694 return ExprError();
2695 return BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
2696 ToType, SCS.CopyConstructor,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002697 ConstructorArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00002698 /*HadMultipleCandidates*/ false,
Richard Smithd59b8322012-12-19 01:39:02 +00002699 /*ListInit*/ false, /*ZeroInit*/ false,
John Wiegley01296292011-04-08 18:41:53 +00002700 CXXConstructExpr::CK_Complete,
2701 SourceRange());
Fariborz Jahanian49850df2009-09-25 18:59:21 +00002702 }
John Wiegley01296292011-04-08 18:41:53 +00002703 return BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
2704 ToType, SCS.CopyConstructor,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002705 From, /*HadMultipleCandidates*/ false,
Richard Smithd59b8322012-12-19 01:39:02 +00002706 /*ListInit*/ false, /*ZeroInit*/ false,
John Wiegley01296292011-04-08 18:41:53 +00002707 CXXConstructExpr::CK_Complete,
2708 SourceRange());
Douglas Gregor2fe98832008-11-03 19:09:14 +00002709 }
2710
Douglas Gregor980fb162010-04-29 18:24:40 +00002711 // Resolve overloaded function references.
2712 if (Context.hasSameType(FromType, Context.OverloadTy)) {
2713 DeclAccessPair Found;
2714 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
2715 true, Found);
2716 if (!Fn)
John Wiegley01296292011-04-08 18:41:53 +00002717 return ExprError();
Douglas Gregor980fb162010-04-29 18:24:40 +00002718
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002719 if (DiagnoseUseOfDecl(Fn, From->getLocStart()))
John Wiegley01296292011-04-08 18:41:53 +00002720 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002721
Douglas Gregor980fb162010-04-29 18:24:40 +00002722 From = FixOverloadedFunctionReference(From, Found, Fn);
2723 FromType = From->getType();
2724 }
2725
Richard Smitha23ab512013-05-23 00:30:41 +00002726 // If we're converting to an atomic type, first convert to the corresponding
2727 // non-atomic type.
2728 QualType ToAtomicType;
2729 if (const AtomicType *ToAtomic = ToType->getAs<AtomicType>()) {
2730 ToAtomicType = ToType;
2731 ToType = ToAtomic->getValueType();
2732 }
2733
Richard Smith507840d2011-11-29 22:48:16 +00002734 // Perform the first implicit conversion.
Douglas Gregor39c16d42008-10-24 04:54:22 +00002735 switch (SCS.First) {
2736 case ICK_Identity:
Douglas Gregor39c16d42008-10-24 04:54:22 +00002737 // Nothing to do.
2738 break;
2739
Eli Friedman946b7b52012-01-24 22:51:26 +00002740 case ICK_Lvalue_To_Rvalue: {
John McCall526ab472011-10-25 17:37:35 +00002741 assert(From->getObjectKind() != OK_ObjCProperty);
John McCall34376a62010-12-04 03:47:34 +00002742 FromType = FromType.getUnqualifiedType();
Eli Friedman946b7b52012-01-24 22:51:26 +00002743 ExprResult FromRes = DefaultLvalueConversion(From);
2744 assert(!FromRes.isInvalid() && "Can't perform deduced conversion?!");
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002745 From = FromRes.get();
John McCall34376a62010-12-04 03:47:34 +00002746 break;
Eli Friedman946b7b52012-01-24 22:51:26 +00002747 }
John McCall34376a62010-12-04 03:47:34 +00002748
Douglas Gregor39c16d42008-10-24 04:54:22 +00002749 case ICK_Array_To_Pointer:
Douglas Gregor171c45a2009-02-18 21:56:37 +00002750 FromType = Context.getArrayDecayedType(FromType);
Richard Smith507840d2011-11-29 22:48:16 +00002751 From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002752 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor171c45a2009-02-18 21:56:37 +00002753 break;
2754
2755 case ICK_Function_To_Pointer:
Douglas Gregor39c16d42008-10-24 04:54:22 +00002756 FromType = Context.getPointerType(FromType);
Richard Smith507840d2011-11-29 22:48:16 +00002757 From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002758 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00002759 break;
2760
2761 default:
David Blaikie83d382b2011-09-23 05:06:16 +00002762 llvm_unreachable("Improper first standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00002763 }
2764
Richard Smith507840d2011-11-29 22:48:16 +00002765 // Perform the second implicit conversion
Douglas Gregor39c16d42008-10-24 04:54:22 +00002766 switch (SCS.Second) {
2767 case ICK_Identity:
Sebastian Redl5d431642009-10-10 12:04:10 +00002768 // If both sides are functions (or pointers/references to them), there could
2769 // be incompatible exception declarations.
2770 if (CheckExceptionSpecCompatibility(From, ToType))
John Wiegley01296292011-04-08 18:41:53 +00002771 return ExprError();
Sebastian Redl5d431642009-10-10 12:04:10 +00002772 // Nothing else to do.
Douglas Gregor39c16d42008-10-24 04:54:22 +00002773 break;
2774
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00002775 case ICK_NoReturn_Adjustment:
2776 // If both sides are functions (or pointers/references to them), there could
2777 // be incompatible exception declarations.
2778 if (CheckExceptionSpecCompatibility(From, ToType))
John Wiegley01296292011-04-08 18:41:53 +00002779 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002780
Richard Smith507840d2011-11-29 22:48:16 +00002781 From = ImpCastExprToType(From, ToType, CK_NoOp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002782 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00002783 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002784
Douglas Gregor39c16d42008-10-24 04:54:22 +00002785 case ICK_Integral_Promotion:
Douglas Gregor39c16d42008-10-24 04:54:22 +00002786 case ICK_Integral_Conversion:
Richard Smithb9c5a602012-09-13 21:18:54 +00002787 if (ToType->isBooleanType()) {
2788 assert(FromType->castAs<EnumType>()->getDecl()->isFixed() &&
2789 SCS.Second == ICK_Integral_Promotion &&
2790 "only enums with fixed underlying type can promote to bool");
2791 From = ImpCastExprToType(From, ToType, CK_IntegralToBoolean,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002792 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Richard Smithb9c5a602012-09-13 21:18:54 +00002793 } else {
2794 From = ImpCastExprToType(From, ToType, CK_IntegralCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002795 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Richard Smithb9c5a602012-09-13 21:18:54 +00002796 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00002797 break;
2798
2799 case ICK_Floating_Promotion:
Douglas Gregor39c16d42008-10-24 04:54:22 +00002800 case ICK_Floating_Conversion:
Richard Smith507840d2011-11-29 22:48:16 +00002801 From = ImpCastExprToType(From, ToType, CK_FloatingCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002802 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00002803 break;
2804
2805 case ICK_Complex_Promotion:
John McCall8cb679e2010-11-15 09:13:47 +00002806 case ICK_Complex_Conversion: {
2807 QualType FromEl = From->getType()->getAs<ComplexType>()->getElementType();
2808 QualType ToEl = ToType->getAs<ComplexType>()->getElementType();
2809 CastKind CK;
2810 if (FromEl->isRealFloatingType()) {
2811 if (ToEl->isRealFloatingType())
2812 CK = CK_FloatingComplexCast;
2813 else
2814 CK = CK_FloatingComplexToIntegralComplex;
2815 } else if (ToEl->isRealFloatingType()) {
2816 CK = CK_IntegralComplexToFloatingComplex;
2817 } else {
2818 CK = CK_IntegralComplexCast;
2819 }
Richard Smith507840d2011-11-29 22:48:16 +00002820 From = ImpCastExprToType(From, ToType, CK,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002821 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00002822 break;
John McCall8cb679e2010-11-15 09:13:47 +00002823 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00002824
Douglas Gregor39c16d42008-10-24 04:54:22 +00002825 case ICK_Floating_Integral:
Douglas Gregor49b4d732010-06-22 23:07:26 +00002826 if (ToType->isRealFloatingType())
Richard Smith507840d2011-11-29 22:48:16 +00002827 From = ImpCastExprToType(From, ToType, CK_IntegralToFloating,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002828 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00002829 else
Richard Smith507840d2011-11-29 22:48:16 +00002830 From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002831 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00002832 break;
2833
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002834 case ICK_Compatible_Conversion:
Richard Smith507840d2011-11-29 22:48:16 +00002835 From = ImpCastExprToType(From, ToType, CK_NoOp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002836 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00002837 break;
2838
John McCall31168b02011-06-15 23:02:42 +00002839 case ICK_Writeback_Conversion:
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002840 case ICK_Pointer_Conversion: {
Douglas Gregor6dd3a6a2010-12-02 21:47:04 +00002841 if (SCS.IncompatibleObjC && Action != AA_Casting) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00002842 // Diagnose incompatible Objective-C conversions
Douglas Gregor2720dc62011-06-11 04:42:12 +00002843 if (Action == AA_Initializing || Action == AA_Assigning)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002844 Diag(From->getLocStart(),
Fariborz Jahanian413e0642011-03-21 19:08:42 +00002845 diag::ext_typecheck_convert_incompatible_pointer)
2846 << ToType << From->getType() << Action
Anna Zaks3b402712011-07-28 19:51:27 +00002847 << From->getSourceRange() << 0;
Fariborz Jahanian413e0642011-03-21 19:08:42 +00002848 else
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002849 Diag(From->getLocStart(),
Fariborz Jahanian413e0642011-03-21 19:08:42 +00002850 diag::ext_typecheck_convert_incompatible_pointer)
2851 << From->getType() << ToType << Action
Anna Zaks3b402712011-07-28 19:51:27 +00002852 << From->getSourceRange() << 0;
John McCall31168b02011-06-15 23:02:42 +00002853
Douglas Gregor33823722011-06-11 01:09:30 +00002854 if (From->getType()->isObjCObjectPointerType() &&
2855 ToType->isObjCObjectPointerType())
2856 EmitRelatedResultTypeNote(From);
Fariborz Jahanianf2913402011-07-08 17:41:42 +00002857 }
David Blaikiebbafb8a2012-03-11 07:00:24 +00002858 else if (getLangOpts().ObjCAutoRefCount &&
Fariborz Jahanianf2913402011-07-08 17:41:42 +00002859 !CheckObjCARCUnavailableWeakConversion(ToType,
2860 From->getType())) {
John McCall9c3467e2011-09-09 06:12:06 +00002861 if (Action == AA_Initializing)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002862 Diag(From->getLocStart(),
John McCall9c3467e2011-09-09 06:12:06 +00002863 diag::err_arc_weak_unavailable_assign);
2864 else
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002865 Diag(From->getLocStart(),
John McCall9c3467e2011-09-09 06:12:06 +00002866 diag::err_arc_convesion_of_weak_unavailable)
2867 << (Action == AA_Casting) << From->getType() << ToType
2868 << From->getSourceRange();
2869 }
Fariborz Jahanianf2913402011-07-08 17:41:42 +00002870
John McCall8cb679e2010-11-15 09:13:47 +00002871 CastKind Kind = CK_Invalid;
John McCallcf142162010-08-07 06:22:56 +00002872 CXXCastPath BasePath;
Douglas Gregor58281352011-01-27 00:58:17 +00002873 if (CheckPointerConversion(From, ToType, Kind, BasePath, CStyle))
John Wiegley01296292011-04-08 18:41:53 +00002874 return ExprError();
John McCallcd78e802011-09-10 01:16:55 +00002875
2876 // Make sure we extend blocks if necessary.
2877 // FIXME: doing this here is really ugly.
2878 if (Kind == CK_BlockPointerToObjCPointerCast) {
2879 ExprResult E = From;
2880 (void) PrepareCastToObjCObjectPointer(E);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002881 From = E.get();
John McCallcd78e802011-09-10 01:16:55 +00002882 }
Fariborz Jahanian374089e2013-07-31 17:12:26 +00002883 if (getLangOpts().ObjCAutoRefCount)
2884 CheckObjCARCConversion(SourceRange(), ToType, From, CCK);
Richard Smith507840d2011-11-29 22:48:16 +00002885 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002886 .get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00002887 break;
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002888 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002889
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002890 case ICK_Pointer_Member: {
John McCall8cb679e2010-11-15 09:13:47 +00002891 CastKind Kind = CK_Invalid;
John McCallcf142162010-08-07 06:22:56 +00002892 CXXCastPath BasePath;
Douglas Gregor58281352011-01-27 00:58:17 +00002893 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
John Wiegley01296292011-04-08 18:41:53 +00002894 return ExprError();
Sebastian Redl5d431642009-10-10 12:04:10 +00002895 if (CheckExceptionSpecCompatibility(From, ToType))
John Wiegley01296292011-04-08 18:41:53 +00002896 return ExprError();
Richard Smith507840d2011-11-29 22:48:16 +00002897 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002898 .get();
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002899 break;
2900 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002901
Abramo Bagnara7ccce982011-04-07 09:26:19 +00002902 case ICK_Boolean_Conversion:
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00002903 // Perform half-to-boolean conversion via float.
2904 if (From->getType()->isHalfType()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002905 From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).get();
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00002906 FromType = Context.FloatTy;
2907 }
2908
Richard Smith507840d2011-11-29 22:48:16 +00002909 From = ImpCastExprToType(From, Context.BoolTy,
2910 ScalarTypeToBooleanCastKind(FromType),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002911 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00002912 break;
2913
Douglas Gregor88d292c2010-05-13 16:44:06 +00002914 case ICK_Derived_To_Base: {
John McCallcf142162010-08-07 06:22:56 +00002915 CXXCastPath BasePath;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002916 if (CheckDerivedToBaseConversion(From->getType(),
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00002917 ToType.getNonReferenceType(),
2918 From->getLocStart(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002919 From->getSourceRange(),
Douglas Gregor88d292c2010-05-13 16:44:06 +00002920 &BasePath,
Douglas Gregor58281352011-01-27 00:58:17 +00002921 CStyle))
John Wiegley01296292011-04-08 18:41:53 +00002922 return ExprError();
Douglas Gregor88d292c2010-05-13 16:44:06 +00002923
Richard Smith507840d2011-11-29 22:48:16 +00002924 From = ImpCastExprToType(From, ToType.getNonReferenceType(),
2925 CK_DerivedToBase, From->getValueKind(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002926 &BasePath, CCK).get();
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00002927 break;
Douglas Gregor88d292c2010-05-13 16:44:06 +00002928 }
2929
Douglas Gregor46188682010-05-18 22:42:18 +00002930 case ICK_Vector_Conversion:
Richard Smith507840d2011-11-29 22:48:16 +00002931 From = ImpCastExprToType(From, ToType, CK_BitCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002932 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor46188682010-05-18 22:42:18 +00002933 break;
2934
2935 case ICK_Vector_Splat:
Richard Smith507840d2011-11-29 22:48:16 +00002936 From = ImpCastExprToType(From, ToType, CK_VectorSplat,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002937 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor46188682010-05-18 22:42:18 +00002938 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002939
Douglas Gregor46188682010-05-18 22:42:18 +00002940 case ICK_Complex_Real:
John McCall8cb679e2010-11-15 09:13:47 +00002941 // Case 1. x -> _Complex y
2942 if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
2943 QualType ElType = ToComplex->getElementType();
2944 bool isFloatingComplex = ElType->isRealFloatingType();
2945
2946 // x -> y
2947 if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
2948 // do nothing
2949 } else if (From->getType()->isRealFloatingType()) {
Richard Smith507840d2011-11-29 22:48:16 +00002950 From = ImpCastExprToType(From, ElType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002951 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).get();
John McCall8cb679e2010-11-15 09:13:47 +00002952 } else {
2953 assert(From->getType()->isIntegerType());
Richard Smith507840d2011-11-29 22:48:16 +00002954 From = ImpCastExprToType(From, ElType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002955 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).get();
John McCall8cb679e2010-11-15 09:13:47 +00002956 }
2957 // y -> _Complex y
Richard Smith507840d2011-11-29 22:48:16 +00002958 From = ImpCastExprToType(From, ToType,
2959 isFloatingComplex ? CK_FloatingRealToComplex
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002960 : CK_IntegralRealToComplex).get();
John McCall8cb679e2010-11-15 09:13:47 +00002961
2962 // Case 2. _Complex x -> y
2963 } else {
2964 const ComplexType *FromComplex = From->getType()->getAs<ComplexType>();
2965 assert(FromComplex);
2966
2967 QualType ElType = FromComplex->getElementType();
2968 bool isFloatingComplex = ElType->isRealFloatingType();
2969
2970 // _Complex x -> x
Richard Smith507840d2011-11-29 22:48:16 +00002971 From = ImpCastExprToType(From, ElType,
2972 isFloatingComplex ? CK_FloatingComplexToReal
2973 : CK_IntegralComplexToReal,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002974 VK_RValue, /*BasePath=*/nullptr, CCK).get();
John McCall8cb679e2010-11-15 09:13:47 +00002975
2976 // x -> y
2977 if (Context.hasSameUnqualifiedType(ElType, ToType)) {
2978 // do nothing
2979 } else if (ToType->isRealFloatingType()) {
Richard Smith507840d2011-11-29 22:48:16 +00002980 From = ImpCastExprToType(From, ToType,
2981 isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002982 VK_RValue, /*BasePath=*/nullptr, CCK).get();
John McCall8cb679e2010-11-15 09:13:47 +00002983 } else {
2984 assert(ToType->isIntegerType());
Richard Smith507840d2011-11-29 22:48:16 +00002985 From = ImpCastExprToType(From, ToType,
2986 isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002987 VK_RValue, /*BasePath=*/nullptr, CCK).get();
John McCall8cb679e2010-11-15 09:13:47 +00002988 }
2989 }
Douglas Gregor46188682010-05-18 22:42:18 +00002990 break;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002991
2992 case ICK_Block_Pointer_Conversion: {
Richard Smith507840d2011-11-29 22:48:16 +00002993 From = ImpCastExprToType(From, ToType.getUnqualifiedType(), CK_BitCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002994 VK_RValue, /*BasePath=*/nullptr, CCK).get();
John McCall31168b02011-06-15 23:02:42 +00002995 break;
2996 }
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002997
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00002998 case ICK_TransparentUnionConversion: {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002999 ExprResult FromRes = From;
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00003000 Sema::AssignConvertType ConvTy =
John Wiegley01296292011-04-08 18:41:53 +00003001 CheckTransparentUnionArgumentConstraints(ToType, FromRes);
3002 if (FromRes.isInvalid())
3003 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003004 From = FromRes.get();
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00003005 assert ((ConvTy == Sema::Compatible) &&
3006 "Improper transparent union conversion");
3007 (void)ConvTy;
3008 break;
3009 }
3010
Guy Benyei259f9f42013-02-07 16:05:33 +00003011 case ICK_Zero_Event_Conversion:
3012 From = ImpCastExprToType(From, ToType,
3013 CK_ZeroToOCLEvent,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003014 From->getValueKind()).get();
Guy Benyei259f9f42013-02-07 16:05:33 +00003015 break;
3016
Douglas Gregor46188682010-05-18 22:42:18 +00003017 case ICK_Lvalue_To_Rvalue:
3018 case ICK_Array_To_Pointer:
3019 case ICK_Function_To_Pointer:
3020 case ICK_Qualification:
3021 case ICK_Num_Conversion_Kinds:
David Blaikie83d382b2011-09-23 05:06:16 +00003022 llvm_unreachable("Improper second standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00003023 }
3024
3025 switch (SCS.Third) {
3026 case ICK_Identity:
3027 // Nothing to do.
3028 break;
3029
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003030 case ICK_Qualification: {
3031 // The qualification keeps the category of the inner expression, unless the
3032 // target type isn't a reference.
John McCall2536c6d2010-08-25 10:28:54 +00003033 ExprValueKind VK = ToType->isReferenceType() ?
Eli Friedmanbe4b3632011-09-27 21:58:52 +00003034 From->getValueKind() : VK_RValue;
Richard Smith507840d2011-11-29 22:48:16 +00003035 From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003036 CK_NoOp, VK, /*BasePath=*/nullptr, CCK).get();
Douglas Gregore489a7d2010-02-28 18:30:25 +00003037
Douglas Gregore981bb02011-03-14 16:13:32 +00003038 if (SCS.DeprecatedStringLiteralToCharPtr &&
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003039 !getLangOpts().WritableStrings) {
3040 Diag(From->getLocStart(), getLangOpts().CPlusPlus11
3041 ? diag::ext_deprecated_string_literal_conversion
3042 : diag::warn_deprecated_string_literal_conversion)
Douglas Gregore489a7d2010-02-28 18:30:25 +00003043 << ToType.getNonReferenceType();
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003044 }
Douglas Gregore489a7d2010-02-28 18:30:25 +00003045
Douglas Gregor39c16d42008-10-24 04:54:22 +00003046 break;
Richard Smitha23ab512013-05-23 00:30:41 +00003047 }
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003048
Douglas Gregor39c16d42008-10-24 04:54:22 +00003049 default:
David Blaikie83d382b2011-09-23 05:06:16 +00003050 llvm_unreachable("Improper third standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00003051 }
3052
Douglas Gregor298f43d2012-04-12 20:42:30 +00003053 // If this conversion sequence involved a scalar -> atomic conversion, perform
3054 // that conversion now.
Richard Smitha23ab512013-05-23 00:30:41 +00003055 if (!ToAtomicType.isNull()) {
3056 assert(Context.hasSameType(
3057 ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType()));
3058 From = ImpCastExprToType(From, ToAtomicType, CK_NonAtomicToAtomic,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003059 VK_RValue, nullptr, CCK).get();
Richard Smitha23ab512013-05-23 00:30:41 +00003060 }
3061
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003062 return From;
Douglas Gregor39c16d42008-10-24 04:54:22 +00003063}
3064
Chandler Carruth8e172c62011-05-01 06:51:22 +00003065/// \brief Check the completeness of a type in a unary type trait.
3066///
3067/// If the particular type trait requires a complete type, tries to complete
3068/// it. If completing the type fails, a diagnostic is emitted and false
3069/// returned. If completing the type succeeds or no completion was required,
3070/// returns true.
Alp Toker95e7ff22014-01-01 05:57:51 +00003071static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S, TypeTrait UTT,
Chandler Carruth8e172c62011-05-01 06:51:22 +00003072 SourceLocation Loc,
3073 QualType ArgTy) {
3074 // C++0x [meta.unary.prop]p3:
3075 // For all of the class templates X declared in this Clause, instantiating
3076 // that template with a template argument that is a class template
3077 // specialization may result in the implicit instantiation of the template
3078 // argument if and only if the semantics of X require that the argument
3079 // must be a complete type.
3080 // We apply this rule to all the type trait expressions used to implement
3081 // these class templates. We also try to follow any GCC documented behavior
3082 // in these expressions to ensure portability of standard libraries.
3083 switch (UTT) {
Alp Toker95e7ff22014-01-01 05:57:51 +00003084 default: llvm_unreachable("not a UTT");
Chandler Carruth8e172c62011-05-01 06:51:22 +00003085 // is_complete_type somewhat obviously cannot require a complete type.
3086 case UTT_IsCompleteType:
Chandler Carrutha62d8a52011-05-01 19:18:02 +00003087 // Fall-through
Chandler Carruth8e172c62011-05-01 06:51:22 +00003088
3089 // These traits are modeled on the type predicates in C++0x
3090 // [meta.unary.cat] and [meta.unary.comp]. They are not specified as
3091 // requiring a complete type, as whether or not they return true cannot be
3092 // impacted by the completeness of the type.
3093 case UTT_IsVoid:
3094 case UTT_IsIntegral:
3095 case UTT_IsFloatingPoint:
3096 case UTT_IsArray:
3097 case UTT_IsPointer:
3098 case UTT_IsLvalueReference:
3099 case UTT_IsRvalueReference:
3100 case UTT_IsMemberFunctionPointer:
3101 case UTT_IsMemberObjectPointer:
3102 case UTT_IsEnum:
3103 case UTT_IsUnion:
3104 case UTT_IsClass:
3105 case UTT_IsFunction:
3106 case UTT_IsReference:
3107 case UTT_IsArithmetic:
3108 case UTT_IsFundamental:
3109 case UTT_IsObject:
3110 case UTT_IsScalar:
3111 case UTT_IsCompound:
3112 case UTT_IsMemberPointer:
Chandler Carrutha62d8a52011-05-01 19:18:02 +00003113 // Fall-through
Chandler Carruth8e172c62011-05-01 06:51:22 +00003114
3115 // These traits are modeled on type predicates in C++0x [meta.unary.prop]
3116 // which requires some of its traits to have the complete type. However,
3117 // the completeness of the type cannot impact these traits' semantics, and
3118 // so they don't require it. This matches the comments on these traits in
3119 // Table 49.
3120 case UTT_IsConst:
3121 case UTT_IsVolatile:
3122 case UTT_IsSigned:
3123 case UTT_IsUnsigned:
3124 return true;
3125
3126 // C++0x [meta.unary.prop] Table 49 requires the following traits to be
Chandler Carrutha62d8a52011-05-01 19:18:02 +00003127 // applied to a complete type.
Chandler Carruth8e172c62011-05-01 06:51:22 +00003128 case UTT_IsTrivial:
Alexis Huntd9a5cc12011-05-13 00:31:07 +00003129 case UTT_IsTriviallyCopyable:
Chandler Carruth8e172c62011-05-01 06:51:22 +00003130 case UTT_IsStandardLayout:
3131 case UTT_IsPOD:
3132 case UTT_IsLiteral:
3133 case UTT_IsEmpty:
3134 case UTT_IsPolymorphic:
3135 case UTT_IsAbstract:
John McCallbf4a7d72012-09-25 07:32:49 +00003136 case UTT_IsInterfaceClass:
Alp Toker73287bf2014-01-20 00:24:09 +00003137 case UTT_IsDestructible:
3138 case UTT_IsNothrowDestructible:
Chandler Carrutha62d8a52011-05-01 19:18:02 +00003139 // Fall-through
Chandler Carruth8e172c62011-05-01 06:51:22 +00003140
Douglas Gregordca70af2011-12-03 18:14:24 +00003141 // These traits require a complete type.
3142 case UTT_IsFinal:
David Majnemera5433082013-10-18 00:33:31 +00003143 case UTT_IsSealed:
Douglas Gregordca70af2011-12-03 18:14:24 +00003144
Chandler Carrutha62d8a52011-05-01 19:18:02 +00003145 // These trait expressions are designed to help implement predicates in
Chandler Carruth8e172c62011-05-01 06:51:22 +00003146 // [meta.unary.prop] despite not being named the same. They are specified
3147 // by both GCC and the Embarcadero C++ compiler, and require the complete
3148 // type due to the overarching C++0x type predicates being implemented
3149 // requiring the complete type.
3150 case UTT_HasNothrowAssign:
Joao Matosc9523d42013-03-27 01:34:16 +00003151 case UTT_HasNothrowMoveAssign:
Chandler Carruth8e172c62011-05-01 06:51:22 +00003152 case UTT_HasNothrowConstructor:
3153 case UTT_HasNothrowCopy:
3154 case UTT_HasTrivialAssign:
Joao Matosc9523d42013-03-27 01:34:16 +00003155 case UTT_HasTrivialMoveAssign:
Alexis Huntf479f1b2011-05-09 18:22:59 +00003156 case UTT_HasTrivialDefaultConstructor:
Joao Matosc9523d42013-03-27 01:34:16 +00003157 case UTT_HasTrivialMoveConstructor:
Chandler Carruth8e172c62011-05-01 06:51:22 +00003158 case UTT_HasTrivialCopy:
3159 case UTT_HasTrivialDestructor:
3160 case UTT_HasVirtualDestructor:
3161 // Arrays of unknown bound are expressly allowed.
3162 QualType ElTy = ArgTy;
3163 if (ArgTy->isIncompleteArrayType())
3164 ElTy = S.Context.getAsArrayType(ArgTy)->getElementType();
3165
3166 // The void type is expressly allowed.
3167 if (ElTy->isVoidType())
3168 return true;
3169
3170 return !S.RequireCompleteType(
3171 Loc, ElTy, diag::err_incomplete_type_used_in_type_trait_expr);
John Wiegleyd3522222011-04-28 02:06:46 +00003172 }
Chandler Carruth8e172c62011-05-01 06:51:22 +00003173}
3174
Joao Matosc9523d42013-03-27 01:34:16 +00003175static bool HasNoThrowOperator(const RecordType *RT, OverloadedOperatorKind Op,
3176 Sema &Self, SourceLocation KeyLoc, ASTContext &C,
3177 bool (CXXRecordDecl::*HasTrivial)() const,
3178 bool (CXXRecordDecl::*HasNonTrivial)() const,
3179 bool (CXXMethodDecl::*IsDesiredOp)() const)
3180{
3181 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
3182 if ((RD->*HasTrivial)() && !(RD->*HasNonTrivial)())
3183 return true;
3184
3185 DeclarationName Name = C.DeclarationNames.getCXXOperatorName(Op);
3186 DeclarationNameInfo NameInfo(Name, KeyLoc);
3187 LookupResult Res(Self, NameInfo, Sema::LookupOrdinaryName);
3188 if (Self.LookupQualifiedName(Res, RD)) {
3189 bool FoundOperator = false;
3190 Res.suppressDiagnostics();
3191 for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
3192 Op != OpEnd; ++Op) {
3193 if (isa<FunctionTemplateDecl>(*Op))
3194 continue;
3195
3196 CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
3197 if((Operator->*IsDesiredOp)()) {
3198 FoundOperator = true;
3199 const FunctionProtoType *CPT =
3200 Operator->getType()->getAs<FunctionProtoType>();
3201 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
Alp Toker73287bf2014-01-20 00:24:09 +00003202 if (!CPT || !CPT->isNothrow(C))
Joao Matosc9523d42013-03-27 01:34:16 +00003203 return false;
3204 }
3205 }
3206 return FoundOperator;
3207 }
3208 return false;
3209}
3210
Alp Toker95e7ff22014-01-01 05:57:51 +00003211static bool EvaluateUnaryTypeTrait(Sema &Self, TypeTrait UTT,
Chandler Carruth8e172c62011-05-01 06:51:22 +00003212 SourceLocation KeyLoc, QualType T) {
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00003213 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
John Wiegleyd3522222011-04-28 02:06:46 +00003214
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003215 ASTContext &C = Self.Context;
3216 switch(UTT) {
Alp Toker95e7ff22014-01-01 05:57:51 +00003217 default: llvm_unreachable("not a UTT");
Chandler Carruthd2479ea2011-05-01 06:11:07 +00003218 // Type trait expressions corresponding to the primary type category
3219 // predicates in C++0x [meta.unary.cat].
3220 case UTT_IsVoid:
3221 return T->isVoidType();
3222 case UTT_IsIntegral:
3223 return T->isIntegralType(C);
3224 case UTT_IsFloatingPoint:
3225 return T->isFloatingType();
3226 case UTT_IsArray:
3227 return T->isArrayType();
3228 case UTT_IsPointer:
3229 return T->isPointerType();
3230 case UTT_IsLvalueReference:
3231 return T->isLValueReferenceType();
3232 case UTT_IsRvalueReference:
3233 return T->isRValueReferenceType();
3234 case UTT_IsMemberFunctionPointer:
3235 return T->isMemberFunctionPointerType();
3236 case UTT_IsMemberObjectPointer:
3237 return T->isMemberDataPointerType();
3238 case UTT_IsEnum:
3239 return T->isEnumeralType();
Chandler Carruth100f3a92011-05-01 06:11:03 +00003240 case UTT_IsUnion:
Chandler Carruthaf858862011-05-01 09:29:58 +00003241 return T->isUnionType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00003242 case UTT_IsClass:
Joao Matosdc86f942012-08-31 18:45:21 +00003243 return T->isClassType() || T->isStructureType() || T->isInterfaceType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00003244 case UTT_IsFunction:
3245 return T->isFunctionType();
3246
3247 // Type trait expressions which correspond to the convenient composition
3248 // predicates in C++0x [meta.unary.comp].
3249 case UTT_IsReference:
3250 return T->isReferenceType();
3251 case UTT_IsArithmetic:
Chandler Carruthaf858862011-05-01 09:29:58 +00003252 return T->isArithmeticType() && !T->isEnumeralType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00003253 case UTT_IsFundamental:
Chandler Carruthaf858862011-05-01 09:29:58 +00003254 return T->isFundamentalType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00003255 case UTT_IsObject:
Chandler Carruthaf858862011-05-01 09:29:58 +00003256 return T->isObjectType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00003257 case UTT_IsScalar:
John McCall31168b02011-06-15 23:02:42 +00003258 // Note: semantic analysis depends on Objective-C lifetime types to be
3259 // considered scalar types. However, such types do not actually behave
3260 // like scalar types at run time (since they may require retain/release
3261 // operations), so we report them as non-scalar.
3262 if (T->isObjCLifetimeType()) {
3263 switch (T.getObjCLifetime()) {
3264 case Qualifiers::OCL_None:
3265 case Qualifiers::OCL_ExplicitNone:
3266 return true;
3267
3268 case Qualifiers::OCL_Strong:
3269 case Qualifiers::OCL_Weak:
3270 case Qualifiers::OCL_Autoreleasing:
3271 return false;
3272 }
3273 }
3274
Chandler Carruth7ba7bd32011-05-01 09:29:55 +00003275 return T->isScalarType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00003276 case UTT_IsCompound:
Chandler Carruthaf858862011-05-01 09:29:58 +00003277 return T->isCompoundType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00003278 case UTT_IsMemberPointer:
3279 return T->isMemberPointerType();
3280
3281 // Type trait expressions which correspond to the type property predicates
3282 // in C++0x [meta.unary.prop].
3283 case UTT_IsConst:
3284 return T.isConstQualified();
3285 case UTT_IsVolatile:
3286 return T.isVolatileQualified();
3287 case UTT_IsTrivial:
John McCall31168b02011-06-15 23:02:42 +00003288 return T.isTrivialType(Self.Context);
Alexis Huntd9a5cc12011-05-13 00:31:07 +00003289 case UTT_IsTriviallyCopyable:
John McCall31168b02011-06-15 23:02:42 +00003290 return T.isTriviallyCopyableType(Self.Context);
Chandler Carruthd2479ea2011-05-01 06:11:07 +00003291 case UTT_IsStandardLayout:
3292 return T->isStandardLayoutType();
3293 case UTT_IsPOD:
Benjamin Kramera3c0dad2012-04-28 10:00:33 +00003294 return T.isPODType(Self.Context);
Chandler Carruthd2479ea2011-05-01 06:11:07 +00003295 case UTT_IsLiteral:
Richard Smithd9f663b2013-04-22 15:31:51 +00003296 return T->isLiteralType(Self.Context);
Chandler Carruthd2479ea2011-05-01 06:11:07 +00003297 case UTT_IsEmpty:
3298 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3299 return !RD->isUnion() && RD->isEmpty();
3300 return false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003301 case UTT_IsPolymorphic:
Chandler Carruth100f3a92011-05-01 06:11:03 +00003302 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3303 return RD->isPolymorphic();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003304 return false;
3305 case UTT_IsAbstract:
Chandler Carruth100f3a92011-05-01 06:11:03 +00003306 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3307 return RD->isAbstract();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003308 return false;
John McCallbf4a7d72012-09-25 07:32:49 +00003309 case UTT_IsInterfaceClass:
3310 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3311 return RD->isInterface();
3312 return false;
Douglas Gregordca70af2011-12-03 18:14:24 +00003313 case UTT_IsFinal:
3314 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3315 return RD->hasAttr<FinalAttr>();
3316 return false;
David Majnemera5433082013-10-18 00:33:31 +00003317 case UTT_IsSealed:
3318 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3319 if (FinalAttr *FA = RD->getAttr<FinalAttr>())
3320 return FA->isSpelledAsSealed();
3321 return false;
John Wiegley65497cc2011-04-27 23:09:49 +00003322 case UTT_IsSigned:
3323 return T->isSignedIntegerType();
John Wiegley65497cc2011-04-27 23:09:49 +00003324 case UTT_IsUnsigned:
3325 return T->isUnsignedIntegerType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00003326
3327 // Type trait expressions which query classes regarding their construction,
3328 // destruction, and copying. Rather than being based directly on the
3329 // related type predicates in the standard, they are specified by both
3330 // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those
3331 // specifications.
3332 //
3333 // 1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html
3334 // 2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
Richard Smith92f241f2012-12-08 02:53:02 +00003335 //
3336 // Note that these builtins do not behave as documented in g++: if a class
3337 // has both a trivial and a non-trivial special member of a particular kind,
3338 // they return false! For now, we emulate this behavior.
3339 // FIXME: This appears to be a g++ bug: more complex cases reveal that it
3340 // does not correctly compute triviality in the presence of multiple special
3341 // members of the same kind. Revisit this once the g++ bug is fixed.
Alexis Huntf479f1b2011-05-09 18:22:59 +00003342 case UTT_HasTrivialDefaultConstructor:
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003343 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3344 // If __is_pod (type) is true then the trait is true, else if type is
3345 // a cv class or union type (or array thereof) with a trivial default
3346 // constructor ([class.ctor]) then the trait is true, else it is false.
John McCall31168b02011-06-15 23:02:42 +00003347 if (T.isPODType(Self.Context))
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003348 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00003349 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
3350 return RD->hasTrivialDefaultConstructor() &&
3351 !RD->hasNonTrivialDefaultConstructor();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003352 return false;
Joao Matosc9523d42013-03-27 01:34:16 +00003353 case UTT_HasTrivialMoveConstructor:
3354 // This trait is implemented by MSVC 2012 and needed to parse the
3355 // standard library headers. Specifically this is used as the logic
3356 // behind std::is_trivially_move_constructible (20.9.4.3).
3357 if (T.isPODType(Self.Context))
3358 return true;
3359 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
3360 return RD->hasTrivialMoveConstructor() && !RD->hasNonTrivialMoveConstructor();
3361 return false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003362 case UTT_HasTrivialCopy:
3363 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3364 // If __is_pod (type) is true or type is a reference type then
3365 // the trait is true, else if type is a cv class or union type
3366 // with a trivial copy constructor ([class.copy]) then the trait
3367 // is true, else it is false.
John McCall31168b02011-06-15 23:02:42 +00003368 if (T.isPODType(Self.Context) || T->isReferenceType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003369 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00003370 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3371 return RD->hasTrivialCopyConstructor() &&
3372 !RD->hasNonTrivialCopyConstructor();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003373 return false;
Joao Matosc9523d42013-03-27 01:34:16 +00003374 case UTT_HasTrivialMoveAssign:
3375 // This trait is implemented by MSVC 2012 and needed to parse the
3376 // standard library headers. Specifically it is used as the logic
3377 // behind std::is_trivially_move_assignable (20.9.4.3)
3378 if (T.isPODType(Self.Context))
3379 return true;
3380 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
3381 return RD->hasTrivialMoveAssignment() && !RD->hasNonTrivialMoveAssignment();
3382 return false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003383 case UTT_HasTrivialAssign:
3384 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3385 // If type is const qualified or is a reference type then the
3386 // trait is false. Otherwise if __is_pod (type) is true then the
3387 // trait is true, else if type is a cv class or union type with
3388 // a trivial copy assignment ([class.copy]) then the trait is
3389 // true, else it is false.
3390 // Note: the const and reference restrictions are interesting,
3391 // given that const and reference members don't prevent a class
3392 // from having a trivial copy assignment operator (but do cause
3393 // errors if the copy assignment operator is actually used, q.v.
3394 // [class.copy]p12).
3395
Richard Smith92f241f2012-12-08 02:53:02 +00003396 if (T.isConstQualified())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003397 return false;
John McCall31168b02011-06-15 23:02:42 +00003398 if (T.isPODType(Self.Context))
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003399 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00003400 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3401 return RD->hasTrivialCopyAssignment() &&
3402 !RD->hasNonTrivialCopyAssignment();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003403 return false;
Alp Toker73287bf2014-01-20 00:24:09 +00003404 case UTT_IsDestructible:
3405 case UTT_IsNothrowDestructible:
3406 // FIXME: Implement UTT_IsDestructible and UTT_IsNothrowDestructible.
3407 // For now, let's fall through.
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003408 case UTT_HasTrivialDestructor:
Alp Toker73287bf2014-01-20 00:24:09 +00003409 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003410 // If __is_pod (type) is true or type is a reference type
3411 // then the trait is true, else if type is a cv class or union
3412 // type (or array thereof) with a trivial destructor
3413 // ([class.dtor]) then the trait is true, else it is
3414 // false.
John McCall31168b02011-06-15 23:02:42 +00003415 if (T.isPODType(Self.Context) || T->isReferenceType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003416 return true;
John McCall31168b02011-06-15 23:02:42 +00003417
3418 // Objective-C++ ARC: autorelease types don't require destruction.
3419 if (T->isObjCLifetimeType() &&
3420 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
3421 return true;
3422
Richard Smith92f241f2012-12-08 02:53:02 +00003423 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
3424 return RD->hasTrivialDestructor();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003425 return false;
3426 // TODO: Propagate nothrowness for implicitly declared special members.
3427 case UTT_HasNothrowAssign:
3428 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3429 // If type is const qualified or is a reference type then the
3430 // trait is false. Otherwise if __has_trivial_assign (type)
3431 // is true then the trait is true, else if type is a cv class
3432 // or union type with copy assignment operators that are known
3433 // not to throw an exception then the trait is true, else it is
3434 // false.
3435 if (C.getBaseElementType(T).isConstQualified())
3436 return false;
3437 if (T->isReferenceType())
3438 return false;
John McCall31168b02011-06-15 23:02:42 +00003439 if (T.isPODType(Self.Context) || T->isObjCLifetimeType())
Joao Matosc9523d42013-03-27 01:34:16 +00003440 return true;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003441
Joao Matosc9523d42013-03-27 01:34:16 +00003442 if (const RecordType *RT = T->getAs<RecordType>())
3443 return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
3444 &CXXRecordDecl::hasTrivialCopyAssignment,
3445 &CXXRecordDecl::hasNonTrivialCopyAssignment,
3446 &CXXMethodDecl::isCopyAssignmentOperator);
3447 return false;
3448 case UTT_HasNothrowMoveAssign:
3449 // This trait is implemented by MSVC 2012 and needed to parse the
3450 // standard library headers. Specifically this is used as the logic
3451 // behind std::is_nothrow_move_assignable (20.9.4.3).
3452 if (T.isPODType(Self.Context))
3453 return true;
3454
3455 if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>())
3456 return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
3457 &CXXRecordDecl::hasTrivialMoveAssignment,
3458 &CXXRecordDecl::hasNonTrivialMoveAssignment,
3459 &CXXMethodDecl::isMoveAssignmentOperator);
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003460 return false;
3461 case UTT_HasNothrowCopy:
3462 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3463 // If __has_trivial_copy (type) is true then the trait is true, else
3464 // if type is a cv class or union type with copy constructors that are
3465 // known not to throw an exception then the trait is true, else it is
3466 // false.
John McCall31168b02011-06-15 23:02:42 +00003467 if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003468 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00003469 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
3470 if (RD->hasTrivialCopyConstructor() &&
3471 !RD->hasNonTrivialCopyConstructor())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003472 return true;
3473
3474 bool FoundConstructor = false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003475 unsigned FoundTQs;
David Blaikieff7d47a2012-12-19 00:45:41 +00003476 DeclContext::lookup_const_result R = Self.LookupConstructors(RD);
3477 for (DeclContext::lookup_const_iterator Con = R.begin(),
3478 ConEnd = R.end(); Con != ConEnd; ++Con) {
Sebastian Redl5c649bc2010-09-13 22:18:28 +00003479 // A template constructor is never a copy constructor.
3480 // FIXME: However, it may actually be selected at the actual overload
3481 // resolution point.
3482 if (isa<FunctionTemplateDecl>(*Con))
3483 continue;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003484 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
3485 if (Constructor->isCopyConstructor(FoundTQs)) {
3486 FoundConstructor = true;
3487 const FunctionProtoType *CPT
3488 = Constructor->getType()->getAs<FunctionProtoType>();
Richard Smithf623c962012-04-17 00:58:00 +00003489 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
3490 if (!CPT)
3491 return false;
Alp Toker73287bf2014-01-20 00:24:09 +00003492 // TODO: check whether evaluating default arguments can throw.
Sebastian Redlc15c3262010-09-13 22:02:47 +00003493 // For now, we'll be conservative and assume that they can throw.
Alp Toker9cacbab2014-01-20 20:26:09 +00003494 if (!CPT->isNothrow(Self.Context) || CPT->getNumParams() > 1)
Richard Smith938f40b2011-06-11 17:19:42 +00003495 return false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003496 }
3497 }
3498
Richard Smith938f40b2011-06-11 17:19:42 +00003499 return FoundConstructor;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003500 }
3501 return false;
3502 case UTT_HasNothrowConstructor:
Alp Tokerb4bca412014-01-20 00:23:47 +00003503 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003504 // If __has_trivial_constructor (type) is true then the trait is
3505 // true, else if type is a cv class or union type (or array
3506 // thereof) with a default constructor that is known not to
3507 // throw an exception then the trait is true, else it is false.
John McCall31168b02011-06-15 23:02:42 +00003508 if (T.isPODType(C) || T->isObjCLifetimeType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003509 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00003510 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
3511 if (RD->hasTrivialDefaultConstructor() &&
3512 !RD->hasNonTrivialDefaultConstructor())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003513 return true;
3514
Alp Tokerb4bca412014-01-20 00:23:47 +00003515 bool FoundConstructor = false;
David Blaikieff7d47a2012-12-19 00:45:41 +00003516 DeclContext::lookup_const_result R = Self.LookupConstructors(RD);
3517 for (DeclContext::lookup_const_iterator Con = R.begin(),
3518 ConEnd = R.end(); Con != ConEnd; ++Con) {
Sebastian Redl5c649bc2010-09-13 22:18:28 +00003519 // FIXME: In C++0x, a constructor template can be a default constructor.
3520 if (isa<FunctionTemplateDecl>(*Con))
3521 continue;
Sebastian Redlc15c3262010-09-13 22:02:47 +00003522 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
3523 if (Constructor->isDefaultConstructor()) {
Alp Tokerb4bca412014-01-20 00:23:47 +00003524 FoundConstructor = true;
Sebastian Redlc15c3262010-09-13 22:02:47 +00003525 const FunctionProtoType *CPT
3526 = Constructor->getType()->getAs<FunctionProtoType>();
Richard Smithf623c962012-04-17 00:58:00 +00003527 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
3528 if (!CPT)
3529 return false;
Alp Tokerb4bca412014-01-20 00:23:47 +00003530 // FIXME: check whether evaluating default arguments can throw.
Sebastian Redlc15c3262010-09-13 22:02:47 +00003531 // For now, we'll be conservative and assume that they can throw.
Alp Toker9cacbab2014-01-20 20:26:09 +00003532 if (!CPT->isNothrow(Self.Context) || CPT->getNumParams() > 0)
Alp Tokerb4bca412014-01-20 00:23:47 +00003533 return false;
Sebastian Redlc15c3262010-09-13 22:02:47 +00003534 }
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003535 }
Alp Tokerb4bca412014-01-20 00:23:47 +00003536 return FoundConstructor;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003537 }
3538 return false;
3539 case UTT_HasVirtualDestructor:
3540 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3541 // If type is a class type with a virtual destructor ([class.dtor])
3542 // then the trait is true, else it is false.
Richard Smith92f241f2012-12-08 02:53:02 +00003543 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
Sebastian Redl058fc822010-09-14 23:40:14 +00003544 if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003545 return Destructor->isVirtual();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003546 return false;
Chandler Carruthd2479ea2011-05-01 06:11:07 +00003547
3548 // These type trait expressions are modeled on the specifications for the
3549 // Embarcadero C++0x type trait functions:
3550 // http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
3551 case UTT_IsCompleteType:
3552 // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_):
3553 // Returns True if and only if T is a complete type at the point of the
3554 // function call.
3555 return !T->isIncompleteType();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003556 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00003557}
Sebastian Redl5822f082009-02-07 20:10:22 +00003558
Douglas Gregor6bd56ca2012-06-29 00:49:17 +00003559/// \brief Determine whether T has a non-trivial Objective-C lifetime in
3560/// ARC mode.
3561static bool hasNontrivialObjCLifetime(QualType T) {
3562 switch (T.getObjCLifetime()) {
3563 case Qualifiers::OCL_ExplicitNone:
3564 return false;
3565
3566 case Qualifiers::OCL_Strong:
3567 case Qualifiers::OCL_Weak:
3568 case Qualifiers::OCL_Autoreleasing:
3569 return true;
3570
3571 case Qualifiers::OCL_None:
3572 return T->isObjCLifetimeType();
3573 }
3574
3575 llvm_unreachable("Unknown ObjC lifetime qualifier");
3576}
3577
Alp Tokercbb90342013-12-13 20:49:58 +00003578static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
3579 QualType RhsT, SourceLocation KeyLoc);
3580
Douglas Gregor29c42f22012-02-24 07:38:34 +00003581static bool evaluateTypeTrait(Sema &S, TypeTrait Kind, SourceLocation KWLoc,
3582 ArrayRef<TypeSourceInfo *> Args,
3583 SourceLocation RParenLoc) {
Alp Toker95e7ff22014-01-01 05:57:51 +00003584 if (Kind <= UTT_Last)
3585 return EvaluateUnaryTypeTrait(S, Kind, KWLoc, Args[0]->getType());
3586
Alp Tokercbb90342013-12-13 20:49:58 +00003587 if (Kind <= BTT_Last)
3588 return EvaluateBinaryTypeTrait(S, Kind, Args[0]->getType(),
3589 Args[1]->getType(), RParenLoc);
3590
Douglas Gregor29c42f22012-02-24 07:38:34 +00003591 switch (Kind) {
Alp Toker73287bf2014-01-20 00:24:09 +00003592 case clang::TT_IsConstructible:
3593 case clang::TT_IsNothrowConstructible:
Douglas Gregor29c42f22012-02-24 07:38:34 +00003594 case clang::TT_IsTriviallyConstructible: {
3595 // C++11 [meta.unary.prop]:
Dmitri Gribenko85e87642012-02-24 20:03:35 +00003596 // is_trivially_constructible is defined as:
Douglas Gregor29c42f22012-02-24 07:38:34 +00003597 //
Dmitri Gribenko85e87642012-02-24 20:03:35 +00003598 // is_constructible<T, Args...>::value is true and the variable
Richard Smith8b86f2d2013-11-04 01:48:18 +00003599 // definition for is_constructible, as defined below, is known to call
3600 // no operation that is not trivial.
Douglas Gregor29c42f22012-02-24 07:38:34 +00003601 //
3602 // The predicate condition for a template specialization
3603 // is_constructible<T, Args...> shall be satisfied if and only if the
3604 // following variable definition would be well-formed for some invented
3605 // variable t:
3606 //
3607 // T t(create<Args>()...);
Alp Toker40f9b1c2013-12-12 21:23:03 +00003608 assert(!Args.empty());
Eli Friedman9ea1e162013-09-11 02:53:02 +00003609
3610 // Precondition: T and all types in the parameter pack Args shall be
3611 // complete types, (possibly cv-qualified) void, or arrays of
3612 // unknown bound.
Douglas Gregor29c42f22012-02-24 07:38:34 +00003613 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
Eli Friedman9ea1e162013-09-11 02:53:02 +00003614 QualType ArgTy = Args[I]->getType();
3615 if (ArgTy->isVoidType() || ArgTy->isIncompleteArrayType())
Douglas Gregor29c42f22012-02-24 07:38:34 +00003616 continue;
Eli Friedman9ea1e162013-09-11 02:53:02 +00003617
3618 if (S.RequireCompleteType(KWLoc, ArgTy,
Douglas Gregor29c42f22012-02-24 07:38:34 +00003619 diag::err_incomplete_type_used_in_type_trait_expr))
3620 return false;
3621 }
Eli Friedman9ea1e162013-09-11 02:53:02 +00003622
3623 // Make sure the first argument is a complete type.
3624 if (Args[0]->getType()->isIncompleteType())
Douglas Gregor29c42f22012-02-24 07:38:34 +00003625 return false;
Eli Friedman9ea1e162013-09-11 02:53:02 +00003626
Nikola Smiljanic1b4b6ba2014-04-15 11:30:15 +00003627 // Make sure the first argument is not an abstract type.
3628 CXXRecordDecl *RD = Args[0]->getType()->getAsCXXRecordDecl();
3629 if (RD && RD->isAbstract())
3630 return false;
3631
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003632 SmallVector<OpaqueValueExpr, 2> OpaqueArgExprs;
3633 SmallVector<Expr *, 2> ArgExprs;
Douglas Gregor29c42f22012-02-24 07:38:34 +00003634 ArgExprs.reserve(Args.size() - 1);
3635 for (unsigned I = 1, N = Args.size(); I != N; ++I) {
3636 QualType T = Args[I]->getType();
3637 if (T->isObjectType() || T->isFunctionType())
3638 T = S.Context.getRValueReferenceType(T);
3639 OpaqueArgExprs.push_back(
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003640 OpaqueValueExpr(Args[I]->getTypeLoc().getLocStart(),
Douglas Gregor29c42f22012-02-24 07:38:34 +00003641 T.getNonLValueExprType(S.Context),
3642 Expr::getValueKindForType(T)));
3643 ArgExprs.push_back(&OpaqueArgExprs.back());
3644 }
3645
3646 // Perform the initialization in an unevaluated context within a SFINAE
3647 // trap at translation unit scope.
3648 EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated);
3649 Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true);
3650 Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl());
3651 InitializedEntity To(InitializedEntity::InitializeTemporary(Args[0]));
3652 InitializationKind InitKind(InitializationKind::CreateDirect(KWLoc, KWLoc,
3653 RParenLoc));
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003654 InitializationSequence Init(S, To, InitKind, ArgExprs);
Douglas Gregor29c42f22012-02-24 07:38:34 +00003655 if (Init.Failed())
3656 return false;
Alp Toker73287bf2014-01-20 00:24:09 +00003657
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00003658 ExprResult Result = Init.Perform(S, To, InitKind, ArgExprs);
Douglas Gregor29c42f22012-02-24 07:38:34 +00003659 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
3660 return false;
Douglas Gregor6bd56ca2012-06-29 00:49:17 +00003661
Alp Toker73287bf2014-01-20 00:24:09 +00003662 if (Kind == clang::TT_IsConstructible)
3663 return true;
Douglas Gregor6bd56ca2012-06-29 00:49:17 +00003664
Alp Toker73287bf2014-01-20 00:24:09 +00003665 if (Kind == clang::TT_IsNothrowConstructible)
3666 return S.canThrow(Result.get()) == CT_Cannot;
3667
3668 if (Kind == clang::TT_IsTriviallyConstructible) {
3669 // Under Objective-C ARC, if the destination has non-trivial Objective-C
3670 // lifetime, this is a non-trivial construction.
3671 if (S.getLangOpts().ObjCAutoRefCount &&
3672 hasNontrivialObjCLifetime(Args[0]->getType().getNonReferenceType()))
3673 return false;
3674
3675 // The initialization succeeded; now make sure there are no non-trivial
3676 // calls.
3677 return !Result.get()->hasNonTrivialCall(S.Context);
3678 }
3679
3680 llvm_unreachable("unhandled type trait");
3681 return false;
Douglas Gregor29c42f22012-02-24 07:38:34 +00003682 }
Alp Tokercbb90342013-12-13 20:49:58 +00003683 default: llvm_unreachable("not a TT");
Douglas Gregor29c42f22012-02-24 07:38:34 +00003684 }
3685
3686 return false;
3687}
3688
3689ExprResult Sema::BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
3690 ArrayRef<TypeSourceInfo *> Args,
3691 SourceLocation RParenLoc) {
Alp Toker5294e6e2013-12-25 01:47:02 +00003692 QualType ResultType = Context.getLogicalOperationType();
Alp Tokercbb90342013-12-13 20:49:58 +00003693
Alp Toker95e7ff22014-01-01 05:57:51 +00003694 if (Kind <= UTT_Last && !CheckUnaryTypeTraitTypeCompleteness(
3695 *this, Kind, KWLoc, Args[0]->getType()))
3696 return ExprError();
3697
Douglas Gregor29c42f22012-02-24 07:38:34 +00003698 bool Dependent = false;
3699 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
3700 if (Args[I]->getType()->isDependentType()) {
3701 Dependent = true;
3702 break;
3703 }
3704 }
Alp Tokercbb90342013-12-13 20:49:58 +00003705
3706 bool Result = false;
Douglas Gregor29c42f22012-02-24 07:38:34 +00003707 if (!Dependent)
Alp Tokercbb90342013-12-13 20:49:58 +00003708 Result = evaluateTypeTrait(*this, Kind, KWLoc, Args, RParenLoc);
3709
3710 return TypeTraitExpr::Create(Context, ResultType, KWLoc, Kind, Args,
3711 RParenLoc, Result);
Douglas Gregor29c42f22012-02-24 07:38:34 +00003712}
3713
Alp Toker88f64e62013-12-13 21:19:30 +00003714ExprResult Sema::ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
3715 ArrayRef<ParsedType> Args,
Douglas Gregor29c42f22012-02-24 07:38:34 +00003716 SourceLocation RParenLoc) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003717 SmallVector<TypeSourceInfo *, 4> ConvertedArgs;
Douglas Gregor29c42f22012-02-24 07:38:34 +00003718 ConvertedArgs.reserve(Args.size());
3719
3720 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
3721 TypeSourceInfo *TInfo;
3722 QualType T = GetTypeFromParser(Args[I], &TInfo);
3723 if (!TInfo)
3724 TInfo = Context.getTrivialTypeSourceInfo(T, KWLoc);
3725
3726 ConvertedArgs.push_back(TInfo);
3727 }
Alp Tokercbb90342013-12-13 20:49:58 +00003728
Douglas Gregor29c42f22012-02-24 07:38:34 +00003729 return BuildTypeTrait(Kind, KWLoc, ConvertedArgs, RParenLoc);
3730}
3731
Alp Tokercbb90342013-12-13 20:49:58 +00003732static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
3733 QualType RhsT, SourceLocation KeyLoc) {
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00003734 assert(!LhsT->isDependentType() && !RhsT->isDependentType() &&
3735 "Cannot evaluate traits of dependent types");
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00003736
3737 switch(BTT) {
John McCall388ef532011-01-28 22:02:36 +00003738 case BTT_IsBaseOf: {
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00003739 // C++0x [meta.rel]p2
John McCall388ef532011-01-28 22:02:36 +00003740 // Base is a base class of Derived without regard to cv-qualifiers or
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00003741 // Base and Derived are not unions and name the same class type without
3742 // regard to cv-qualifiers.
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00003743
John McCall388ef532011-01-28 22:02:36 +00003744 const RecordType *lhsRecord = LhsT->getAs<RecordType>();
3745 if (!lhsRecord) return false;
3746
3747 const RecordType *rhsRecord = RhsT->getAs<RecordType>();
3748 if (!rhsRecord) return false;
3749
3750 assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)
3751 == (lhsRecord == rhsRecord));
3752
3753 if (lhsRecord == rhsRecord)
3754 return !lhsRecord->getDecl()->isUnion();
3755
3756 // C++0x [meta.rel]p2:
3757 // If Base and Derived are class types and are different types
3758 // (ignoring possible cv-qualifiers) then Derived shall be a
3759 // complete type.
3760 if (Self.RequireCompleteType(KeyLoc, RhsT,
3761 diag::err_incomplete_type_used_in_type_trait_expr))
3762 return false;
3763
3764 return cast<CXXRecordDecl>(rhsRecord->getDecl())
3765 ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
3766 }
John Wiegley65497cc2011-04-27 23:09:49 +00003767 case BTT_IsSame:
3768 return Self.Context.hasSameType(LhsT, RhsT);
Francois Pichet34b21132010-12-08 22:35:30 +00003769 case BTT_TypeCompatible:
3770 return Self.Context.typesAreCompatible(LhsT.getUnqualifiedType(),
3771 RhsT.getUnqualifiedType());
John Wiegley65497cc2011-04-27 23:09:49 +00003772 case BTT_IsConvertible:
Douglas Gregor8006e762011-01-27 20:28:01 +00003773 case BTT_IsConvertibleTo: {
3774 // C++0x [meta.rel]p4:
3775 // Given the following function prototype:
3776 //
3777 // template <class T>
3778 // typename add_rvalue_reference<T>::type create();
3779 //
3780 // the predicate condition for a template specialization
3781 // is_convertible<From, To> shall be satisfied if and only if
3782 // the return expression in the following code would be
3783 // well-formed, including any implicit conversions to the return
3784 // type of the function:
3785 //
3786 // To test() {
3787 // return create<From>();
3788 // }
3789 //
3790 // Access checking is performed as if in a context unrelated to To and
3791 // From. Only the validity of the immediate context of the expression
3792 // of the return-statement (including conversions to the return type)
3793 // is considered.
3794 //
3795 // We model the initialization as a copy-initialization of a temporary
3796 // of the appropriate type, which for this expression is identical to the
3797 // return statement (since NRVO doesn't apply).
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00003798
3799 // Functions aren't allowed to return function or array types.
3800 if (RhsT->isFunctionType() || RhsT->isArrayType())
3801 return false;
3802
3803 // A return statement in a void function must have void type.
3804 if (RhsT->isVoidType())
3805 return LhsT->isVoidType();
3806
3807 // A function definition requires a complete, non-abstract return type.
3808 if (Self.RequireCompleteType(KeyLoc, RhsT, 0) ||
3809 Self.RequireNonAbstractType(KeyLoc, RhsT, 0))
3810 return false;
3811
3812 // Compute the result of add_rvalue_reference.
Douglas Gregor8006e762011-01-27 20:28:01 +00003813 if (LhsT->isObjectType() || LhsT->isFunctionType())
3814 LhsT = Self.Context.getRValueReferenceType(LhsT);
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00003815
3816 // Build a fake source and destination for initialization.
Douglas Gregor8006e762011-01-27 20:28:01 +00003817 InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT));
Douglas Gregorc03a1082011-01-28 02:26:04 +00003818 OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
Douglas Gregor8006e762011-01-27 20:28:01 +00003819 Expr::getValueKindForType(LhsT));
3820 Expr *FromPtr = &From;
3821 InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc,
3822 SourceLocation()));
3823
Eli Friedmana59b1902012-01-25 01:05:57 +00003824 // Perform the initialization in an unevaluated context within a SFINAE
3825 // trap at translation unit scope.
3826 EnterExpressionEvaluationContext Unevaluated(Self, Sema::Unevaluated);
Douglas Gregoredb76852011-01-27 22:31:44 +00003827 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
3828 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003829 InitializationSequence Init(Self, To, Kind, FromPtr);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00003830 if (Init.Failed())
Douglas Gregor8006e762011-01-27 20:28:01 +00003831 return false;
Douglas Gregoredb76852011-01-27 22:31:44 +00003832
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00003833 ExprResult Result = Init.Perform(Self, To, Kind, FromPtr);
Douglas Gregor8006e762011-01-27 20:28:01 +00003834 return !Result.isInvalid() && !SFINAE.hasErrorOccurred();
3835 }
Alp Toker73287bf2014-01-20 00:24:09 +00003836
3837 case BTT_IsNothrowAssignable:
Douglas Gregor1be329d2012-02-23 07:33:15 +00003838 case BTT_IsTriviallyAssignable: {
3839 // C++11 [meta.unary.prop]p3:
3840 // is_trivially_assignable is defined as:
3841 // is_assignable<T, U>::value is true and the assignment, as defined by
3842 // is_assignable, is known to call no operation that is not trivial
3843 //
3844 // is_assignable is defined as:
3845 // The expression declval<T>() = declval<U>() is well-formed when
3846 // treated as an unevaluated operand (Clause 5).
3847 //
3848 // For both, T and U shall be complete types, (possibly cv-qualified)
3849 // void, or arrays of unknown bound.
3850 if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType() &&
3851 Self.RequireCompleteType(KeyLoc, LhsT,
3852 diag::err_incomplete_type_used_in_type_trait_expr))
3853 return false;
3854 if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType() &&
3855 Self.RequireCompleteType(KeyLoc, RhsT,
3856 diag::err_incomplete_type_used_in_type_trait_expr))
3857 return false;
3858
3859 // cv void is never assignable.
3860 if (LhsT->isVoidType() || RhsT->isVoidType())
3861 return false;
3862
3863 // Build expressions that emulate the effect of declval<T>() and
3864 // declval<U>().
3865 if (LhsT->isObjectType() || LhsT->isFunctionType())
3866 LhsT = Self.Context.getRValueReferenceType(LhsT);
3867 if (RhsT->isObjectType() || RhsT->isFunctionType())
3868 RhsT = Self.Context.getRValueReferenceType(RhsT);
3869 OpaqueValueExpr Lhs(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
3870 Expr::getValueKindForType(LhsT));
3871 OpaqueValueExpr Rhs(KeyLoc, RhsT.getNonLValueExprType(Self.Context),
3872 Expr::getValueKindForType(RhsT));
3873
3874 // Attempt the assignment in an unevaluated context within a SFINAE
3875 // trap at translation unit scope.
3876 EnterExpressionEvaluationContext Unevaluated(Self, Sema::Unevaluated);
3877 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
3878 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00003879 ExprResult Result = Self.BuildBinOp(/*S=*/nullptr, KeyLoc, BO_Assign, &Lhs,
3880 &Rhs);
Douglas Gregor1be329d2012-02-23 07:33:15 +00003881 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
3882 return false;
3883
Alp Toker73287bf2014-01-20 00:24:09 +00003884 if (BTT == BTT_IsNothrowAssignable)
3885 return Self.canThrow(Result.get()) == CT_Cannot;
Douglas Gregor6bd56ca2012-06-29 00:49:17 +00003886
Alp Toker73287bf2014-01-20 00:24:09 +00003887 if (BTT == BTT_IsTriviallyAssignable) {
3888 // Under Objective-C ARC, if the destination has non-trivial Objective-C
3889 // lifetime, this is a non-trivial assignment.
3890 if (Self.getLangOpts().ObjCAutoRefCount &&
3891 hasNontrivialObjCLifetime(LhsT.getNonReferenceType()))
3892 return false;
3893
3894 return !Result.get()->hasNonTrivialCall(Self.Context);
3895 }
3896
3897 llvm_unreachable("unhandled type trait");
3898 return false;
Douglas Gregor1be329d2012-02-23 07:33:15 +00003899 }
Alp Tokercbb90342013-12-13 20:49:58 +00003900 default: llvm_unreachable("not a BTT");
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00003901 }
3902 llvm_unreachable("Unknown type trait or not implemented");
3903}
3904
John Wiegley6242b6a2011-04-28 00:16:57 +00003905ExprResult Sema::ActOnArrayTypeTrait(ArrayTypeTrait ATT,
3906 SourceLocation KWLoc,
3907 ParsedType Ty,
3908 Expr* DimExpr,
3909 SourceLocation RParen) {
3910 TypeSourceInfo *TSInfo;
3911 QualType T = GetTypeFromParser(Ty, &TSInfo);
3912 if (!TSInfo)
3913 TSInfo = Context.getTrivialTypeSourceInfo(T);
3914
3915 return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen);
3916}
3917
3918static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT,
3919 QualType T, Expr *DimExpr,
3920 SourceLocation KeyLoc) {
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00003921 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
John Wiegley6242b6a2011-04-28 00:16:57 +00003922
3923 switch(ATT) {
3924 case ATT_ArrayRank:
3925 if (T->isArrayType()) {
3926 unsigned Dim = 0;
3927 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
3928 ++Dim;
3929 T = AT->getElementType();
3930 }
3931 return Dim;
John Wiegley6242b6a2011-04-28 00:16:57 +00003932 }
John Wiegleyd3522222011-04-28 02:06:46 +00003933 return 0;
3934
John Wiegley6242b6a2011-04-28 00:16:57 +00003935 case ATT_ArrayExtent: {
3936 llvm::APSInt Value;
3937 uint64_t Dim;
Richard Smithf4c51d92012-02-04 09:53:13 +00003938 if (Self.VerifyIntegerConstantExpression(DimExpr, &Value,
Douglas Gregore2b37442012-05-04 22:38:52 +00003939 diag::err_dimension_expr_not_constant_integer,
Richard Smithf4c51d92012-02-04 09:53:13 +00003940 false).isInvalid())
3941 return 0;
3942 if (Value.isSigned() && Value.isNegative()) {
Daniel Dunbar900cead2012-03-09 21:38:22 +00003943 Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer)
3944 << DimExpr->getSourceRange();
Richard Smithf4c51d92012-02-04 09:53:13 +00003945 return 0;
John Wiegleyd3522222011-04-28 02:06:46 +00003946 }
Richard Smithf4c51d92012-02-04 09:53:13 +00003947 Dim = Value.getLimitedValue();
John Wiegley6242b6a2011-04-28 00:16:57 +00003948
3949 if (T->isArrayType()) {
3950 unsigned D = 0;
3951 bool Matched = false;
3952 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
3953 if (Dim == D) {
3954 Matched = true;
3955 break;
3956 }
3957 ++D;
3958 T = AT->getElementType();
3959 }
3960
John Wiegleyd3522222011-04-28 02:06:46 +00003961 if (Matched && T->isArrayType()) {
3962 if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T))
3963 return CAT->getSize().getLimitedValue();
3964 }
John Wiegley6242b6a2011-04-28 00:16:57 +00003965 }
John Wiegleyd3522222011-04-28 02:06:46 +00003966 return 0;
John Wiegley6242b6a2011-04-28 00:16:57 +00003967 }
3968 }
3969 llvm_unreachable("Unknown type trait or not implemented");
3970}
3971
3972ExprResult Sema::BuildArrayTypeTrait(ArrayTypeTrait ATT,
3973 SourceLocation KWLoc,
3974 TypeSourceInfo *TSInfo,
3975 Expr* DimExpr,
3976 SourceLocation RParen) {
3977 QualType T = TSInfo->getType();
John Wiegley6242b6a2011-04-28 00:16:57 +00003978
Chandler Carruthc5276e52011-05-01 08:48:21 +00003979 // FIXME: This should likely be tracked as an APInt to remove any host
3980 // assumptions about the width of size_t on the target.
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00003981 uint64_t Value = 0;
3982 if (!T->isDependentType())
3983 Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc);
3984
Chandler Carruthc5276e52011-05-01 08:48:21 +00003985 // While the specification for these traits from the Embarcadero C++
3986 // compiler's documentation says the return type is 'unsigned int', Clang
3987 // returns 'size_t'. On Windows, the primary platform for the Embarcadero
3988 // compiler, there is no difference. On several other platforms this is an
3989 // important distinction.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003990 return new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value, DimExpr,
3991 RParen, Context.getSizeType());
John Wiegley6242b6a2011-04-28 00:16:57 +00003992}
3993
John Wiegleyf9f65842011-04-25 06:54:41 +00003994ExprResult Sema::ActOnExpressionTrait(ExpressionTrait ET,
Chandler Carruth20b9bc82011-05-01 07:44:20 +00003995 SourceLocation KWLoc,
3996 Expr *Queried,
3997 SourceLocation RParen) {
John Wiegleyf9f65842011-04-25 06:54:41 +00003998 // If error parsing the expression, ignore.
3999 if (!Queried)
Chandler Carruth20b9bc82011-05-01 07:44:20 +00004000 return ExprError();
John Wiegleyf9f65842011-04-25 06:54:41 +00004001
Chandler Carruth20b9bc82011-05-01 07:44:20 +00004002 ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen);
John Wiegleyf9f65842011-04-25 06:54:41 +00004003
Benjamin Kramer62b95d82012-08-23 21:35:17 +00004004 return Result;
John Wiegleyf9f65842011-04-25 06:54:41 +00004005}
4006
Chandler Carruth20b9bc82011-05-01 07:44:20 +00004007static bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E) {
4008 switch (ET) {
4009 case ET_IsLValueExpr: return E->isLValue();
4010 case ET_IsRValueExpr: return E->isRValue();
4011 }
4012 llvm_unreachable("Expression trait not covered by switch");
4013}
4014
John Wiegleyf9f65842011-04-25 06:54:41 +00004015ExprResult Sema::BuildExpressionTrait(ExpressionTrait ET,
Chandler Carruth20b9bc82011-05-01 07:44:20 +00004016 SourceLocation KWLoc,
4017 Expr *Queried,
4018 SourceLocation RParen) {
John Wiegleyf9f65842011-04-25 06:54:41 +00004019 if (Queried->isTypeDependent()) {
4020 // Delay type-checking for type-dependent expressions.
4021 } else if (Queried->getType()->isPlaceholderType()) {
4022 ExprResult PE = CheckPlaceholderExpr(Queried);
4023 if (PE.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004024 return BuildExpressionTrait(ET, KWLoc, PE.get(), RParen);
John Wiegleyf9f65842011-04-25 06:54:41 +00004025 }
4026
Chandler Carruth20b9bc82011-05-01 07:44:20 +00004027 bool Value = EvaluateExpressionTrait(ET, Queried);
Chandler Carruthf57eba32011-05-01 08:48:19 +00004028
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004029 return new (Context)
4030 ExpressionTraitExpr(KWLoc, ET, Queried, Value, RParen, Context.BoolTy);
John Wiegleyf9f65842011-04-25 06:54:41 +00004031}
4032
Richard Trieu82402a02011-09-15 21:56:47 +00004033QualType Sema::CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS,
John McCall7decc9e2010-11-18 06:31:45 +00004034 ExprValueKind &VK,
4035 SourceLocation Loc,
4036 bool isIndirect) {
Richard Trieu82402a02011-09-15 21:56:47 +00004037 assert(!LHS.get()->getType()->isPlaceholderType() &&
4038 !RHS.get()->getType()->isPlaceholderType() &&
John McCall0b645e92011-06-30 17:15:34 +00004039 "placeholders should have been weeded out by now");
4040
4041 // The LHS undergoes lvalue conversions if this is ->*.
4042 if (isIndirect) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004043 LHS = DefaultLvalueConversion(LHS.get());
Richard Trieu82402a02011-09-15 21:56:47 +00004044 if (LHS.isInvalid()) return QualType();
John McCall0b645e92011-06-30 17:15:34 +00004045 }
4046
4047 // The RHS always undergoes lvalue conversions.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004048 RHS = DefaultLvalueConversion(RHS.get());
Richard Trieu82402a02011-09-15 21:56:47 +00004049 if (RHS.isInvalid()) return QualType();
John McCall0b645e92011-06-30 17:15:34 +00004050
Sebastian Redl5822f082009-02-07 20:10:22 +00004051 const char *OpSpelling = isIndirect ? "->*" : ".*";
4052 // C++ 5.5p2
4053 // The binary operator .* [p3: ->*] binds its second operand, which shall
4054 // be of type "pointer to member of T" (where T is a completely-defined
4055 // class type) [...]
Richard Trieu82402a02011-09-15 21:56:47 +00004056 QualType RHSType = RHS.get()->getType();
4057 const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>();
Douglas Gregorac1fb652009-03-24 19:52:54 +00004058 if (!MemPtr) {
Sebastian Redl5822f082009-02-07 20:10:22 +00004059 Diag(Loc, diag::err_bad_memptr_rhs)
Richard Trieu82402a02011-09-15 21:56:47 +00004060 << OpSpelling << RHSType << RHS.get()->getSourceRange();
Sebastian Redl5822f082009-02-07 20:10:22 +00004061 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00004062 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00004063
Sebastian Redl5822f082009-02-07 20:10:22 +00004064 QualType Class(MemPtr->getClass(), 0);
4065
Douglas Gregord07ba342010-10-13 20:41:14 +00004066 // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
4067 // member pointer points must be completely-defined. However, there is no
4068 // reason for this semantic distinction, and the rule is not enforced by
4069 // other compilers. Therefore, we do not check this property, as it is
4070 // likely to be considered a defect.
Sebastian Redlc72350e2010-04-10 10:14:54 +00004071
Sebastian Redl5822f082009-02-07 20:10:22 +00004072 // C++ 5.5p2
4073 // [...] to its first operand, which shall be of class T or of a class of
4074 // which T is an unambiguous and accessible base class. [p3: a pointer to
4075 // such a class]
Richard Trieu82402a02011-09-15 21:56:47 +00004076 QualType LHSType = LHS.get()->getType();
Sebastian Redl5822f082009-02-07 20:10:22 +00004077 if (isIndirect) {
Richard Trieu82402a02011-09-15 21:56:47 +00004078 if (const PointerType *Ptr = LHSType->getAs<PointerType>())
4079 LHSType = Ptr->getPointeeType();
Sebastian Redl5822f082009-02-07 20:10:22 +00004080 else {
4081 Diag(Loc, diag::err_bad_memptr_lhs)
Richard Trieu82402a02011-09-15 21:56:47 +00004082 << OpSpelling << 1 << LHSType
Douglas Gregora771f462010-03-31 17:46:05 +00004083 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl5822f082009-02-07 20:10:22 +00004084 return QualType();
4085 }
4086 }
4087
Richard Trieu82402a02011-09-15 21:56:47 +00004088 if (!Context.hasSameUnqualifiedType(Class, LHSType)) {
Sebastian Redl26a0f1c2010-04-23 17:18:26 +00004089 // If we want to check the hierarchy, we need a complete type.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00004090 if (RequireCompleteType(Loc, LHSType, diag::err_bad_memptr_lhs,
4091 OpSpelling, (int)isIndirect)) {
Sebastian Redl26a0f1c2010-04-23 17:18:26 +00004092 return QualType();
4093 }
Richard Smithdb05cd32013-12-12 03:40:18 +00004094
4095 if (!IsDerivedFrom(LHSType, Class)) {
Sebastian Redl5822f082009-02-07 20:10:22 +00004096 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Richard Trieu82402a02011-09-15 21:56:47 +00004097 << (int)isIndirect << LHS.get()->getType();
Sebastian Redl5822f082009-02-07 20:10:22 +00004098 return QualType();
4099 }
Richard Smithdb05cd32013-12-12 03:40:18 +00004100
4101 CXXCastPath BasePath;
4102 if (CheckDerivedToBaseConversion(LHSType, Class, Loc,
4103 SourceRange(LHS.get()->getLocStart(),
4104 RHS.get()->getLocEnd()),
4105 &BasePath))
4106 return QualType();
4107
Eli Friedman1fcf66b2010-01-16 00:00:48 +00004108 // Cast LHS to type of use.
4109 QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
Eli Friedmanbe4b3632011-09-27 21:58:52 +00004110 ExprValueKind VK = isIndirect ? VK_RValue : LHS.get()->getValueKind();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004111 LHS = ImpCastExprToType(LHS.get(), UseType, CK_DerivedToBase, VK,
Richard Trieu82402a02011-09-15 21:56:47 +00004112 &BasePath);
Sebastian Redl5822f082009-02-07 20:10:22 +00004113 }
4114
Richard Trieu82402a02011-09-15 21:56:47 +00004115 if (isa<CXXScalarValueInitExpr>(RHS.get()->IgnoreParens())) {
Fariborz Jahanian1bc0f9a2009-11-18 21:54:48 +00004116 // Diagnose use of pointer-to-member type which when used as
4117 // the functional cast in a pointer-to-member expression.
4118 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
4119 return QualType();
4120 }
John McCall7decc9e2010-11-18 06:31:45 +00004121
Sebastian Redl5822f082009-02-07 20:10:22 +00004122 // C++ 5.5p2
4123 // The result is an object or a function of the type specified by the
4124 // second operand.
4125 // The cv qualifiers are the union of those in the pointer and the left side,
4126 // in accordance with 5.5p5 and 5.2.5.
Sebastian Redl5822f082009-02-07 20:10:22 +00004127 QualType Result = MemPtr->getPointeeType();
Richard Trieu82402a02011-09-15 21:56:47 +00004128 Result = Context.getCVRQualifiedType(Result, LHSType.getCVRQualifiers());
John McCall7decc9e2010-11-18 06:31:45 +00004129
Douglas Gregor1d042092011-01-26 16:40:18 +00004130 // C++0x [expr.mptr.oper]p6:
4131 // In a .* expression whose object expression is an rvalue, the program is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004132 // ill-formed if the second operand is a pointer to member function with
4133 // ref-qualifier &. In a ->* expression or in a .* expression whose object
4134 // expression is an lvalue, the program is ill-formed if the second operand
Douglas Gregor1d042092011-01-26 16:40:18 +00004135 // is a pointer to member function with ref-qualifier &&.
4136 if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
4137 switch (Proto->getRefQualifier()) {
4138 case RQ_None:
4139 // Do nothing
4140 break;
4141
4142 case RQ_LValue:
Richard Trieu82402a02011-09-15 21:56:47 +00004143 if (!isIndirect && !LHS.get()->Classify(Context).isLValue())
Douglas Gregor1d042092011-01-26 16:40:18 +00004144 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
Richard Trieu82402a02011-09-15 21:56:47 +00004145 << RHSType << 1 << LHS.get()->getSourceRange();
Douglas Gregor1d042092011-01-26 16:40:18 +00004146 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004147
Douglas Gregor1d042092011-01-26 16:40:18 +00004148 case RQ_RValue:
Richard Trieu82402a02011-09-15 21:56:47 +00004149 if (isIndirect || !LHS.get()->Classify(Context).isRValue())
Douglas Gregor1d042092011-01-26 16:40:18 +00004150 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
Richard Trieu82402a02011-09-15 21:56:47 +00004151 << RHSType << 0 << LHS.get()->getSourceRange();
Douglas Gregor1d042092011-01-26 16:40:18 +00004152 break;
4153 }
4154 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004155
John McCall7decc9e2010-11-18 06:31:45 +00004156 // C++ [expr.mptr.oper]p6:
4157 // The result of a .* expression whose second operand is a pointer
4158 // to a data member is of the same value category as its
4159 // first operand. The result of a .* expression whose second
4160 // operand is a pointer to a member function is a prvalue. The
4161 // result of an ->* expression is an lvalue if its second operand
4162 // is a pointer to data member and a prvalue otherwise.
John McCall0009fcc2011-04-26 20:42:42 +00004163 if (Result->isFunctionType()) {
John McCall7decc9e2010-11-18 06:31:45 +00004164 VK = VK_RValue;
John McCall0009fcc2011-04-26 20:42:42 +00004165 return Context.BoundMemberTy;
4166 } else if (isIndirect) {
John McCall7decc9e2010-11-18 06:31:45 +00004167 VK = VK_LValue;
John McCall0009fcc2011-04-26 20:42:42 +00004168 } else {
Richard Trieu82402a02011-09-15 21:56:47 +00004169 VK = LHS.get()->getValueKind();
John McCall0009fcc2011-04-26 20:42:42 +00004170 }
John McCall7decc9e2010-11-18 06:31:45 +00004171
Sebastian Redl5822f082009-02-07 20:10:22 +00004172 return Result;
4173}
Sebastian Redl1a99f442009-04-16 17:51:27 +00004174
Sebastian Redl1a99f442009-04-16 17:51:27 +00004175/// \brief Try to convert a type to another according to C++0x 5.16p3.
4176///
4177/// This is part of the parameter validation for the ? operator. If either
4178/// value operand is a class type, the two operands are attempted to be
4179/// converted to each other. This function does the conversion in one direction.
Douglas Gregor838fcc32010-03-26 20:14:36 +00004180/// It returns true if the program is ill-formed and has already been diagnosed
4181/// as such.
Sebastian Redl1a99f442009-04-16 17:51:27 +00004182static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
4183 SourceLocation QuestionLoc,
Douglas Gregor838fcc32010-03-26 20:14:36 +00004184 bool &HaveConversion,
4185 QualType &ToType) {
4186 HaveConversion = false;
4187 ToType = To->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004188
4189 InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
Douglas Gregor838fcc32010-03-26 20:14:36 +00004190 SourceLocation());
Sebastian Redl1a99f442009-04-16 17:51:27 +00004191 // C++0x 5.16p3
4192 // The process for determining whether an operand expression E1 of type T1
4193 // can be converted to match an operand expression E2 of type T2 is defined
4194 // as follows:
4195 // -- If E2 is an lvalue:
John McCall086a4642010-11-24 05:12:34 +00004196 bool ToIsLvalue = To->isLValue();
Douglas Gregorf9edf802010-03-26 20:59:55 +00004197 if (ToIsLvalue) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00004198 // E1 can be converted to match E2 if E1 can be implicitly converted to
4199 // type "lvalue reference to T2", subject to the constraint that in the
4200 // conversion the reference must bind directly to E1.
Douglas Gregor838fcc32010-03-26 20:14:36 +00004201 QualType T = Self.Context.getLValueReferenceType(ToType);
4202 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004203
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004204 InitializationSequence InitSeq(Self, Entity, Kind, From);
Douglas Gregor838fcc32010-03-26 20:14:36 +00004205 if (InitSeq.isDirectReferenceBinding()) {
4206 ToType = T;
4207 HaveConversion = true;
4208 return false;
Sebastian Redl1a99f442009-04-16 17:51:27 +00004209 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004210
Douglas Gregor838fcc32010-03-26 20:14:36 +00004211 if (InitSeq.isAmbiguous())
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004212 return InitSeq.Diagnose(Self, Entity, Kind, From);
Sebastian Redl1a99f442009-04-16 17:51:27 +00004213 }
John McCall65eb8792010-02-25 01:37:24 +00004214
Sebastian Redl1a99f442009-04-16 17:51:27 +00004215 // -- If E2 is an rvalue, or if the conversion above cannot be done:
4216 // -- if E1 and E2 have class type, and the underlying class types are
4217 // the same or one is a base class of the other:
4218 QualType FTy = From->getType();
4219 QualType TTy = To->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004220 const RecordType *FRec = FTy->getAs<RecordType>();
4221 const RecordType *TRec = TTy->getAs<RecordType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004222 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
Douglas Gregor838fcc32010-03-26 20:14:36 +00004223 Self.IsDerivedFrom(FTy, TTy);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004224 if (FRec && TRec &&
Douglas Gregor838fcc32010-03-26 20:14:36 +00004225 (FRec == TRec || FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00004226 // E1 can be converted to match E2 if the class of T2 is the
4227 // same type as, or a base class of, the class of T1, and
4228 // [cv2 > cv1].
John McCall65eb8792010-02-25 01:37:24 +00004229 if (FRec == TRec || FDerivedFromT) {
4230 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00004231 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004232 InitializationSequence InitSeq(Self, Entity, Kind, From);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00004233 if (InitSeq) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00004234 HaveConversion = true;
4235 return false;
4236 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004237
Douglas Gregor838fcc32010-03-26 20:14:36 +00004238 if (InitSeq.isAmbiguous())
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004239 return InitSeq.Diagnose(Self, Entity, Kind, From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004240 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00004241 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004242
Douglas Gregor838fcc32010-03-26 20:14:36 +00004243 return false;
Sebastian Redl1a99f442009-04-16 17:51:27 +00004244 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004245
Douglas Gregor838fcc32010-03-26 20:14:36 +00004246 // -- Otherwise: E1 can be converted to match E2 if E1 can be
4247 // implicitly converted to the type that expression E2 would have
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004248 // if E2 were converted to an rvalue (or the type it has, if E2 is
Douglas Gregorf9edf802010-03-26 20:59:55 +00004249 // an rvalue).
4250 //
4251 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
4252 // to the array-to-pointer or function-to-pointer conversions.
4253 if (!TTy->getAs<TagType>())
4254 TTy = TTy.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004255
Douglas Gregor838fcc32010-03-26 20:14:36 +00004256 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004257 InitializationSequence InitSeq(Self, Entity, Kind, From);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00004258 HaveConversion = !InitSeq.Failed();
Douglas Gregor838fcc32010-03-26 20:14:36 +00004259 ToType = TTy;
4260 if (InitSeq.isAmbiguous())
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004261 return InitSeq.Diagnose(Self, Entity, Kind, From);
Douglas Gregor838fcc32010-03-26 20:14:36 +00004262
Sebastian Redl1a99f442009-04-16 17:51:27 +00004263 return false;
4264}
4265
4266/// \brief Try to find a common type for two according to C++0x 5.16p5.
4267///
4268/// This is part of the parameter validation for the ? operator. If either
4269/// value operand is a class type, overload resolution is used to find a
4270/// conversion to a common type.
John Wiegley01296292011-04-08 18:41:53 +00004271static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS,
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004272 SourceLocation QuestionLoc) {
John Wiegley01296292011-04-08 18:41:53 +00004273 Expr *Args[2] = { LHS.get(), RHS.get() };
Richard Smith100b24a2014-04-17 01:52:14 +00004274 OverloadCandidateSet CandidateSet(QuestionLoc,
4275 OverloadCandidateSet::CSK_Operator);
Richard Smithe54c3072013-05-05 15:51:06 +00004276 Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args,
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004277 CandidateSet);
Sebastian Redl1a99f442009-04-16 17:51:27 +00004278
4279 OverloadCandidateSet::iterator Best;
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004280 switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
John Wiegley01296292011-04-08 18:41:53 +00004281 case OR_Success: {
Sebastian Redl1a99f442009-04-16 17:51:27 +00004282 // We found a match. Perform the conversions on the arguments and move on.
John Wiegley01296292011-04-08 18:41:53 +00004283 ExprResult LHSRes =
4284 Self.PerformImplicitConversion(LHS.get(), Best->BuiltinTypes.ParamTypes[0],
4285 Best->Conversions[0], Sema::AA_Converting);
4286 if (LHSRes.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00004287 break;
Benjamin Kramer62b95d82012-08-23 21:35:17 +00004288 LHS = LHSRes;
John Wiegley01296292011-04-08 18:41:53 +00004289
4290 ExprResult RHSRes =
4291 Self.PerformImplicitConversion(RHS.get(), Best->BuiltinTypes.ParamTypes[1],
4292 Best->Conversions[1], Sema::AA_Converting);
4293 if (RHSRes.isInvalid())
4294 break;
Benjamin Kramer62b95d82012-08-23 21:35:17 +00004295 RHS = RHSRes;
Chandler Carruth30141632011-02-25 19:41:05 +00004296 if (Best->Function)
Eli Friedmanfa0df832012-02-02 03:46:19 +00004297 Self.MarkFunctionReferenced(QuestionLoc, Best->Function);
Sebastian Redl1a99f442009-04-16 17:51:27 +00004298 return false;
John Wiegley01296292011-04-08 18:41:53 +00004299 }
4300
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004301 case OR_No_Viable_Function:
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004302
4303 // Emit a better diagnostic if one of the expressions is a null pointer
4304 // constant and the other is a pointer type. In this case, the user most
4305 // likely forgot to take the address of the other expression.
John Wiegley01296292011-04-08 18:41:53 +00004306 if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004307 return true;
4308
4309 Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley01296292011-04-08 18:41:53 +00004310 << LHS.get()->getType() << RHS.get()->getType()
4311 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00004312 return true;
4313
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004314 case OR_Ambiguous:
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004315 Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
John Wiegley01296292011-04-08 18:41:53 +00004316 << LHS.get()->getType() << RHS.get()->getType()
4317 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Mike Stump87c57ac2009-05-16 07:39:55 +00004318 // FIXME: Print the possible common types by printing the return types of
4319 // the viable candidates.
Sebastian Redl1a99f442009-04-16 17:51:27 +00004320 break;
4321
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004322 case OR_Deleted:
David Blaikie83d382b2011-09-23 05:06:16 +00004323 llvm_unreachable("Conditional operator has only built-in overloads");
Sebastian Redl1a99f442009-04-16 17:51:27 +00004324 }
4325 return true;
4326}
4327
Sebastian Redl5775af1a2009-04-17 16:30:52 +00004328/// \brief Perform an "extended" implicit conversion as returned by
4329/// TryClassUnification.
John Wiegley01296292011-04-08 18:41:53 +00004330static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00004331 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
John Wiegley01296292011-04-08 18:41:53 +00004332 InitializationKind Kind = InitializationKind::CreateCopy(E.get()->getLocStart(),
Douglas Gregor838fcc32010-03-26 20:14:36 +00004333 SourceLocation());
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004334 Expr *Arg = E.get();
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004335 InitializationSequence InitSeq(Self, Entity, Kind, Arg);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00004336 ExprResult Result = InitSeq.Perform(Self, Entity, Kind, Arg);
Douglas Gregor838fcc32010-03-26 20:14:36 +00004337 if (Result.isInvalid())
Sebastian Redl5775af1a2009-04-17 16:30:52 +00004338 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004339
John Wiegley01296292011-04-08 18:41:53 +00004340 E = Result;
Sebastian Redl5775af1a2009-04-17 16:30:52 +00004341 return false;
4342}
4343
Sebastian Redl1a99f442009-04-16 17:51:27 +00004344/// \brief Check the operands of ?: under C++ semantics.
4345///
4346/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
4347/// extension. In this case, LHS == Cond. (But they're not aliases.)
Richard Smithf2b084f2012-08-08 06:13:49 +00004348QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
4349 ExprResult &RHS, ExprValueKind &VK,
4350 ExprObjectKind &OK,
Sebastian Redl1a99f442009-04-16 17:51:27 +00004351 SourceLocation QuestionLoc) {
Mike Stump87c57ac2009-05-16 07:39:55 +00004352 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
4353 // interface pointers.
Sebastian Redl1a99f442009-04-16 17:51:27 +00004354
Richard Smith45edb702012-08-07 22:06:48 +00004355 // C++11 [expr.cond]p1
Sebastian Redl1a99f442009-04-16 17:51:27 +00004356 // The first expression is contextually converted to bool.
John Wiegley01296292011-04-08 18:41:53 +00004357 if (!Cond.get()->isTypeDependent()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004358 ExprResult CondRes = CheckCXXBooleanCondition(Cond.get());
John Wiegley01296292011-04-08 18:41:53 +00004359 if (CondRes.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00004360 return QualType();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00004361 Cond = CondRes;
Sebastian Redl1a99f442009-04-16 17:51:27 +00004362 }
4363
John McCall7decc9e2010-11-18 06:31:45 +00004364 // Assume r-value.
4365 VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00004366 OK = OK_Ordinary;
John McCall7decc9e2010-11-18 06:31:45 +00004367
Sebastian Redl1a99f442009-04-16 17:51:27 +00004368 // Either of the arguments dependent?
John Wiegley01296292011-04-08 18:41:53 +00004369 if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent())
Sebastian Redl1a99f442009-04-16 17:51:27 +00004370 return Context.DependentTy;
4371
Richard Smith45edb702012-08-07 22:06:48 +00004372 // C++11 [expr.cond]p2
Sebastian Redl1a99f442009-04-16 17:51:27 +00004373 // If either the second or the third operand has type (cv) void, ...
John Wiegley01296292011-04-08 18:41:53 +00004374 QualType LTy = LHS.get()->getType();
4375 QualType RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00004376 bool LVoid = LTy->isVoidType();
4377 bool RVoid = RTy->isVoidType();
4378 if (LVoid || RVoid) {
Richard Smith6a6a4bb2014-01-27 04:19:56 +00004379 // ... one of the following shall hold:
4380 // -- The second or the third operand (but not both) is a (possibly
4381 // parenthesized) throw-expression; the result is of the type
4382 // and value category of the other.
4383 bool LThrow = isa<CXXThrowExpr>(LHS.get()->IgnoreParenImpCasts());
4384 bool RThrow = isa<CXXThrowExpr>(RHS.get()->IgnoreParenImpCasts());
4385 if (LThrow != RThrow) {
4386 Expr *NonThrow = LThrow ? RHS.get() : LHS.get();
4387 VK = NonThrow->getValueKind();
4388 // DR (no number yet): the result is a bit-field if the
4389 // non-throw-expression operand is a bit-field.
4390 OK = NonThrow->getObjectKind();
4391 return NonThrow->getType();
Richard Smith45edb702012-08-07 22:06:48 +00004392 }
4393
Sebastian Redl1a99f442009-04-16 17:51:27 +00004394 // -- Both the second and third operands have type void; the result is of
Richard Smith45edb702012-08-07 22:06:48 +00004395 // type void and is a prvalue.
Sebastian Redl1a99f442009-04-16 17:51:27 +00004396 if (LVoid && RVoid)
4397 return Context.VoidTy;
4398
4399 // Neither holds, error.
4400 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
4401 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
John Wiegley01296292011-04-08 18:41:53 +00004402 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00004403 return QualType();
4404 }
4405
4406 // Neither is void.
4407
Richard Smithf2b084f2012-08-08 06:13:49 +00004408 // C++11 [expr.cond]p3
Sebastian Redl1a99f442009-04-16 17:51:27 +00004409 // Otherwise, if the second and third operand have different types, and
Richard Smithf2b084f2012-08-08 06:13:49 +00004410 // either has (cv) class type [...] an attempt is made to convert each of
4411 // those operands to the type of the other.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004412 if (!Context.hasSameType(LTy, RTy) &&
Sebastian Redl1a99f442009-04-16 17:51:27 +00004413 (LTy->isRecordType() || RTy->isRecordType())) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00004414 // These return true if a single direction is already ambiguous.
Douglas Gregor838fcc32010-03-26 20:14:36 +00004415 QualType L2RType, R2LType;
4416 bool HaveL2R, HaveR2L;
John Wiegley01296292011-04-08 18:41:53 +00004417 if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00004418 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00004419 if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00004420 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004421
Sebastian Redl1a99f442009-04-16 17:51:27 +00004422 // If both can be converted, [...] the program is ill-formed.
4423 if (HaveL2R && HaveR2L) {
4424 Diag(QuestionLoc, diag::err_conditional_ambiguous)
John Wiegley01296292011-04-08 18:41:53 +00004425 << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00004426 return QualType();
4427 }
4428
4429 // If exactly one conversion is possible, that conversion is applied to
4430 // the chosen operand and the converted operands are used in place of the
4431 // original operands for the remainder of this section.
4432 if (HaveL2R) {
John Wiegley01296292011-04-08 18:41:53 +00004433 if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00004434 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00004435 LTy = LHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00004436 } else if (HaveR2L) {
John Wiegley01296292011-04-08 18:41:53 +00004437 if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00004438 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00004439 RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00004440 }
4441 }
4442
Richard Smithf2b084f2012-08-08 06:13:49 +00004443 // C++11 [expr.cond]p3
4444 // if both are glvalues of the same value category and the same type except
4445 // for cv-qualification, an attempt is made to convert each of those
4446 // operands to the type of the other.
4447 ExprValueKind LVK = LHS.get()->getValueKind();
4448 ExprValueKind RVK = RHS.get()->getValueKind();
4449 if (!Context.hasSameType(LTy, RTy) &&
4450 Context.hasSameUnqualifiedType(LTy, RTy) &&
4451 LVK == RVK && LVK != VK_RValue) {
4452 // Since the unqualified types are reference-related and we require the
4453 // result to be as if a reference bound directly, the only conversion
4454 // we can perform is to add cv-qualifiers.
4455 Qualifiers LCVR = Qualifiers::fromCVRMask(LTy.getCVRQualifiers());
4456 Qualifiers RCVR = Qualifiers::fromCVRMask(RTy.getCVRQualifiers());
4457 if (RCVR.isStrictSupersetOf(LCVR)) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004458 LHS = ImpCastExprToType(LHS.get(), RTy, CK_NoOp, LVK);
Richard Smithf2b084f2012-08-08 06:13:49 +00004459 LTy = LHS.get()->getType();
4460 }
4461 else if (LCVR.isStrictSupersetOf(RCVR)) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004462 RHS = ImpCastExprToType(RHS.get(), LTy, CK_NoOp, RVK);
Richard Smithf2b084f2012-08-08 06:13:49 +00004463 RTy = RHS.get()->getType();
4464 }
4465 }
4466
4467 // C++11 [expr.cond]p4
John McCall7decc9e2010-11-18 06:31:45 +00004468 // If the second and third operands are glvalues of the same value
4469 // category and have the same type, the result is of that type and
4470 // value category and it is a bit-field if the second or the third
4471 // operand is a bit-field, or if both are bit-fields.
John McCall4bc41ae2010-11-18 19:01:18 +00004472 // We only extend this to bitfields, not to the crazy other kinds of
4473 // l-values.
Douglas Gregor697a3912010-04-01 22:47:07 +00004474 bool Same = Context.hasSameType(LTy, RTy);
Richard Smithf2b084f2012-08-08 06:13:49 +00004475 if (Same && LVK == RVK && LVK != VK_RValue &&
John Wiegley01296292011-04-08 18:41:53 +00004476 LHS.get()->isOrdinaryOrBitFieldObject() &&
4477 RHS.get()->isOrdinaryOrBitFieldObject()) {
4478 VK = LHS.get()->getValueKind();
4479 if (LHS.get()->getObjectKind() == OK_BitField ||
4480 RHS.get()->getObjectKind() == OK_BitField)
John McCall4bc41ae2010-11-18 19:01:18 +00004481 OK = OK_BitField;
John McCall7decc9e2010-11-18 06:31:45 +00004482 return LTy;
Fariborz Jahanianc60da032010-09-25 01:08:05 +00004483 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00004484
Richard Smithf2b084f2012-08-08 06:13:49 +00004485 // C++11 [expr.cond]p5
4486 // Otherwise, the result is a prvalue. If the second and third operands
Sebastian Redl1a99f442009-04-16 17:51:27 +00004487 // do not have the same type, and either has (cv) class type, ...
4488 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
4489 // ... overload resolution is used to determine the conversions (if any)
4490 // to be applied to the operands. If the overload resolution fails, the
4491 // program is ill-formed.
4492 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
4493 return QualType();
4494 }
4495
Richard Smithf2b084f2012-08-08 06:13:49 +00004496 // C++11 [expr.cond]p6
4497 // Lvalue-to-rvalue, array-to-pointer, and function-to-pointer standard
Sebastian Redl1a99f442009-04-16 17:51:27 +00004498 // conversions are performed on the second and third operands.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004499 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
4500 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
John Wiegley01296292011-04-08 18:41:53 +00004501 if (LHS.isInvalid() || RHS.isInvalid())
4502 return QualType();
4503 LTy = LHS.get()->getType();
4504 RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00004505
4506 // After those conversions, one of the following shall hold:
4507 // -- The second and third operands have the same type; the result
Douglas Gregorfa6010b2010-05-19 23:40:50 +00004508 // is of that type. If the operands have class type, the result
4509 // is a prvalue temporary of the result type, which is
4510 // copy-initialized from either the second operand or the third
4511 // operand depending on the value of the first operand.
4512 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
4513 if (LTy->isRecordType()) {
4514 // The operands have class type. Make a temporary copy.
David Blaikie6154ef92012-09-10 22:05:41 +00004515 if (RequireNonAbstractType(QuestionLoc, LTy,
4516 diag::err_allocation_of_abstract_type))
4517 return QualType();
Douglas Gregorfa6010b2010-05-19 23:40:50 +00004518 InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
David Blaikie6154ef92012-09-10 22:05:41 +00004519
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004520 ExprResult LHSCopy = PerformCopyInitialization(Entity,
4521 SourceLocation(),
John Wiegley01296292011-04-08 18:41:53 +00004522 LHS);
Douglas Gregorfa6010b2010-05-19 23:40:50 +00004523 if (LHSCopy.isInvalid())
4524 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004525
4526 ExprResult RHSCopy = PerformCopyInitialization(Entity,
4527 SourceLocation(),
John Wiegley01296292011-04-08 18:41:53 +00004528 RHS);
Douglas Gregorfa6010b2010-05-19 23:40:50 +00004529 if (RHSCopy.isInvalid())
4530 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004531
John Wiegley01296292011-04-08 18:41:53 +00004532 LHS = LHSCopy;
4533 RHS = RHSCopy;
Douglas Gregorfa6010b2010-05-19 23:40:50 +00004534 }
4535
Sebastian Redl1a99f442009-04-16 17:51:27 +00004536 return LTy;
Douglas Gregorfa6010b2010-05-19 23:40:50 +00004537 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00004538
Douglas Gregor46188682010-05-18 22:42:18 +00004539 // Extension: conditional operator involving vector types.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004540 if (LTy->isVectorType() || RTy->isVectorType())
Eli Friedman1408bc92011-06-23 18:10:35 +00004541 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
Douglas Gregor46188682010-05-18 22:42:18 +00004542
Sebastian Redl1a99f442009-04-16 17:51:27 +00004543 // -- The second and third operands have arithmetic or enumeration type;
4544 // the usual arithmetic conversions are performed to bring them to a
4545 // common type, and the result is of that type.
4546 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
4547 UsualArithmeticConversions(LHS, RHS);
John Wiegley01296292011-04-08 18:41:53 +00004548 if (LHS.isInvalid() || RHS.isInvalid())
4549 return QualType();
4550 return LHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00004551 }
4552
4553 // -- The second and third operands have pointer type, or one has pointer
Richard Smithf2b084f2012-08-08 06:13:49 +00004554 // type and the other is a null pointer constant, or both are null
4555 // pointer constants, at least one of which is non-integral; pointer
4556 // conversions and qualification conversions are performed to bring them
4557 // to their composite pointer type. The result is of the composite
4558 // pointer type.
Eli Friedman81390df2010-01-02 22:56:07 +00004559 // -- The second and third operands have pointer to member type, or one has
4560 // pointer to member type and the other is a null pointer constant;
4561 // pointer to member conversions and qualification conversions are
4562 // performed to bring them to a common type, whose cv-qualification
4563 // shall match the cv-qualification of either the second or the third
4564 // operand. The result is of the common type.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00004565 bool NonStandardCompositeType = false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00004566 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS,
Craig Topperc3ec1492014-05-26 06:22:03 +00004567 isSFINAEContext() ? nullptr
4568 : &NonStandardCompositeType);
Douglas Gregor6f5f6422010-02-25 22:29:57 +00004569 if (!Composite.isNull()) {
4570 if (NonStandardCompositeType)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004571 Diag(QuestionLoc,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00004572 diag::ext_typecheck_cond_incompatible_operands_nonstandard)
4573 << LTy << RTy << Composite
John Wiegley01296292011-04-08 18:41:53 +00004574 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004575
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00004576 return Composite;
Douglas Gregor6f5f6422010-02-25 22:29:57 +00004577 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004578
Douglas Gregor697a3912010-04-01 22:47:07 +00004579 // Similarly, attempt to find composite type of two objective-c pointers.
Fariborz Jahanian798d2bd2009-12-10 20:46:08 +00004580 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
4581 if (!Composite.isNull())
4582 return Composite;
Sebastian Redl1a99f442009-04-16 17:51:27 +00004583
Chandler Carruth9c9127e2011-02-19 00:13:59 +00004584 // Check if we are using a null with a non-pointer type.
John Wiegley01296292011-04-08 18:41:53 +00004585 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carruth9c9127e2011-02-19 00:13:59 +00004586 return QualType();
4587
Sebastian Redl1a99f442009-04-16 17:51:27 +00004588 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley01296292011-04-08 18:41:53 +00004589 << LHS.get()->getType() << RHS.get()->getType()
4590 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00004591 return QualType();
4592}
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00004593
4594/// \brief Find a merged pointer type and convert the two expressions to it.
4595///
Douglas Gregorb00b10e2009-08-24 17:42:35 +00004596/// This finds the composite pointer type (or member pointer type) for @p E1
Richard Smithf2b084f2012-08-08 06:13:49 +00004597/// and @p E2 according to C++11 5.9p2. It converts both expressions to this
Douglas Gregorb00b10e2009-08-24 17:42:35 +00004598/// type and returns it.
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00004599/// It does not emit diagnostics.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00004600///
Douglas Gregor19175ff2010-04-16 23:20:25 +00004601/// \param Loc The location of the operator requiring these two expressions to
4602/// be converted to the composite pointer type.
4603///
Douglas Gregor6f5f6422010-02-25 22:29:57 +00004604/// If \p NonStandardCompositeType is non-NULL, then we are permitted to find
4605/// a non-standard (but still sane) composite type to which both expressions
4606/// can be converted. When such a type is chosen, \c *NonStandardCompositeType
4607/// will be set true.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004608QualType Sema::FindCompositePointerType(SourceLocation Loc,
Douglas Gregor19175ff2010-04-16 23:20:25 +00004609 Expr *&E1, Expr *&E2,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00004610 bool *NonStandardCompositeType) {
4611 if (NonStandardCompositeType)
4612 *NonStandardCompositeType = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004613
David Blaikiebbafb8a2012-03-11 07:00:24 +00004614 assert(getLangOpts().CPlusPlus && "This function assumes C++");
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00004615 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump11289f42009-09-09 15:08:12 +00004616
Richard Smithf2b084f2012-08-08 06:13:49 +00004617 // C++11 5.9p2
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00004618 // Pointer conversions and qualification conversions are performed on
4619 // pointer operands to bring them to their composite pointer type. If
4620 // one operand is a null pointer constant, the composite pointer type is
Richard Smithf2b084f2012-08-08 06:13:49 +00004621 // std::nullptr_t if the other operand is also a null pointer constant or,
4622 // if the other operand is a pointer, the type of the other operand.
4623 if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
4624 !T2->isAnyPointerType() && !T2->isMemberPointerType()) {
4625 if (T1->isNullPtrType() &&
4626 E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004627 E2 = ImpCastExprToType(E2, T1, CK_NullToPointer).get();
Richard Smithf2b084f2012-08-08 06:13:49 +00004628 return T1;
4629 }
4630 if (T2->isNullPtrType() &&
4631 E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004632 E1 = ImpCastExprToType(E1, T2, CK_NullToPointer).get();
Richard Smithf2b084f2012-08-08 06:13:49 +00004633 return T2;
4634 }
4635 return QualType();
4636 }
4637
Douglas Gregor56751b52009-09-25 04:25:58 +00004638 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004639 if (T2->isMemberPointerType())
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004640 E1 = ImpCastExprToType(E1, T2, CK_NullToMemberPointer).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00004641 else
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004642 E1 = ImpCastExprToType(E1, T2, CK_NullToPointer).get();
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00004643 return T2;
4644 }
Douglas Gregor56751b52009-09-25 04:25:58 +00004645 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004646 if (T1->isMemberPointerType())
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004647 E2 = ImpCastExprToType(E2, T1, CK_NullToMemberPointer).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00004648 else
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004649 E2 = ImpCastExprToType(E2, T1, CK_NullToPointer).get();
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00004650 return T1;
4651 }
Mike Stump11289f42009-09-09 15:08:12 +00004652
Douglas Gregorb00b10e2009-08-24 17:42:35 +00004653 // Now both have to be pointers or member pointers.
Sebastian Redl658262f2009-11-16 21:03:45 +00004654 if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
4655 (!T2->isPointerType() && !T2->isMemberPointerType()))
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00004656 return QualType();
4657
4658 // Otherwise, of one of the operands has type "pointer to cv1 void," then
4659 // the other has type "pointer to cv2 T" and the composite pointer type is
4660 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
4661 // Otherwise, the composite pointer type is a pointer type similar to the
4662 // type of one of the operands, with a cv-qualification signature that is
4663 // the union of the cv-qualification signatures of the operand types.
4664 // In practice, the first part here is redundant; it's subsumed by the second.
4665 // What we do here is, we build the two possible composite types, and try the
4666 // conversions in both directions. If only one works, or if the two composite
4667 // types are the same, we have succeeded.
John McCall8ccfcb52009-09-24 19:53:00 +00004668 // FIXME: extended qualifiers?
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004669 typedef SmallVector<unsigned, 4> QualifierVector;
Sebastian Redl658262f2009-11-16 21:03:45 +00004670 QualifierVector QualifierUnion;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004671 typedef SmallVector<std::pair<const Type *, const Type *>, 4>
Sebastian Redl658262f2009-11-16 21:03:45 +00004672 ContainingClassVector;
4673 ContainingClassVector MemberOfClass;
4674 QualType Composite1 = Context.getCanonicalType(T1),
4675 Composite2 = Context.getCanonicalType(T2);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004676 unsigned NeedConstBefore = 0;
Douglas Gregorb00b10e2009-08-24 17:42:35 +00004677 do {
4678 const PointerType *Ptr1, *Ptr2;
4679 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
4680 (Ptr2 = Composite2->getAs<PointerType>())) {
4681 Composite1 = Ptr1->getPointeeType();
4682 Composite2 = Ptr2->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004683
Douglas Gregor6f5f6422010-02-25 22:29:57 +00004684 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004685 // of where we need to fill in additional 'const' qualifiers.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00004686 if (NonStandardCompositeType &&
4687 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
4688 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004689
Douglas Gregorb00b10e2009-08-24 17:42:35 +00004690 QualifierUnion.push_back(
4691 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
Craig Topperc3ec1492014-05-26 06:22:03 +00004692 MemberOfClass.push_back(std::make_pair(nullptr, nullptr));
Douglas Gregorb00b10e2009-08-24 17:42:35 +00004693 continue;
4694 }
Mike Stump11289f42009-09-09 15:08:12 +00004695
Douglas Gregorb00b10e2009-08-24 17:42:35 +00004696 const MemberPointerType *MemPtr1, *MemPtr2;
4697 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
4698 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
4699 Composite1 = MemPtr1->getPointeeType();
4700 Composite2 = MemPtr2->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004701
Douglas Gregor6f5f6422010-02-25 22:29:57 +00004702 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004703 // of where we need to fill in additional 'const' qualifiers.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00004704 if (NonStandardCompositeType &&
4705 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
4706 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004707
Douglas Gregorb00b10e2009-08-24 17:42:35 +00004708 QualifierUnion.push_back(
4709 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
4710 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
4711 MemPtr2->getClass()));
4712 continue;
4713 }
Mike Stump11289f42009-09-09 15:08:12 +00004714
Douglas Gregorb00b10e2009-08-24 17:42:35 +00004715 // FIXME: block pointer types?
Mike Stump11289f42009-09-09 15:08:12 +00004716
Douglas Gregorb00b10e2009-08-24 17:42:35 +00004717 // Cannot unwrap any more types.
4718 break;
4719 } while (true);
Mike Stump11289f42009-09-09 15:08:12 +00004720
Douglas Gregor6f5f6422010-02-25 22:29:57 +00004721 if (NeedConstBefore && NonStandardCompositeType) {
4722 // Extension: Add 'const' to qualifiers that come before the first qualifier
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004723 // mismatch, so that our (non-standard!) composite type meets the
Douglas Gregor6f5f6422010-02-25 22:29:57 +00004724 // requirements of C++ [conv.qual]p4 bullet 3.
4725 for (unsigned I = 0; I != NeedConstBefore; ++I) {
4726 if ((QualifierUnion[I] & Qualifiers::Const) == 0) {
4727 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
4728 *NonStandardCompositeType = true;
4729 }
4730 }
4731 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004732
Douglas Gregorb00b10e2009-08-24 17:42:35 +00004733 // Rewrap the composites as pointers or member pointers with the union CVRs.
Sebastian Redl658262f2009-11-16 21:03:45 +00004734 ContainingClassVector::reverse_iterator MOC
4735 = MemberOfClass.rbegin();
4736 for (QualifierVector::reverse_iterator
4737 I = QualifierUnion.rbegin(),
4738 E = QualifierUnion.rend();
Douglas Gregorb00b10e2009-08-24 17:42:35 +00004739 I != E; (void)++I, ++MOC) {
John McCall8ccfcb52009-09-24 19:53:00 +00004740 Qualifiers Quals = Qualifiers::fromCVRMask(*I);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00004741 if (MOC->first && MOC->second) {
4742 // Rebuild member pointer type
John McCall8ccfcb52009-09-24 19:53:00 +00004743 Composite1 = Context.getMemberPointerType(
4744 Context.getQualifiedType(Composite1, Quals),
4745 MOC->first);
4746 Composite2 = Context.getMemberPointerType(
4747 Context.getQualifiedType(Composite2, Quals),
4748 MOC->second);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00004749 } else {
4750 // Rebuild pointer type
John McCall8ccfcb52009-09-24 19:53:00 +00004751 Composite1
4752 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
4753 Composite2
4754 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregorb00b10e2009-08-24 17:42:35 +00004755 }
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00004756 }
4757
Douglas Gregor19175ff2010-04-16 23:20:25 +00004758 // Try to convert to the first composite pointer type.
4759 InitializedEntity Entity1
4760 = InitializedEntity::InitializeTemporary(Composite1);
4761 InitializationKind Kind
4762 = InitializationKind::CreateCopy(Loc, SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004763 InitializationSequence E1ToC1(*this, Entity1, Kind, E1);
4764 InitializationSequence E2ToC1(*this, Entity1, Kind, E2);
Mike Stump11289f42009-09-09 15:08:12 +00004765
Douglas Gregor19175ff2010-04-16 23:20:25 +00004766 if (E1ToC1 && E2ToC1) {
4767 // Conversion to Composite1 is viable.
4768 if (!Context.hasSameType(Composite1, Composite2)) {
4769 // Composite2 is a different type from Composite1. Check whether
4770 // Composite2 is also viable.
4771 InitializedEntity Entity2
4772 = InitializedEntity::InitializeTemporary(Composite2);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004773 InitializationSequence E1ToC2(*this, Entity2, Kind, E1);
4774 InitializationSequence E2ToC2(*this, Entity2, Kind, E2);
Douglas Gregor19175ff2010-04-16 23:20:25 +00004775 if (E1ToC2 && E2ToC2) {
4776 // Both Composite1 and Composite2 are viable and are different;
4777 // this is an ambiguity.
4778 return QualType();
4779 }
4780 }
4781
4782 // Convert E1 to Composite1
John McCalldadc5752010-08-24 06:29:42 +00004783 ExprResult E1Result
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00004784 = E1ToC1.Perform(*this, Entity1, Kind, E1);
Douglas Gregor19175ff2010-04-16 23:20:25 +00004785 if (E1Result.isInvalid())
4786 return QualType();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004787 E1 = E1Result.getAs<Expr>();
Douglas Gregor19175ff2010-04-16 23:20:25 +00004788
4789 // Convert E2 to Composite1
John McCalldadc5752010-08-24 06:29:42 +00004790 ExprResult E2Result
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00004791 = E2ToC1.Perform(*this, Entity1, Kind, E2);
Douglas Gregor19175ff2010-04-16 23:20:25 +00004792 if (E2Result.isInvalid())
4793 return QualType();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004794 E2 = E2Result.getAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004795
Douglas Gregor19175ff2010-04-16 23:20:25 +00004796 return Composite1;
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00004797 }
4798
Douglas Gregor19175ff2010-04-16 23:20:25 +00004799 // Check whether Composite2 is viable.
4800 InitializedEntity Entity2
4801 = InitializedEntity::InitializeTemporary(Composite2);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004802 InitializationSequence E1ToC2(*this, Entity2, Kind, E1);
4803 InitializationSequence E2ToC2(*this, Entity2, Kind, E2);
Douglas Gregor19175ff2010-04-16 23:20:25 +00004804 if (!E1ToC2 || !E2ToC2)
4805 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004806
Douglas Gregor19175ff2010-04-16 23:20:25 +00004807 // Convert E1 to Composite2
John McCalldadc5752010-08-24 06:29:42 +00004808 ExprResult E1Result
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00004809 = E1ToC2.Perform(*this, Entity2, Kind, E1);
Douglas Gregor19175ff2010-04-16 23:20:25 +00004810 if (E1Result.isInvalid())
4811 return QualType();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004812 E1 = E1Result.getAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004813
Douglas Gregor19175ff2010-04-16 23:20:25 +00004814 // Convert E2 to Composite2
John McCalldadc5752010-08-24 06:29:42 +00004815 ExprResult E2Result
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00004816 = E2ToC2.Perform(*this, Entity2, Kind, E2);
Douglas Gregor19175ff2010-04-16 23:20:25 +00004817 if (E2Result.isInvalid())
4818 return QualType();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004819 E2 = E2Result.getAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004820
Douglas Gregor19175ff2010-04-16 23:20:25 +00004821 return Composite2;
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00004822}
Anders Carlsson85a307d2009-05-17 18:41:29 +00004823
John McCalldadc5752010-08-24 06:29:42 +00004824ExprResult Sema::MaybeBindToTemporary(Expr *E) {
Douglas Gregor298087b2010-11-01 21:10:29 +00004825 if (!E)
4826 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004827
John McCall31168b02011-06-15 23:02:42 +00004828 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
4829
4830 // If the result is a glvalue, we shouldn't bind it.
4831 if (!E->isRValue())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004832 return E;
Mike Stump11289f42009-09-09 15:08:12 +00004833
John McCall31168b02011-06-15 23:02:42 +00004834 // In ARC, calls that return a retainable type can return retained,
4835 // in which case we have to insert a consuming cast.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004836 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00004837 E->getType()->isObjCRetainableType()) {
4838
4839 bool ReturnsRetained;
4840
4841 // For actual calls, we compute this by examining the type of the
4842 // called value.
4843 if (CallExpr *Call = dyn_cast<CallExpr>(E)) {
4844 Expr *Callee = Call->getCallee()->IgnoreParens();
4845 QualType T = Callee->getType();
4846
4847 if (T == Context.BoundMemberTy) {
4848 // Handle pointer-to-members.
4849 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Callee))
4850 T = BinOp->getRHS()->getType();
4851 else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Callee))
4852 T = Mem->getMemberDecl()->getType();
4853 }
4854
4855 if (const PointerType *Ptr = T->getAs<PointerType>())
4856 T = Ptr->getPointeeType();
4857 else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>())
4858 T = Ptr->getPointeeType();
4859 else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>())
4860 T = MemPtr->getPointeeType();
4861
4862 const FunctionType *FTy = T->getAs<FunctionType>();
4863 assert(FTy && "call to value not of function type?");
4864 ReturnsRetained = FTy->getExtInfo().getProducesResult();
4865
4866 // ActOnStmtExpr arranges things so that StmtExprs of retainable
4867 // type always produce a +1 object.
4868 } else if (isa<StmtExpr>(E)) {
4869 ReturnsRetained = true;
4870
Ted Kremeneke65b0862012-03-06 20:05:56 +00004871 // We hit this case with the lambda conversion-to-block optimization;
4872 // we don't want any extra casts here.
4873 } else if (isa<CastExpr>(E) &&
4874 isa<BlockExpr>(cast<CastExpr>(E)->getSubExpr())) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004875 return E;
Ted Kremeneke65b0862012-03-06 20:05:56 +00004876
John McCall31168b02011-06-15 23:02:42 +00004877 // For message sends and property references, we try to find an
4878 // actual method. FIXME: we should infer retention by selector in
4879 // cases where we don't have an actual method.
Ted Kremeneke65b0862012-03-06 20:05:56 +00004880 } else {
Craig Topperc3ec1492014-05-26 06:22:03 +00004881 ObjCMethodDecl *D = nullptr;
Ted Kremeneke65b0862012-03-06 20:05:56 +00004882 if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(E)) {
4883 D = Send->getMethodDecl();
Patrick Beard0caa3942012-04-19 00:25:12 +00004884 } else if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(E)) {
4885 D = BoxedExpr->getBoxingMethod();
Ted Kremeneke65b0862012-03-06 20:05:56 +00004886 } else if (ObjCArrayLiteral *ArrayLit = dyn_cast<ObjCArrayLiteral>(E)) {
4887 D = ArrayLit->getArrayWithObjectsMethod();
4888 } else if (ObjCDictionaryLiteral *DictLit
4889 = dyn_cast<ObjCDictionaryLiteral>(E)) {
4890 D = DictLit->getDictWithObjectsMethod();
4891 }
John McCall31168b02011-06-15 23:02:42 +00004892
4893 ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>());
John McCall32a4da02011-08-03 07:02:44 +00004894
4895 // Don't do reclaims on performSelector calls; despite their
4896 // return type, the invoked method doesn't necessarily actually
4897 // return an object.
4898 if (!ReturnsRetained &&
4899 D && D->getMethodFamily() == OMF_performSelector)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004900 return E;
John McCall31168b02011-06-15 23:02:42 +00004901 }
4902
John McCall16de4d22011-11-14 19:53:16 +00004903 // Don't reclaim an object of Class type.
4904 if (!ReturnsRetained && E->getType()->isObjCARCImplicitlyUnretainedType())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004905 return E;
John McCall16de4d22011-11-14 19:53:16 +00004906
John McCall4db5c3c2011-07-07 06:58:02 +00004907 ExprNeedsCleanups = true;
4908
John McCall2d637d22011-09-10 06:18:15 +00004909 CastKind ck = (ReturnsRetained ? CK_ARCConsumeObject
4910 : CK_ARCReclaimReturnedObject);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004911 return ImplicitCastExpr::Create(Context, E->getType(), ck, E, nullptr,
4912 VK_RValue);
John McCall31168b02011-06-15 23:02:42 +00004913 }
4914
David Blaikiebbafb8a2012-03-11 07:00:24 +00004915 if (!getLangOpts().CPlusPlus)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004916 return E;
Douglas Gregor363b1512009-12-24 18:51:59 +00004917
Peter Collingbournec331a1e2012-01-26 03:33:51 +00004918 // Search for the base element type (cf. ASTContext::getBaseElementType) with
4919 // a fast path for the common case that the type is directly a RecordType.
4920 const Type *T = Context.getCanonicalType(E->getType().getTypePtr());
Craig Topperc3ec1492014-05-26 06:22:03 +00004921 const RecordType *RT = nullptr;
Peter Collingbournec331a1e2012-01-26 03:33:51 +00004922 while (!RT) {
4923 switch (T->getTypeClass()) {
4924 case Type::Record:
4925 RT = cast<RecordType>(T);
4926 break;
4927 case Type::ConstantArray:
4928 case Type::IncompleteArray:
4929 case Type::VariableArray:
4930 case Type::DependentSizedArray:
4931 T = cast<ArrayType>(T)->getElementType().getTypePtr();
4932 break;
4933 default:
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004934 return E;
Peter Collingbournec331a1e2012-01-26 03:33:51 +00004935 }
4936 }
Mike Stump11289f42009-09-09 15:08:12 +00004937
Richard Smithfd555f62012-02-22 02:04:18 +00004938 // That should be enough to guarantee that this type is complete, if we're
4939 // not processing a decltype expression.
Jeffrey Yasskinbbc4eea2011-01-27 19:17:54 +00004940 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Richard Smitheec915d62012-02-18 04:13:32 +00004941 if (RD->isInvalidDecl() || RD->isDependentContext())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004942 return E;
Richard Smithfd555f62012-02-22 02:04:18 +00004943
4944 bool IsDecltype = ExprEvalContexts.back().IsDecltype;
Craig Topperc3ec1492014-05-26 06:22:03 +00004945 CXXDestructorDecl *Destructor = IsDecltype ? nullptr : LookupDestructor(RD);
John McCall31168b02011-06-15 23:02:42 +00004946
John McCall31168b02011-06-15 23:02:42 +00004947 if (Destructor) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00004948 MarkFunctionReferenced(E->getExprLoc(), Destructor);
John McCall8e36d532010-04-07 00:41:46 +00004949 CheckDestructorAccess(E->getExprLoc(), Destructor,
4950 PDiag(diag::err_access_dtor_temp)
4951 << E->getType());
Richard Smith22262ab2013-05-04 06:44:46 +00004952 if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
4953 return ExprError();
John McCall31168b02011-06-15 23:02:42 +00004954
Richard Smithfd555f62012-02-22 02:04:18 +00004955 // If destructor is trivial, we can avoid the extra copy.
4956 if (Destructor->isTrivial())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004957 return E;
Richard Smitheec915d62012-02-18 04:13:32 +00004958
John McCall28fc7092011-11-10 05:35:25 +00004959 // We need a cleanup, but we don't need to remember the temporary.
John McCall31168b02011-06-15 23:02:42 +00004960 ExprNeedsCleanups = true;
Richard Smithfd555f62012-02-22 02:04:18 +00004961 }
Richard Smitheec915d62012-02-18 04:13:32 +00004962
4963 CXXTemporary *Temp = CXXTemporary::Create(Context, Destructor);
Richard Smithfd555f62012-02-22 02:04:18 +00004964 CXXBindTemporaryExpr *Bind = CXXBindTemporaryExpr::Create(Context, Temp, E);
4965
4966 if (IsDecltype)
4967 ExprEvalContexts.back().DelayedDecltypeBinds.push_back(Bind);
4968
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004969 return Bind;
Anders Carlsson2d4cada2009-05-30 20:36:53 +00004970}
4971
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004972ExprResult
John McCall5d413782010-12-06 08:20:24 +00004973Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) {
Douglas Gregorb6ea6082009-12-22 22:17:25 +00004974 if (SubExpr.isInvalid())
4975 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004976
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004977 return MaybeCreateExprWithCleanups(SubExpr.get());
Douglas Gregorb6ea6082009-12-22 22:17:25 +00004978}
4979
John McCall28fc7092011-11-10 05:35:25 +00004980Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) {
Alp Toker028ed912013-12-06 17:56:43 +00004981 assert(SubExpr && "subexpression can't be null!");
John McCall28fc7092011-11-10 05:35:25 +00004982
Eli Friedman3bda6b12012-02-02 23:15:15 +00004983 CleanupVarDeclMarking();
4984
John McCall28fc7092011-11-10 05:35:25 +00004985 unsigned FirstCleanup = ExprEvalContexts.back().NumCleanupObjects;
4986 assert(ExprCleanupObjects.size() >= FirstCleanup);
4987 assert(ExprNeedsCleanups || ExprCleanupObjects.size() == FirstCleanup);
4988 if (!ExprNeedsCleanups)
4989 return SubExpr;
4990
4991 ArrayRef<ExprWithCleanups::CleanupObject> Cleanups
4992 = llvm::makeArrayRef(ExprCleanupObjects.begin() + FirstCleanup,
4993 ExprCleanupObjects.size() - FirstCleanup);
4994
4995 Expr *E = ExprWithCleanups::Create(Context, SubExpr, Cleanups);
4996 DiscardCleanupsInEvaluationContext();
4997
4998 return E;
4999}
5000
John McCall5d413782010-12-06 08:20:24 +00005001Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) {
Alp Toker028ed912013-12-06 17:56:43 +00005002 assert(SubStmt && "sub-statement can't be null!");
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00005003
Eli Friedman3bda6b12012-02-02 23:15:15 +00005004 CleanupVarDeclMarking();
5005
John McCall31168b02011-06-15 23:02:42 +00005006 if (!ExprNeedsCleanups)
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00005007 return SubStmt;
5008
5009 // FIXME: In order to attach the temporaries, wrap the statement into
5010 // a StmtExpr; currently this is only used for asm statements.
5011 // This is hacky, either create a new CXXStmtWithTemporaries statement or
5012 // a new AsmStmtWithTemporaries.
Nico Webera2a0eb92012-12-29 20:03:39 +00005013 CompoundStmt *CompStmt = new (Context) CompoundStmt(Context, SubStmt,
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00005014 SourceLocation(),
5015 SourceLocation());
5016 Expr *E = new (Context) StmtExpr(CompStmt, Context.VoidTy, SourceLocation(),
5017 SourceLocation());
John McCall5d413782010-12-06 08:20:24 +00005018 return MaybeCreateExprWithCleanups(E);
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00005019}
5020
Richard Smithfd555f62012-02-22 02:04:18 +00005021/// Process the expression contained within a decltype. For such expressions,
5022/// certain semantic checks on temporaries are delayed until this point, and
5023/// are omitted for the 'topmost' call in the decltype expression. If the
5024/// topmost call bound a temporary, strip that temporary off the expression.
5025ExprResult Sema::ActOnDecltypeExpression(Expr *E) {
Benjamin Kramer671f4c02012-11-15 15:18:42 +00005026 assert(ExprEvalContexts.back().IsDecltype && "not in a decltype expression");
Richard Smithfd555f62012-02-22 02:04:18 +00005027
5028 // C++11 [expr.call]p11:
5029 // If a function call is a prvalue of object type,
5030 // -- if the function call is either
5031 // -- the operand of a decltype-specifier, or
5032 // -- the right operand of a comma operator that is the operand of a
5033 // decltype-specifier,
5034 // a temporary object is not introduced for the prvalue.
5035
5036 // Recursively rebuild ParenExprs and comma expressions to strip out the
5037 // outermost CXXBindTemporaryExpr, if any.
5038 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
5039 ExprResult SubExpr = ActOnDecltypeExpression(PE->getSubExpr());
5040 if (SubExpr.isInvalid())
5041 return ExprError();
5042 if (SubExpr.get() == PE->getSubExpr())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005043 return E;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005044 return ActOnParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
Richard Smithfd555f62012-02-22 02:04:18 +00005045 }
5046 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5047 if (BO->getOpcode() == BO_Comma) {
5048 ExprResult RHS = ActOnDecltypeExpression(BO->getRHS());
5049 if (RHS.isInvalid())
5050 return ExprError();
5051 if (RHS.get() == BO->getRHS())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005052 return E;
5053 return new (Context) BinaryOperator(
5054 BO->getLHS(), RHS.get(), BO_Comma, BO->getType(), BO->getValueKind(),
5055 BO->getObjectKind(), BO->getOperatorLoc(), BO->isFPContractable());
Richard Smithfd555f62012-02-22 02:04:18 +00005056 }
5057 }
5058
5059 CXXBindTemporaryExpr *TopBind = dyn_cast<CXXBindTemporaryExpr>(E);
Craig Topperc3ec1492014-05-26 06:22:03 +00005060 CallExpr *TopCall = TopBind ? dyn_cast<CallExpr>(TopBind->getSubExpr())
5061 : nullptr;
Richard Smith202dc132014-02-18 03:51:47 +00005062 if (TopCall)
5063 E = TopCall;
5064 else
Craig Topperc3ec1492014-05-26 06:22:03 +00005065 TopBind = nullptr;
Richard Smithfd555f62012-02-22 02:04:18 +00005066
5067 // Disable the special decltype handling now.
Benjamin Kramer671f4c02012-11-15 15:18:42 +00005068 ExprEvalContexts.back().IsDecltype = false;
Richard Smithfd555f62012-02-22 02:04:18 +00005069
Richard Smithf86b0ae2012-07-28 19:54:11 +00005070 // In MS mode, don't perform any extra checking of call return types within a
5071 // decltype expression.
Alp Tokerbfa39342014-01-14 12:51:41 +00005072 if (getLangOpts().MSVCCompat)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005073 return E;
Richard Smithf86b0ae2012-07-28 19:54:11 +00005074
Richard Smithfd555f62012-02-22 02:04:18 +00005075 // Perform the semantic checks we delayed until this point.
Benjamin Kramer671f4c02012-11-15 15:18:42 +00005076 for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeCalls.size();
5077 I != N; ++I) {
5078 CallExpr *Call = ExprEvalContexts.back().DelayedDecltypeCalls[I];
Richard Smithfd555f62012-02-22 02:04:18 +00005079 if (Call == TopCall)
5080 continue;
5081
5082 if (CheckCallReturnType(Call->getCallReturnType(),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005083 Call->getLocStart(),
Richard Smithfd555f62012-02-22 02:04:18 +00005084 Call, Call->getDirectCallee()))
5085 return ExprError();
5086 }
5087
5088 // Now all relevant types are complete, check the destructors are accessible
5089 // and non-deleted, and annotate them on the temporaries.
Benjamin Kramer671f4c02012-11-15 15:18:42 +00005090 for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeBinds.size();
5091 I != N; ++I) {
5092 CXXBindTemporaryExpr *Bind =
5093 ExprEvalContexts.back().DelayedDecltypeBinds[I];
Richard Smithfd555f62012-02-22 02:04:18 +00005094 if (Bind == TopBind)
5095 continue;
5096
5097 CXXTemporary *Temp = Bind->getTemporary();
5098
5099 CXXRecordDecl *RD =
5100 Bind->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
5101 CXXDestructorDecl *Destructor = LookupDestructor(RD);
5102 Temp->setDestructor(Destructor);
5103
Richard Smith7d847b12012-05-11 22:20:10 +00005104 MarkFunctionReferenced(Bind->getExprLoc(), Destructor);
5105 CheckDestructorAccess(Bind->getExprLoc(), Destructor,
Richard Smithfd555f62012-02-22 02:04:18 +00005106 PDiag(diag::err_access_dtor_temp)
Richard Smith7d847b12012-05-11 22:20:10 +00005107 << Bind->getType());
Richard Smith22262ab2013-05-04 06:44:46 +00005108 if (DiagnoseUseOfDecl(Destructor, Bind->getExprLoc()))
5109 return ExprError();
Richard Smithfd555f62012-02-22 02:04:18 +00005110
5111 // We need a cleanup, but we don't need to remember the temporary.
5112 ExprNeedsCleanups = true;
5113 }
5114
5115 // Possibly strip off the top CXXBindTemporaryExpr.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005116 return E;
Richard Smithfd555f62012-02-22 02:04:18 +00005117}
5118
Richard Smith79c927b2013-11-06 19:31:51 +00005119/// Note a set of 'operator->' functions that were used for a member access.
5120static void noteOperatorArrows(Sema &S,
5121 llvm::ArrayRef<FunctionDecl *> OperatorArrows) {
5122 unsigned SkipStart = OperatorArrows.size(), SkipCount = 0;
5123 // FIXME: Make this configurable?
5124 unsigned Limit = 9;
5125 if (OperatorArrows.size() > Limit) {
5126 // Produce Limit-1 normal notes and one 'skipping' note.
5127 SkipStart = (Limit - 1) / 2 + (Limit - 1) % 2;
5128 SkipCount = OperatorArrows.size() - (Limit - 1);
5129 }
5130
5131 for (unsigned I = 0; I < OperatorArrows.size(); /**/) {
5132 if (I == SkipStart) {
5133 S.Diag(OperatorArrows[I]->getLocation(),
5134 diag::note_operator_arrows_suppressed)
5135 << SkipCount;
5136 I += SkipCount;
5137 } else {
5138 S.Diag(OperatorArrows[I]->getLocation(), diag::note_operator_arrow_here)
5139 << OperatorArrows[I]->getCallResultType();
5140 ++I;
5141 }
5142 }
5143}
5144
John McCalldadc5752010-08-24 06:29:42 +00005145ExprResult
John McCallb268a282010-08-23 23:25:46 +00005146Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base, SourceLocation OpLoc,
John McCallba7bf592010-08-24 05:47:05 +00005147 tok::TokenKind OpKind, ParsedType &ObjectType,
Douglas Gregore610ada2010-02-24 18:44:31 +00005148 bool &MayBePseudoDestructor) {
Douglas Gregorb7bfe792009-09-02 22:59:36 +00005149 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00005150 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00005151 if (Result.isInvalid()) return ExprError();
5152 Base = Result.get();
Mike Stump11289f42009-09-09 15:08:12 +00005153
John McCall526ab472011-10-25 17:37:35 +00005154 Result = CheckPlaceholderExpr(Base);
5155 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005156 Base = Result.get();
John McCall526ab472011-10-25 17:37:35 +00005157
John McCallb268a282010-08-23 23:25:46 +00005158 QualType BaseType = Base->getType();
Douglas Gregore610ada2010-02-24 18:44:31 +00005159 MayBePseudoDestructor = false;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00005160 if (BaseType->isDependentType()) {
Douglas Gregor41127182009-11-04 22:49:18 +00005161 // If we have a pointer to a dependent type and are using the -> operator,
5162 // the object type is the type that the pointer points to. We might still
5163 // have enough information about that type to do something useful.
5164 if (OpKind == tok::arrow)
5165 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
5166 BaseType = Ptr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005167
John McCallba7bf592010-08-24 05:47:05 +00005168 ObjectType = ParsedType::make(BaseType);
Douglas Gregore610ada2010-02-24 18:44:31 +00005169 MayBePseudoDestructor = true;
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005170 return Base;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00005171 }
Mike Stump11289f42009-09-09 15:08:12 +00005172
Douglas Gregorb7bfe792009-09-02 22:59:36 +00005173 // C++ [over.match.oper]p8:
Mike Stump11289f42009-09-09 15:08:12 +00005174 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregorb7bfe792009-09-02 22:59:36 +00005175 // returned, with the original second operand.
5176 if (OpKind == tok::arrow) {
Richard Smith79c927b2013-11-06 19:31:51 +00005177 QualType StartingType = BaseType;
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00005178 bool NoArrowOperatorFound = false;
5179 bool FirstIteration = true;
5180 FunctionDecl *CurFD = dyn_cast<FunctionDecl>(CurContext);
John McCallc1538c02009-09-30 01:01:30 +00005181 // The set of types we've considered so far.
John McCallbd0465b2009-09-30 01:30:54 +00005182 llvm::SmallPtrSet<CanQualType,8> CTypes;
Richard Smith79c927b2013-11-06 19:31:51 +00005183 SmallVector<FunctionDecl*, 8> OperatorArrows;
John McCallbd0465b2009-09-30 01:30:54 +00005184 CTypes.insert(Context.getCanonicalType(BaseType));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005185
Douglas Gregorb7bfe792009-09-02 22:59:36 +00005186 while (BaseType->isRecordType()) {
Richard Smith79c927b2013-11-06 19:31:51 +00005187 if (OperatorArrows.size() >= getLangOpts().ArrowDepth) {
5188 Diag(OpLoc, diag::err_operator_arrow_depth_exceeded)
Richard Smith9dbc5742013-11-06 19:43:09 +00005189 << StartingType << getLangOpts().ArrowDepth << Base->getSourceRange();
Richard Smith79c927b2013-11-06 19:31:51 +00005190 noteOperatorArrows(*this, OperatorArrows);
5191 Diag(OpLoc, diag::note_operator_arrow_depth)
5192 << getLangOpts().ArrowDepth;
5193 return ExprError();
5194 }
5195
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00005196 Result = BuildOverloadedArrowExpr(
5197 S, Base, OpLoc,
5198 // When in a template specialization and on the first loop iteration,
5199 // potentially give the default diagnostic (with the fixit in a
5200 // separate note) instead of having the error reported back to here
5201 // and giving a diagnostic with a fixit attached to the error itself.
5202 (FirstIteration && CurFD && CurFD->isFunctionTemplateSpecialization())
Craig Topperc3ec1492014-05-26 06:22:03 +00005203 ? nullptr
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00005204 : &NoArrowOperatorFound);
5205 if (Result.isInvalid()) {
5206 if (NoArrowOperatorFound) {
5207 if (FirstIteration) {
5208 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
Richard Smith9dbc5742013-11-06 19:43:09 +00005209 << BaseType << 1 << Base->getSourceRange()
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00005210 << FixItHint::CreateReplacement(OpLoc, ".");
5211 OpKind = tok::period;
5212 break;
Kaelyn Uhrain957c8b12013-07-31 20:16:17 +00005213 }
5214 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
5215 << BaseType << Base->getSourceRange();
5216 CallExpr *CE = dyn_cast<CallExpr>(Base);
Craig Topperc3ec1492014-05-26 06:22:03 +00005217 if (Decl *CD = (CE ? CE->getCalleeDecl() : nullptr)) {
Kaelyn Uhrain957c8b12013-07-31 20:16:17 +00005218 Diag(CD->getLocStart(),
5219 diag::note_member_reference_arrow_from_operator_arrow);
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00005220 }
5221 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +00005222 return ExprError();
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00005223 }
John McCallb268a282010-08-23 23:25:46 +00005224 Base = Result.get();
5225 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
Richard Smith79c927b2013-11-06 19:31:51 +00005226 OperatorArrows.push_back(OpCall->getDirectCallee());
John McCallb268a282010-08-23 23:25:46 +00005227 BaseType = Base->getType();
John McCallc1538c02009-09-30 01:01:30 +00005228 CanQualType CBaseType = Context.getCanonicalType(BaseType);
John McCallbd0465b2009-09-30 01:30:54 +00005229 if (!CTypes.insert(CBaseType)) {
Richard Smith79c927b2013-11-06 19:31:51 +00005230 Diag(OpLoc, diag::err_operator_arrow_circular) << StartingType;
5231 noteOperatorArrows(*this, OperatorArrows);
Fariborz Jahanian10ce9582009-09-30 00:19:41 +00005232 return ExprError();
5233 }
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00005234 FirstIteration = false;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00005235 }
Mike Stump11289f42009-09-09 15:08:12 +00005236
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00005237 if (OpKind == tok::arrow &&
5238 (BaseType->isPointerType() || BaseType->isObjCObjectPointerType()))
Douglas Gregore4f764f2009-11-20 19:58:21 +00005239 BaseType = BaseType->getPointeeType();
5240 }
Mike Stump11289f42009-09-09 15:08:12 +00005241
Douglas Gregorbf3a8262012-01-12 16:11:24 +00005242 // Objective-C properties allow "." access on Objective-C pointer types,
5243 // so adjust the base type to the object type itself.
5244 if (BaseType->isObjCObjectPointerType())
5245 BaseType = BaseType->getPointeeType();
5246
5247 // C++ [basic.lookup.classref]p2:
5248 // [...] If the type of the object expression is of pointer to scalar
5249 // type, the unqualified-id is looked up in the context of the complete
5250 // postfix-expression.
5251 //
5252 // This also indicates that we could be parsing a pseudo-destructor-name.
5253 // Note that Objective-C class and object types can be pseudo-destructor
5254 // expressions or normal member (ivar or property) access expressions.
5255 if (BaseType->isObjCObjectOrInterfaceType()) {
5256 MayBePseudoDestructor = true;
5257 } else if (!BaseType->isRecordType()) {
John McCallba7bf592010-08-24 05:47:05 +00005258 ObjectType = ParsedType();
Douglas Gregore610ada2010-02-24 18:44:31 +00005259 MayBePseudoDestructor = true;
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005260 return Base;
Douglas Gregor2b6ca462009-09-03 21:38:09 +00005261 }
Mike Stump11289f42009-09-09 15:08:12 +00005262
Douglas Gregor3024f072012-04-16 07:05:22 +00005263 // The object type must be complete (or dependent), or
5264 // C++11 [expr.prim.general]p3:
5265 // Unlike the object expression in other contexts, *this is not required to
5266 // be of complete type for purposes of class member access (5.2.5) outside
5267 // the member function body.
Douglas Gregor3fad6172009-11-17 05:17:33 +00005268 if (!BaseType->isDependentType() &&
Douglas Gregor3024f072012-04-16 07:05:22 +00005269 !isThisOutsideMemberFunctionBody(BaseType) &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005270 RequireCompleteType(OpLoc, BaseType, diag::err_incomplete_member_access))
Douglas Gregor3fad6172009-11-17 05:17:33 +00005271 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005272
Douglas Gregor2b6ca462009-09-03 21:38:09 +00005273 // C++ [basic.lookup.classref]p2:
Mike Stump11289f42009-09-09 15:08:12 +00005274 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor3fad6172009-11-17 05:17:33 +00005275 // unqualified-id, and the type of the object expression is of a class
Douglas Gregor2b6ca462009-09-03 21:38:09 +00005276 // type C (or of pointer to a class type C), the unqualified-id is looked
5277 // up in the scope of class C. [...]
John McCallba7bf592010-08-24 05:47:05 +00005278 ObjectType = ParsedType::make(BaseType);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005279 return Base;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00005280}
5281
John McCalldadc5752010-08-24 06:29:42 +00005282ExprResult Sema::DiagnoseDtorReference(SourceLocation NameLoc,
John McCallb268a282010-08-23 23:25:46 +00005283 Expr *MemExpr) {
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00005284 SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(NameLoc);
John McCallb268a282010-08-23 23:25:46 +00005285 Diag(MemExpr->getLocStart(), diag::err_dtor_expr_without_call)
5286 << isa<CXXPseudoDestructorExpr>(MemExpr)
Douglas Gregora771f462010-03-31 17:46:05 +00005287 << FixItHint::CreateInsertion(ExpectedLParenLoc, "()");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005288
Craig Topperc3ec1492014-05-26 06:22:03 +00005289 return ActOnCallExpr(/*Scope*/ nullptr,
John McCallb268a282010-08-23 23:25:46 +00005290 MemExpr,
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00005291 /*LPLoc*/ ExpectedLParenLoc,
Dmitri Gribenko78852e92013-05-05 20:40:26 +00005292 None,
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00005293 /*RPLoc*/ ExpectedLParenLoc);
5294}
Douglas Gregore610ada2010-02-24 18:44:31 +00005295
Eli Friedman6601b552012-01-25 04:29:24 +00005296static bool CheckArrow(Sema& S, QualType& ObjectType, Expr *&Base,
David Blaikie1d578782011-12-16 16:03:09 +00005297 tok::TokenKind& OpKind, SourceLocation OpLoc) {
Eli Friedman6601b552012-01-25 04:29:24 +00005298 if (Base->hasPlaceholderType()) {
5299 ExprResult result = S.CheckPlaceholderExpr(Base);
5300 if (result.isInvalid()) return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005301 Base = result.get();
Eli Friedman6601b552012-01-25 04:29:24 +00005302 }
5303 ObjectType = Base->getType();
5304
David Blaikie1d578782011-12-16 16:03:09 +00005305 // C++ [expr.pseudo]p2:
5306 // The left-hand side of the dot operator shall be of scalar type. The
5307 // left-hand side of the arrow operator shall be of pointer to scalar type.
5308 // This scalar type is the object type.
Eli Friedman6601b552012-01-25 04:29:24 +00005309 // Note that this is rather different from the normal handling for the
5310 // arrow operator.
David Blaikie1d578782011-12-16 16:03:09 +00005311 if (OpKind == tok::arrow) {
5312 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
5313 ObjectType = Ptr->getPointeeType();
5314 } else if (!Base->isTypeDependent()) {
5315 // The user wrote "p->" when she probably meant "p."; fix it.
5316 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
5317 << ObjectType << true
5318 << FixItHint::CreateReplacement(OpLoc, ".");
5319 if (S.isSFINAEContext())
5320 return true;
5321
5322 OpKind = tok::period;
5323 }
5324 }
5325
5326 return false;
5327}
5328
John McCalldadc5752010-08-24 06:29:42 +00005329ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
John McCalla2c4e722011-02-25 05:21:17 +00005330 SourceLocation OpLoc,
5331 tok::TokenKind OpKind,
5332 const CXXScopeSpec &SS,
5333 TypeSourceInfo *ScopeTypeInfo,
5334 SourceLocation CCLoc,
5335 SourceLocation TildeLoc,
Douglas Gregor678f90d2010-02-25 01:56:36 +00005336 PseudoDestructorTypeStorage Destructed,
John McCalla2c4e722011-02-25 05:21:17 +00005337 bool HasTrailingLParen) {
Douglas Gregor678f90d2010-02-25 01:56:36 +00005338 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005339
Eli Friedman0ce4de42012-01-25 04:35:06 +00005340 QualType ObjectType;
David Blaikie1d578782011-12-16 16:03:09 +00005341 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
5342 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005343
Douglas Gregorc5c57342012-09-10 14:57:06 +00005344 if (!ObjectType->isDependentType() && !ObjectType->isScalarType() &&
5345 !ObjectType->isVectorType()) {
Alp Tokerbfa39342014-01-14 12:51:41 +00005346 if (getLangOpts().MSVCCompat && ObjectType->isVoidType())
Nico Weber4bc64992012-01-23 06:08:16 +00005347 Diag(OpLoc, diag::ext_pseudo_dtor_on_void) << Base->getSourceRange();
Reid Klecknere5025072014-05-01 16:50:23 +00005348 else {
Nico Weber58829272012-01-23 05:50:57 +00005349 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
5350 << ObjectType << Base->getSourceRange();
Reid Klecknere5025072014-05-01 16:50:23 +00005351 return ExprError();
5352 }
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00005353 }
5354
5355 // C++ [expr.pseudo]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005356 // [...] The cv-unqualified versions of the object type and of the type
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00005357 // designated by the pseudo-destructor-name shall be the same type.
Douglas Gregor678f90d2010-02-25 01:56:36 +00005358 if (DestructedTypeInfo) {
5359 QualType DestructedType = DestructedTypeInfo->getType();
5360 SourceLocation DestructedTypeStart
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00005361 = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
John McCall31168b02011-06-15 23:02:42 +00005362 if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) {
5363 if (!Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
5364 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
5365 << ObjectType << DestructedType << Base->getSourceRange()
5366 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005367
John McCall31168b02011-06-15 23:02:42 +00005368 // Recover by setting the destructed type to the object type.
5369 DestructedType = ObjectType;
5370 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
Douglas Gregor678f90d2010-02-25 01:56:36 +00005371 DestructedTypeStart);
John McCall31168b02011-06-15 23:02:42 +00005372 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
5373 } else if (DestructedType.getObjCLifetime() !=
5374 ObjectType.getObjCLifetime()) {
5375
5376 if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) {
5377 // Okay: just pretend that the user provided the correctly-qualified
5378 // type.
5379 } else {
5380 Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals)
5381 << ObjectType << DestructedType << Base->getSourceRange()
5382 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
5383 }
5384
5385 // Recover by setting the destructed type to the object type.
5386 DestructedType = ObjectType;
5387 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
5388 DestructedTypeStart);
5389 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
5390 }
Douglas Gregor678f90d2010-02-25 01:56:36 +00005391 }
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00005392 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005393
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00005394 // C++ [expr.pseudo]p2:
5395 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
5396 // form
5397 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005398 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00005399 //
5400 // shall designate the same scalar type.
5401 if (ScopeTypeInfo) {
5402 QualType ScopeType = ScopeTypeInfo->getType();
5403 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
John McCallb86a6b82010-06-11 17:36:40 +00005404 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005405
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00005406 Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00005407 diag::err_pseudo_dtor_type_mismatch)
John McCallb268a282010-08-23 23:25:46 +00005408 << ObjectType << ScopeType << Base->getSourceRange()
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00005409 << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005410
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00005411 ScopeType = QualType();
Craig Topperc3ec1492014-05-26 06:22:03 +00005412 ScopeTypeInfo = nullptr;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00005413 }
5414 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005415
John McCallb268a282010-08-23 23:25:46 +00005416 Expr *Result
5417 = new (Context) CXXPseudoDestructorExpr(Context, Base,
5418 OpKind == tok::arrow, OpLoc,
Douglas Gregora6ce6082011-02-25 18:19:59 +00005419 SS.getWithLocInContext(Context),
John McCallb268a282010-08-23 23:25:46 +00005420 ScopeTypeInfo,
5421 CCLoc,
5422 TildeLoc,
5423 Destructed);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005424
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00005425 if (HasTrailingLParen)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005426 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005427
John McCallb268a282010-08-23 23:25:46 +00005428 return DiagnoseDtorReference(Destructed.getLocation(), Result);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00005429}
5430
John McCalldadc5752010-08-24 06:29:42 +00005431ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
John McCalla2c4e722011-02-25 05:21:17 +00005432 SourceLocation OpLoc,
5433 tok::TokenKind OpKind,
5434 CXXScopeSpec &SS,
5435 UnqualifiedId &FirstTypeName,
5436 SourceLocation CCLoc,
5437 SourceLocation TildeLoc,
5438 UnqualifiedId &SecondTypeName,
5439 bool HasTrailingLParen) {
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00005440 assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
5441 FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
5442 "Invalid first type name in pseudo-destructor");
5443 assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
5444 SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
5445 "Invalid second type name in pseudo-destructor");
5446
Eli Friedman0ce4de42012-01-25 04:35:06 +00005447 QualType ObjectType;
David Blaikie1d578782011-12-16 16:03:09 +00005448 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
5449 return ExprError();
Douglas Gregor678f90d2010-02-25 01:56:36 +00005450
5451 // Compute the object type that we should use for name lookup purposes. Only
5452 // record types and dependent types matter.
John McCallba7bf592010-08-24 05:47:05 +00005453 ParsedType ObjectTypePtrForLookup;
Douglas Gregor678f90d2010-02-25 01:56:36 +00005454 if (!SS.isSet()) {
John McCalla2c4e722011-02-25 05:21:17 +00005455 if (ObjectType->isRecordType())
5456 ObjectTypePtrForLookup = ParsedType::make(ObjectType);
John McCallba7bf592010-08-24 05:47:05 +00005457 else if (ObjectType->isDependentType())
5458 ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
Douglas Gregor678f90d2010-02-25 01:56:36 +00005459 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005460
5461 // Convert the name of the type being destructed (following the ~) into a
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00005462 // type (with source-location information).
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00005463 QualType DestructedType;
Craig Topperc3ec1492014-05-26 06:22:03 +00005464 TypeSourceInfo *DestructedTypeInfo = nullptr;
Douglas Gregor678f90d2010-02-25 01:56:36 +00005465 PseudoDestructorTypeStorage Destructed;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00005466 if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005467 ParsedType T = getTypeName(*SecondTypeName.Identifier,
John McCallba7bf592010-08-24 05:47:05 +00005468 SecondTypeName.StartLocation,
Fariborz Jahanian87967422011-02-08 18:05:59 +00005469 S, &SS, true, false, ObjectTypePtrForLookup);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005470 if (!T &&
Douglas Gregor678f90d2010-02-25 01:56:36 +00005471 ((SS.isSet() && !computeDeclContext(SS, false)) ||
5472 (!SS.isSet() && ObjectType->isDependentType()))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005473 // The name of the type being destroyed is a dependent name, and we
Douglas Gregor678f90d2010-02-25 01:56:36 +00005474 // couldn't find anything useful in scope. Just store the identifier and
5475 // it's location, and we'll perform (qualified) name lookup again at
5476 // template instantiation time.
5477 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
5478 SecondTypeName.StartLocation);
5479 } else if (!T) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005480 Diag(SecondTypeName.StartLocation,
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00005481 diag::err_pseudo_dtor_destructor_non_type)
5482 << SecondTypeName.Identifier << ObjectType;
5483 if (isSFINAEContext())
5484 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005485
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00005486 // Recover by assuming we had the right type all along.
5487 DestructedType = ObjectType;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00005488 } else
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00005489 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00005490 } else {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00005491 // Resolve the template-id to a type.
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00005492 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00005493 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00005494 TemplateId->NumArgs);
Douglas Gregore7c20652011-03-02 00:47:37 +00005495 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00005496 TemplateId->TemplateKWLoc,
Douglas Gregore7c20652011-03-02 00:47:37 +00005497 TemplateId->Template,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00005498 TemplateId->TemplateNameLoc,
5499 TemplateId->LAngleLoc,
5500 TemplateArgsPtr,
5501 TemplateId->RAngleLoc);
5502 if (T.isInvalid() || !T.get()) {
5503 // Recover by assuming we had the right type all along.
5504 DestructedType = ObjectType;
5505 } else
5506 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00005507 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005508
5509 // If we've performed some kind of recovery, (re-)build the type source
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00005510 // information.
Douglas Gregor678f90d2010-02-25 01:56:36 +00005511 if (!DestructedType.isNull()) {
5512 if (!DestructedTypeInfo)
5513 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00005514 SecondTypeName.StartLocation);
Douglas Gregor678f90d2010-02-25 01:56:36 +00005515 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
5516 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005517
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00005518 // Convert the name of the scope type (the type prior to '::') into a type.
Craig Topperc3ec1492014-05-26 06:22:03 +00005519 TypeSourceInfo *ScopeTypeInfo = nullptr;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00005520 QualType ScopeType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005521 if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00005522 FirstTypeName.Identifier) {
5523 if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005524 ParsedType T = getTypeName(*FirstTypeName.Identifier,
John McCallba7bf592010-08-24 05:47:05 +00005525 FirstTypeName.StartLocation,
Douglas Gregora6ce6082011-02-25 18:19:59 +00005526 S, &SS, true, false, ObjectTypePtrForLookup);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00005527 if (!T) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005528 Diag(FirstTypeName.StartLocation,
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00005529 diag::err_pseudo_dtor_destructor_non_type)
5530 << FirstTypeName.Identifier << ObjectType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005531
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00005532 if (isSFINAEContext())
5533 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005534
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00005535 // Just drop this type. It's unnecessary anyway.
5536 ScopeType = QualType();
5537 } else
5538 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00005539 } else {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00005540 // Resolve the template-id to a type.
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00005541 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00005542 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00005543 TemplateId->NumArgs);
Douglas Gregore7c20652011-03-02 00:47:37 +00005544 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00005545 TemplateId->TemplateKWLoc,
Douglas Gregore7c20652011-03-02 00:47:37 +00005546 TemplateId->Template,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00005547 TemplateId->TemplateNameLoc,
5548 TemplateId->LAngleLoc,
5549 TemplateArgsPtr,
5550 TemplateId->RAngleLoc);
5551 if (T.isInvalid() || !T.get()) {
5552 // Recover by dropping this type.
5553 ScopeType = QualType();
5554 } else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005555 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00005556 }
5557 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005558
Douglas Gregor90ad9222010-02-24 23:02:30 +00005559 if (!ScopeType.isNull() && !ScopeTypeInfo)
5560 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
5561 FirstTypeName.StartLocation);
5562
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005563
John McCallb268a282010-08-23 23:25:46 +00005564 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
Douglas Gregorcdbd5152010-02-24 23:50:37 +00005565 ScopeTypeInfo, CCLoc, TildeLoc,
Douglas Gregor678f90d2010-02-25 01:56:36 +00005566 Destructed, HasTrailingLParen);
Douglas Gregore610ada2010-02-24 18:44:31 +00005567}
5568
David Blaikie1d578782011-12-16 16:03:09 +00005569ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
5570 SourceLocation OpLoc,
5571 tok::TokenKind OpKind,
5572 SourceLocation TildeLoc,
5573 const DeclSpec& DS,
5574 bool HasTrailingLParen) {
Eli Friedman0ce4de42012-01-25 04:35:06 +00005575 QualType ObjectType;
David Blaikie1d578782011-12-16 16:03:09 +00005576 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
5577 return ExprError();
5578
5579 QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
5580
5581 TypeLocBuilder TLB;
5582 DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T);
5583 DecltypeTL.setNameLoc(DS.getTypeSpecTypeLoc());
5584 TypeSourceInfo *DestructedTypeInfo = TLB.getTypeSourceInfo(Context, T);
5585 PseudoDestructorTypeStorage Destructed(DestructedTypeInfo);
5586
5587 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, CXXScopeSpec(),
Craig Topperc3ec1492014-05-26 06:22:03 +00005588 nullptr, SourceLocation(), TildeLoc,
David Blaikie1d578782011-12-16 16:03:09 +00005589 Destructed, HasTrailingLParen);
5590}
5591
John Wiegley01296292011-04-08 18:41:53 +00005592ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,
Eli Friedman2fb85122012-03-01 01:30:04 +00005593 CXXConversionDecl *Method,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005594 bool HadMultipleCandidates) {
Eli Friedman98b01ed2012-03-01 04:01:32 +00005595 if (Method->getParent()->isLambda() &&
5596 Method->getConversionType()->isBlockPointerType()) {
5597 // This is a lambda coversion to block pointer; check if the argument
5598 // is a LambdaExpr.
5599 Expr *SubE = E;
5600 CastExpr *CE = dyn_cast<CastExpr>(SubE);
5601 if (CE && CE->getCastKind() == CK_NoOp)
5602 SubE = CE->getSubExpr();
5603 SubE = SubE->IgnoreParens();
5604 if (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(SubE))
5605 SubE = BE->getSubExpr();
5606 if (isa<LambdaExpr>(SubE)) {
5607 // For the conversion to block pointer on a lambda expression, we
5608 // construct a special BlockLiteral instead; this doesn't really make
5609 // a difference in ARC, but outside of ARC the resulting block literal
5610 // follows the normal lifetime rules for block literals instead of being
5611 // autoreleased.
5612 DiagnosticErrorTrap Trap(Diags);
5613 ExprResult Exp = BuildBlockForLambdaConversion(E->getExprLoc(),
5614 E->getExprLoc(),
5615 Method, E);
5616 if (Exp.isInvalid())
5617 Diag(E->getExprLoc(), diag::note_lambda_to_block_conv);
5618 return Exp;
5619 }
5620 }
Eli Friedman98b01ed2012-03-01 04:01:32 +00005621
Craig Topperc3ec1492014-05-26 06:22:03 +00005622 ExprResult Exp = PerformObjectArgumentInitialization(E, /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +00005623 FoundDecl, Method);
5624 if (Exp.isInvalid())
Douglas Gregor668443e2011-01-20 00:18:04 +00005625 return true;
Eli Friedmanf7195532009-12-09 04:53:56 +00005626
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005627 MemberExpr *ME =
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005628 new (Context) MemberExpr(Exp.get(), /*IsArrow=*/false, Method,
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00005629 SourceLocation(), Context.BoundMemberTy,
John McCall7decc9e2010-11-18 06:31:45 +00005630 VK_RValue, OK_Ordinary);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005631 if (HadMultipleCandidates)
5632 ME->setHadMultipleCandidates(true);
Nick Lewyckya096b142013-02-12 08:08:54 +00005633 MarkMemberReferenced(ME);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005634
Alp Toker314cc812014-01-25 16:55:45 +00005635 QualType ResultType = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +00005636 ExprValueKind VK = Expr::getValueKindForType(ResultType);
5637 ResultType = ResultType.getNonLValueExprType(Context);
5638
Douglas Gregor27381f32009-11-23 12:27:39 +00005639 CXXMemberCallExpr *CE =
Dmitri Gribenko78852e92013-05-05 20:40:26 +00005640 new (Context) CXXMemberCallExpr(Context, ME, None, ResultType, VK,
John Wiegley01296292011-04-08 18:41:53 +00005641 Exp.get()->getLocEnd());
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00005642 return CE;
5643}
5644
Sebastian Redl4202c0f2010-09-10 20:55:43 +00005645ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
5646 SourceLocation RParen) {
Richard Smithf623c962012-04-17 00:58:00 +00005647 CanThrowResult CanThrow = canThrow(Operand);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005648 return new (Context)
5649 CXXNoexceptExpr(Context.BoolTy, Operand, CanThrow, KeyLoc, RParen);
Sebastian Redl4202c0f2010-09-10 20:55:43 +00005650}
5651
5652ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,
5653 Expr *Operand, SourceLocation RParen) {
5654 return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
Sebastian Redl22e3a932010-09-10 20:55:37 +00005655}
5656
Eli Friedmanf798f652012-05-24 22:04:19 +00005657static bool IsSpecialDiscardedValue(Expr *E) {
5658 // In C++11, discarded-value expressions of a certain form are special,
5659 // according to [expr]p10:
5660 // The lvalue-to-rvalue conversion (4.1) is applied only if the
5661 // expression is an lvalue of volatile-qualified type and it has
5662 // one of the following forms:
5663 E = E->IgnoreParens();
5664
Eli Friedmanc49c2262012-05-24 22:36:31 +00005665 // - id-expression (5.1.1),
Eli Friedmanf798f652012-05-24 22:04:19 +00005666 if (isa<DeclRefExpr>(E))
5667 return true;
5668
Eli Friedmanc49c2262012-05-24 22:36:31 +00005669 // - subscripting (5.2.1),
Eli Friedmanf798f652012-05-24 22:04:19 +00005670 if (isa<ArraySubscriptExpr>(E))
5671 return true;
5672
Eli Friedmanc49c2262012-05-24 22:36:31 +00005673 // - class member access (5.2.5),
Eli Friedmanf798f652012-05-24 22:04:19 +00005674 if (isa<MemberExpr>(E))
5675 return true;
5676
Eli Friedmanc49c2262012-05-24 22:36:31 +00005677 // - indirection (5.3.1),
Eli Friedmanf798f652012-05-24 22:04:19 +00005678 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E))
5679 if (UO->getOpcode() == UO_Deref)
5680 return true;
5681
5682 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
Eli Friedmanc49c2262012-05-24 22:36:31 +00005683 // - pointer-to-member operation (5.5),
Eli Friedmanf798f652012-05-24 22:04:19 +00005684 if (BO->isPtrMemOp())
5685 return true;
5686
Eli Friedmanc49c2262012-05-24 22:36:31 +00005687 // - comma expression (5.18) where the right operand is one of the above.
Eli Friedmanf798f652012-05-24 22:04:19 +00005688 if (BO->getOpcode() == BO_Comma)
5689 return IsSpecialDiscardedValue(BO->getRHS());
5690 }
5691
Eli Friedmanc49c2262012-05-24 22:36:31 +00005692 // - conditional expression (5.16) where both the second and the third
Eli Friedmanf798f652012-05-24 22:04:19 +00005693 // operands are one of the above, or
5694 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E))
5695 return IsSpecialDiscardedValue(CO->getTrueExpr()) &&
5696 IsSpecialDiscardedValue(CO->getFalseExpr());
5697 // The related edge case of "*x ?: *x".
5698 if (BinaryConditionalOperator *BCO =
5699 dyn_cast<BinaryConditionalOperator>(E)) {
5700 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(BCO->getTrueExpr()))
5701 return IsSpecialDiscardedValue(OVE->getSourceExpr()) &&
5702 IsSpecialDiscardedValue(BCO->getFalseExpr());
5703 }
5704
5705 // Objective-C++ extensions to the rule.
5706 if (isa<PseudoObjectExpr>(E) || isa<ObjCIvarRefExpr>(E))
5707 return true;
5708
5709 return false;
5710}
5711
John McCall34376a62010-12-04 03:47:34 +00005712/// Perform the conversions required for an expression used in a
5713/// context that ignores the result.
John Wiegley01296292011-04-08 18:41:53 +00005714ExprResult Sema::IgnoredValueConversions(Expr *E) {
John McCall526ab472011-10-25 17:37:35 +00005715 if (E->hasPlaceholderType()) {
5716 ExprResult result = CheckPlaceholderExpr(E);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005717 if (result.isInvalid()) return E;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005718 E = result.get();
John McCall526ab472011-10-25 17:37:35 +00005719 }
5720
John McCallfee942d2010-12-02 02:07:15 +00005721 // C99 6.3.2.1:
5722 // [Except in specific positions,] an lvalue that does not have
5723 // array type is converted to the value stored in the
5724 // designated object (and is no longer an lvalue).
John McCalld68b2d02011-06-27 21:24:11 +00005725 if (E->isRValue()) {
5726 // In C, function designators (i.e. expressions of function type)
5727 // are r-values, but we still want to do function-to-pointer decay
5728 // on them. This is both technically correct and convenient for
5729 // some clients.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005730 if (!getLangOpts().CPlusPlus && E->getType()->isFunctionType())
John McCalld68b2d02011-06-27 21:24:11 +00005731 return DefaultFunctionArrayConversion(E);
5732
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005733 return E;
John McCalld68b2d02011-06-27 21:24:11 +00005734 }
John McCallfee942d2010-12-02 02:07:15 +00005735
Eli Friedmanf798f652012-05-24 22:04:19 +00005736 if (getLangOpts().CPlusPlus) {
5737 // The C++11 standard defines the notion of a discarded-value expression;
5738 // normally, we don't need to do anything to handle it, but if it is a
5739 // volatile lvalue with a special form, we perform an lvalue-to-rvalue
5740 // conversion.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005741 if (getLangOpts().CPlusPlus11 && E->isGLValue() &&
Eli Friedmanf798f652012-05-24 22:04:19 +00005742 E->getType().isVolatileQualified() &&
5743 IsSpecialDiscardedValue(E)) {
5744 ExprResult Res = DefaultLvalueConversion(E);
5745 if (Res.isInvalid())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005746 return E;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005747 E = Res.get();
Faisal Valia17d19f2013-11-07 05:17:06 +00005748 }
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005749 return E;
Eli Friedmanf798f652012-05-24 22:04:19 +00005750 }
John McCall34376a62010-12-04 03:47:34 +00005751
5752 // GCC seems to also exclude expressions of incomplete enum type.
5753 if (const EnumType *T = E->getType()->getAs<EnumType>()) {
5754 if (!T->getDecl()->isComplete()) {
5755 // FIXME: stupid workaround for a codegen bug!
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005756 E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).get();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005757 return E;
John McCall34376a62010-12-04 03:47:34 +00005758 }
5759 }
5760
John Wiegley01296292011-04-08 18:41:53 +00005761 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
5762 if (Res.isInvalid())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005763 return E;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005764 E = Res.get();
John Wiegley01296292011-04-08 18:41:53 +00005765
John McCallca61b652010-12-04 12:29:11 +00005766 if (!E->getType()->isVoidType())
5767 RequireCompleteType(E->getExprLoc(), E->getType(),
5768 diag::err_incomplete_type);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005769 return E;
John McCall34376a62010-12-04 03:47:34 +00005770}
5771
Faisal Valia17d19f2013-11-07 05:17:06 +00005772// If we can unambiguously determine whether Var can never be used
5773// in a constant expression, return true.
5774// - if the variable and its initializer are non-dependent, then
5775// we can unambiguously check if the variable is a constant expression.
5776// - if the initializer is not value dependent - we can determine whether
5777// it can be used to initialize a constant expression. If Init can not
5778// be used to initialize a constant expression we conclude that Var can
5779// never be a constant expression.
5780// - FXIME: if the initializer is dependent, we can still do some analysis and
5781// identify certain cases unambiguously as non-const by using a Visitor:
5782// - such as those that involve odr-use of a ParmVarDecl, involve a new
5783// delete, lambda-expr, dynamic-cast, reinterpret-cast etc...
5784static inline bool VariableCanNeverBeAConstantExpression(VarDecl *Var,
5785 ASTContext &Context) {
5786 if (isa<ParmVarDecl>(Var)) return true;
Craig Topperc3ec1492014-05-26 06:22:03 +00005787 const VarDecl *DefVD = nullptr;
Faisal Valia17d19f2013-11-07 05:17:06 +00005788
5789 // If there is no initializer - this can not be a constant expression.
5790 if (!Var->getAnyInitializer(DefVD)) return true;
5791 assert(DefVD);
5792 if (DefVD->isWeak()) return false;
5793 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
Richard Smithc941ba92014-02-06 23:35:16 +00005794
Faisal Valia17d19f2013-11-07 05:17:06 +00005795 Expr *Init = cast<Expr>(Eval->Value);
5796
5797 if (Var->getType()->isDependentType() || Init->isValueDependent()) {
Richard Smithc941ba92014-02-06 23:35:16 +00005798 // FIXME: Teach the constant evaluator to deal with the non-dependent parts
5799 // of value-dependent expressions, and use it here to determine whether the
5800 // initializer is a potential constant expression.
Faisal Valia17d19f2013-11-07 05:17:06 +00005801 return false;
Richard Smithc941ba92014-02-06 23:35:16 +00005802 }
5803
Faisal Valia17d19f2013-11-07 05:17:06 +00005804 return !IsVariableAConstantExpression(Var, Context);
5805}
5806
Faisal Valiab3d6462013-12-07 20:22:44 +00005807/// \brief Check if the current lambda has any potential captures
5808/// that must be captured by any of its enclosing lambdas that are ready to
5809/// capture. If there is a lambda that can capture a nested
5810/// potential-capture, go ahead and do so. Also, check to see if any
5811/// variables are uncaptureable or do not involve an odr-use so do not
5812/// need to be captured.
Faisal Valia17d19f2013-11-07 05:17:06 +00005813
Faisal Valiab3d6462013-12-07 20:22:44 +00005814static void CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(
5815 Expr *const FE, LambdaScopeInfo *const CurrentLSI, Sema &S) {
5816
Faisal Valia17d19f2013-11-07 05:17:06 +00005817 assert(!S.isUnevaluatedContext());
5818 assert(S.CurContext->isDependentContext());
Faisal Valiab3d6462013-12-07 20:22:44 +00005819 assert(CurrentLSI->CallOperator == S.CurContext &&
5820 "The current call operator must be synchronized with Sema's CurContext");
5821
5822 const bool IsFullExprInstantiationDependent = FE->isInstantiationDependent();
5823
5824 ArrayRef<const FunctionScopeInfo *> FunctionScopesArrayRef(
5825 S.FunctionScopes.data(), S.FunctionScopes.size());
5826
5827 // All the potentially captureable variables in the current nested
Faisal Valia17d19f2013-11-07 05:17:06 +00005828 // lambda (within a generic outer lambda), must be captured by an
5829 // outer lambda that is enclosed within a non-dependent context.
Faisal Valiab3d6462013-12-07 20:22:44 +00005830 const unsigned NumPotentialCaptures =
5831 CurrentLSI->getNumPotentialVariableCaptures();
5832 for (unsigned I = 0; I != NumPotentialCaptures; ++I) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005833 Expr *VarExpr = nullptr;
5834 VarDecl *Var = nullptr;
Faisal Valia17d19f2013-11-07 05:17:06 +00005835 CurrentLSI->getPotentialVariableCapture(I, Var, VarExpr);
Faisal Valiab3d6462013-12-07 20:22:44 +00005836 // If the variable is clearly identified as non-odr-used and the full
5837 // expression is not instantiation dependent, only then do we not
5838 // need to check enclosing lambda's for speculative captures.
5839 // For e.g.:
5840 // Even though 'x' is not odr-used, it should be captured.
5841 // int test() {
5842 // const int x = 10;
5843 // auto L = [=](auto a) {
5844 // (void) +x + a;
5845 // };
5846 // }
5847 if (CurrentLSI->isVariableExprMarkedAsNonODRUsed(VarExpr) &&
Faisal Valia17d19f2013-11-07 05:17:06 +00005848 !IsFullExprInstantiationDependent)
Faisal Valiab3d6462013-12-07 20:22:44 +00005849 continue;
5850
5851 // If we have a capture-capable lambda for the variable, go ahead and
5852 // capture the variable in that lambda (and all its enclosing lambdas).
5853 if (const Optional<unsigned> Index =
5854 getStackIndexOfNearestEnclosingCaptureCapableLambda(
5855 FunctionScopesArrayRef, Var, S)) {
5856 const unsigned FunctionScopeIndexOfCapturableLambda = Index.getValue();
5857 MarkVarDeclODRUsed(Var, VarExpr->getExprLoc(), S,
5858 &FunctionScopeIndexOfCapturableLambda);
Faisal Valia17d19f2013-11-07 05:17:06 +00005859 }
5860 const bool IsVarNeverAConstantExpression =
5861 VariableCanNeverBeAConstantExpression(Var, S.Context);
5862 if (!IsFullExprInstantiationDependent || IsVarNeverAConstantExpression) {
5863 // This full expression is not instantiation dependent or the variable
5864 // can not be used in a constant expression - which means
5865 // this variable must be odr-used here, so diagnose a
5866 // capture violation early, if the variable is un-captureable.
5867 // This is purely for diagnosing errors early. Otherwise, this
5868 // error would get diagnosed when the lambda becomes capture ready.
5869 QualType CaptureType, DeclRefType;
5870 SourceLocation ExprLoc = VarExpr->getExprLoc();
5871 if (S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
5872 /*EllipsisLoc*/ SourceLocation(),
5873 /*BuildAndDiagnose*/false, CaptureType,
Craig Topperc3ec1492014-05-26 06:22:03 +00005874 DeclRefType, nullptr)) {
Faisal Valia17d19f2013-11-07 05:17:06 +00005875 // We will never be able to capture this variable, and we need
5876 // to be able to in any and all instantiations, so diagnose it.
5877 S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
5878 /*EllipsisLoc*/ SourceLocation(),
5879 /*BuildAndDiagnose*/true, CaptureType,
Craig Topperc3ec1492014-05-26 06:22:03 +00005880 DeclRefType, nullptr);
Faisal Valia17d19f2013-11-07 05:17:06 +00005881 }
5882 }
5883 }
5884
Faisal Valiab3d6462013-12-07 20:22:44 +00005885 // Check if 'this' needs to be captured.
Faisal Valia17d19f2013-11-07 05:17:06 +00005886 if (CurrentLSI->hasPotentialThisCapture()) {
Faisal Valiab3d6462013-12-07 20:22:44 +00005887 // If we have a capture-capable lambda for 'this', go ahead and capture
5888 // 'this' in that lambda (and all its enclosing lambdas).
5889 if (const Optional<unsigned> Index =
5890 getStackIndexOfNearestEnclosingCaptureCapableLambda(
Craig Topperc3ec1492014-05-26 06:22:03 +00005891 FunctionScopesArrayRef, /*0 is 'this'*/ nullptr, S)) {
Faisal Valiab3d6462013-12-07 20:22:44 +00005892 const unsigned FunctionScopeIndexOfCapturableLambda = Index.getValue();
5893 S.CheckCXXThisCapture(CurrentLSI->PotentialThisCaptureLocation,
5894 /*Explicit*/ false, /*BuildAndDiagnose*/ true,
5895 &FunctionScopeIndexOfCapturableLambda);
Faisal Valia17d19f2013-11-07 05:17:06 +00005896 }
5897 }
Faisal Valiab3d6462013-12-07 20:22:44 +00005898
5899 // Reset all the potential captures at the end of each full-expression.
Faisal Valia17d19f2013-11-07 05:17:06 +00005900 CurrentLSI->clearPotentialCaptures();
5901}
5902
5903
Richard Smith945f8d32013-01-14 22:39:08 +00005904ExprResult Sema::ActOnFinishFullExpr(Expr *FE, SourceLocation CC,
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00005905 bool DiscardedValue,
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00005906 bool IsConstexpr,
5907 bool IsLambdaInitCaptureInitializer) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005908 ExprResult FullExpr = FE;
John Wiegley01296292011-04-08 18:41:53 +00005909
5910 if (!FullExpr.get())
Douglas Gregora6e053e2010-12-15 01:34:56 +00005911 return ExprError();
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00005912
5913 // If we are an init-expression in a lambdas init-capture, we should not
5914 // diagnose an unexpanded pack now (will be diagnosed once lambda-expr
5915 // containing full-expression is done).
5916 // template<class ... Ts> void test(Ts ... t) {
5917 // test([&a(t)]() { <-- (t) is an init-expr that shouldn't be diagnosed now.
5918 // return a;
5919 // }() ...);
5920 // }
5921 // FIXME: This is a hack. It would be better if we pushed the lambda scope
5922 // when we parse the lambda introducer, and teach capturing (but not
5923 // unexpanded pack detection) to walk over LambdaScopeInfos which don't have a
5924 // corresponding class yet (that is, have LambdaScopeInfo either represent a
5925 // lambda where we've entered the introducer but not the body, or represent a
5926 // lambda where we've entered the body, depending on where the
5927 // parser/instantiation has got to).
5928 if (!IsLambdaInitCaptureInitializer &&
5929 DiagnoseUnexpandedParameterPack(FullExpr.get()))
Douglas Gregor506bd562010-12-13 22:49:22 +00005930 return ExprError();
5931
Douglas Gregorb5af2e92013-03-07 22:57:58 +00005932 // Top-level expressions default to 'id' when we're in a debugger.
Richard Smith945f8d32013-01-14 22:39:08 +00005933 if (DiscardedValue && getLangOpts().DebuggerCastResultToId &&
Douglas Gregorb5af2e92013-03-07 22:57:58 +00005934 FullExpr.get()->getType() == Context.UnknownAnyTy) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005935 FullExpr = forceUnknownAnyToType(FullExpr.get(), Context.getObjCIdType());
Douglas Gregor95715f92011-12-15 00:53:32 +00005936 if (FullExpr.isInvalid())
5937 return ExprError();
5938 }
Douglas Gregor0ec210b2011-03-07 02:05:23 +00005939
Richard Smith945f8d32013-01-14 22:39:08 +00005940 if (DiscardedValue) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005941 FullExpr = CheckPlaceholderExpr(FullExpr.get());
Richard Smith945f8d32013-01-14 22:39:08 +00005942 if (FullExpr.isInvalid())
5943 return ExprError();
5944
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005945 FullExpr = IgnoredValueConversions(FullExpr.get());
Richard Smith945f8d32013-01-14 22:39:08 +00005946 if (FullExpr.isInvalid())
5947 return ExprError();
5948 }
John Wiegley01296292011-04-08 18:41:53 +00005949
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00005950 CheckCompletedExpr(FullExpr.get(), CC, IsConstexpr);
Faisal Valia17d19f2013-11-07 05:17:06 +00005951
Faisal Vali218e94b2013-11-12 03:56:08 +00005952 // At the end of this full expression (which could be a deeply nested
5953 // lambda), if there is a potential capture within the nested lambda,
5954 // have the outer capture-able lambda try and capture it.
Faisal Valia17d19f2013-11-07 05:17:06 +00005955 // Consider the following code:
5956 // void f(int, int);
5957 // void f(const int&, double);
5958 // void foo() {
5959 // const int x = 10, y = 20;
5960 // auto L = [=](auto a) {
5961 // auto M = [=](auto b) {
5962 // f(x, b); <-- requires x to be captured by L and M
5963 // f(y, a); <-- requires y to be captured by L, but not all Ms
5964 // };
5965 // };
5966 // }
5967
5968 // FIXME: Also consider what happens for something like this that involves
5969 // the gnu-extension statement-expressions or even lambda-init-captures:
5970 // void f() {
5971 // const int n = 0;
5972 // auto L = [&](auto a) {
5973 // +n + ({ 0; a; });
5974 // };
5975 // }
5976 //
Faisal Vali218e94b2013-11-12 03:56:08 +00005977 // Here, we see +n, and then the full-expression 0; ends, so we don't
5978 // capture n (and instead remove it from our list of potential captures),
5979 // and then the full-expression +n + ({ 0; }); ends, but it's too late
5980 // for us to see that we need to capture n after all.
Faisal Valia17d19f2013-11-07 05:17:06 +00005981
Faisal Vali8bc2bc72013-11-12 03:48:27 +00005982 LambdaScopeInfo *const CurrentLSI = getCurLambda();
5983 // FIXME: PR 17877 showed that getCurLambda() can return a valid pointer
5984 // even if CurContext is not a lambda call operator. Refer to that Bug Report
5985 // for an example of the code that might cause this asynchrony.
5986 // By ensuring we are in the context of a lambda's call operator
5987 // we can fix the bug (we only need to check whether we need to capture
5988 // if we are within a lambda's body); but per the comments in that
5989 // PR, a proper fix would entail :
5990 // "Alternative suggestion:
5991 // - Add to Sema an integer holding the smallest (outermost) scope
5992 // index that we are *lexically* within, and save/restore/set to
5993 // FunctionScopes.size() in InstantiatingTemplate's
5994 // constructor/destructor.
5995 // - Teach the handful of places that iterate over FunctionScopes to
Faisal Valiab3d6462013-12-07 20:22:44 +00005996 // stop at the outermost enclosing lexical scope."
5997 const bool IsInLambdaDeclContext = isLambdaCallOperator(CurContext);
5998 if (IsInLambdaDeclContext && CurrentLSI &&
Faisal Vali8bc2bc72013-11-12 03:48:27 +00005999 CurrentLSI->hasPotentialCaptures() && !FullExpr.isInvalid())
Faisal Valiab3d6462013-12-07 20:22:44 +00006000 CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(FE, CurrentLSI,
6001 *this);
John McCall5d413782010-12-06 08:20:24 +00006002 return MaybeCreateExprWithCleanups(FullExpr);
Anders Carlsson85a307d2009-05-17 18:41:29 +00006003}
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00006004
6005StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) {
6006 if (!FullStmt) return StmtError();
6007
John McCall5d413782010-12-06 08:20:24 +00006008 return MaybeCreateStmtWithCleanups(FullStmt);
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00006009}
Francois Pichet4a7de3e2011-05-06 20:48:22 +00006010
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00006011Sema::IfExistsResult
6012Sema::CheckMicrosoftIfExistsSymbol(Scope *S,
6013 CXXScopeSpec &SS,
6014 const DeclarationNameInfo &TargetNameInfo) {
Francois Pichet4a7de3e2011-05-06 20:48:22 +00006015 DeclarationName TargetName = TargetNameInfo.getName();
6016 if (!TargetName)
Douglas Gregor43edb322011-10-24 22:31:10 +00006017 return IER_DoesNotExist;
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00006018
Douglas Gregor43edb322011-10-24 22:31:10 +00006019 // If the name itself is dependent, then the result is dependent.
6020 if (TargetName.isDependentName())
6021 return IER_Dependent;
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00006022
Francois Pichet4a7de3e2011-05-06 20:48:22 +00006023 // Do the redeclaration lookup in the current scope.
6024 LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName,
6025 Sema::NotForRedeclaration);
Douglas Gregor43edb322011-10-24 22:31:10 +00006026 LookupParsedName(R, S, &SS);
Francois Pichet4a7de3e2011-05-06 20:48:22 +00006027 R.suppressDiagnostics();
Douglas Gregor43edb322011-10-24 22:31:10 +00006028
6029 switch (R.getResultKind()) {
6030 case LookupResult::Found:
6031 case LookupResult::FoundOverloaded:
6032 case LookupResult::FoundUnresolvedValue:
6033 case LookupResult::Ambiguous:
6034 return IER_Exists;
6035
6036 case LookupResult::NotFound:
6037 return IER_DoesNotExist;
6038
6039 case LookupResult::NotFoundInCurrentInstantiation:
6040 return IER_Dependent;
6041 }
David Blaikie8a40f702012-01-17 06:56:22 +00006042
6043 llvm_unreachable("Invalid LookupResult Kind!");
Francois Pichet4a7de3e2011-05-06 20:48:22 +00006044}
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00006045
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00006046Sema::IfExistsResult
6047Sema::CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
6048 bool IsIfExists, CXXScopeSpec &SS,
6049 UnqualifiedId &Name) {
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00006050 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00006051
6052 // Check for unexpanded parameter packs.
6053 SmallVector<UnexpandedParameterPack, 4> Unexpanded;
6054 collectUnexpandedParameterPacks(SS, Unexpanded);
6055 collectUnexpandedParameterPacks(TargetNameInfo, Unexpanded);
6056 if (!Unexpanded.empty()) {
6057 DiagnoseUnexpandedParameterPacks(KeywordLoc,
6058 IsIfExists? UPPC_IfExists
6059 : UPPC_IfNotExists,
6060 Unexpanded);
6061 return IER_Error;
6062 }
6063
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00006064 return CheckMicrosoftIfExistsSymbol(S, SS, TargetNameInfo);
6065}