blob: 100681df5e6394e4d46d315b25d852bf86c826d3 [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//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ expressions.
11//
12//===----------------------------------------------------------------------===//
13
John McCall83024632010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
John McCall19c1bfd2010-08-25 05:32:35 +000015#include "clang/Sema/DeclSpec.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000016#include "clang/Sema/Initialization.h"
17#include "clang/Sema/Lookup.h"
John McCall19c1bfd2010-08-25 05:32:35 +000018#include "clang/Sema/ParsedTemplate.h"
John McCallc63de662011-02-02 13:00:07 +000019#include "clang/Sema/ScopeInfo.h"
Richard Smith938f40b2011-06-11 17:19:42 +000020#include "clang/Sema/Scope.h"
John McCall19c1bfd2010-08-25 05:32:35 +000021#include "clang/Sema/TemplateDeduction.h"
Steve Naroffaac94152007-08-25 14:02:58 +000022#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000023#include "clang/AST/CXXInheritance.h"
John McCallde6836a2010-08-24 07:21:54 +000024#include "clang/AST/DeclObjC.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000025#include "clang/AST/ExprCXX.h"
Fariborz Jahanian1d446082010-06-16 18:56:04 +000026#include "clang/AST/ExprObjC.h"
Douglas Gregorb1dd23f2010-02-24 22:38:50 +000027#include "clang/AST/TypeLoc.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000028#include "clang/Basic/PartialDiagnostic.h"
Sebastian Redlfaf68082008-12-03 20:26:15 +000029#include "clang/Basic/TargetInfo.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000030#include "clang/Lex/Preprocessor.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000031#include "llvm/ADT/STLExtras.h"
Chandler Carruth8b0cf1d2011-05-01 07:23:17 +000032#include "llvm/Support/ErrorHandling.h"
Chris Lattner29375652006-12-04 18:06:35 +000033using namespace clang;
John McCall19c1bfd2010-08-25 05:32:35 +000034using namespace sema;
Chris Lattner29375652006-12-04 18:06:35 +000035
John McCallba7bf592010-08-24 05:47:05 +000036ParsedType Sema::getDestructorName(SourceLocation TildeLoc,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000037 IdentifierInfo &II,
John McCallba7bf592010-08-24 05:47:05 +000038 SourceLocation NameLoc,
39 Scope *S, CXXScopeSpec &SS,
40 ParsedType ObjectTypePtr,
41 bool EnteringContext) {
Douglas Gregorfe17d252010-02-16 19:09:40 +000042 // Determine where to perform name lookup.
43
44 // FIXME: This area of the standard is very messy, and the current
45 // wording is rather unclear about which scopes we search for the
46 // destructor name; see core issues 399 and 555. Issue 399 in
47 // particular shows where the current description of destructor name
48 // lookup is completely out of line with existing practice, e.g.,
49 // this appears to be ill-formed:
50 //
51 // namespace N {
52 // template <typename T> struct S {
53 // ~S();
54 // };
55 // }
56 //
57 // void f(N::S<int>* s) {
58 // s->N::S<int>::~S();
59 // }
60 //
Douglas Gregor46841e12010-02-23 00:15:22 +000061 // See also PR6358 and PR6359.
Sebastian Redla771d222010-07-07 23:17:38 +000062 // For this reason, we're currently only doing the C++03 version of this
63 // code; the C++0x version has to wait until we get a proper spec.
Douglas Gregorfe17d252010-02-16 19:09:40 +000064 QualType SearchType;
65 DeclContext *LookupCtx = 0;
66 bool isDependent = false;
67 bool LookInScope = false;
68
69 // If we have an object type, it's because we are in a
70 // pseudo-destructor-expression or a member access expression, and
71 // we know what type we're looking for.
72 if (ObjectTypePtr)
73 SearchType = GetTypeFromParser(ObjectTypePtr);
74
75 if (SS.isSet()) {
Douglas Gregor46841e12010-02-23 00:15:22 +000076 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000077
Douglas Gregor46841e12010-02-23 00:15:22 +000078 bool AlreadySearched = false;
79 bool LookAtPrefix = true;
Sebastian Redla771d222010-07-07 23:17:38 +000080 // C++ [basic.lookup.qual]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000081 // If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier,
Sebastian Redla771d222010-07-07 23:17:38 +000082 // the type-names are looked up as types in the scope designated by the
83 // nested-name-specifier. In a qualified-id of the form:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +000084 //
85 // ::[opt] nested-name-specifier ~ class-name
Sebastian Redla771d222010-07-07 23:17:38 +000086 //
87 // where the nested-name-specifier designates a namespace scope, and in
Chandler Carruth8f254812010-02-21 10:19:54 +000088 // a qualified-id of the form:
Douglas Gregorfe17d252010-02-16 19:09:40 +000089 //
NAKAMURA Takumi7c288862011-01-27 07:09:49 +000090 // ::opt nested-name-specifier class-name :: ~ class-name
Douglas Gregorfe17d252010-02-16 19:09:40 +000091 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000092 // the class-names are looked up as types in the scope designated by
Sebastian Redla771d222010-07-07 23:17:38 +000093 // the nested-name-specifier.
Douglas Gregorfe17d252010-02-16 19:09:40 +000094 //
Sebastian Redla771d222010-07-07 23:17:38 +000095 // Here, we check the first case (completely) and determine whether the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000096 // code below is permitted to look at the prefix of the
Sebastian Redla771d222010-07-07 23:17:38 +000097 // nested-name-specifier.
98 DeclContext *DC = computeDeclContext(SS, EnteringContext);
99 if (DC && DC->isFileContext()) {
100 AlreadySearched = true;
101 LookupCtx = DC;
102 isDependent = false;
103 } else if (DC && isa<CXXRecordDecl>(DC))
104 LookAtPrefix = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000105
Sebastian Redla771d222010-07-07 23:17:38 +0000106 // The second case from the C++03 rules quoted further above.
Douglas Gregor46841e12010-02-23 00:15:22 +0000107 NestedNameSpecifier *Prefix = 0;
108 if (AlreadySearched) {
109 // Nothing left to do.
110 } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) {
111 CXXScopeSpec PrefixSS;
Douglas Gregor10176412011-02-25 16:07:42 +0000112 PrefixSS.Adopt(NestedNameSpecifierLoc(Prefix, SS.location_data()));
Douglas Gregor46841e12010-02-23 00:15:22 +0000113 LookupCtx = computeDeclContext(PrefixSS, EnteringContext);
114 isDependent = isDependentScopeSpecifier(PrefixSS);
Douglas Gregor46841e12010-02-23 00:15:22 +0000115 } else if (ObjectTypePtr) {
Douglas Gregorfe17d252010-02-16 19:09:40 +0000116 LookupCtx = computeDeclContext(SearchType);
117 isDependent = SearchType->isDependentType();
118 } else {
119 LookupCtx = computeDeclContext(SS, EnteringContext);
Douglas Gregor46841e12010-02-23 00:15:22 +0000120 isDependent = LookupCtx && LookupCtx->isDependentContext();
Douglas Gregorfe17d252010-02-16 19:09:40 +0000121 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000122
Douglas Gregorcd3f49f2010-02-25 04:46:04 +0000123 LookInScope = false;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000124 } else if (ObjectTypePtr) {
125 // C++ [basic.lookup.classref]p3:
126 // If the unqualified-id is ~type-name, the type-name is looked up
127 // in the context of the entire postfix-expression. If the type T
128 // of the object expression is of a class type C, the type-name is
129 // also looked up in the scope of class C. At least one of the
130 // lookups shall find a name that refers to (possibly
131 // cv-qualified) T.
132 LookupCtx = computeDeclContext(SearchType);
133 isDependent = SearchType->isDependentType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000134 assert((isDependent || !SearchType->isIncompleteType()) &&
Douglas Gregorfe17d252010-02-16 19:09:40 +0000135 "Caller should have completed object type");
136
137 LookInScope = true;
138 } else {
139 // Perform lookup into the current scope (only).
140 LookInScope = true;
141 }
142
Douglas Gregor4cf85a72011-03-04 22:32:08 +0000143 TypeDecl *NonMatchingTypeDecl = 0;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000144 LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName);
145 for (unsigned Step = 0; Step != 2; ++Step) {
146 // Look for the name first in the computed lookup context (if we
Douglas Gregor4cf85a72011-03-04 22:32:08 +0000147 // have one) and, if that fails to find a match, in the scope (if
Douglas Gregorfe17d252010-02-16 19:09:40 +0000148 // we're allowed to look there).
149 Found.clear();
150 if (Step == 0 && LookupCtx)
151 LookupQualifiedName(Found, LookupCtx);
Douglas Gregor678f90d2010-02-25 01:56:36 +0000152 else if (Step == 1 && LookInScope && S)
Douglas Gregorfe17d252010-02-16 19:09:40 +0000153 LookupName(Found, S);
154 else
155 continue;
156
157 // FIXME: Should we be suppressing ambiguities here?
158 if (Found.isAmbiguous())
John McCallba7bf592010-08-24 05:47:05 +0000159 return ParsedType();
Douglas Gregorfe17d252010-02-16 19:09:40 +0000160
161 if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
162 QualType T = Context.getTypeDeclType(Type);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000163
164 if (SearchType.isNull() || SearchType->isDependentType() ||
165 Context.hasSameUnqualifiedType(T, SearchType)) {
166 // We found our type!
167
John McCallba7bf592010-08-24 05:47:05 +0000168 return ParsedType::make(T);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000169 }
John Wiegleyb4a9e512011-03-08 08:13:22 +0000170
Douglas Gregor4cf85a72011-03-04 22:32:08 +0000171 if (!SearchType.isNull())
172 NonMatchingTypeDecl = Type;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000173 }
174
175 // If the name that we found is a class template name, and it is
176 // the same name as the template name in the last part of the
177 // nested-name-specifier (if present) or the object type, then
178 // this is the destructor for that class.
179 // FIXME: This is a workaround until we get real drafting for core
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000180 // issue 399, for which there isn't even an obvious direction.
Douglas Gregorfe17d252010-02-16 19:09:40 +0000181 if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) {
182 QualType MemberOfType;
183 if (SS.isSet()) {
184 if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) {
185 // Figure out the type of the context, if it has one.
John McCalle78aac42010-03-10 03:28:59 +0000186 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx))
187 MemberOfType = Context.getTypeDeclType(Record);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000188 }
189 }
190 if (MemberOfType.isNull())
191 MemberOfType = SearchType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000192
Douglas Gregorfe17d252010-02-16 19:09:40 +0000193 if (MemberOfType.isNull())
194 continue;
195
196 // We're referring into a class template specialization. If the
197 // class template we found is the same as the template being
198 // specialized, we found what we are looking for.
199 if (const RecordType *Record = MemberOfType->getAs<RecordType>()) {
200 if (ClassTemplateSpecializationDecl *Spec
201 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
202 if (Spec->getSpecializedTemplate()->getCanonicalDecl() ==
203 Template->getCanonicalDecl())
John McCallba7bf592010-08-24 05:47:05 +0000204 return ParsedType::make(MemberOfType);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000205 }
206
207 continue;
208 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000209
Douglas Gregorfe17d252010-02-16 19:09:40 +0000210 // We're referring to an unresolved class template
211 // specialization. Determine whether we class template we found
212 // is the same as the template being specialized or, if we don't
213 // know which template is being specialized, that it at least
214 // has the same name.
215 if (const TemplateSpecializationType *SpecType
216 = MemberOfType->getAs<TemplateSpecializationType>()) {
217 TemplateName SpecName = SpecType->getTemplateName();
218
219 // The class template we found is the same template being
220 // specialized.
221 if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) {
222 if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl())
John McCallba7bf592010-08-24 05:47:05 +0000223 return ParsedType::make(MemberOfType);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000224
225 continue;
226 }
227
228 // The class template we found has the same name as the
229 // (dependent) template name being specialized.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000230 if (DependentTemplateName *DepTemplate
Douglas Gregorfe17d252010-02-16 19:09:40 +0000231 = SpecName.getAsDependentTemplateName()) {
232 if (DepTemplate->isIdentifier() &&
233 DepTemplate->getIdentifier() == Template->getIdentifier())
John McCallba7bf592010-08-24 05:47:05 +0000234 return ParsedType::make(MemberOfType);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000235
236 continue;
237 }
238 }
239 }
240 }
241
242 if (isDependent) {
243 // We didn't find our type, but that's okay: it's dependent
244 // anyway.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +0000245
246 // FIXME: What if we have no nested-name-specifier?
247 QualType T = CheckTypenameType(ETK_None, SourceLocation(),
248 SS.getWithLocInContext(Context),
249 II, NameLoc);
John McCallba7bf592010-08-24 05:47:05 +0000250 return ParsedType::make(T);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000251 }
252
Douglas Gregor4cf85a72011-03-04 22:32:08 +0000253 if (NonMatchingTypeDecl) {
254 QualType T = Context.getTypeDeclType(NonMatchingTypeDecl);
255 Diag(NameLoc, diag::err_destructor_expr_type_mismatch)
256 << T << SearchType;
257 Diag(NonMatchingTypeDecl->getLocation(), diag::note_destructor_type_here)
258 << T;
259 } else if (ObjectTypePtr)
260 Diag(NameLoc, diag::err_ident_in_dtor_not_a_type)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000261 << &II;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000262 else
263 Diag(NameLoc, diag::err_destructor_class_name);
264
John McCallba7bf592010-08-24 05:47:05 +0000265 return ParsedType();
Douglas Gregorfe17d252010-02-16 19:09:40 +0000266}
267
Douglas Gregor9da64192010-04-26 22:37:10 +0000268/// \brief Build a C++ typeid expression with a type operand.
John McCalldadc5752010-08-24 06:29:42 +0000269ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000270 SourceLocation TypeidLoc,
271 TypeSourceInfo *Operand,
272 SourceLocation RParenLoc) {
Douglas Gregor9da64192010-04-26 22:37:10 +0000273 // C++ [expr.typeid]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000274 // The top-level cv-qualifiers of the lvalue expression or the type-id
Douglas Gregor9da64192010-04-26 22:37:10 +0000275 // that is the operand of typeid are always ignored.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000276 // If the type of the type-id is a class type or a reference to a class
Douglas Gregor9da64192010-04-26 22:37:10 +0000277 // type, the class shall be completely-defined.
Douglas Gregor876cec22010-06-02 06:16:02 +0000278 Qualifiers Quals;
279 QualType T
280 = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
281 Quals);
Douglas Gregor9da64192010-04-26 22:37:10 +0000282 if (T->getAs<RecordType>() &&
283 RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
284 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000285
Douglas Gregor9da64192010-04-26 22:37:10 +0000286 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
287 Operand,
288 SourceRange(TypeidLoc, RParenLoc)));
289}
290
291/// \brief Build a C++ typeid expression with an expression operand.
John McCalldadc5752010-08-24 06:29:42 +0000292ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000293 SourceLocation TypeidLoc,
294 Expr *E,
295 SourceLocation RParenLoc) {
Douglas Gregor9da64192010-04-26 22:37:10 +0000296 bool isUnevaluatedOperand = true;
Douglas Gregor9da64192010-04-26 22:37:10 +0000297 if (E && !E->isTypeDependent()) {
298 QualType T = E->getType();
299 if (const RecordType *RecordT = T->getAs<RecordType>()) {
300 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
301 // C++ [expr.typeid]p3:
302 // [...] If the type of the expression is a class type, the class
303 // shall be completely-defined.
304 if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
305 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000306
Douglas Gregor9da64192010-04-26 22:37:10 +0000307 // C++ [expr.typeid]p3:
Sebastian Redlc57d34b2010-07-20 04:20:21 +0000308 // When typeid is applied to an expression other than an glvalue of a
Douglas Gregor9da64192010-04-26 22:37:10 +0000309 // polymorphic class type [...] [the] expression is an unevaluated
310 // operand. [...]
Sebastian Redlc57d34b2010-07-20 04:20:21 +0000311 if (RecordD->isPolymorphic() && E->Classify(Context).isGLValue()) {
Douglas Gregor9da64192010-04-26 22:37:10 +0000312 isUnevaluatedOperand = false;
Douglas Gregor88d292c2010-05-13 16:44:06 +0000313
314 // We require a vtable to query the type at run time.
315 MarkVTableUsed(TypeidLoc, RecordD);
316 }
Douglas Gregor9da64192010-04-26 22:37:10 +0000317 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000318
Douglas Gregor9da64192010-04-26 22:37:10 +0000319 // C++ [expr.typeid]p4:
320 // [...] If the type of the type-id is a reference to a possibly
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000321 // cv-qualified type, the result of the typeid expression refers to a
322 // std::type_info object representing the cv-unqualified referenced
Douglas Gregor9da64192010-04-26 22:37:10 +0000323 // type.
Douglas Gregor876cec22010-06-02 06:16:02 +0000324 Qualifiers Quals;
325 QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
326 if (!Context.hasSameType(T, UnqualT)) {
327 T = UnqualT;
John Wiegley01296292011-04-08 18:41:53 +0000328 E = ImpCastExprToType(E, UnqualT, CK_NoOp, CastCategory(E)).take();
Douglas Gregor9da64192010-04-26 22:37:10 +0000329 }
330 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000331
Douglas Gregor9da64192010-04-26 22:37:10 +0000332 // If this is an unevaluated operand, clear out the set of
333 // declaration references we have been computing and eliminate any
334 // temporaries introduced in its computation.
335 if (isUnevaluatedOperand)
336 ExprEvalContexts.back().Context = Unevaluated;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000337
Douglas Gregor9da64192010-04-26 22:37:10 +0000338 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
John McCallb268a282010-08-23 23:25:46 +0000339 E,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000340 SourceRange(TypeidLoc, RParenLoc)));
Douglas Gregor9da64192010-04-26 22:37:10 +0000341}
342
343/// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
John McCalldadc5752010-08-24 06:29:42 +0000344ExprResult
Sebastian Redlc4704762008-11-11 11:37:55 +0000345Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
346 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Douglas Gregor9da64192010-04-26 22:37:10 +0000347 // Find the std::type_info type.
Sebastian Redl7ac97412011-03-31 19:29:24 +0000348 if (!getStdNamespace())
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000349 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000350
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000351 if (!CXXTypeInfoDecl) {
352 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
353 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
354 LookupQualifiedName(R, getStdNamespace());
355 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
356 if (!CXXTypeInfoDecl)
357 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
358 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000359
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000360 QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000361
Douglas Gregor9da64192010-04-26 22:37:10 +0000362 if (isType) {
363 // The operand is a type; handle it as such.
364 TypeSourceInfo *TInfo = 0;
John McCallba7bf592010-08-24 05:47:05 +0000365 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
366 &TInfo);
Douglas Gregor9da64192010-04-26 22:37:10 +0000367 if (T.isNull())
368 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000369
Douglas Gregor9da64192010-04-26 22:37:10 +0000370 if (!TInfo)
371 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
Sebastian Redlc4704762008-11-11 11:37:55 +0000372
Douglas Gregor9da64192010-04-26 22:37:10 +0000373 return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
Douglas Gregor0b6a6242009-06-22 20:57:11 +0000374 }
Mike Stump11289f42009-09-09 15:08:12 +0000375
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000376 // The operand is an expression.
John McCallb268a282010-08-23 23:25:46 +0000377 return BuildCXXTypeId(TypeInfoType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
Sebastian Redlc4704762008-11-11 11:37:55 +0000378}
379
Francois Pichetb7577652010-12-27 01:32:00 +0000380/// Retrieve the UuidAttr associated with QT.
381static UuidAttr *GetUuidAttrOfType(QualType QT) {
382 // Optionally remove one level of pointer, reference or array indirection.
John McCall424cec92011-01-19 06:33:43 +0000383 const Type *Ty = QT.getTypePtr();;
Francois Pichet9dddd402010-12-20 03:51:03 +0000384 if (QT->isPointerType() || QT->isReferenceType())
385 Ty = QT->getPointeeType().getTypePtr();
386 else if (QT->isArrayType())
387 Ty = cast<ArrayType>(QT)->getElementType().getTypePtr();
388
Francois Pichet59d2b012011-05-08 10:02:20 +0000389 // Loop all record redeclaration looking for an uuid attribute.
Francois Pichetb7577652010-12-27 01:32:00 +0000390 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
Francois Pichet59d2b012011-05-08 10:02:20 +0000391 for (CXXRecordDecl::redecl_iterator I = RD->redecls_begin(),
392 E = RD->redecls_end(); I != E; ++I) {
393 if (UuidAttr *Uuid = I->getAttr<UuidAttr>())
Francois Pichetb7577652010-12-27 01:32:00 +0000394 return Uuid;
Francois Pichetb7577652010-12-27 01:32:00 +0000395 }
Francois Pichet59d2b012011-05-08 10:02:20 +0000396
Francois Pichetb7577652010-12-27 01:32:00 +0000397 return 0;
Francois Pichet9dddd402010-12-20 03:51:03 +0000398}
399
Francois Pichet9f4f2072010-09-08 12:20:18 +0000400/// \brief Build a Microsoft __uuidof expression with a type operand.
401ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
402 SourceLocation TypeidLoc,
403 TypeSourceInfo *Operand,
404 SourceLocation RParenLoc) {
Francois Pichetb7577652010-12-27 01:32:00 +0000405 if (!Operand->getType()->isDependentType()) {
406 if (!GetUuidAttrOfType(Operand->getType()))
407 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
408 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000409
Francois Pichet9f4f2072010-09-08 12:20:18 +0000410 // FIXME: add __uuidof semantic analysis for type operand.
411 return Owned(new (Context) CXXUuidofExpr(TypeInfoType.withConst(),
412 Operand,
413 SourceRange(TypeidLoc, RParenLoc)));
414}
415
416/// \brief Build a Microsoft __uuidof expression with an expression operand.
417ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
418 SourceLocation TypeidLoc,
419 Expr *E,
420 SourceLocation RParenLoc) {
Francois Pichetb7577652010-12-27 01:32:00 +0000421 if (!E->getType()->isDependentType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000422 if (!GetUuidAttrOfType(E->getType()) &&
Francois Pichetb7577652010-12-27 01:32:00 +0000423 !E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
424 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
425 }
426 // FIXME: add __uuidof semantic analysis for type operand.
Francois Pichet9f4f2072010-09-08 12:20:18 +0000427 return Owned(new (Context) CXXUuidofExpr(TypeInfoType.withConst(),
428 E,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000429 SourceRange(TypeidLoc, RParenLoc)));
Francois Pichet9f4f2072010-09-08 12:20:18 +0000430}
431
432/// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
433ExprResult
434Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc,
435 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000436 // If MSVCGuidDecl has not been cached, do the lookup.
Francois Pichet9f4f2072010-09-08 12:20:18 +0000437 if (!MSVCGuidDecl) {
438 IdentifierInfo *GuidII = &PP.getIdentifierTable().get("_GUID");
439 LookupResult R(*this, GuidII, SourceLocation(), LookupTagName);
440 LookupQualifiedName(R, Context.getTranslationUnitDecl());
441 MSVCGuidDecl = R.getAsSingle<RecordDecl>();
442 if (!MSVCGuidDecl)
443 return ExprError(Diag(OpLoc, diag::err_need_header_before_ms_uuidof));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000444 }
445
Francois Pichet9f4f2072010-09-08 12:20:18 +0000446 QualType GuidType = Context.getTypeDeclType(MSVCGuidDecl);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000447
Francois Pichet9f4f2072010-09-08 12:20:18 +0000448 if (isType) {
449 // The operand is a type; handle it as such.
450 TypeSourceInfo *TInfo = 0;
451 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
452 &TInfo);
453 if (T.isNull())
454 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000455
Francois Pichet9f4f2072010-09-08 12:20:18 +0000456 if (!TInfo)
457 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
458
459 return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);
460 }
461
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000462 // The operand is an expression.
Francois Pichet9f4f2072010-09-08 12:20:18 +0000463 return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
464}
465
Steve Naroff66356bd2007-09-16 14:56:35 +0000466/// ActOnCXXBoolLiteral - Parse {true,false} literals.
John McCalldadc5752010-08-24 06:29:42 +0000467ExprResult
Steve Naroff66356bd2007-09-16 14:56:35 +0000468Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor08d918a2008-10-24 15:36:09 +0000469 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Bill Wendlingbf313b02007-02-13 20:09:46 +0000470 "Unknown C++ Boolean value!");
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000471 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
472 Context.BoolTy, OpLoc));
Bill Wendling4073ed52007-02-13 01:51:42 +0000473}
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000474
Sebastian Redl576fd422009-05-10 18:38:11 +0000475/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
John McCalldadc5752010-08-24 06:29:42 +0000476ExprResult
Sebastian Redl576fd422009-05-10 18:38:11 +0000477Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
478 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
479}
480
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000481/// ActOnCXXThrow - Parse throw expressions.
John McCalldadc5752010-08-24 06:29:42 +0000482ExprResult
John McCallb268a282010-08-23 23:25:46 +0000483Sema::ActOnCXXThrow(SourceLocation OpLoc, Expr *Ex) {
Anders Carlssond99dbcc2011-02-23 03:46:46 +0000484 // Don't report an error if 'throw' is used in system headers.
Anders Carlssone96ab552011-02-28 02:27:16 +0000485 if (!getLangOptions().CXXExceptions &&
Anders Carlssond99dbcc2011-02-23 03:46:46 +0000486 !getSourceManager().isInSystemHeader(OpLoc))
Anders Carlssonb94ad3e2011-02-19 21:53:09 +0000487 Diag(OpLoc, diag::err_exceptions_disabled) << "throw";
Anders Carlsson68b36af2011-02-19 19:26:44 +0000488
John Wiegley01296292011-04-08 18:41:53 +0000489 if (Ex && !Ex->isTypeDependent()) {
490 ExprResult ExRes = CheckCXXThrowOperand(OpLoc, Ex);
491 if (ExRes.isInvalid())
492 return ExprError();
493 Ex = ExRes.take();
494 }
Sebastian Redl4de47b42009-04-27 20:27:31 +0000495 return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc));
496}
497
498/// CheckCXXThrowOperand - Validate the operand of a throw.
John Wiegley01296292011-04-08 18:41:53 +0000499ExprResult Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *E) {
Sebastian Redl4de47b42009-04-27 20:27:31 +0000500 // C++ [except.throw]p3:
Douglas Gregor247894b2009-12-23 22:04:40 +0000501 // A throw-expression initializes a temporary object, called the exception
502 // object, the type of which is determined by removing any top-level
503 // cv-qualifiers from the static type of the operand of throw and adjusting
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000504 // the type from "array of T" or "function returning T" to "pointer to T"
Douglas Gregor247894b2009-12-23 22:04:40 +0000505 // or "pointer to function returning T", [...]
506 if (E->getType().hasQualifiers())
John Wiegley01296292011-04-08 18:41:53 +0000507 E = ImpCastExprToType(E, E->getType().getUnqualifiedType(), CK_NoOp,
508 CastCategory(E)).take();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000509
John Wiegley01296292011-04-08 18:41:53 +0000510 ExprResult Res = DefaultFunctionArrayConversion(E);
511 if (Res.isInvalid())
512 return ExprError();
513 E = Res.take();
Sebastian Redl4de47b42009-04-27 20:27:31 +0000514
515 // If the type of the exception would be an incomplete type or a pointer
516 // to an incomplete type other than (cv) void the program is ill-formed.
517 QualType Ty = E->getType();
John McCall2e6567a2010-04-22 01:10:34 +0000518 bool isPointer = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000519 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl4de47b42009-04-27 20:27:31 +0000520 Ty = Ptr->getPointeeType();
John McCall2e6567a2010-04-22 01:10:34 +0000521 isPointer = true;
Sebastian Redl4de47b42009-04-27 20:27:31 +0000522 }
523 if (!isPointer || !Ty->isVoidType()) {
524 if (RequireCompleteType(ThrowLoc, Ty,
Anders Carlsson029fc692009-08-26 22:59:12 +0000525 PDiag(isPointer ? diag::err_throw_incomplete_ptr
526 : diag::err_throw_incomplete)
527 << E->getSourceRange()))
John Wiegley01296292011-04-08 18:41:53 +0000528 return ExprError();
Rafael Espindola70e040d2010-03-02 21:28:26 +0000529
Douglas Gregore8154332010-04-15 18:05:39 +0000530 if (RequireNonAbstractType(ThrowLoc, E->getType(),
531 PDiag(diag::err_throw_abstract_type)
532 << E->getSourceRange()))
John Wiegley01296292011-04-08 18:41:53 +0000533 return ExprError();
Sebastian Redl4de47b42009-04-27 20:27:31 +0000534 }
535
John McCall2e6567a2010-04-22 01:10:34 +0000536 // Initialize the exception result. This implicitly weeds out
537 // abstract types or types with inaccessible copy constructors.
Douglas Gregorc74edc22011-01-21 22:46:35 +0000538 const VarDecl *NRVOVariable = getCopyElisionCandidate(QualType(), E, false);
539
Douglas Gregor5d369002011-01-21 18:05:27 +0000540 // FIXME: Determine whether we can elide this copy per C++0x [class.copy]p32.
John McCall2e6567a2010-04-22 01:10:34 +0000541 InitializedEntity Entity =
Douglas Gregorc74edc22011-01-21 22:46:35 +0000542 InitializedEntity::InitializeException(ThrowLoc, E->getType(),
543 /*NRVO=*/false);
John Wiegley01296292011-04-08 18:41:53 +0000544 Res = PerformMoveOrCopyInitialization(Entity, NRVOVariable,
545 QualType(), E);
John McCall2e6567a2010-04-22 01:10:34 +0000546 if (Res.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +0000547 return ExprError();
548 E = Res.take();
Douglas Gregor88d292c2010-05-13 16:44:06 +0000549
Eli Friedman91a3d272010-06-03 20:39:03 +0000550 // If the exception has class type, we need additional handling.
551 const RecordType *RecordTy = Ty->getAs<RecordType>();
552 if (!RecordTy)
John Wiegley01296292011-04-08 18:41:53 +0000553 return Owned(E);
Eli Friedman91a3d272010-06-03 20:39:03 +0000554 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
555
Douglas Gregor88d292c2010-05-13 16:44:06 +0000556 // If we are throwing a polymorphic class type or pointer thereof,
557 // exception handling will make use of the vtable.
Eli Friedman91a3d272010-06-03 20:39:03 +0000558 MarkVTableUsed(ThrowLoc, RD);
559
Eli Friedman36ebbec2010-10-12 20:32:36 +0000560 // If a pointer is thrown, the referenced object will not be destroyed.
561 if (isPointer)
John Wiegley01296292011-04-08 18:41:53 +0000562 return Owned(E);
Eli Friedman36ebbec2010-10-12 20:32:36 +0000563
Eli Friedman91a3d272010-06-03 20:39:03 +0000564 // If the class has a non-trivial destructor, we must be able to call it.
565 if (RD->hasTrivialDestructor())
John Wiegley01296292011-04-08 18:41:53 +0000566 return Owned(E);
Eli Friedman91a3d272010-06-03 20:39:03 +0000567
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000568 CXXDestructorDecl *Destructor
Douglas Gregore71edda2010-07-01 22:47:18 +0000569 = const_cast<CXXDestructorDecl*>(LookupDestructor(RD));
Eli Friedman91a3d272010-06-03 20:39:03 +0000570 if (!Destructor)
John Wiegley01296292011-04-08 18:41:53 +0000571 return Owned(E);
Eli Friedman91a3d272010-06-03 20:39:03 +0000572
573 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
574 CheckDestructorAccess(E->getExprLoc(), Destructor,
Douglas Gregor747eb782010-07-08 06:14:04 +0000575 PDiag(diag::err_access_dtor_exception) << Ty);
John Wiegley01296292011-04-08 18:41:53 +0000576 return Owned(E);
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000577}
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000578
Richard Smith938f40b2011-06-11 17:19:42 +0000579QualType Sema::getAndCaptureCurrentThisType() {
John McCallf3a88602011-02-03 08:15:49 +0000580 // Ignore block scopes: we can capture through them.
581 // Ignore nested enum scopes: we'll diagnose non-constant expressions
582 // where they're invalid, and other uses are legitimate.
583 // Don't ignore nested class scopes: you can't use 'this' in a local class.
John McCallc63de662011-02-02 13:00:07 +0000584 DeclContext *DC = CurContext;
Richard Smith938f40b2011-06-11 17:19:42 +0000585 unsigned NumBlocks = 0;
John McCallf3a88602011-02-03 08:15:49 +0000586 while (true) {
Richard Smith938f40b2011-06-11 17:19:42 +0000587 if (isa<BlockDecl>(DC)) {
588 DC = cast<BlockDecl>(DC)->getDeclContext();
589 ++NumBlocks;
590 } else if (isa<EnumDecl>(DC))
591 DC = cast<EnumDecl>(DC)->getDeclContext();
John McCallf3a88602011-02-03 08:15:49 +0000592 else break;
593 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000594
Richard Smith938f40b2011-06-11 17:19:42 +0000595 QualType ThisTy;
596 if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC)) {
597 if (method && method->isInstance())
598 ThisTy = method->getThisType(Context);
599 } else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
600 // C++0x [expr.prim]p4:
601 // Otherwise, if a member-declarator declares a non-static data member
602 // of a class X, the expression this is a prvalue of type "pointer to X"
603 // within the optional brace-or-equal-initializer.
604 Scope *S = getScopeForContext(DC);
605 if (!S || S->getFlags() & Scope::ThisScope)
606 ThisTy = Context.getPointerType(Context.getRecordType(RD));
607 }
John McCallc63de662011-02-02 13:00:07 +0000608
Richard Smith938f40b2011-06-11 17:19:42 +0000609 // Mark that we're closing on 'this' in all the block scopes we ignored.
610 if (!ThisTy.isNull())
611 for (unsigned idx = FunctionScopes.size() - 1;
612 NumBlocks; --idx, --NumBlocks)
613 cast<BlockScopeInfo>(FunctionScopes[idx])->CapturesCXXThis = true;
John McCallc63de662011-02-02 13:00:07 +0000614
Richard Smith938f40b2011-06-11 17:19:42 +0000615 return ThisTy;
John McCallf3a88602011-02-03 08:15:49 +0000616}
617
Richard Smith938f40b2011-06-11 17:19:42 +0000618ExprResult Sema::ActOnCXXThis(SourceLocation Loc) {
John McCallf3a88602011-02-03 08:15:49 +0000619 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
620 /// is a non-lvalue expression whose value is the address of the object for
621 /// which the function is called.
622
Richard Smith938f40b2011-06-11 17:19:42 +0000623 QualType ThisTy = getAndCaptureCurrentThisType();
624 if (ThisTy.isNull()) return Diag(Loc, diag::err_invalid_this_use);
John McCallf3a88602011-02-03 08:15:49 +0000625
Richard Smith938f40b2011-06-11 17:19:42 +0000626 return Owned(new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit=*/false));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000627}
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000628
John McCalldadc5752010-08-24 06:29:42 +0000629ExprResult
Douglas Gregor2b88c112010-09-08 00:15:04 +0000630Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000631 SourceLocation LParenLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000632 MultiExprArg exprs,
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000633 SourceLocation RParenLoc) {
Douglas Gregor7df89f52010-02-05 19:11:37 +0000634 if (!TypeRep)
635 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000636
John McCall97513962010-01-15 18:39:57 +0000637 TypeSourceInfo *TInfo;
638 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
639 if (!TInfo)
640 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
Douglas Gregor2b88c112010-09-08 00:15:04 +0000641
642 return BuildCXXTypeConstructExpr(TInfo, LParenLoc, exprs, RParenLoc);
643}
644
645/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
646/// Can be interpreted either as function-style casting ("int(x)")
647/// or class type construction ("ClassType(x,y,z)")
648/// or creation of a value-initialized type ("int()").
649ExprResult
650Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
651 SourceLocation LParenLoc,
652 MultiExprArg exprs,
653 SourceLocation RParenLoc) {
654 QualType Ty = TInfo->getType();
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000655 unsigned NumExprs = exprs.size();
656 Expr **Exprs = (Expr**)exprs.get();
Douglas Gregor2b88c112010-09-08 00:15:04 +0000657 SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000658 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
659
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000660 if (Ty->isDependentType() ||
Douglas Gregor0950e412009-03-13 21:01:28 +0000661 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000662 exprs.release();
Mike Stump11289f42009-09-09 15:08:12 +0000663
Douglas Gregor2b88c112010-09-08 00:15:04 +0000664 return Owned(CXXUnresolvedConstructExpr::Create(Context, TInfo,
Douglas Gregorce934142009-05-20 18:46:25 +0000665 LParenLoc,
666 Exprs, NumExprs,
667 RParenLoc));
Douglas Gregor0950e412009-03-13 21:01:28 +0000668 }
669
Anders Carlsson55243162009-08-27 03:53:50 +0000670 if (Ty->isArrayType())
671 return ExprError(Diag(TyBeginLoc,
672 diag::err_value_init_for_array_type) << FullRange);
673 if (!Ty->isVoidType() &&
674 RequireCompleteType(TyBeginLoc, Ty,
675 PDiag(diag::err_invalid_incomplete_type_use)
676 << FullRange))
677 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000678
Anders Carlsson55243162009-08-27 03:53:50 +0000679 if (RequireNonAbstractType(TyBeginLoc, Ty,
680 diag::err_allocation_of_abstract_type))
681 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +0000682
683
Douglas Gregordd04d332009-01-16 18:33:17 +0000684 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000685 // If the expression list is a single expression, the type conversion
686 // expression is equivalent (in definedness, and if defined in meaning) to the
687 // corresponding cast expression.
688 //
689 if (NumExprs == 1) {
John McCall8cb679e2010-11-15 09:13:47 +0000690 CastKind Kind = CK_Invalid;
John McCall7decc9e2010-11-18 06:31:45 +0000691 ExprValueKind VK = VK_RValue;
John McCallcf142162010-08-07 06:22:56 +0000692 CXXCastPath BasePath;
John Wiegley01296292011-04-08 18:41:53 +0000693 ExprResult CastExpr =
John McCall31168b02011-06-15 23:02:42 +0000694 CheckCastTypes(TInfo->getTypeLoc().getBeginLoc(),
695 TInfo->getTypeLoc().getSourceRange(), Ty, Exprs[0],
John Wiegley01296292011-04-08 18:41:53 +0000696 Kind, VK, BasePath,
697 /*FunctionalStyle=*/true);
698 if (CastExpr.isInvalid())
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000699 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +0000700 Exprs[0] = CastExpr.take();
Anders Carlssone9766d52009-09-09 21:33:21 +0000701
702 exprs.release();
Anders Carlssone9766d52009-09-09 21:33:21 +0000703
John McCallcf142162010-08-07 06:22:56 +0000704 return Owned(CXXFunctionalCastExpr::Create(Context,
Douglas Gregor2b88c112010-09-08 00:15:04 +0000705 Ty.getNonLValueExprType(Context),
John McCall7decc9e2010-11-18 06:31:45 +0000706 VK, TInfo, TyBeginLoc, Kind,
John McCallcf142162010-08-07 06:22:56 +0000707 Exprs[0], &BasePath,
708 RParenLoc));
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000709 }
710
Douglas Gregor8ec51732010-09-08 21:40:08 +0000711 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo);
712 InitializationKind Kind
713 = NumExprs ? InitializationKind::CreateDirect(TyBeginLoc,
714 LParenLoc, RParenLoc)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000715 : InitializationKind::CreateValue(TyBeginLoc,
Douglas Gregor8ec51732010-09-08 21:40:08 +0000716 LParenLoc, RParenLoc);
717 InitializationSequence InitSeq(*this, Entity, Kind, Exprs, NumExprs);
718 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(exprs));
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000719
Douglas Gregor8ec51732010-09-08 21:40:08 +0000720 // FIXME: Improve AST representation?
721 return move(Result);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000722}
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +0000723
John McCall284c48f2011-01-27 09:37:56 +0000724/// doesUsualArrayDeleteWantSize - Answers whether the usual
725/// operator delete[] for the given type has a size_t parameter.
726static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc,
727 QualType allocType) {
728 const RecordType *record =
729 allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
730 if (!record) return false;
731
732 // Try to find an operator delete[] in class scope.
733
734 DeclarationName deleteName =
735 S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
736 LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
737 S.LookupQualifiedName(ops, record->getDecl());
738
739 // We're just doing this for information.
740 ops.suppressDiagnostics();
741
742 // Very likely: there's no operator delete[].
743 if (ops.empty()) return false;
744
745 // If it's ambiguous, it should be illegal to call operator delete[]
746 // on this thing, so it doesn't matter if we allocate extra space or not.
747 if (ops.isAmbiguous()) return false;
748
749 LookupResult::Filter filter = ops.makeFilter();
750 while (filter.hasNext()) {
751 NamedDecl *del = filter.next()->getUnderlyingDecl();
752
753 // C++0x [basic.stc.dynamic.deallocation]p2:
754 // A template instance is never a usual deallocation function,
755 // regardless of its signature.
756 if (isa<FunctionTemplateDecl>(del)) {
757 filter.erase();
758 continue;
759 }
760
761 // C++0x [basic.stc.dynamic.deallocation]p2:
762 // If class T does not declare [an operator delete[] with one
763 // parameter] but does declare a member deallocation function
764 // named operator delete[] with exactly two parameters, the
765 // second of which has type std::size_t, then this function
766 // is a usual deallocation function.
767 if (!cast<CXXMethodDecl>(del)->isUsualDeallocationFunction()) {
768 filter.erase();
769 continue;
770 }
771 }
772 filter.done();
773
774 if (!ops.isSingleResult()) return false;
775
776 const FunctionDecl *del = cast<FunctionDecl>(ops.getFoundDecl());
777 return (del->getNumParams() == 2);
778}
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +0000779
Sebastian Redlbd150f42008-11-21 19:14:01 +0000780/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
781/// @code new (memory) int[size][4] @endcode
782/// or
783/// @code ::new Foo(23, "hello") @endcode
784/// For the interpretation of this heap of arguments, consult the base version.
John McCalldadc5752010-08-24 06:29:42 +0000785ExprResult
Sebastian Redlbd150f42008-11-21 19:14:01 +0000786Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000787 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000788 SourceLocation PlacementRParen, SourceRange TypeIdParens,
Sebastian Redl351bb782008-12-02 14:43:59 +0000789 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000790 MultiExprArg ConstructorArgs,
Mike Stump11289f42009-09-09 15:08:12 +0000791 SourceLocation ConstructorRParen) {
Richard Smith30482bc2011-02-20 03:19:35 +0000792 bool TypeContainsAuto = D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto;
793
Sebastian Redl351bb782008-12-02 14:43:59 +0000794 Expr *ArraySize = 0;
Sebastian Redl351bb782008-12-02 14:43:59 +0000795 // If the specified type is an array, unwrap it and save the expression.
796 if (D.getNumTypeObjects() > 0 &&
797 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
798 DeclaratorChunk &Chunk = D.getTypeObject(0);
Richard Smith30482bc2011-02-20 03:19:35 +0000799 if (TypeContainsAuto)
800 return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
801 << D.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +0000802 if (Chunk.Arr.hasStatic)
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000803 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
804 << D.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +0000805 if (!Chunk.Arr.NumElts)
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000806 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
807 << D.getSourceRange());
Sebastian Redld7b3d7d2009-10-25 21:45:37 +0000808
Sebastian Redl351bb782008-12-02 14:43:59 +0000809 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redld7b3d7d2009-10-25 21:45:37 +0000810 D.DropFirstTypeObject();
Sebastian Redl351bb782008-12-02 14:43:59 +0000811 }
812
Douglas Gregor73341c42009-09-11 00:18:58 +0000813 // Every dimension shall be of constant size.
Sebastian Redld7b3d7d2009-10-25 21:45:37 +0000814 if (ArraySize) {
815 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor73341c42009-09-11 00:18:58 +0000816 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
817 break;
818
819 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
820 if (Expr *NumElts = (Expr *)Array.NumElts) {
821 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
822 !NumElts->isIntegerConstantExpr(Context)) {
823 Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst)
824 << NumElts->getSourceRange();
825 return ExprError();
826 }
827 }
828 }
829 }
Sebastian Redld7b3d7d2009-10-25 21:45:37 +0000830
Argyrios Kyrtzidis3ff13572011-06-28 03:01:23 +0000831 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/0);
John McCall8cb7bdf2010-06-04 23:28:52 +0000832 QualType AllocType = TInfo->getType();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +0000833 if (D.isInvalidType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000834 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000835
Mike Stump11289f42009-09-09 15:08:12 +0000836 return BuildCXXNew(StartLoc, UseGlobal,
Douglas Gregord0fefba2009-05-21 00:00:09 +0000837 PlacementLParen,
Mike Stump11289f42009-09-09 15:08:12 +0000838 move(PlacementArgs),
Douglas Gregord0fefba2009-05-21 00:00:09 +0000839 PlacementRParen,
Douglas Gregorf2753b32010-07-13 15:54:32 +0000840 TypeIdParens,
Mike Stump11289f42009-09-09 15:08:12 +0000841 AllocType,
Douglas Gregor0744ef62010-09-07 21:49:58 +0000842 TInfo,
John McCallb268a282010-08-23 23:25:46 +0000843 ArraySize,
Douglas Gregord0fefba2009-05-21 00:00:09 +0000844 ConstructorLParen,
845 move(ConstructorArgs),
Richard Smith30482bc2011-02-20 03:19:35 +0000846 ConstructorRParen,
847 TypeContainsAuto);
Douglas Gregord0fefba2009-05-21 00:00:09 +0000848}
849
John McCalldadc5752010-08-24 06:29:42 +0000850ExprResult
Douglas Gregord0fefba2009-05-21 00:00:09 +0000851Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
852 SourceLocation PlacementLParen,
853 MultiExprArg PlacementArgs,
854 SourceLocation PlacementRParen,
Douglas Gregorf2753b32010-07-13 15:54:32 +0000855 SourceRange TypeIdParens,
Douglas Gregord0fefba2009-05-21 00:00:09 +0000856 QualType AllocType,
Douglas Gregor0744ef62010-09-07 21:49:58 +0000857 TypeSourceInfo *AllocTypeInfo,
John McCallb268a282010-08-23 23:25:46 +0000858 Expr *ArraySize,
Douglas Gregord0fefba2009-05-21 00:00:09 +0000859 SourceLocation ConstructorLParen,
860 MultiExprArg ConstructorArgs,
Richard Smith30482bc2011-02-20 03:19:35 +0000861 SourceLocation ConstructorRParen,
862 bool TypeMayContainAuto) {
Douglas Gregor0744ef62010-09-07 21:49:58 +0000863 SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
Sebastian Redl351bb782008-12-02 14:43:59 +0000864
Richard Smith30482bc2011-02-20 03:19:35 +0000865 // C++0x [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
866 if (TypeMayContainAuto && AllocType->getContainedAutoType()) {
867 if (ConstructorArgs.size() == 0)
868 return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
869 << AllocType << TypeRange);
870 if (ConstructorArgs.size() != 1) {
871 Expr *FirstBad = ConstructorArgs.get()[1];
872 return ExprError(Diag(FirstBad->getSourceRange().getBegin(),
873 diag::err_auto_new_ctor_multiple_expressions)
874 << AllocType << TypeRange);
875 }
Richard Smith9647d3c2011-03-17 16:11:59 +0000876 TypeSourceInfo *DeducedType = 0;
877 if (!DeduceAutoType(AllocTypeInfo, ConstructorArgs.get()[0], DeducedType))
Richard Smith30482bc2011-02-20 03:19:35 +0000878 return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
879 << AllocType
880 << ConstructorArgs.get()[0]->getType()
881 << TypeRange
882 << ConstructorArgs.get()[0]->getSourceRange());
Richard Smith9647d3c2011-03-17 16:11:59 +0000883 if (!DeducedType)
884 return ExprError();
Richard Smith30482bc2011-02-20 03:19:35 +0000885
Richard Smith9647d3c2011-03-17 16:11:59 +0000886 AllocTypeInfo = DeducedType;
887 AllocType = AllocTypeInfo->getType();
Richard Smith30482bc2011-02-20 03:19:35 +0000888 }
889
Douglas Gregorcda95f42010-05-16 16:01:03 +0000890 // Per C++0x [expr.new]p5, the type being constructed may be a
891 // typedef of an array type.
John McCallb268a282010-08-23 23:25:46 +0000892 if (!ArraySize) {
Douglas Gregorcda95f42010-05-16 16:01:03 +0000893 if (const ConstantArrayType *Array
894 = Context.getAsConstantArrayType(AllocType)) {
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +0000895 ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
896 Context.getSizeType(),
897 TypeRange.getEnd());
Douglas Gregorcda95f42010-05-16 16:01:03 +0000898 AllocType = Array->getElementType();
899 }
900 }
Sebastian Redlbd150f42008-11-21 19:14:01 +0000901
Douglas Gregor3999e152010-10-06 16:00:31 +0000902 if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
903 return ExprError();
904
John McCall31168b02011-06-15 23:02:42 +0000905 // In ARC, infer 'retaining' for the allocated
906 if (getLangOptions().ObjCAutoRefCount &&
907 AllocType.getObjCLifetime() == Qualifiers::OCL_None &&
908 AllocType->isObjCLifetimeType()) {
909 AllocType = Context.getLifetimeQualifiedType(AllocType,
910 AllocType->getObjCARCImplicitLifetime());
911 }
Sebastian Redl351bb782008-12-02 14:43:59 +0000912
John McCall31168b02011-06-15 23:02:42 +0000913 QualType ResultType = Context.getPointerType(AllocType);
914
Sebastian Redlbd150f42008-11-21 19:14:01 +0000915 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
916 // or enumeration type with a non-negative value."
Sebastian Redl8d2ccae2009-02-26 14:39:58 +0000917 if (ArraySize && !ArraySize->isTypeDependent()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000918
Sebastian Redl351bb782008-12-02 14:43:59 +0000919 QualType SizeType = ArraySize->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000920
John McCalldadc5752010-08-24 06:29:42 +0000921 ExprResult ConvertedSize
John McCallb268a282010-08-23 23:25:46 +0000922 = ConvertToIntegralOrEnumerationType(StartLoc, ArraySize,
Douglas Gregor4799d032010-06-30 00:20:43 +0000923 PDiag(diag::err_array_size_not_integral),
924 PDiag(diag::err_array_size_incomplete_type)
925 << ArraySize->getSourceRange(),
926 PDiag(diag::err_array_size_explicit_conversion),
927 PDiag(diag::note_array_size_conversion),
928 PDiag(diag::err_array_size_ambiguous_conversion),
929 PDiag(diag::note_array_size_conversion),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000930 PDiag(getLangOptions().CPlusPlus0x? 0
Douglas Gregor4799d032010-06-30 00:20:43 +0000931 : diag::ext_array_size_conversion));
932 if (ConvertedSize.isInvalid())
933 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000934
John McCallb268a282010-08-23 23:25:46 +0000935 ArraySize = ConvertedSize.take();
Douglas Gregor4799d032010-06-30 00:20:43 +0000936 SizeType = ArraySize->getType();
Douglas Gregor0bf31402010-10-08 23:50:27 +0000937 if (!SizeType->isIntegralOrUnscopedEnumerationType())
Douglas Gregor4799d032010-06-30 00:20:43 +0000938 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000939
Sebastian Redl351bb782008-12-02 14:43:59 +0000940 // Let's see if this is a constant < 0. If so, we reject it out of hand.
941 // We don't care about special rules, so we tell the machinery it's not
942 // evaluated - it gives us a result in more cases.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +0000943 if (!ArraySize->isValueDependent()) {
944 llvm::APSInt Value;
945 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
946 if (Value < llvm::APSInt(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000947 llvm::APInt::getNullValue(Value.getBitWidth()),
Anders Carlsson8ab20bb2009-09-23 00:37:25 +0000948 Value.isUnsigned()))
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000949 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
Douglas Gregorcaa1bf42010-08-18 00:39:00 +0000950 diag::err_typecheck_negative_array_size)
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000951 << ArraySize->getSourceRange());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000952
Douglas Gregorcaa1bf42010-08-18 00:39:00 +0000953 if (!AllocType->isDependentType()) {
954 unsigned ActiveSizeBits
955 = ConstantArrayType::getNumAddressingBits(Context, AllocType, Value);
956 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000957 Diag(ArraySize->getSourceRange().getBegin(),
Douglas Gregorcaa1bf42010-08-18 00:39:00 +0000958 diag::err_array_too_large)
959 << Value.toString(10)
960 << ArraySize->getSourceRange();
961 return ExprError();
962 }
963 }
Douglas Gregorf2753b32010-07-13 15:54:32 +0000964 } else if (TypeIdParens.isValid()) {
965 // Can't have dynamic array size when the type-id is in parentheses.
966 Diag(ArraySize->getLocStart(), diag::ext_new_paren_array_nonconst)
967 << ArraySize->getSourceRange()
968 << FixItHint::CreateRemoval(TypeIdParens.getBegin())
969 << FixItHint::CreateRemoval(TypeIdParens.getEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000970
Douglas Gregorf2753b32010-07-13 15:54:32 +0000971 TypeIdParens = SourceRange();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +0000972 }
Sebastian Redl351bb782008-12-02 14:43:59 +0000973 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000974
John McCall31168b02011-06-15 23:02:42 +0000975 // ARC: warn about ABI issues.
976 if (getLangOptions().ObjCAutoRefCount) {
977 QualType BaseAllocType = Context.getBaseElementType(AllocType);
978 if (BaseAllocType.hasStrongOrWeakObjCLifetime())
979 Diag(StartLoc, diag::warn_err_new_delete_object_array)
980 << 0 << BaseAllocType;
981 }
982
John McCall036f2f62011-05-15 07:14:44 +0000983 // Note that we do *not* convert the argument in any way. It can
984 // be signed, larger than size_t, whatever.
Sebastian Redl351bb782008-12-02 14:43:59 +0000985 }
Sebastian Redlbd150f42008-11-21 19:14:01 +0000986
Sebastian Redlbd150f42008-11-21 19:14:01 +0000987 FunctionDecl *OperatorNew = 0;
988 FunctionDecl *OperatorDelete = 0;
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000989 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
990 unsigned NumPlaceArgs = PlacementArgs.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000991
Sebastian Redl8d2ccae2009-02-26 14:39:58 +0000992 if (!AllocType->isDependentType() &&
993 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
994 FindAllocationFunctions(StartLoc,
Sebastian Redl1df2bbe2009-02-09 18:24:27 +0000995 SourceRange(PlacementLParen, PlacementRParen),
996 UseGlobal, AllocType, ArraySize, PlaceArgs,
997 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000998 return ExprError();
John McCall284c48f2011-01-27 09:37:56 +0000999
1000 // If this is an array allocation, compute whether the usual array
1001 // deallocation function for the type has a size_t parameter.
1002 bool UsualArrayDeleteWantsSize = false;
1003 if (ArraySize && !AllocType->isDependentType())
1004 UsualArrayDeleteWantsSize
1005 = doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
1006
Fariborz Jahanian835026e2009-11-24 18:29:37 +00001007 llvm::SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +00001008 if (OperatorNew) {
1009 // Add default arguments, if any.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001010 const FunctionProtoType *Proto =
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +00001011 OperatorNew->getType()->getAs<FunctionProtoType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001012 VariadicCallType CallType =
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00001013 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001014
Anders Carlssonc144bc22010-05-03 02:07:56 +00001015 if (GatherArgumentsForCall(PlacementLParen, OperatorNew,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001016 Proto, 1, PlaceArgs, NumPlaceArgs,
Anders Carlssonc144bc22010-05-03 02:07:56 +00001017 AllPlaceArgs, CallType))
Fariborz Jahanian835026e2009-11-24 18:29:37 +00001018 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001019
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +00001020 NumPlaceArgs = AllPlaceArgs.size();
1021 if (NumPlaceArgs > 0)
1022 PlaceArgs = &AllPlaceArgs[0];
1023 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001024
Sebastian Redlbd150f42008-11-21 19:14:01 +00001025 bool Init = ConstructorLParen.isValid();
1026 // --- Choosing a constructor ---
Sebastian Redlbd150f42008-11-21 19:14:01 +00001027 CXXConstructorDecl *Constructor = 0;
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001028 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
1029 unsigned NumConsArgs = ConstructorArgs.size();
John McCall37ad5512010-08-23 06:44:23 +00001030 ASTOwningVector<Expr*> ConvertedConstructorArgs(*this);
Eli Friedmanfd8d4e12009-11-08 22:15:39 +00001031
Anders Carlssonc6bb0e12010-05-03 15:45:23 +00001032 // Array 'new' can't have any initializers.
Anders Carlssone6ae81b2010-05-16 16:24:20 +00001033 if (NumConsArgs && (ResultType->isArrayType() || ArraySize)) {
Anders Carlssonc6bb0e12010-05-03 15:45:23 +00001034 SourceRange InitRange(ConsArgs[0]->getLocStart(),
1035 ConsArgs[NumConsArgs - 1]->getLocEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001036
Anders Carlssonc6bb0e12010-05-03 15:45:23 +00001037 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
1038 return ExprError();
1039 }
1040
Douglas Gregor85dabae2009-12-16 01:38:02 +00001041 if (!AllocType->isDependentType() &&
1042 !Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) {
1043 // C++0x [expr.new]p15:
1044 // A new-expression that creates an object of type T initializes that
1045 // object as follows:
1046 InitializationKind Kind
1047 // - If the new-initializer is omitted, the object is default-
1048 // initialized (8.5); if no initialization is performed,
1049 // the object has indeterminate value
Douglas Gregor0744ef62010-09-07 21:49:58 +00001050 = !Init? InitializationKind::CreateDefault(TypeRange.getBegin())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001051 // - Otherwise, the new-initializer is interpreted according to the
Douglas Gregor85dabae2009-12-16 01:38:02 +00001052 // initialization rules of 8.5 for direct-initialization.
Douglas Gregor0744ef62010-09-07 21:49:58 +00001053 : InitializationKind::CreateDirect(TypeRange.getBegin(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001054 ConstructorLParen,
Douglas Gregor85dabae2009-12-16 01:38:02 +00001055 ConstructorRParen);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001056
Douglas Gregor85dabae2009-12-16 01:38:02 +00001057 InitializedEntity Entity
Douglas Gregor1b303932009-12-22 15:35:07 +00001058 = InitializedEntity::InitializeNew(StartLoc, AllocType);
Douglas Gregor85dabae2009-12-16 01:38:02 +00001059 InitializationSequence InitSeq(*this, Entity, Kind, ConsArgs, NumConsArgs);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001060 ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
Douglas Gregor85dabae2009-12-16 01:38:02 +00001061 move(ConstructorArgs));
1062 if (FullInit.isInvalid())
1063 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001064
1065 // FullInit is our initializer; walk through it to determine if it's a
Douglas Gregor85dabae2009-12-16 01:38:02 +00001066 // constructor call, which CXXNewExpr handles directly.
1067 if (Expr *FullInitExpr = (Expr *)FullInit.get()) {
1068 if (CXXBindTemporaryExpr *Binder
1069 = dyn_cast<CXXBindTemporaryExpr>(FullInitExpr))
1070 FullInitExpr = Binder->getSubExpr();
1071 if (CXXConstructExpr *Construct
1072 = dyn_cast<CXXConstructExpr>(FullInitExpr)) {
1073 Constructor = Construct->getConstructor();
1074 for (CXXConstructExpr::arg_iterator A = Construct->arg_begin(),
1075 AEnd = Construct->arg_end();
1076 A != AEnd; ++A)
John McCallc3007a22010-10-26 07:05:15 +00001077 ConvertedConstructorArgs.push_back(*A);
Douglas Gregor85dabae2009-12-16 01:38:02 +00001078 } else {
1079 // Take the converted initializer.
1080 ConvertedConstructorArgs.push_back(FullInit.release());
1081 }
1082 } else {
1083 // No initialization required.
1084 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001085
Douglas Gregor85dabae2009-12-16 01:38:02 +00001086 // Take the converted arguments and use them for the new expression.
Douglas Gregor5d3507d2009-09-09 23:08:42 +00001087 NumConsArgs = ConvertedConstructorArgs.size();
1088 ConsArgs = (Expr **)ConvertedConstructorArgs.take();
Sebastian Redlbd150f42008-11-21 19:14:01 +00001089 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001090
Douglas Gregor6642ca22010-02-26 05:06:18 +00001091 // Mark the new and delete operators as referenced.
1092 if (OperatorNew)
1093 MarkDeclarationReferenced(StartLoc, OperatorNew);
1094 if (OperatorDelete)
1095 MarkDeclarationReferenced(StartLoc, OperatorDelete);
1096
Sebastian Redlbd150f42008-11-21 19:14:01 +00001097 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001098
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001099 PlacementArgs.release();
1100 ConstructorArgs.release();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001101
Ted Kremenek9d6eb402010-02-11 22:51:03 +00001102 return Owned(new (Context) CXXNewExpr(Context, UseGlobal, OperatorNew,
Douglas Gregorf2753b32010-07-13 15:54:32 +00001103 PlaceArgs, NumPlaceArgs, TypeIdParens,
Ted Kremenek9d6eb402010-02-11 22:51:03 +00001104 ArraySize, Constructor, Init,
1105 ConsArgs, NumConsArgs, OperatorDelete,
John McCall284c48f2011-01-27 09:37:56 +00001106 UsualArrayDeleteWantsSize,
Douglas Gregor0744ef62010-09-07 21:49:58 +00001107 ResultType, AllocTypeInfo,
1108 StartLoc,
Ted Kremenek9d6eb402010-02-11 22:51:03 +00001109 Init ? ConstructorRParen :
Chandler Carruth01718152010-10-25 08:47:36 +00001110 TypeRange.getEnd(),
1111 ConstructorLParen, ConstructorRParen));
Sebastian Redlbd150f42008-11-21 19:14:01 +00001112}
1113
1114/// CheckAllocatedType - Checks that a type is suitable as the allocated type
1115/// in a new-expression.
1116/// dimension off and stores the size expression in ArraySize.
Douglas Gregord0fefba2009-05-21 00:00:09 +00001117bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00001118 SourceRange R) {
Sebastian Redlbd150f42008-11-21 19:14:01 +00001119 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
1120 // abstract class type or array thereof.
Douglas Gregorac1fb652009-03-24 19:52:54 +00001121 if (AllocType->isFunctionType())
Douglas Gregord0fefba2009-05-21 00:00:09 +00001122 return Diag(Loc, diag::err_bad_new_type)
1123 << AllocType << 0 << R;
Douglas Gregorac1fb652009-03-24 19:52:54 +00001124 else if (AllocType->isReferenceType())
Douglas Gregord0fefba2009-05-21 00:00:09 +00001125 return Diag(Loc, diag::err_bad_new_type)
1126 << AllocType << 1 << R;
Douglas Gregorac1fb652009-03-24 19:52:54 +00001127 else if (!AllocType->isDependentType() &&
Douglas Gregord0fefba2009-05-21 00:00:09 +00001128 RequireCompleteType(Loc, AllocType,
Anders Carlssond624e162009-08-26 23:45:07 +00001129 PDiag(diag::err_new_incomplete_type)
1130 << R))
Sebastian Redlbd150f42008-11-21 19:14:01 +00001131 return true;
Douglas Gregord0fefba2009-05-21 00:00:09 +00001132 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregorac1fb652009-03-24 19:52:54 +00001133 diag::err_allocation_of_abstract_type))
1134 return true;
Douglas Gregor3999e152010-10-06 16:00:31 +00001135 else if (AllocType->isVariablyModifiedType())
1136 return Diag(Loc, diag::err_variably_modified_new_type)
1137 << AllocType;
Douglas Gregor39d1a092011-04-15 19:46:20 +00001138 else if (unsigned AddressSpace = AllocType.getAddressSpace())
1139 return Diag(Loc, diag::err_address_space_qualified_new)
1140 << AllocType.getUnqualifiedType() << AddressSpace;
John McCall31168b02011-06-15 23:02:42 +00001141 else if (getLangOptions().ObjCAutoRefCount) {
1142 if (const ArrayType *AT = Context.getAsArrayType(AllocType)) {
1143 QualType BaseAllocType = Context.getBaseElementType(AT);
1144 if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None &&
1145 BaseAllocType->isObjCLifetimeType())
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00001146 return Diag(Loc, diag::err_arc_new_array_without_ownership)
John McCall31168b02011-06-15 23:02:42 +00001147 << BaseAllocType;
1148 }
1149 }
Douglas Gregor39d1a092011-04-15 19:46:20 +00001150
Sebastian Redlbd150f42008-11-21 19:14:01 +00001151 return false;
1152}
1153
Douglas Gregor6642ca22010-02-26 05:06:18 +00001154/// \brief Determine whether the given function is a non-placement
1155/// deallocation function.
1156static bool isNonPlacementDeallocationFunction(FunctionDecl *FD) {
1157 if (FD->isInvalidDecl())
1158 return false;
1159
1160 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
1161 return Method->isUsualDeallocationFunction();
1162
1163 return ((FD->getOverloadedOperator() == OO_Delete ||
1164 FD->getOverloadedOperator() == OO_Array_Delete) &&
1165 FD->getNumParams() == 1);
1166}
1167
Sebastian Redlfaf68082008-12-03 20:26:15 +00001168/// FindAllocationFunctions - Finds the overloads of operator new and delete
1169/// that are appropriate for the allocation.
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00001170bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
1171 bool UseGlobal, QualType AllocType,
1172 bool IsArray, Expr **PlaceArgs,
1173 unsigned NumPlaceArgs,
Sebastian Redlfaf68082008-12-03 20:26:15 +00001174 FunctionDecl *&OperatorNew,
Mike Stump11289f42009-09-09 15:08:12 +00001175 FunctionDecl *&OperatorDelete) {
Sebastian Redlfaf68082008-12-03 20:26:15 +00001176 // --- Choosing an allocation function ---
1177 // C++ 5.3.4p8 - 14 & 18
1178 // 1) If UseGlobal is true, only look in the global scope. Else, also look
1179 // in the scope of the allocated class.
1180 // 2) If an array size is given, look for operator new[], else look for
1181 // operator new.
1182 // 3) The first argument is always size_t. Append the arguments from the
1183 // placement form.
Sebastian Redlfaf68082008-12-03 20:26:15 +00001184
1185 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
1186 // We don't care about the actual value of this argument.
1187 // FIXME: Should the Sema create the expression and embed it in the syntax
1188 // tree? Or should the consumer just recalculate the value?
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00001189 IntegerLiteral Size(Context, llvm::APInt::getNullValue(
Anders Carlssona471db02009-08-16 20:29:29 +00001190 Context.Target.getPointerWidth(0)),
1191 Context.getSizeType(),
1192 SourceLocation());
1193 AllocArgs[0] = &Size;
Sebastian Redlfaf68082008-12-03 20:26:15 +00001194 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
1195
Douglas Gregor6642ca22010-02-26 05:06:18 +00001196 // C++ [expr.new]p8:
1197 // If the allocated type is a non-array type, the allocation
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001198 // function's name is operator new and the deallocation function's
Douglas Gregor6642ca22010-02-26 05:06:18 +00001199 // name is operator delete. If the allocated type is an array
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001200 // type, the allocation function's name is operator new[] and the
1201 // deallocation function's name is operator delete[].
Sebastian Redlfaf68082008-12-03 20:26:15 +00001202 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
1203 IsArray ? OO_Array_New : OO_New);
Douglas Gregor6642ca22010-02-26 05:06:18 +00001204 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1205 IsArray ? OO_Array_Delete : OO_Delete);
1206
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00001207 QualType AllocElemType = Context.getBaseElementType(AllocType);
1208
1209 if (AllocElemType->isRecordType() && !UseGlobal) {
Mike Stump11289f42009-09-09 15:08:12 +00001210 CXXRecordDecl *Record
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00001211 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00001212 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl33a31012008-12-04 22:20:51 +00001213 AllocArgs.size(), Record, /*AllowMissing=*/true,
1214 OperatorNew))
Sebastian Redlfaf68082008-12-03 20:26:15 +00001215 return true;
Sebastian Redlfaf68082008-12-03 20:26:15 +00001216 }
1217 if (!OperatorNew) {
1218 // Didn't find a member overload. Look for a global one.
1219 DeclareGlobalNewDelete();
Sebastian Redl33a31012008-12-04 22:20:51 +00001220 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00001221 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl33a31012008-12-04 22:20:51 +00001222 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
1223 OperatorNew))
Sebastian Redlfaf68082008-12-03 20:26:15 +00001224 return true;
Sebastian Redlfaf68082008-12-03 20:26:15 +00001225 }
1226
John McCall0f55a032010-04-20 02:18:25 +00001227 // We don't need an operator delete if we're running under
1228 // -fno-exceptions.
1229 if (!getLangOptions().Exceptions) {
1230 OperatorDelete = 0;
1231 return false;
1232 }
1233
Anders Carlsson6f9dabf2009-05-31 20:26:12 +00001234 // FindAllocationOverload can change the passed in arguments, so we need to
1235 // copy them back.
1236 if (NumPlaceArgs > 0)
1237 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
Mike Stump11289f42009-09-09 15:08:12 +00001238
Douglas Gregor6642ca22010-02-26 05:06:18 +00001239 // C++ [expr.new]p19:
1240 //
1241 // If the new-expression begins with a unary :: operator, the
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001242 // deallocation function's name is looked up in the global
Douglas Gregor6642ca22010-02-26 05:06:18 +00001243 // scope. Otherwise, if the allocated type is a class type T or an
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001244 // array thereof, the deallocation function's name is looked up in
Douglas Gregor6642ca22010-02-26 05:06:18 +00001245 // the scope of T. If this lookup fails to find the name, or if
1246 // the allocated type is not a class type or array thereof, the
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001247 // deallocation function's name is looked up in the global scope.
Douglas Gregor6642ca22010-02-26 05:06:18 +00001248 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00001249 if (AllocElemType->isRecordType() && !UseGlobal) {
Douglas Gregor6642ca22010-02-26 05:06:18 +00001250 CXXRecordDecl *RD
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00001251 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Douglas Gregor6642ca22010-02-26 05:06:18 +00001252 LookupQualifiedName(FoundDelete, RD);
1253 }
John McCallfb6f5262010-03-18 08:19:33 +00001254 if (FoundDelete.isAmbiguous())
1255 return true; // FIXME: clean up expressions?
Douglas Gregor6642ca22010-02-26 05:06:18 +00001256
1257 if (FoundDelete.empty()) {
1258 DeclareGlobalNewDelete();
1259 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
1260 }
1261
1262 FoundDelete.suppressDiagnostics();
John McCalla0296f72010-03-19 07:35:19 +00001263
1264 llvm::SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
1265
John McCalld3be2c82010-09-14 21:34:24 +00001266 // Whether we're looking for a placement operator delete is dictated
1267 // by whether we selected a placement operator new, not by whether
1268 // we had explicit placement arguments. This matters for things like
1269 // struct A { void *operator new(size_t, int = 0); ... };
1270 // A *a = new A()
1271 bool isPlacementNew = (NumPlaceArgs > 0 || OperatorNew->param_size() != 1);
1272
1273 if (isPlacementNew) {
Douglas Gregor6642ca22010-02-26 05:06:18 +00001274 // C++ [expr.new]p20:
1275 // A declaration of a placement deallocation function matches the
1276 // declaration of a placement allocation function if it has the
1277 // same number of parameters and, after parameter transformations
1278 // (8.3.5), all parameter types except the first are
1279 // identical. [...]
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001280 //
Douglas Gregor6642ca22010-02-26 05:06:18 +00001281 // To perform this comparison, we compute the function type that
1282 // the deallocation function should have, and use that type both
1283 // for template argument deduction and for comparison purposes.
John McCalldb40c7f2010-12-14 08:05:40 +00001284 //
1285 // FIXME: this comparison should ignore CC and the like.
Douglas Gregor6642ca22010-02-26 05:06:18 +00001286 QualType ExpectedFunctionType;
1287 {
1288 const FunctionProtoType *Proto
1289 = OperatorNew->getType()->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00001290
Douglas Gregor6642ca22010-02-26 05:06:18 +00001291 llvm::SmallVector<QualType, 4> ArgTypes;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001292 ArgTypes.push_back(Context.VoidPtrTy);
Douglas Gregor6642ca22010-02-26 05:06:18 +00001293 for (unsigned I = 1, N = Proto->getNumArgs(); I < N; ++I)
1294 ArgTypes.push_back(Proto->getArgType(I));
1295
John McCalldb40c7f2010-12-14 08:05:40 +00001296 FunctionProtoType::ExtProtoInfo EPI;
1297 EPI.Variadic = Proto->isVariadic();
1298
Douglas Gregor6642ca22010-02-26 05:06:18 +00001299 ExpectedFunctionType
1300 = Context.getFunctionType(Context.VoidTy, ArgTypes.data(),
John McCalldb40c7f2010-12-14 08:05:40 +00001301 ArgTypes.size(), EPI);
Douglas Gregor6642ca22010-02-26 05:06:18 +00001302 }
1303
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001304 for (LookupResult::iterator D = FoundDelete.begin(),
Douglas Gregor6642ca22010-02-26 05:06:18 +00001305 DEnd = FoundDelete.end();
1306 D != DEnd; ++D) {
1307 FunctionDecl *Fn = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001308 if (FunctionTemplateDecl *FnTmpl
Douglas Gregor6642ca22010-02-26 05:06:18 +00001309 = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
1310 // Perform template argument deduction to try to match the
1311 // expected function type.
1312 TemplateDeductionInfo Info(Context, StartLoc);
1313 if (DeduceTemplateArguments(FnTmpl, 0, ExpectedFunctionType, Fn, Info))
1314 continue;
1315 } else
1316 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
1317
1318 if (Context.hasSameType(Fn->getType(), ExpectedFunctionType))
John McCalla0296f72010-03-19 07:35:19 +00001319 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6642ca22010-02-26 05:06:18 +00001320 }
1321 } else {
1322 // C++ [expr.new]p20:
1323 // [...] Any non-placement deallocation function matches a
1324 // non-placement allocation function. [...]
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001325 for (LookupResult::iterator D = FoundDelete.begin(),
Douglas Gregor6642ca22010-02-26 05:06:18 +00001326 DEnd = FoundDelete.end();
1327 D != DEnd; ++D) {
1328 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>((*D)->getUnderlyingDecl()))
1329 if (isNonPlacementDeallocationFunction(Fn))
John McCalla0296f72010-03-19 07:35:19 +00001330 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6642ca22010-02-26 05:06:18 +00001331 }
1332 }
1333
1334 // C++ [expr.new]p20:
1335 // [...] If the lookup finds a single matching deallocation
1336 // function, that function will be called; otherwise, no
1337 // deallocation function will be called.
1338 if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00001339 OperatorDelete = Matches[0].second;
Douglas Gregor6642ca22010-02-26 05:06:18 +00001340
1341 // C++0x [expr.new]p20:
1342 // If the lookup finds the two-parameter form of a usual
1343 // deallocation function (3.7.4.2) and that function, considered
1344 // as a placement deallocation function, would have been
1345 // selected as a match for the allocation function, the program
1346 // is ill-formed.
1347 if (NumPlaceArgs && getLangOptions().CPlusPlus0x &&
1348 isNonPlacementDeallocationFunction(OperatorDelete)) {
1349 Diag(StartLoc, diag::err_placement_new_non_placement_delete)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001350 << SourceRange(PlaceArgs[0]->getLocStart(),
Douglas Gregor6642ca22010-02-26 05:06:18 +00001351 PlaceArgs[NumPlaceArgs - 1]->getLocEnd());
1352 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
1353 << DeleteName;
John McCallfb6f5262010-03-18 08:19:33 +00001354 } else {
1355 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
John McCalla0296f72010-03-19 07:35:19 +00001356 Matches[0].first);
Douglas Gregor6642ca22010-02-26 05:06:18 +00001357 }
1358 }
1359
Sebastian Redlfaf68082008-12-03 20:26:15 +00001360 return false;
1361}
1362
Sebastian Redl33a31012008-12-04 22:20:51 +00001363/// FindAllocationOverload - Find an fitting overload for the allocation
1364/// function in the specified scope.
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00001365bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
1366 DeclarationName Name, Expr** Args,
1367 unsigned NumArgs, DeclContext *Ctx,
Alexis Hunt1f69a022011-05-12 22:46:29 +00001368 bool AllowMissing, FunctionDecl *&Operator,
1369 bool Diagnose) {
John McCall27b18f82009-11-17 02:14:36 +00001370 LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
1371 LookupQualifiedName(R, Ctx);
John McCall9f3059a2009-10-09 21:13:30 +00001372 if (R.empty()) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00001373 if (AllowMissing || !Diagnose)
Sebastian Redl33a31012008-12-04 22:20:51 +00001374 return false;
Sebastian Redl33a31012008-12-04 22:20:51 +00001375 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner45d9d602009-02-17 07:29:20 +00001376 << Name << Range;
Sebastian Redl33a31012008-12-04 22:20:51 +00001377 }
1378
John McCallfb6f5262010-03-18 08:19:33 +00001379 if (R.isAmbiguous())
1380 return true;
1381
1382 R.suppressDiagnostics();
John McCall9f3059a2009-10-09 21:13:30 +00001383
John McCallbc077cf2010-02-08 23:07:23 +00001384 OverloadCandidateSet Candidates(StartLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001385 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
Douglas Gregor80a6cc52009-09-30 00:03:47 +00001386 Alloc != AllocEnd; ++Alloc) {
Douglas Gregor55297ac2008-12-23 00:26:44 +00001387 // Even member operator new/delete are implicitly treated as
1388 // static, so don't use AddMemberCandidate.
John McCalla0296f72010-03-19 07:35:19 +00001389 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
Chandler Carruth93538422010-02-03 11:02:14 +00001390
John McCalla0296f72010-03-19 07:35:19 +00001391 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
1392 AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
Chandler Carruth93538422010-02-03 11:02:14 +00001393 /*ExplicitTemplateArgs=*/0, Args, NumArgs,
1394 Candidates,
1395 /*SuppressUserConversions=*/false);
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001396 continue;
Chandler Carruth93538422010-02-03 11:02:14 +00001397 }
1398
John McCalla0296f72010-03-19 07:35:19 +00001399 FunctionDecl *Fn = cast<FunctionDecl>(D);
1400 AddOverloadCandidate(Fn, Alloc.getPair(), Args, NumArgs, Candidates,
Chandler Carruth93538422010-02-03 11:02:14 +00001401 /*SuppressUserConversions=*/false);
Sebastian Redl33a31012008-12-04 22:20:51 +00001402 }
1403
1404 // Do the resolution.
1405 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00001406 switch (Candidates.BestViableFunction(*this, StartLoc, Best)) {
Sebastian Redl33a31012008-12-04 22:20:51 +00001407 case OR_Success: {
1408 // Got one!
1409 FunctionDecl *FnDecl = Best->Function;
Chandler Carruth30141632011-02-25 19:41:05 +00001410 MarkDeclarationReferenced(StartLoc, FnDecl);
Sebastian Redl33a31012008-12-04 22:20:51 +00001411 // The first argument is size_t, and the first parameter must be size_t,
1412 // too. This is checked on declaration and can be assumed. (It can't be
1413 // asserted on, though, since invalid decls are left in there.)
John McCallfb6f5262010-03-18 08:19:33 +00001414 // Watch out for variadic allocator function.
Fariborz Jahanian835026e2009-11-24 18:29:37 +00001415 unsigned NumArgsInFnDecl = FnDecl->getNumParams();
1416 for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00001417 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1418 FnDecl->getParamDecl(i));
1419
1420 if (!Diagnose && !CanPerformCopyInitialization(Entity, Owned(Args[i])))
1421 return true;
1422
John McCalldadc5752010-08-24 06:29:42 +00001423 ExprResult Result
Alexis Hunt1f69a022011-05-12 22:46:29 +00001424 = PerformCopyInitialization(Entity, SourceLocation(), Owned(Args[i]));
Douglas Gregor34147272010-03-26 20:35:59 +00001425 if (Result.isInvalid())
Sebastian Redl33a31012008-12-04 22:20:51 +00001426 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001427
Douglas Gregor34147272010-03-26 20:35:59 +00001428 Args[i] = Result.takeAs<Expr>();
Sebastian Redl33a31012008-12-04 22:20:51 +00001429 }
1430 Operator = FnDecl;
Alexis Hunt1f69a022011-05-12 22:46:29 +00001431 CheckAllocationAccess(StartLoc, Range, R.getNamingClass(), Best->FoundDecl,
1432 Diagnose);
Sebastian Redl33a31012008-12-04 22:20:51 +00001433 return false;
1434 }
1435
1436 case OR_No_Viable_Function:
Chandler Carruthe6c88182011-06-08 10:26:03 +00001437 if (Diagnose) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00001438 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
1439 << Name << Range;
Chandler Carruthe6c88182011-06-08 10:26:03 +00001440 Candidates.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
1441 }
Sebastian Redl33a31012008-12-04 22:20:51 +00001442 return true;
1443
1444 case OR_Ambiguous:
Chandler Carruthe6c88182011-06-08 10:26:03 +00001445 if (Diagnose) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00001446 Diag(StartLoc, diag::err_ovl_ambiguous_call)
1447 << Name << Range;
Chandler Carruthe6c88182011-06-08 10:26:03 +00001448 Candidates.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
1449 }
Sebastian Redl33a31012008-12-04 22:20:51 +00001450 return true;
Douglas Gregor171c45a2009-02-18 21:56:37 +00001451
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001452 case OR_Deleted: {
Chandler Carruthe6c88182011-06-08 10:26:03 +00001453 if (Diagnose) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00001454 Diag(StartLoc, diag::err_ovl_deleted_call)
1455 << Best->Function->isDeleted()
1456 << Name
1457 << getDeletedOrUnavailableSuffix(Best->Function)
1458 << Range;
Chandler Carruthe6c88182011-06-08 10:26:03 +00001459 Candidates.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
1460 }
Douglas Gregor171c45a2009-02-18 21:56:37 +00001461 return true;
Sebastian Redl33a31012008-12-04 22:20:51 +00001462 }
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001463 }
Sebastian Redl33a31012008-12-04 22:20:51 +00001464 assert(false && "Unreachable, bad result from BestViableFunction");
1465 return true;
1466}
1467
1468
Sebastian Redlfaf68082008-12-03 20:26:15 +00001469/// DeclareGlobalNewDelete - Declare the global forms of operator new and
1470/// delete. These are:
1471/// @code
Sebastian Redl37588092011-03-14 18:08:30 +00001472/// // C++03:
Sebastian Redlfaf68082008-12-03 20:26:15 +00001473/// void* operator new(std::size_t) throw(std::bad_alloc);
1474/// void* operator new[](std::size_t) throw(std::bad_alloc);
1475/// void operator delete(void *) throw();
1476/// void operator delete[](void *) throw();
Sebastian Redl37588092011-03-14 18:08:30 +00001477/// // C++0x:
1478/// void* operator new(std::size_t);
1479/// void* operator new[](std::size_t);
1480/// void operator delete(void *);
1481/// void operator delete[](void *);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001482/// @endcode
Sebastian Redl37588092011-03-14 18:08:30 +00001483/// C++0x operator delete is implicitly noexcept.
Sebastian Redlfaf68082008-12-03 20:26:15 +00001484/// Note that the placement and nothrow forms of new are *not* implicitly
1485/// declared. Their use requires including \<new\>.
Mike Stump11289f42009-09-09 15:08:12 +00001486void Sema::DeclareGlobalNewDelete() {
Sebastian Redlfaf68082008-12-03 20:26:15 +00001487 if (GlobalNewDeleteDeclared)
1488 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001489
Douglas Gregor87f54062009-09-15 22:30:29 +00001490 // C++ [basic.std.dynamic]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001491 // [...] The following allocation and deallocation functions (18.4) are
1492 // implicitly declared in global scope in each translation unit of a
Douglas Gregor87f54062009-09-15 22:30:29 +00001493 // program
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001494 //
Sebastian Redl37588092011-03-14 18:08:30 +00001495 // C++03:
Douglas Gregor87f54062009-09-15 22:30:29 +00001496 // void* operator new(std::size_t) throw(std::bad_alloc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001497 // void* operator new[](std::size_t) throw(std::bad_alloc);
1498 // void operator delete(void*) throw();
Douglas Gregor87f54062009-09-15 22:30:29 +00001499 // void operator delete[](void*) throw();
Sebastian Redl37588092011-03-14 18:08:30 +00001500 // C++0x:
1501 // void* operator new(std::size_t);
1502 // void* operator new[](std::size_t);
1503 // void operator delete(void*);
1504 // void operator delete[](void*);
Douglas Gregor87f54062009-09-15 22:30:29 +00001505 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001506 // These implicit declarations introduce only the function names operator
Douglas Gregor87f54062009-09-15 22:30:29 +00001507 // new, operator new[], operator delete, operator delete[].
1508 //
1509 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
1510 // "std" or "bad_alloc" as necessary to form the exception specification.
1511 // However, we do not make these implicit declarations visible to name
1512 // lookup.
Sebastian Redl37588092011-03-14 18:08:30 +00001513 // Note that the C++0x versions of operator delete are deallocation functions,
1514 // and thus are implicitly noexcept.
1515 if (!StdBadAlloc && !getLangOptions().CPlusPlus0x) {
Douglas Gregor87f54062009-09-15 22:30:29 +00001516 // The "std::bad_alloc" class has not yet been declared, so build it
1517 // implicitly.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001518 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
1519 getOrCreateStdNamespace(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00001520 SourceLocation(), SourceLocation(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001521 &PP.getIdentifierTable().get("bad_alloc"),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00001522 0);
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00001523 getStdBadAlloc()->setImplicit(true);
Douglas Gregor87f54062009-09-15 22:30:29 +00001524 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001525
Sebastian Redlfaf68082008-12-03 20:26:15 +00001526 GlobalNewDeleteDeclared = true;
1527
1528 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
1529 QualType SizeT = Context.getSizeType();
Nuno Lopes13c88c72009-12-16 16:59:22 +00001530 bool AssumeSaneOperatorNew = getLangOptions().AssumeSaneOperatorNew;
Sebastian Redlfaf68082008-12-03 20:26:15 +00001531
Sebastian Redlfaf68082008-12-03 20:26:15 +00001532 DeclareGlobalAllocationFunction(
1533 Context.DeclarationNames.getCXXOperatorName(OO_New),
Nuno Lopes13c88c72009-12-16 16:59:22 +00001534 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001535 DeclareGlobalAllocationFunction(
1536 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
Nuno Lopes13c88c72009-12-16 16:59:22 +00001537 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001538 DeclareGlobalAllocationFunction(
1539 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
1540 Context.VoidTy, VoidPtr);
1541 DeclareGlobalAllocationFunction(
1542 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
1543 Context.VoidTy, VoidPtr);
1544}
1545
1546/// DeclareGlobalAllocationFunction - Declares a single implicit global
1547/// allocation function if it doesn't already exist.
1548void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Nuno Lopes13c88c72009-12-16 16:59:22 +00001549 QualType Return, QualType Argument,
1550 bool AddMallocAttr) {
Sebastian Redlfaf68082008-12-03 20:26:15 +00001551 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
1552
1553 // Check if this function is already declared.
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001554 {
Douglas Gregor17eb26b2008-12-23 22:05:29 +00001555 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001556 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001557 Alloc != AllocEnd; ++Alloc) {
Chandler Carruth93538422010-02-03 11:02:14 +00001558 // Only look at non-template functions, as it is the predefined,
1559 // non-templated allocation function we are trying to declare here.
1560 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
1561 QualType InitialParamType =
Douglas Gregor684d7bd2009-12-22 23:42:49 +00001562 Context.getCanonicalType(
Chandler Carruth93538422010-02-03 11:02:14 +00001563 Func->getParamDecl(0)->getType().getUnqualifiedType());
1564 // FIXME: Do we need to check for default arguments here?
Douglas Gregorc1a42fd2010-08-18 15:06:25 +00001565 if (Func->getNumParams() == 1 && InitialParamType == Argument) {
1566 if(AddMallocAttr && !Func->hasAttr<MallocAttr>())
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001567 Func->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
Chandler Carruth93538422010-02-03 11:02:14 +00001568 return;
Douglas Gregorc1a42fd2010-08-18 15:06:25 +00001569 }
Chandler Carruth93538422010-02-03 11:02:14 +00001570 }
Sebastian Redlfaf68082008-12-03 20:26:15 +00001571 }
1572 }
1573
Douglas Gregor87f54062009-09-15 22:30:29 +00001574 QualType BadAllocType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001575 bool HasBadAllocExceptionSpec
Douglas Gregor87f54062009-09-15 22:30:29 +00001576 = (Name.getCXXOverloadedOperator() == OO_New ||
1577 Name.getCXXOverloadedOperator() == OO_Array_New);
Sebastian Redl37588092011-03-14 18:08:30 +00001578 if (HasBadAllocExceptionSpec && !getLangOptions().CPlusPlus0x) {
Douglas Gregor87f54062009-09-15 22:30:29 +00001579 assert(StdBadAlloc && "Must have std::bad_alloc declared");
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00001580 BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
Douglas Gregor87f54062009-09-15 22:30:29 +00001581 }
John McCalldb40c7f2010-12-14 08:05:40 +00001582
1583 FunctionProtoType::ExtProtoInfo EPI;
John McCalldb40c7f2010-12-14 08:05:40 +00001584 if (HasBadAllocExceptionSpec) {
Sebastian Redl37588092011-03-14 18:08:30 +00001585 if (!getLangOptions().CPlusPlus0x) {
1586 EPI.ExceptionSpecType = EST_Dynamic;
1587 EPI.NumExceptions = 1;
1588 EPI.Exceptions = &BadAllocType;
1589 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00001590 } else {
Sebastian Redl37588092011-03-14 18:08:30 +00001591 EPI.ExceptionSpecType = getLangOptions().CPlusPlus0x ?
1592 EST_BasicNoexcept : EST_DynamicNone;
John McCalldb40c7f2010-12-14 08:05:40 +00001593 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001594
John McCalldb40c7f2010-12-14 08:05:40 +00001595 QualType FnType = Context.getFunctionType(Return, &Argument, 1, EPI);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001596 FunctionDecl *Alloc =
Abramo Bagnaradff19302011-03-08 08:55:46 +00001597 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(),
1598 SourceLocation(), Name,
John McCall8e7d6562010-08-26 03:08:43 +00001599 FnType, /*TInfo=*/0, SC_None,
1600 SC_None, false, true);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001601 Alloc->setImplicit();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001602
Nuno Lopes13c88c72009-12-16 16:59:22 +00001603 if (AddMallocAttr)
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001604 Alloc->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001605
Sebastian Redlfaf68082008-12-03 20:26:15 +00001606 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00001607 SourceLocation(), 0,
1608 Argument, /*TInfo=*/0,
1609 SC_None, SC_None, 0);
Douglas Gregord5058122010-02-11 01:19:42 +00001610 Alloc->setParams(&Param, 1);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001611
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001612 // FIXME: Also add this declaration to the IdentifierResolver, but
1613 // make sure it is at the end of the chain to coincide with the
1614 // global scope.
John McCallcc14d1f2010-08-24 08:50:51 +00001615 Context.getTranslationUnitDecl()->addDecl(Alloc);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001616}
1617
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001618bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
1619 DeclarationName Name,
Alexis Hunt1f69a022011-05-12 22:46:29 +00001620 FunctionDecl* &Operator, bool Diagnose) {
John McCall27b18f82009-11-17 02:14:36 +00001621 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001622 // Try to find operator delete/operator delete[] in class scope.
John McCall27b18f82009-11-17 02:14:36 +00001623 LookupQualifiedName(Found, RD);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001624
John McCall27b18f82009-11-17 02:14:36 +00001625 if (Found.isAmbiguous())
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001626 return true;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001627
Chandler Carruthb6f99172010-06-28 00:30:51 +00001628 Found.suppressDiagnostics();
1629
John McCall66a87592010-08-04 00:31:26 +00001630 llvm::SmallVector<DeclAccessPair,4> Matches;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001631 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1632 F != FEnd; ++F) {
Chandler Carruth9b418232010-08-08 07:04:00 +00001633 NamedDecl *ND = (*F)->getUnderlyingDecl();
1634
1635 // Ignore template operator delete members from the check for a usual
1636 // deallocation function.
1637 if (isa<FunctionTemplateDecl>(ND))
1638 continue;
1639
1640 if (cast<CXXMethodDecl>(ND)->isUsualDeallocationFunction())
John McCall66a87592010-08-04 00:31:26 +00001641 Matches.push_back(F.getPair());
1642 }
1643
1644 // There's exactly one suitable operator; pick it.
1645 if (Matches.size() == 1) {
1646 Operator = cast<CXXMethodDecl>(Matches[0]->getUnderlyingDecl());
Alexis Hunt1f69a022011-05-12 22:46:29 +00001647
1648 if (Operator->isDeleted()) {
1649 if (Diagnose) {
1650 Diag(StartLoc, diag::err_deleted_function_use);
1651 Diag(Operator->getLocation(), diag::note_unavailable_here) << true;
1652 }
1653 return true;
1654 }
1655
John McCall66a87592010-08-04 00:31:26 +00001656 CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
Alexis Hunt1f69a022011-05-12 22:46:29 +00001657 Matches[0], Diagnose);
John McCall66a87592010-08-04 00:31:26 +00001658 return false;
1659
1660 // We found multiple suitable operators; complain about the ambiguity.
1661 } else if (!Matches.empty()) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00001662 if (Diagnose) {
Alexis Huntf91729462011-05-12 22:46:25 +00001663 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
1664 << Name << RD;
John McCall66a87592010-08-04 00:31:26 +00001665
Alexis Huntf91729462011-05-12 22:46:25 +00001666 for (llvm::SmallVectorImpl<DeclAccessPair>::iterator
1667 F = Matches.begin(), FEnd = Matches.end(); F != FEnd; ++F)
1668 Diag((*F)->getUnderlyingDecl()->getLocation(),
1669 diag::note_member_declared_here) << Name;
1670 }
John McCall66a87592010-08-04 00:31:26 +00001671 return true;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001672 }
1673
1674 // We did find operator delete/operator delete[] declarations, but
1675 // none of them were suitable.
1676 if (!Found.empty()) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00001677 if (Diagnose) {
Alexis Huntf91729462011-05-12 22:46:25 +00001678 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
1679 << Name << RD;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001680
Alexis Huntf91729462011-05-12 22:46:25 +00001681 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1682 F != FEnd; ++F)
1683 Diag((*F)->getUnderlyingDecl()->getLocation(),
1684 diag::note_member_declared_here) << Name;
1685 }
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001686 return true;
1687 }
1688
1689 // Look for a global declaration.
1690 DeclareGlobalNewDelete();
1691 DeclContext *TUDecl = Context.getTranslationUnitDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001692
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001693 CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation());
1694 Expr* DeallocArgs[1];
1695 DeallocArgs[0] = &Null;
1696 if (FindAllocationOverload(StartLoc, SourceRange(), Name,
Alexis Hunt1f69a022011-05-12 22:46:29 +00001697 DeallocArgs, 1, TUDecl, !Diagnose,
1698 Operator, Diagnose))
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001699 return true;
1700
1701 assert(Operator && "Did not find a deallocation function!");
1702 return false;
1703}
1704
Sebastian Redlbd150f42008-11-21 19:14:01 +00001705/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
1706/// @code ::delete ptr; @endcode
1707/// or
1708/// @code delete [] ptr; @endcode
John McCalldadc5752010-08-24 06:29:42 +00001709ExprResult
Sebastian Redlbd150f42008-11-21 19:14:01 +00001710Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
John Wiegley01296292011-04-08 18:41:53 +00001711 bool ArrayForm, Expr *ExE) {
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001712 // C++ [expr.delete]p1:
1713 // The operand shall have a pointer type, or a class type having a single
1714 // conversion function to a pointer type. The result has type void.
1715 //
Sebastian Redlbd150f42008-11-21 19:14:01 +00001716 // DR599 amends "pointer type" to "pointer to object type" in both cases.
1717
John Wiegley01296292011-04-08 18:41:53 +00001718 ExprResult Ex = Owned(ExE);
Anders Carlssona471db02009-08-16 20:29:29 +00001719 FunctionDecl *OperatorDelete = 0;
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00001720 bool ArrayFormAsWritten = ArrayForm;
John McCall284c48f2011-01-27 09:37:56 +00001721 bool UsualArrayDeleteWantsSize = false;
Mike Stump11289f42009-09-09 15:08:12 +00001722
John Wiegley01296292011-04-08 18:41:53 +00001723 if (!Ex.get()->isTypeDependent()) {
1724 QualType Type = Ex.get()->getType();
Sebastian Redlbd150f42008-11-21 19:14:01 +00001725
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001726 if (const RecordType *Record = Type->getAs<RecordType>()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001727 if (RequireCompleteType(StartLoc, Type,
Douglas Gregorf65f4902010-07-29 14:44:35 +00001728 PDiag(diag::err_delete_incomplete_class_type)))
1729 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001730
John McCallda4458e2010-03-31 01:36:47 +00001731 llvm::SmallVector<CXXConversionDecl*, 4> ObjectPtrConversions;
1732
Fariborz Jahanianb54ccb22009-09-11 21:44:33 +00001733 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001734 const UnresolvedSetImpl *Conversions = RD->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00001735 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00001736 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00001737 NamedDecl *D = I.getDecl();
1738 if (isa<UsingShadowDecl>(D))
1739 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1740
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001741 // Skip over templated conversion functions; they aren't considered.
John McCallda4458e2010-03-31 01:36:47 +00001742 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001743 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001744
John McCallda4458e2010-03-31 01:36:47 +00001745 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001746
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001747 QualType ConvType = Conv->getConversionType().getNonReferenceType();
1748 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
Eli Friedmana170cd62010-08-05 02:49:48 +00001749 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
Fariborz Jahanianadcea102009-09-15 22:15:23 +00001750 ObjectPtrConversions.push_back(Conv);
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001751 }
Fariborz Jahanianadcea102009-09-15 22:15:23 +00001752 if (ObjectPtrConversions.size() == 1) {
1753 // We have a single conversion to a pointer-to-object type. Perform
1754 // that conversion.
John McCallda4458e2010-03-31 01:36:47 +00001755 // TODO: don't redo the conversion calculation.
John Wiegley01296292011-04-08 18:41:53 +00001756 ExprResult Res =
1757 PerformImplicitConversion(Ex.get(),
John McCallda4458e2010-03-31 01:36:47 +00001758 ObjectPtrConversions.front()->getConversionType(),
John Wiegley01296292011-04-08 18:41:53 +00001759 AA_Converting);
1760 if (Res.isUsable()) {
1761 Ex = move(Res);
1762 Type = Ex.get()->getType();
Fariborz Jahanianadcea102009-09-15 22:15:23 +00001763 }
1764 }
1765 else if (ObjectPtrConversions.size() > 1) {
1766 Diag(StartLoc, diag::err_ambiguous_delete_operand)
John Wiegley01296292011-04-08 18:41:53 +00001767 << Type << Ex.get()->getSourceRange();
John McCallda4458e2010-03-31 01:36:47 +00001768 for (unsigned i= 0; i < ObjectPtrConversions.size(); i++)
1769 NoteOverloadCandidate(ObjectPtrConversions[i]);
Fariborz Jahanianadcea102009-09-15 22:15:23 +00001770 return ExprError();
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001771 }
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001772 }
1773
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001774 if (!Type->isPointerType())
1775 return ExprError(Diag(StartLoc, diag::err_delete_operand)
John Wiegley01296292011-04-08 18:41:53 +00001776 << Type << Ex.get()->getSourceRange());
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001777
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001778 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Douglas Gregorbb3348e2010-05-24 17:01:56 +00001779 if (Pointee->isVoidType() && !isSFINAEContext()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001780 // The C++ standard bans deleting a pointer to a non-object type, which
Douglas Gregorbb3348e2010-05-24 17:01:56 +00001781 // effectively bans deletion of "void*". However, most compilers support
1782 // this, so we treat it as a warning unless we're in a SFINAE context.
1783 Diag(StartLoc, diag::ext_delete_void_ptr_operand)
John Wiegley01296292011-04-08 18:41:53 +00001784 << Type << Ex.get()->getSourceRange();
Douglas Gregorbb3348e2010-05-24 17:01:56 +00001785 } else if (Pointee->isFunctionType() || Pointee->isVoidType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001786 return ExprError(Diag(StartLoc, diag::err_delete_operand)
John Wiegley01296292011-04-08 18:41:53 +00001787 << Type << Ex.get()->getSourceRange());
Douglas Gregorc9a1a3b2009-03-24 20:13:58 +00001788 else if (!Pointee->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00001789 RequireCompleteType(StartLoc, Pointee,
Anders Carlssond624e162009-08-26 23:45:07 +00001790 PDiag(diag::warn_delete_incomplete)
John Wiegley01296292011-04-08 18:41:53 +00001791 << Ex.get()->getSourceRange()))
Douglas Gregorc9a1a3b2009-03-24 20:13:58 +00001792 return ExprError();
Douglas Gregor39d1a092011-04-15 19:46:20 +00001793 else if (unsigned AddressSpace = Pointee.getAddressSpace())
1794 return Diag(Ex.get()->getLocStart(),
1795 diag::err_address_space_qualified_delete)
1796 << Pointee.getUnqualifiedType() << AddressSpace;
Douglas Gregor98496dc2009-09-29 21:38:53 +00001797 // C++ [expr.delete]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001798 // [Note: a pointer to a const type can be the operand of a
1799 // delete-expression; it is not necessary to cast away the constness
1800 // (5.2.11) of the pointer expression before it is used as the operand
Douglas Gregor98496dc2009-09-29 21:38:53 +00001801 // of the delete-expression. ]
John McCall31168b02011-06-15 23:02:42 +00001802 if (!Context.hasSameType(Ex.get()->getType(), Context.VoidPtrTy))
1803 Ex = Owned(ImplicitCastExpr::Create(Context, Context.VoidPtrTy, CK_NoOp,
1804 Ex.take(), 0, VK_RValue));
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00001805
1806 if (Pointee->isArrayType() && !ArrayForm) {
1807 Diag(StartLoc, diag::warn_delete_array_type)
John Wiegley01296292011-04-08 18:41:53 +00001808 << Type << Ex.get()->getSourceRange()
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00001809 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(StartLoc), "[]");
1810 ArrayForm = true;
1811 }
1812
Anders Carlssona471db02009-08-16 20:29:29 +00001813 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1814 ArrayForm ? OO_Array_Delete : OO_Delete);
1815
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00001816 QualType PointeeElem = Context.getBaseElementType(Pointee);
1817 if (const RecordType *RT = PointeeElem->getAs<RecordType>()) {
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001818 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1819
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001820 if (!UseGlobal &&
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001821 FindDeallocationFunction(StartLoc, RD, DeleteName, OperatorDelete))
Anders Carlsson654e5c72009-11-14 03:17:38 +00001822 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001823
John McCall284c48f2011-01-27 09:37:56 +00001824 // If we're allocating an array of records, check whether the
1825 // usual operator delete[] has a size_t parameter.
1826 if (ArrayForm) {
1827 // If the user specifically asked to use the global allocator,
1828 // we'll need to do the lookup into the class.
1829 if (UseGlobal)
1830 UsualArrayDeleteWantsSize =
1831 doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
1832
1833 // Otherwise, the usual operator delete[] should be the
1834 // function we just found.
1835 else if (isa<CXXMethodDecl>(OperatorDelete))
1836 UsualArrayDeleteWantsSize = (OperatorDelete->getNumParams() == 2);
1837 }
1838
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001839 if (!RD->hasTrivialDestructor())
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00001840 if (CXXDestructorDecl *Dtor = LookupDestructor(RD)) {
Mike Stump11289f42009-09-09 15:08:12 +00001841 MarkDeclarationReferenced(StartLoc,
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001842 const_cast<CXXDestructorDecl*>(Dtor));
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00001843 DiagnoseUseOfDecl(Dtor, StartLoc);
1844 }
Argyrios Kyrtzidis8bd42852011-05-24 19:53:26 +00001845
1846 // C++ [expr.delete]p3:
1847 // In the first alternative (delete object), if the static type of the
1848 // object to be deleted is different from its dynamic type, the static
1849 // type shall be a base class of the dynamic type of the object to be
1850 // deleted and the static type shall have a virtual destructor or the
1851 // behavior is undefined.
1852 //
1853 // Note: a final class cannot be derived from, no issue there
1854 if (!ArrayForm && RD->isPolymorphic() && !RD->hasAttr<FinalAttr>()) {
1855 CXXDestructorDecl *dtor = RD->getDestructor();
1856 if (!dtor || !dtor->isVirtual())
1857 Diag(StartLoc, diag::warn_delete_non_virtual_dtor) << PointeeElem;
1858 }
John McCall31168b02011-06-15 23:02:42 +00001859
1860 } else if (getLangOptions().ObjCAutoRefCount &&
1861 PointeeElem->isObjCLifetimeType() &&
1862 (PointeeElem.getObjCLifetime() == Qualifiers::OCL_Strong ||
1863 PointeeElem.getObjCLifetime() == Qualifiers::OCL_Weak) &&
1864 ArrayForm) {
1865 Diag(StartLoc, diag::warn_err_new_delete_object_array)
1866 << 1 << PointeeElem;
Anders Carlssona471db02009-08-16 20:29:29 +00001867 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001868
Anders Carlssona471db02009-08-16 20:29:29 +00001869 if (!OperatorDelete) {
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001870 // Look for a global declaration.
Anders Carlssona471db02009-08-16 20:29:29 +00001871 DeclareGlobalNewDelete();
1872 DeclContext *TUDecl = Context.getTranslationUnitDecl();
John Wiegley01296292011-04-08 18:41:53 +00001873 Expr *Arg = Ex.get();
Mike Stump11289f42009-09-09 15:08:12 +00001874 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
John Wiegley01296292011-04-08 18:41:53 +00001875 &Arg, 1, TUDecl, /*AllowMissing=*/false,
Anders Carlssona471db02009-08-16 20:29:29 +00001876 OperatorDelete))
1877 return ExprError();
1878 }
Mike Stump11289f42009-09-09 15:08:12 +00001879
John McCall0f55a032010-04-20 02:18:25 +00001880 MarkDeclarationReferenced(StartLoc, OperatorDelete);
John McCall284c48f2011-01-27 09:37:56 +00001881
Douglas Gregorfa778132011-02-01 15:50:11 +00001882 // Check access and ambiguity of operator delete and destructor.
1883 if (const RecordType *RT = PointeeElem->getAs<RecordType>()) {
1884 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1885 if (CXXDestructorDecl *Dtor = LookupDestructor(RD)) {
John Wiegley01296292011-04-08 18:41:53 +00001886 CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor,
Douglas Gregorfa778132011-02-01 15:50:11 +00001887 PDiag(diag::err_access_dtor) << PointeeElem);
1888 }
1889 }
1890
Sebastian Redlbd150f42008-11-21 19:14:01 +00001891 }
1892
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001893 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
John McCall284c48f2011-01-27 09:37:56 +00001894 ArrayFormAsWritten,
1895 UsualArrayDeleteWantsSize,
John Wiegley01296292011-04-08 18:41:53 +00001896 OperatorDelete, Ex.take(), StartLoc));
Sebastian Redlbd150f42008-11-21 19:14:01 +00001897}
1898
Douglas Gregor633caca2009-11-23 23:44:04 +00001899/// \brief Check the use of the given variable as a C++ condition in an if,
1900/// while, do-while, or switch statement.
John McCalldadc5752010-08-24 06:29:42 +00001901ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
John McCall7decc9e2010-11-18 06:31:45 +00001902 SourceLocation StmtLoc,
1903 bool ConvertToBoolean) {
Douglas Gregor633caca2009-11-23 23:44:04 +00001904 QualType T = ConditionVar->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001905
Douglas Gregor633caca2009-11-23 23:44:04 +00001906 // C++ [stmt.select]p2:
1907 // The declarator shall not specify a function or an array.
1908 if (T->isFunctionType())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001909 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor633caca2009-11-23 23:44:04 +00001910 diag::err_invalid_use_of_function_type)
1911 << ConditionVar->getSourceRange());
1912 else if (T->isArrayType())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001913 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor633caca2009-11-23 23:44:04 +00001914 diag::err_invalid_use_of_array_type)
1915 << ConditionVar->getSourceRange());
Douglas Gregor0156d1c2009-11-24 16:07:02 +00001916
John Wiegley01296292011-04-08 18:41:53 +00001917 ExprResult Condition =
1918 Owned(DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
Douglas Gregorea972d32011-02-28 21:54:11 +00001919 ConditionVar,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001920 ConditionVar->getLocation(),
John McCall7decc9e2010-11-18 06:31:45 +00001921 ConditionVar->getType().getNonReferenceType(),
John Wiegley01296292011-04-08 18:41:53 +00001922 VK_LValue));
1923 if (ConvertToBoolean) {
1924 Condition = CheckBooleanCondition(Condition.take(), StmtLoc);
1925 if (Condition.isInvalid())
1926 return ExprError();
1927 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001928
John Wiegley01296292011-04-08 18:41:53 +00001929 return move(Condition);
Douglas Gregor633caca2009-11-23 23:44:04 +00001930}
1931
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001932/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
John Wiegley01296292011-04-08 18:41:53 +00001933ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr) {
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001934 // C++ 6.4p4:
1935 // The value of a condition that is an initialized declaration in a statement
1936 // other than a switch statement is the value of the declared variable
1937 // implicitly converted to type bool. If that conversion is ill-formed, the
1938 // program is ill-formed.
1939 // The value of a condition that is an expression is the value of the
1940 // expression, implicitly converted to bool.
1941 //
Douglas Gregor5fb53972009-01-14 15:45:31 +00001942 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001943}
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001944
1945/// Helper function to determine whether this is the (deprecated) C++
1946/// conversion from a string literal to a pointer to non-const char or
1947/// non-const wchar_t (for narrow and wide string literals,
1948/// respectively).
Mike Stump11289f42009-09-09 15:08:12 +00001949bool
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001950Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
1951 // Look inside the implicit cast, if it exists.
1952 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
1953 From = Cast->getSubExpr();
1954
1955 // A string literal (2.13.4) that is not a wide string literal can
1956 // be converted to an rvalue of type "pointer to char"; a wide
1957 // string literal can be converted to an rvalue of type "pointer
1958 // to wchar_t" (C++ 4.2p2).
Douglas Gregor689999d2010-06-22 23:47:37 +00001959 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001960 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump11289f42009-09-09 15:08:12 +00001961 if (const BuiltinType *ToPointeeType
John McCall9dd450b2009-09-21 23:43:11 +00001962 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001963 // This conversion is considered only when there is an
1964 // explicit appropriate pointer target type (C++ 4.2p2).
John McCall8ccfcb52009-09-24 19:53:00 +00001965 if (!ToPtrType->getPointeeType().hasQualifiers() &&
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001966 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
1967 (!StrLit->isWide() &&
1968 (ToPointeeType->getKind() == BuiltinType::Char_U ||
1969 ToPointeeType->getKind() == BuiltinType::Char_S))))
1970 return true;
1971 }
1972
1973 return false;
1974}
Douglas Gregor39c16d42008-10-24 04:54:22 +00001975
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001976static ExprResult BuildCXXCastArgument(Sema &S,
John McCalle3027922010-08-25 11:45:40 +00001977 SourceLocation CastLoc,
1978 QualType Ty,
1979 CastKind Kind,
1980 CXXMethodDecl *Method,
Douglas Gregor2bbfba02011-01-20 01:32:05 +00001981 NamedDecl *FoundDecl,
John McCalle3027922010-08-25 11:45:40 +00001982 Expr *From) {
Douglas Gregora4253922010-04-16 22:17:36 +00001983 switch (Kind) {
1984 default: assert(0 && "Unhandled cast kind!");
John McCalle3027922010-08-25 11:45:40 +00001985 case CK_ConstructorConversion: {
John McCall37ad5512010-08-23 06:44:23 +00001986 ASTOwningVector<Expr*> ConstructorArgs(S);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001987
Douglas Gregora4253922010-04-16 22:17:36 +00001988 if (S.CompleteConstructorCall(cast<CXXConstructorDecl>(Method),
John McCallfaf5fb42010-08-26 23:41:50 +00001989 MultiExprArg(&From, 1),
Douglas Gregora4253922010-04-16 22:17:36 +00001990 CastLoc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00001991 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001992
1993 ExprResult Result =
1994 S.BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
John McCallbfd822c2010-08-24 07:32:53 +00001995 move_arg(ConstructorArgs),
Chandler Carruth01718152010-10-25 08:47:36 +00001996 /*ZeroInit*/ false, CXXConstructExpr::CK_Complete,
1997 SourceRange());
Douglas Gregora4253922010-04-16 22:17:36 +00001998 if (Result.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00001999 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002000
Douglas Gregora4253922010-04-16 22:17:36 +00002001 return S.MaybeBindToTemporary(Result.takeAs<Expr>());
2002 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002003
John McCalle3027922010-08-25 11:45:40 +00002004 case CK_UserDefinedConversion: {
Douglas Gregora4253922010-04-16 22:17:36 +00002005 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002006
Douglas Gregora4253922010-04-16 22:17:36 +00002007 // Create an implicit call expr that calls it.
Douglas Gregor2bbfba02011-01-20 01:32:05 +00002008 ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Method);
Douglas Gregor668443e2011-01-20 00:18:04 +00002009 if (Result.isInvalid())
2010 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002011
Douglas Gregor668443e2011-01-20 00:18:04 +00002012 return S.MaybeBindToTemporary(Result.get());
Douglas Gregora4253922010-04-16 22:17:36 +00002013 }
2014 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002015}
Douglas Gregora4253922010-04-16 22:17:36 +00002016
Douglas Gregor5fb53972009-01-14 15:45:31 +00002017/// PerformImplicitConversion - Perform an implicit conversion of the
2018/// expression From to the type ToType using the pre-computed implicit
John Wiegley01296292011-04-08 18:41:53 +00002019/// conversion sequence ICS. Returns the converted
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00002020/// expression. Action is the kind of conversion we're performing,
Douglas Gregor5fb53972009-01-14 15:45:31 +00002021/// used in the error message.
John Wiegley01296292011-04-08 18:41:53 +00002022ExprResult
2023Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor5fb53972009-01-14 15:45:31 +00002024 const ImplicitConversionSequence &ICS,
John McCall31168b02011-06-15 23:02:42 +00002025 AssignmentAction Action,
2026 CheckedConversionKind CCK) {
John McCall0d1da222010-01-12 00:44:57 +00002027 switch (ICS.getKind()) {
John Wiegley01296292011-04-08 18:41:53 +00002028 case ImplicitConversionSequence::StandardConversion: {
2029 ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard,
John McCall31168b02011-06-15 23:02:42 +00002030 Action, CCK);
John Wiegley01296292011-04-08 18:41:53 +00002031 if (Res.isInvalid())
2032 return ExprError();
2033 From = Res.take();
Douglas Gregor39c16d42008-10-24 04:54:22 +00002034 break;
John Wiegley01296292011-04-08 18:41:53 +00002035 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00002036
Anders Carlsson110b07b2009-09-15 06:28:28 +00002037 case ImplicitConversionSequence::UserDefinedConversion: {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002038
Fariborz Jahanian2fee79a2009-08-28 22:04:50 +00002039 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
John McCall8cb679e2010-11-15 09:13:47 +00002040 CastKind CastKind;
Anders Carlsson110b07b2009-09-15 06:28:28 +00002041 QualType BeforeToType;
2042 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
John McCalle3027922010-08-25 11:45:40 +00002043 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002044
Anders Carlsson110b07b2009-09-15 06:28:28 +00002045 // If the user-defined conversion is specified by a conversion function,
2046 // the initial standard conversion sequence converts the source type to
2047 // the implicit object parameter of the conversion function.
2048 BeforeToType = Context.getTagDeclType(Conv->getParent());
John McCalla03edda2010-12-04 09:57:16 +00002049 } else {
2050 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
John McCalle3027922010-08-25 11:45:40 +00002051 CastKind = CK_ConstructorConversion;
Fariborz Jahanian55824512009-11-06 00:23:08 +00002052 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregor3153da72009-11-20 02:31:03 +00002053 if (!ICS.UserDefined.EllipsisConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002054 // If the user-defined conversion is specified by a constructor, the
Fariborz Jahanian55824512009-11-06 00:23:08 +00002055 // initial standard conversion sequence converts the source type to the
2056 // type required by the argument of the constructor
Douglas Gregor3153da72009-11-20 02:31:03 +00002057 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
2058 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002059 }
Douglas Gregor6dd3a6a2010-12-02 21:47:04 +00002060 // Watch out for elipsis conversion.
Fariborz Jahanianeec642f2009-11-06 00:55:14 +00002061 if (!ICS.UserDefined.EllipsisConversion) {
John Wiegley01296292011-04-08 18:41:53 +00002062 ExprResult Res =
2063 PerformImplicitConversion(From, BeforeToType,
2064 ICS.UserDefined.Before, AA_Converting,
John McCall31168b02011-06-15 23:02:42 +00002065 CCK);
John Wiegley01296292011-04-08 18:41:53 +00002066 if (Res.isInvalid())
2067 return ExprError();
2068 From = Res.take();
Fariborz Jahanian55824512009-11-06 00:23:08 +00002069 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002070
2071 ExprResult CastArg
Douglas Gregora4253922010-04-16 22:17:36 +00002072 = BuildCXXCastArgument(*this,
2073 From->getLocStart(),
Anders Carlssone9766d52009-09-09 21:33:21 +00002074 ToType.getNonReferenceType(),
Douglas Gregor2bbfba02011-01-20 01:32:05 +00002075 CastKind, cast<CXXMethodDecl>(FD),
2076 ICS.UserDefined.FoundConversionFunction,
John McCallb268a282010-08-23 23:25:46 +00002077 From);
Anders Carlssone9766d52009-09-09 21:33:21 +00002078
2079 if (CastArg.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00002080 return ExprError();
Eli Friedmane96f1d32009-11-27 04:41:50 +00002081
John Wiegley01296292011-04-08 18:41:53 +00002082 From = CastArg.take();
Eli Friedmane96f1d32009-11-27 04:41:50 +00002083
Eli Friedmane96f1d32009-11-27 04:41:50 +00002084 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
John McCall31168b02011-06-15 23:02:42 +00002085 AA_Converting, CCK);
Fariborz Jahanianda21efb2009-10-16 19:20:59 +00002086 }
John McCall0d1da222010-01-12 00:44:57 +00002087
2088 case ImplicitConversionSequence::AmbiguousConversion:
John McCall5c32be02010-08-24 20:38:10 +00002089 ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
John McCall0d1da222010-01-12 00:44:57 +00002090 PDiag(diag::err_typecheck_ambiguous_condition)
2091 << From->getSourceRange());
John Wiegley01296292011-04-08 18:41:53 +00002092 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002093
Douglas Gregor39c16d42008-10-24 04:54:22 +00002094 case ImplicitConversionSequence::EllipsisConversion:
2095 assert(false && "Cannot perform an ellipsis conversion");
John Wiegley01296292011-04-08 18:41:53 +00002096 return Owned(From);
Douglas Gregor39c16d42008-10-24 04:54:22 +00002097
2098 case ImplicitConversionSequence::BadConversion:
John Wiegley01296292011-04-08 18:41:53 +00002099 return ExprError();
Douglas Gregor39c16d42008-10-24 04:54:22 +00002100 }
2101
2102 // Everything went well.
John Wiegley01296292011-04-08 18:41:53 +00002103 return Owned(From);
Douglas Gregor39c16d42008-10-24 04:54:22 +00002104}
2105
2106/// PerformImplicitConversion - Perform an implicit conversion of the
2107/// expression From to the type ToType by following the standard
John Wiegley01296292011-04-08 18:41:53 +00002108/// conversion sequence SCS. Returns the converted
Douglas Gregor47d3f272008-12-19 17:40:08 +00002109/// expression. Flavor is the context in which we're performing this
2110/// conversion, for use in error messages.
John Wiegley01296292011-04-08 18:41:53 +00002111ExprResult
2112Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor47d3f272008-12-19 17:40:08 +00002113 const StandardConversionSequence& SCS,
John McCall31168b02011-06-15 23:02:42 +00002114 AssignmentAction Action,
2115 CheckedConversionKind CCK) {
2116 bool CStyle = (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast);
2117
Mike Stump87c57ac2009-05-16 07:39:55 +00002118 // Overall FIXME: we are recomputing too many types here and doing far too
2119 // much extra work. What this means is that we need to keep track of more
2120 // information that is computed when we try the implicit conversion initially,
2121 // so that we don't need to recompute anything here.
Douglas Gregor39c16d42008-10-24 04:54:22 +00002122 QualType FromType = From->getType();
John McCall31168b02011-06-15 23:02:42 +00002123
Douglas Gregor2fe98832008-11-03 19:09:14 +00002124 if (SCS.CopyConstructor) {
Anders Carlsson549c5bd2009-05-19 04:45:15 +00002125 // FIXME: When can ToType be a reference type?
2126 assert(!ToType->isReferenceType());
Fariborz Jahanian49850df2009-09-25 18:59:21 +00002127 if (SCS.Second == ICK_Derived_To_Base) {
John McCall37ad5512010-08-23 06:44:23 +00002128 ASTOwningVector<Expr*> ConstructorArgs(*this);
Fariborz Jahanian49850df2009-09-25 18:59:21 +00002129 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
John McCall37ad5512010-08-23 06:44:23 +00002130 MultiExprArg(*this, &From, 1),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002131 /*FIXME:ConstructLoc*/SourceLocation(),
Fariborz Jahanian49850df2009-09-25 18:59:21 +00002132 ConstructorArgs))
John Wiegley01296292011-04-08 18:41:53 +00002133 return ExprError();
2134 return BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
2135 ToType, SCS.CopyConstructor,
2136 move_arg(ConstructorArgs),
2137 /*ZeroInit*/ false,
2138 CXXConstructExpr::CK_Complete,
2139 SourceRange());
Fariborz Jahanian49850df2009-09-25 18:59:21 +00002140 }
John Wiegley01296292011-04-08 18:41:53 +00002141 return BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
2142 ToType, SCS.CopyConstructor,
2143 MultiExprArg(*this, &From, 1),
2144 /*ZeroInit*/ false,
2145 CXXConstructExpr::CK_Complete,
2146 SourceRange());
Douglas Gregor2fe98832008-11-03 19:09:14 +00002147 }
2148
Douglas Gregor980fb162010-04-29 18:24:40 +00002149 // Resolve overloaded function references.
2150 if (Context.hasSameType(FromType, Context.OverloadTy)) {
2151 DeclAccessPair Found;
2152 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
2153 true, Found);
2154 if (!Fn)
John Wiegley01296292011-04-08 18:41:53 +00002155 return ExprError();
Douglas Gregor980fb162010-04-29 18:24:40 +00002156
2157 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
John Wiegley01296292011-04-08 18:41:53 +00002158 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002159
Douglas Gregor980fb162010-04-29 18:24:40 +00002160 From = FixOverloadedFunctionReference(From, Found, Fn);
2161 FromType = From->getType();
2162 }
2163
Douglas Gregor39c16d42008-10-24 04:54:22 +00002164 // Perform the first implicit conversion.
2165 switch (SCS.First) {
2166 case ICK_Identity:
Douglas Gregor39c16d42008-10-24 04:54:22 +00002167 // Nothing to do.
2168 break;
2169
John McCall34376a62010-12-04 03:47:34 +00002170 case ICK_Lvalue_To_Rvalue:
2171 // Should this get its own ICK?
2172 if (From->getObjectKind() == OK_ObjCProperty) {
John Wiegley01296292011-04-08 18:41:53 +00002173 ExprResult FromRes = ConvertPropertyForRValue(From);
2174 if (FromRes.isInvalid())
2175 return ExprError();
2176 From = FromRes.take();
John McCalled75c092010-12-07 22:54:16 +00002177 if (!From->isGLValue()) break;
John McCall34376a62010-12-04 03:47:34 +00002178 }
2179
Chandler Carruth1af88f12011-02-17 21:10:52 +00002180 // Check for trivial buffer overflows.
Ted Kremenekdf26df72011-03-01 18:41:00 +00002181 CheckArrayAccess(From);
Chandler Carruth1af88f12011-02-17 21:10:52 +00002182
John McCall34376a62010-12-04 03:47:34 +00002183 FromType = FromType.getUnqualifiedType();
2184 From = ImplicitCastExpr::Create(Context, FromType, CK_LValueToRValue,
2185 From, 0, VK_RValue);
2186 break;
2187
Douglas Gregor39c16d42008-10-24 04:54:22 +00002188 case ICK_Array_To_Pointer:
Douglas Gregor171c45a2009-02-18 21:56:37 +00002189 FromType = Context.getArrayDecayedType(FromType);
John McCall31168b02011-06-15 23:02:42 +00002190 From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay,
2191 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor171c45a2009-02-18 21:56:37 +00002192 break;
2193
2194 case ICK_Function_To_Pointer:
Douglas Gregor39c16d42008-10-24 04:54:22 +00002195 FromType = Context.getPointerType(FromType);
John McCall31168b02011-06-15 23:02:42 +00002196 From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay,
2197 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor39c16d42008-10-24 04:54:22 +00002198 break;
2199
2200 default:
2201 assert(false && "Improper first standard conversion");
2202 break;
2203 }
2204
2205 // Perform the second implicit conversion
2206 switch (SCS.Second) {
2207 case ICK_Identity:
Sebastian Redl5d431642009-10-10 12:04:10 +00002208 // If both sides are functions (or pointers/references to them), there could
2209 // be incompatible exception declarations.
2210 if (CheckExceptionSpecCompatibility(From, ToType))
John Wiegley01296292011-04-08 18:41:53 +00002211 return ExprError();
Sebastian Redl5d431642009-10-10 12:04:10 +00002212 // Nothing else to do.
Douglas Gregor39c16d42008-10-24 04:54:22 +00002213 break;
2214
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00002215 case ICK_NoReturn_Adjustment:
2216 // If both sides are functions (or pointers/references to them), there could
2217 // be incompatible exception declarations.
2218 if (CheckExceptionSpecCompatibility(From, ToType))
John Wiegley01296292011-04-08 18:41:53 +00002219 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002220
John McCall31168b02011-06-15 23:02:42 +00002221 From = ImpCastExprToType(From, ToType, CK_NoOp,
2222 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00002223 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002224
Douglas Gregor39c16d42008-10-24 04:54:22 +00002225 case ICK_Integral_Promotion:
Douglas Gregor39c16d42008-10-24 04:54:22 +00002226 case ICK_Integral_Conversion:
John McCall31168b02011-06-15 23:02:42 +00002227 From = ImpCastExprToType(From, ToType, CK_IntegralCast,
2228 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman06ed2a52009-10-20 08:27:19 +00002229 break;
2230
2231 case ICK_Floating_Promotion:
Douglas Gregor39c16d42008-10-24 04:54:22 +00002232 case ICK_Floating_Conversion:
John McCall31168b02011-06-15 23:02:42 +00002233 From = ImpCastExprToType(From, ToType, CK_FloatingCast,
2234 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman06ed2a52009-10-20 08:27:19 +00002235 break;
2236
2237 case ICK_Complex_Promotion:
John McCall8cb679e2010-11-15 09:13:47 +00002238 case ICK_Complex_Conversion: {
2239 QualType FromEl = From->getType()->getAs<ComplexType>()->getElementType();
2240 QualType ToEl = ToType->getAs<ComplexType>()->getElementType();
2241 CastKind CK;
2242 if (FromEl->isRealFloatingType()) {
2243 if (ToEl->isRealFloatingType())
2244 CK = CK_FloatingComplexCast;
2245 else
2246 CK = CK_FloatingComplexToIntegralComplex;
2247 } else if (ToEl->isRealFloatingType()) {
2248 CK = CK_IntegralComplexToFloatingComplex;
2249 } else {
2250 CK = CK_IntegralComplexCast;
2251 }
John McCall31168b02011-06-15 23:02:42 +00002252 From = ImpCastExprToType(From, ToType, CK,
2253 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman06ed2a52009-10-20 08:27:19 +00002254 break;
John McCall8cb679e2010-11-15 09:13:47 +00002255 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00002256
Douglas Gregor39c16d42008-10-24 04:54:22 +00002257 case ICK_Floating_Integral:
Douglas Gregor49b4d732010-06-22 23:07:26 +00002258 if (ToType->isRealFloatingType())
John McCall31168b02011-06-15 23:02:42 +00002259 From = ImpCastExprToType(From, ToType, CK_IntegralToFloating,
2260 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman06ed2a52009-10-20 08:27:19 +00002261 else
John McCall31168b02011-06-15 23:02:42 +00002262 From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral,
2263 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman06ed2a52009-10-20 08:27:19 +00002264 break;
2265
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002266 case ICK_Compatible_Conversion:
John McCall31168b02011-06-15 23:02:42 +00002267 From = ImpCastExprToType(From, ToType, CK_NoOp,
2268 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor39c16d42008-10-24 04:54:22 +00002269 break;
2270
John McCall31168b02011-06-15 23:02:42 +00002271 case ICK_Writeback_Conversion:
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002272 case ICK_Pointer_Conversion: {
Douglas Gregor6dd3a6a2010-12-02 21:47:04 +00002273 if (SCS.IncompatibleObjC && Action != AA_Casting) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00002274 // Diagnose incompatible Objective-C conversions
Douglas Gregor2720dc62011-06-11 04:42:12 +00002275 if (Action == AA_Initializing || Action == AA_Assigning)
Fariborz Jahanian413e0642011-03-21 19:08:42 +00002276 Diag(From->getSourceRange().getBegin(),
2277 diag::ext_typecheck_convert_incompatible_pointer)
2278 << ToType << From->getType() << Action
2279 << From->getSourceRange();
2280 else
2281 Diag(From->getSourceRange().getBegin(),
2282 diag::ext_typecheck_convert_incompatible_pointer)
2283 << From->getType() << ToType << Action
2284 << From->getSourceRange();
John McCall31168b02011-06-15 23:02:42 +00002285
Douglas Gregor33823722011-06-11 01:09:30 +00002286 if (From->getType()->isObjCObjectPointerType() &&
2287 ToType->isObjCObjectPointerType())
2288 EmitRelatedResultTypeNote(From);
Douglas Gregor47d3f272008-12-19 17:40:08 +00002289 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002290
John McCall8cb679e2010-11-15 09:13:47 +00002291 CastKind Kind = CK_Invalid;
John McCallcf142162010-08-07 06:22:56 +00002292 CXXCastPath BasePath;
Douglas Gregor58281352011-01-27 00:58:17 +00002293 if (CheckPointerConversion(From, ToType, Kind, BasePath, CStyle))
John Wiegley01296292011-04-08 18:41:53 +00002294 return ExprError();
John McCall31168b02011-06-15 23:02:42 +00002295 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
2296 .take();
Douglas Gregor39c16d42008-10-24 04:54:22 +00002297 break;
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002298 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002299
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002300 case ICK_Pointer_Member: {
John McCall8cb679e2010-11-15 09:13:47 +00002301 CastKind Kind = CK_Invalid;
John McCallcf142162010-08-07 06:22:56 +00002302 CXXCastPath BasePath;
Douglas Gregor58281352011-01-27 00:58:17 +00002303 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
John Wiegley01296292011-04-08 18:41:53 +00002304 return ExprError();
Sebastian Redl5d431642009-10-10 12:04:10 +00002305 if (CheckExceptionSpecCompatibility(From, ToType))
John Wiegley01296292011-04-08 18:41:53 +00002306 return ExprError();
John McCall31168b02011-06-15 23:02:42 +00002307 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
2308 .take();
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002309 break;
2310 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002311
Abramo Bagnara7ccce982011-04-07 09:26:19 +00002312 case ICK_Boolean_Conversion:
John Wiegley01296292011-04-08 18:41:53 +00002313 From = ImpCastExprToType(From, Context.BoolTy,
John McCall31168b02011-06-15 23:02:42 +00002314 ScalarTypeToBooleanCastKind(FromType),
2315 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor39c16d42008-10-24 04:54:22 +00002316 break;
2317
Douglas Gregor88d292c2010-05-13 16:44:06 +00002318 case ICK_Derived_To_Base: {
John McCallcf142162010-08-07 06:22:56 +00002319 CXXCastPath BasePath;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002320 if (CheckDerivedToBaseConversion(From->getType(),
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00002321 ToType.getNonReferenceType(),
2322 From->getLocStart(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002323 From->getSourceRange(),
Douglas Gregor88d292c2010-05-13 16:44:06 +00002324 &BasePath,
Douglas Gregor58281352011-01-27 00:58:17 +00002325 CStyle))
John Wiegley01296292011-04-08 18:41:53 +00002326 return ExprError();
Douglas Gregor88d292c2010-05-13 16:44:06 +00002327
John Wiegley01296292011-04-08 18:41:53 +00002328 From = ImpCastExprToType(From, ToType.getNonReferenceType(),
John McCalle3027922010-08-25 11:45:40 +00002329 CK_DerivedToBase, CastCategory(From),
John McCall31168b02011-06-15 23:02:42 +00002330 &BasePath, CCK).take();
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00002331 break;
Douglas Gregor88d292c2010-05-13 16:44:06 +00002332 }
2333
Douglas Gregor46188682010-05-18 22:42:18 +00002334 case ICK_Vector_Conversion:
John McCall31168b02011-06-15 23:02:42 +00002335 From = ImpCastExprToType(From, ToType, CK_BitCast,
2336 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor46188682010-05-18 22:42:18 +00002337 break;
2338
2339 case ICK_Vector_Splat:
John McCall31168b02011-06-15 23:02:42 +00002340 From = ImpCastExprToType(From, ToType, CK_VectorSplat,
2341 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor46188682010-05-18 22:42:18 +00002342 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002343
Douglas Gregor46188682010-05-18 22:42:18 +00002344 case ICK_Complex_Real:
John McCall8cb679e2010-11-15 09:13:47 +00002345 // Case 1. x -> _Complex y
2346 if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
2347 QualType ElType = ToComplex->getElementType();
2348 bool isFloatingComplex = ElType->isRealFloatingType();
2349
2350 // x -> y
2351 if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
2352 // do nothing
2353 } else if (From->getType()->isRealFloatingType()) {
John Wiegley01296292011-04-08 18:41:53 +00002354 From = ImpCastExprToType(From, ElType,
2355 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).take();
John McCall8cb679e2010-11-15 09:13:47 +00002356 } else {
2357 assert(From->getType()->isIntegerType());
John Wiegley01296292011-04-08 18:41:53 +00002358 From = ImpCastExprToType(From, ElType,
2359 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).take();
John McCall8cb679e2010-11-15 09:13:47 +00002360 }
2361 // y -> _Complex y
John Wiegley01296292011-04-08 18:41:53 +00002362 From = ImpCastExprToType(From, ToType,
John McCall8cb679e2010-11-15 09:13:47 +00002363 isFloatingComplex ? CK_FloatingRealToComplex
John Wiegley01296292011-04-08 18:41:53 +00002364 : CK_IntegralRealToComplex).take();
John McCall8cb679e2010-11-15 09:13:47 +00002365
2366 // Case 2. _Complex x -> y
2367 } else {
2368 const ComplexType *FromComplex = From->getType()->getAs<ComplexType>();
2369 assert(FromComplex);
2370
2371 QualType ElType = FromComplex->getElementType();
2372 bool isFloatingComplex = ElType->isRealFloatingType();
2373
2374 // _Complex x -> x
John Wiegley01296292011-04-08 18:41:53 +00002375 From = ImpCastExprToType(From, ElType,
John McCall8cb679e2010-11-15 09:13:47 +00002376 isFloatingComplex ? CK_FloatingComplexToReal
John McCall31168b02011-06-15 23:02:42 +00002377 : CK_IntegralComplexToReal,
2378 VK_RValue, /*BasePath=*/0, CCK).take();
John McCall8cb679e2010-11-15 09:13:47 +00002379
2380 // x -> y
2381 if (Context.hasSameUnqualifiedType(ElType, ToType)) {
2382 // do nothing
2383 } else if (ToType->isRealFloatingType()) {
John Wiegley01296292011-04-08 18:41:53 +00002384 From = ImpCastExprToType(From, ToType,
John McCall31168b02011-06-15 23:02:42 +00002385 isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating,
2386 VK_RValue, /*BasePath=*/0, CCK).take();
John McCall8cb679e2010-11-15 09:13:47 +00002387 } else {
2388 assert(ToType->isIntegerType());
John Wiegley01296292011-04-08 18:41:53 +00002389 From = ImpCastExprToType(From, ToType,
John McCall31168b02011-06-15 23:02:42 +00002390 isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast,
2391 VK_RValue, /*BasePath=*/0, CCK).take();
John McCall8cb679e2010-11-15 09:13:47 +00002392 }
2393 }
Douglas Gregor46188682010-05-18 22:42:18 +00002394 break;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002395
2396 case ICK_Block_Pointer_Conversion: {
John McCall31168b02011-06-15 23:02:42 +00002397 From = ImpCastExprToType(From, ToType.getUnqualifiedType(), CK_BitCast,
2398 VK_RValue, /*BasePath=*/0, CCK).take();
2399 break;
2400 }
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002401
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00002402 case ICK_TransparentUnionConversion: {
John Wiegley01296292011-04-08 18:41:53 +00002403 ExprResult FromRes = Owned(From);
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00002404 Sema::AssignConvertType ConvTy =
John Wiegley01296292011-04-08 18:41:53 +00002405 CheckTransparentUnionArgumentConstraints(ToType, FromRes);
2406 if (FromRes.isInvalid())
2407 return ExprError();
2408 From = FromRes.take();
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00002409 assert ((ConvTy == Sema::Compatible) &&
2410 "Improper transparent union conversion");
2411 (void)ConvTy;
2412 break;
2413 }
2414
Douglas Gregor46188682010-05-18 22:42:18 +00002415 case ICK_Lvalue_To_Rvalue:
2416 case ICK_Array_To_Pointer:
2417 case ICK_Function_To_Pointer:
2418 case ICK_Qualification:
2419 case ICK_Num_Conversion_Kinds:
Douglas Gregor39c16d42008-10-24 04:54:22 +00002420 assert(false && "Improper second standard conversion");
2421 break;
2422 }
2423
2424 switch (SCS.Third) {
2425 case ICK_Identity:
2426 // Nothing to do.
2427 break;
2428
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002429 case ICK_Qualification: {
2430 // The qualification keeps the category of the inner expression, unless the
2431 // target type isn't a reference.
John McCall2536c6d2010-08-25 10:28:54 +00002432 ExprValueKind VK = ToType->isReferenceType() ?
2433 CastCategory(From) : VK_RValue;
John Wiegley01296292011-04-08 18:41:53 +00002434 From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context),
John McCall31168b02011-06-15 23:02:42 +00002435 CK_NoOp, VK, /*BasePath=*/0, CCK).take();
Douglas Gregore489a7d2010-02-28 18:30:25 +00002436
Douglas Gregore981bb02011-03-14 16:13:32 +00002437 if (SCS.DeprecatedStringLiteralToCharPtr &&
2438 !getLangOptions().WritableStrings)
Douglas Gregore489a7d2010-02-28 18:30:25 +00002439 Diag(From->getLocStart(), diag::warn_deprecated_string_literal_conversion)
2440 << ToType.getNonReferenceType();
2441
Douglas Gregor39c16d42008-10-24 04:54:22 +00002442 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002443 }
2444
Douglas Gregor39c16d42008-10-24 04:54:22 +00002445 default:
Douglas Gregor46188682010-05-18 22:42:18 +00002446 assert(false && "Improper third standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00002447 break;
2448 }
2449
John Wiegley01296292011-04-08 18:41:53 +00002450 return Owned(From);
Douglas Gregor39c16d42008-10-24 04:54:22 +00002451}
2452
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002453ExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait UTT,
Douglas Gregor54e5b132010-09-09 16:14:44 +00002454 SourceLocation KWLoc,
2455 ParsedType Ty,
2456 SourceLocation RParen) {
2457 TypeSourceInfo *TSInfo;
2458 QualType T = GetTypeFromParser(Ty, &TSInfo);
Mike Stump11289f42009-09-09 15:08:12 +00002459
Douglas Gregor54e5b132010-09-09 16:14:44 +00002460 if (!TSInfo)
2461 TSInfo = Context.getTrivialTypeSourceInfo(T);
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002462 return BuildUnaryTypeTrait(UTT, KWLoc, TSInfo, RParen);
Douglas Gregor54e5b132010-09-09 16:14:44 +00002463}
2464
Chandler Carruth8e172c62011-05-01 06:51:22 +00002465/// \brief Check the completeness of a type in a unary type trait.
2466///
2467/// If the particular type trait requires a complete type, tries to complete
2468/// it. If completing the type fails, a diagnostic is emitted and false
2469/// returned. If completing the type succeeds or no completion was required,
2470/// returns true.
2471static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S,
2472 UnaryTypeTrait UTT,
2473 SourceLocation Loc,
2474 QualType ArgTy) {
2475 // C++0x [meta.unary.prop]p3:
2476 // For all of the class templates X declared in this Clause, instantiating
2477 // that template with a template argument that is a class template
2478 // specialization may result in the implicit instantiation of the template
2479 // argument if and only if the semantics of X require that the argument
2480 // must be a complete type.
2481 // We apply this rule to all the type trait expressions used to implement
2482 // these class templates. We also try to follow any GCC documented behavior
2483 // in these expressions to ensure portability of standard libraries.
2484 switch (UTT) {
Chandler Carruth8e172c62011-05-01 06:51:22 +00002485 // is_complete_type somewhat obviously cannot require a complete type.
2486 case UTT_IsCompleteType:
Chandler Carrutha62d8a52011-05-01 19:18:02 +00002487 // Fall-through
Chandler Carruth8e172c62011-05-01 06:51:22 +00002488
2489 // These traits are modeled on the type predicates in C++0x
2490 // [meta.unary.cat] and [meta.unary.comp]. They are not specified as
2491 // requiring a complete type, as whether or not they return true cannot be
2492 // impacted by the completeness of the type.
2493 case UTT_IsVoid:
2494 case UTT_IsIntegral:
2495 case UTT_IsFloatingPoint:
2496 case UTT_IsArray:
2497 case UTT_IsPointer:
2498 case UTT_IsLvalueReference:
2499 case UTT_IsRvalueReference:
2500 case UTT_IsMemberFunctionPointer:
2501 case UTT_IsMemberObjectPointer:
2502 case UTT_IsEnum:
2503 case UTT_IsUnion:
2504 case UTT_IsClass:
2505 case UTT_IsFunction:
2506 case UTT_IsReference:
2507 case UTT_IsArithmetic:
2508 case UTT_IsFundamental:
2509 case UTT_IsObject:
2510 case UTT_IsScalar:
2511 case UTT_IsCompound:
2512 case UTT_IsMemberPointer:
Chandler Carrutha62d8a52011-05-01 19:18:02 +00002513 // Fall-through
Chandler Carruth8e172c62011-05-01 06:51:22 +00002514
2515 // These traits are modeled on type predicates in C++0x [meta.unary.prop]
2516 // which requires some of its traits to have the complete type. However,
2517 // the completeness of the type cannot impact these traits' semantics, and
2518 // so they don't require it. This matches the comments on these traits in
2519 // Table 49.
2520 case UTT_IsConst:
2521 case UTT_IsVolatile:
2522 case UTT_IsSigned:
2523 case UTT_IsUnsigned:
2524 return true;
2525
2526 // C++0x [meta.unary.prop] Table 49 requires the following traits to be
Chandler Carrutha62d8a52011-05-01 19:18:02 +00002527 // applied to a complete type.
Chandler Carruth8e172c62011-05-01 06:51:22 +00002528 case UTT_IsTrivial:
Alexis Huntd9a5cc12011-05-13 00:31:07 +00002529 case UTT_IsTriviallyCopyable:
Chandler Carruth8e172c62011-05-01 06:51:22 +00002530 case UTT_IsStandardLayout:
2531 case UTT_IsPOD:
2532 case UTT_IsLiteral:
2533 case UTT_IsEmpty:
2534 case UTT_IsPolymorphic:
2535 case UTT_IsAbstract:
Chandler Carrutha62d8a52011-05-01 19:18:02 +00002536 // Fall-through
Chandler Carruth8e172c62011-05-01 06:51:22 +00002537
Chandler Carrutha62d8a52011-05-01 19:18:02 +00002538 // These trait expressions are designed to help implement predicates in
Chandler Carruth8e172c62011-05-01 06:51:22 +00002539 // [meta.unary.prop] despite not being named the same. They are specified
2540 // by both GCC and the Embarcadero C++ compiler, and require the complete
2541 // type due to the overarching C++0x type predicates being implemented
2542 // requiring the complete type.
2543 case UTT_HasNothrowAssign:
2544 case UTT_HasNothrowConstructor:
2545 case UTT_HasNothrowCopy:
2546 case UTT_HasTrivialAssign:
Alexis Huntf479f1b2011-05-09 18:22:59 +00002547 case UTT_HasTrivialDefaultConstructor:
Chandler Carruth8e172c62011-05-01 06:51:22 +00002548 case UTT_HasTrivialCopy:
2549 case UTT_HasTrivialDestructor:
2550 case UTT_HasVirtualDestructor:
2551 // Arrays of unknown bound are expressly allowed.
2552 QualType ElTy = ArgTy;
2553 if (ArgTy->isIncompleteArrayType())
2554 ElTy = S.Context.getAsArrayType(ArgTy)->getElementType();
2555
2556 // The void type is expressly allowed.
2557 if (ElTy->isVoidType())
2558 return true;
2559
2560 return !S.RequireCompleteType(
2561 Loc, ElTy, diag::err_incomplete_type_used_in_type_trait_expr);
John Wiegleyd3522222011-04-28 02:06:46 +00002562 }
Chandler Carruth8b0cf1d2011-05-01 07:23:17 +00002563 llvm_unreachable("Type trait not handled by switch");
Chandler Carruth8e172c62011-05-01 06:51:22 +00002564}
2565
2566static bool EvaluateUnaryTypeTrait(Sema &Self, UnaryTypeTrait UTT,
2567 SourceLocation KeyLoc, QualType T) {
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00002568 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
John Wiegleyd3522222011-04-28 02:06:46 +00002569
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002570 ASTContext &C = Self.Context;
2571 switch(UTT) {
Chandler Carruthd2479ea2011-05-01 06:11:07 +00002572 // Type trait expressions corresponding to the primary type category
2573 // predicates in C++0x [meta.unary.cat].
2574 case UTT_IsVoid:
2575 return T->isVoidType();
2576 case UTT_IsIntegral:
2577 return T->isIntegralType(C);
2578 case UTT_IsFloatingPoint:
2579 return T->isFloatingType();
2580 case UTT_IsArray:
2581 return T->isArrayType();
2582 case UTT_IsPointer:
2583 return T->isPointerType();
2584 case UTT_IsLvalueReference:
2585 return T->isLValueReferenceType();
2586 case UTT_IsRvalueReference:
2587 return T->isRValueReferenceType();
2588 case UTT_IsMemberFunctionPointer:
2589 return T->isMemberFunctionPointerType();
2590 case UTT_IsMemberObjectPointer:
2591 return T->isMemberDataPointerType();
2592 case UTT_IsEnum:
2593 return T->isEnumeralType();
Chandler Carruth100f3a92011-05-01 06:11:03 +00002594 case UTT_IsUnion:
Chandler Carruthaf858862011-05-01 09:29:58 +00002595 return T->isUnionType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00002596 case UTT_IsClass:
Chandler Carruthaf858862011-05-01 09:29:58 +00002597 return T->isClassType() || T->isStructureType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00002598 case UTT_IsFunction:
2599 return T->isFunctionType();
2600
2601 // Type trait expressions which correspond to the convenient composition
2602 // predicates in C++0x [meta.unary.comp].
2603 case UTT_IsReference:
2604 return T->isReferenceType();
2605 case UTT_IsArithmetic:
Chandler Carruthaf858862011-05-01 09:29:58 +00002606 return T->isArithmeticType() && !T->isEnumeralType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00002607 case UTT_IsFundamental:
Chandler Carruthaf858862011-05-01 09:29:58 +00002608 return T->isFundamentalType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00002609 case UTT_IsObject:
Chandler Carruthaf858862011-05-01 09:29:58 +00002610 return T->isObjectType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00002611 case UTT_IsScalar:
John McCall31168b02011-06-15 23:02:42 +00002612 // Note: semantic analysis depends on Objective-C lifetime types to be
2613 // considered scalar types. However, such types do not actually behave
2614 // like scalar types at run time (since they may require retain/release
2615 // operations), so we report them as non-scalar.
2616 if (T->isObjCLifetimeType()) {
2617 switch (T.getObjCLifetime()) {
2618 case Qualifiers::OCL_None:
2619 case Qualifiers::OCL_ExplicitNone:
2620 return true;
2621
2622 case Qualifiers::OCL_Strong:
2623 case Qualifiers::OCL_Weak:
2624 case Qualifiers::OCL_Autoreleasing:
2625 return false;
2626 }
2627 }
2628
Chandler Carruth7ba7bd32011-05-01 09:29:55 +00002629 return T->isScalarType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00002630 case UTT_IsCompound:
Chandler Carruthaf858862011-05-01 09:29:58 +00002631 return T->isCompoundType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00002632 case UTT_IsMemberPointer:
2633 return T->isMemberPointerType();
2634
2635 // Type trait expressions which correspond to the type property predicates
2636 // in C++0x [meta.unary.prop].
2637 case UTT_IsConst:
2638 return T.isConstQualified();
2639 case UTT_IsVolatile:
2640 return T.isVolatileQualified();
2641 case UTT_IsTrivial:
John McCall31168b02011-06-15 23:02:42 +00002642 return T.isTrivialType(Self.Context);
Alexis Huntd9a5cc12011-05-13 00:31:07 +00002643 case UTT_IsTriviallyCopyable:
John McCall31168b02011-06-15 23:02:42 +00002644 return T.isTriviallyCopyableType(Self.Context);
Chandler Carruthd2479ea2011-05-01 06:11:07 +00002645 case UTT_IsStandardLayout:
2646 return T->isStandardLayoutType();
2647 case UTT_IsPOD:
John McCall31168b02011-06-15 23:02:42 +00002648 return T.isPODType(Self.Context);
Chandler Carruthd2479ea2011-05-01 06:11:07 +00002649 case UTT_IsLiteral:
2650 return T->isLiteralType();
2651 case UTT_IsEmpty:
2652 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2653 return !RD->isUnion() && RD->isEmpty();
2654 return false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002655 case UTT_IsPolymorphic:
Chandler Carruth100f3a92011-05-01 06:11:03 +00002656 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2657 return RD->isPolymorphic();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002658 return false;
2659 case UTT_IsAbstract:
Chandler Carruth100f3a92011-05-01 06:11:03 +00002660 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2661 return RD->isAbstract();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002662 return false;
John Wiegley65497cc2011-04-27 23:09:49 +00002663 case UTT_IsSigned:
2664 return T->isSignedIntegerType();
John Wiegley65497cc2011-04-27 23:09:49 +00002665 case UTT_IsUnsigned:
2666 return T->isUnsignedIntegerType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00002667
2668 // Type trait expressions which query classes regarding their construction,
2669 // destruction, and copying. Rather than being based directly on the
2670 // related type predicates in the standard, they are specified by both
2671 // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those
2672 // specifications.
2673 //
2674 // 1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html
2675 // 2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
Alexis Huntf479f1b2011-05-09 18:22:59 +00002676 case UTT_HasTrivialDefaultConstructor:
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002677 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2678 // If __is_pod (type) is true then the trait is true, else if type is
2679 // a cv class or union type (or array thereof) with a trivial default
2680 // constructor ([class.ctor]) then the trait is true, else it is false.
John McCall31168b02011-06-15 23:02:42 +00002681 if (T.isPODType(Self.Context))
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002682 return true;
2683 if (const RecordType *RT =
2684 C.getBaseElementType(T)->getAs<RecordType>())
Alexis Huntf479f1b2011-05-09 18:22:59 +00002685 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialDefaultConstructor();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002686 return false;
2687 case UTT_HasTrivialCopy:
2688 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2689 // If __is_pod (type) is true or type is a reference type then
2690 // the trait is true, else if type is a cv class or union type
2691 // with a trivial copy constructor ([class.copy]) then the trait
2692 // is true, else it is false.
John McCall31168b02011-06-15 23:02:42 +00002693 if (T.isPODType(Self.Context) || T->isReferenceType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002694 return true;
2695 if (const RecordType *RT = T->getAs<RecordType>())
2696 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialCopyConstructor();
2697 return false;
2698 case UTT_HasTrivialAssign:
2699 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2700 // If type is const qualified or is a reference type then the
2701 // trait is false. Otherwise if __is_pod (type) is true then the
2702 // trait is true, else if type is a cv class or union type with
2703 // a trivial copy assignment ([class.copy]) then the trait is
2704 // true, else it is false.
2705 // Note: the const and reference restrictions are interesting,
2706 // given that const and reference members don't prevent a class
2707 // from having a trivial copy assignment operator (but do cause
2708 // errors if the copy assignment operator is actually used, q.v.
2709 // [class.copy]p12).
2710
2711 if (C.getBaseElementType(T).isConstQualified())
2712 return false;
John McCall31168b02011-06-15 23:02:42 +00002713 if (T.isPODType(Self.Context))
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002714 return true;
2715 if (const RecordType *RT = T->getAs<RecordType>())
2716 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialCopyAssignment();
2717 return false;
2718 case UTT_HasTrivialDestructor:
2719 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2720 // If __is_pod (type) is true or type is a reference type
2721 // then the trait is true, else if type is a cv class or union
2722 // type (or array thereof) with a trivial destructor
2723 // ([class.dtor]) then the trait is true, else it is
2724 // false.
John McCall31168b02011-06-15 23:02:42 +00002725 if (T.isPODType(Self.Context) || T->isReferenceType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002726 return true;
John McCall31168b02011-06-15 23:02:42 +00002727
2728 // Objective-C++ ARC: autorelease types don't require destruction.
2729 if (T->isObjCLifetimeType() &&
2730 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
2731 return true;
2732
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002733 if (const RecordType *RT =
2734 C.getBaseElementType(T)->getAs<RecordType>())
2735 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialDestructor();
2736 return false;
2737 // TODO: Propagate nothrowness for implicitly declared special members.
2738 case UTT_HasNothrowAssign:
2739 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2740 // If type is const qualified or is a reference type then the
2741 // trait is false. Otherwise if __has_trivial_assign (type)
2742 // is true then the trait is true, else if type is a cv class
2743 // or union type with copy assignment operators that are known
2744 // not to throw an exception then the trait is true, else it is
2745 // false.
2746 if (C.getBaseElementType(T).isConstQualified())
2747 return false;
2748 if (T->isReferenceType())
2749 return false;
John McCall31168b02011-06-15 23:02:42 +00002750 if (T.isPODType(Self.Context) || T->isObjCLifetimeType())
2751 return true;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002752 if (const RecordType *RT = T->getAs<RecordType>()) {
2753 CXXRecordDecl* RD = cast<CXXRecordDecl>(RT->getDecl());
2754 if (RD->hasTrivialCopyAssignment())
2755 return true;
2756
2757 bool FoundAssign = false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002758 DeclarationName Name = C.DeclarationNames.getCXXOperatorName(OO_Equal);
Sebastian Redl058fc822010-09-14 23:40:14 +00002759 LookupResult Res(Self, DeclarationNameInfo(Name, KeyLoc),
2760 Sema::LookupOrdinaryName);
2761 if (Self.LookupQualifiedName(Res, RD)) {
2762 for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
2763 Op != OpEnd; ++Op) {
2764 CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
2765 if (Operator->isCopyAssignmentOperator()) {
2766 FoundAssign = true;
2767 const FunctionProtoType *CPT
2768 = Operator->getType()->getAs<FunctionProtoType>();
Richard Smith938f40b2011-06-11 17:19:42 +00002769 if (CPT->getExceptionSpecType() == EST_Delayed)
2770 return false;
2771 if (!CPT->isNothrow(Self.Context))
2772 return false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002773 }
2774 }
2775 }
2776
Richard Smith938f40b2011-06-11 17:19:42 +00002777 return FoundAssign;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002778 }
2779 return false;
2780 case UTT_HasNothrowCopy:
2781 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2782 // If __has_trivial_copy (type) is true then the trait is true, else
2783 // if type is a cv class or union type with copy constructors that are
2784 // known not to throw an exception then the trait is true, else it is
2785 // false.
John McCall31168b02011-06-15 23:02:42 +00002786 if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002787 return true;
2788 if (const RecordType *RT = T->getAs<RecordType>()) {
2789 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2790 if (RD->hasTrivialCopyConstructor())
2791 return true;
2792
2793 bool FoundConstructor = false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002794 unsigned FoundTQs;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002795 DeclContext::lookup_const_iterator Con, ConEnd;
Sebastian Redl951006f2010-09-13 21:10:20 +00002796 for (llvm::tie(Con, ConEnd) = Self.LookupConstructors(RD);
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002797 Con != ConEnd; ++Con) {
Sebastian Redl5c649bc2010-09-13 22:18:28 +00002798 // A template constructor is never a copy constructor.
2799 // FIXME: However, it may actually be selected at the actual overload
2800 // resolution point.
2801 if (isa<FunctionTemplateDecl>(*Con))
2802 continue;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002803 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
2804 if (Constructor->isCopyConstructor(FoundTQs)) {
2805 FoundConstructor = true;
2806 const FunctionProtoType *CPT
2807 = Constructor->getType()->getAs<FunctionProtoType>();
Richard Smith938f40b2011-06-11 17:19:42 +00002808 if (CPT->getExceptionSpecType() == EST_Delayed)
2809 return false;
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002810 // FIXME: check whether evaluating default arguments can throw.
Sebastian Redlc15c3262010-09-13 22:02:47 +00002811 // For now, we'll be conservative and assume that they can throw.
Richard Smith938f40b2011-06-11 17:19:42 +00002812 if (!CPT->isNothrow(Self.Context) || CPT->getNumArgs() > 1)
2813 return false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002814 }
2815 }
2816
Richard Smith938f40b2011-06-11 17:19:42 +00002817 return FoundConstructor;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002818 }
2819 return false;
2820 case UTT_HasNothrowConstructor:
2821 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2822 // If __has_trivial_constructor (type) is true then the trait is
2823 // true, else if type is a cv class or union type (or array
2824 // thereof) with a default constructor that is known not to
2825 // throw an exception then the trait is true, else it is false.
John McCall31168b02011-06-15 23:02:42 +00002826 if (T.isPODType(C) || T->isObjCLifetimeType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002827 return true;
2828 if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>()) {
2829 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Alexis Huntf479f1b2011-05-09 18:22:59 +00002830 if (RD->hasTrivialDefaultConstructor())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002831 return true;
2832
Sebastian Redlc15c3262010-09-13 22:02:47 +00002833 DeclContext::lookup_const_iterator Con, ConEnd;
2834 for (llvm::tie(Con, ConEnd) = Self.LookupConstructors(RD);
2835 Con != ConEnd; ++Con) {
Sebastian Redl5c649bc2010-09-13 22:18:28 +00002836 // FIXME: In C++0x, a constructor template can be a default constructor.
2837 if (isa<FunctionTemplateDecl>(*Con))
2838 continue;
Sebastian Redlc15c3262010-09-13 22:02:47 +00002839 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
2840 if (Constructor->isDefaultConstructor()) {
2841 const FunctionProtoType *CPT
2842 = Constructor->getType()->getAs<FunctionProtoType>();
Richard Smith938f40b2011-06-11 17:19:42 +00002843 if (CPT->getExceptionSpecType() == EST_Delayed)
2844 return false;
Sebastian Redlc15c3262010-09-13 22:02:47 +00002845 // TODO: check whether evaluating default arguments can throw.
2846 // For now, we'll be conservative and assume that they can throw.
Sebastian Redl31ad7542011-03-13 17:09:40 +00002847 return CPT->isNothrow(Self.Context) && CPT->getNumArgs() == 0;
Sebastian Redlc15c3262010-09-13 22:02:47 +00002848 }
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002849 }
2850 }
2851 return false;
2852 case UTT_HasVirtualDestructor:
2853 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2854 // If type is a class type with a virtual destructor ([class.dtor])
2855 // then the trait is true, else it is false.
2856 if (const RecordType *Record = T->getAs<RecordType>()) {
2857 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
Sebastian Redl058fc822010-09-14 23:40:14 +00002858 if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002859 return Destructor->isVirtual();
2860 }
2861 return false;
Chandler Carruthd2479ea2011-05-01 06:11:07 +00002862
2863 // These type trait expressions are modeled on the specifications for the
2864 // Embarcadero C++0x type trait functions:
2865 // http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
2866 case UTT_IsCompleteType:
2867 // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_):
2868 // Returns True if and only if T is a complete type at the point of the
2869 // function call.
2870 return !T->isIncompleteType();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002871 }
Chandler Carruthb42fb192011-05-01 07:44:17 +00002872 llvm_unreachable("Type trait not covered by switch");
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002873}
2874
2875ExprResult Sema::BuildUnaryTypeTrait(UnaryTypeTrait UTT,
Douglas Gregor54e5b132010-09-09 16:14:44 +00002876 SourceLocation KWLoc,
2877 TypeSourceInfo *TSInfo,
2878 SourceLocation RParen) {
2879 QualType T = TSInfo->getType();
Chandler Carruthb0776202011-04-30 10:07:32 +00002880 if (!CheckUnaryTypeTraitTypeCompleteness(*this, UTT, KWLoc, T))
2881 return ExprError();
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002882
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002883 bool Value = false;
2884 if (!T->isDependentType())
Chandler Carruth8e172c62011-05-01 06:51:22 +00002885 Value = EvaluateUnaryTypeTrait(*this, UTT, KWLoc, T);
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002886
2887 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, UTT, TSInfo, Value,
Anders Carlsson1f9648d2009-07-07 19:06:02 +00002888 RParen, Context.BoolTy));
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002889}
Sebastian Redl5822f082009-02-07 20:10:22 +00002890
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00002891ExprResult Sema::ActOnBinaryTypeTrait(BinaryTypeTrait BTT,
2892 SourceLocation KWLoc,
2893 ParsedType LhsTy,
2894 ParsedType RhsTy,
2895 SourceLocation RParen) {
2896 TypeSourceInfo *LhsTSInfo;
2897 QualType LhsT = GetTypeFromParser(LhsTy, &LhsTSInfo);
2898 if (!LhsTSInfo)
2899 LhsTSInfo = Context.getTrivialTypeSourceInfo(LhsT);
2900
2901 TypeSourceInfo *RhsTSInfo;
2902 QualType RhsT = GetTypeFromParser(RhsTy, &RhsTSInfo);
2903 if (!RhsTSInfo)
2904 RhsTSInfo = Context.getTrivialTypeSourceInfo(RhsT);
2905
2906 return BuildBinaryTypeTrait(BTT, KWLoc, LhsTSInfo, RhsTSInfo, RParen);
2907}
2908
2909static bool EvaluateBinaryTypeTrait(Sema &Self, BinaryTypeTrait BTT,
2910 QualType LhsT, QualType RhsT,
2911 SourceLocation KeyLoc) {
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00002912 assert(!LhsT->isDependentType() && !RhsT->isDependentType() &&
2913 "Cannot evaluate traits of dependent types");
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00002914
2915 switch(BTT) {
John McCall388ef532011-01-28 22:02:36 +00002916 case BTT_IsBaseOf: {
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00002917 // C++0x [meta.rel]p2
John McCall388ef532011-01-28 22:02:36 +00002918 // Base is a base class of Derived without regard to cv-qualifiers or
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00002919 // Base and Derived are not unions and name the same class type without
2920 // regard to cv-qualifiers.
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00002921
John McCall388ef532011-01-28 22:02:36 +00002922 const RecordType *lhsRecord = LhsT->getAs<RecordType>();
2923 if (!lhsRecord) return false;
2924
2925 const RecordType *rhsRecord = RhsT->getAs<RecordType>();
2926 if (!rhsRecord) return false;
2927
2928 assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)
2929 == (lhsRecord == rhsRecord));
2930
2931 if (lhsRecord == rhsRecord)
2932 return !lhsRecord->getDecl()->isUnion();
2933
2934 // C++0x [meta.rel]p2:
2935 // If Base and Derived are class types and are different types
2936 // (ignoring possible cv-qualifiers) then Derived shall be a
2937 // complete type.
2938 if (Self.RequireCompleteType(KeyLoc, RhsT,
2939 diag::err_incomplete_type_used_in_type_trait_expr))
2940 return false;
2941
2942 return cast<CXXRecordDecl>(rhsRecord->getDecl())
2943 ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
2944 }
John Wiegley65497cc2011-04-27 23:09:49 +00002945 case BTT_IsSame:
2946 return Self.Context.hasSameType(LhsT, RhsT);
Francois Pichet34b21132010-12-08 22:35:30 +00002947 case BTT_TypeCompatible:
2948 return Self.Context.typesAreCompatible(LhsT.getUnqualifiedType(),
2949 RhsT.getUnqualifiedType());
John Wiegley65497cc2011-04-27 23:09:49 +00002950 case BTT_IsConvertible:
Douglas Gregor8006e762011-01-27 20:28:01 +00002951 case BTT_IsConvertibleTo: {
2952 // C++0x [meta.rel]p4:
2953 // Given the following function prototype:
2954 //
2955 // template <class T>
2956 // typename add_rvalue_reference<T>::type create();
2957 //
2958 // the predicate condition for a template specialization
2959 // is_convertible<From, To> shall be satisfied if and only if
2960 // the return expression in the following code would be
2961 // well-formed, including any implicit conversions to the return
2962 // type of the function:
2963 //
2964 // To test() {
2965 // return create<From>();
2966 // }
2967 //
2968 // Access checking is performed as if in a context unrelated to To and
2969 // From. Only the validity of the immediate context of the expression
2970 // of the return-statement (including conversions to the return type)
2971 // is considered.
2972 //
2973 // We model the initialization as a copy-initialization of a temporary
2974 // of the appropriate type, which for this expression is identical to the
2975 // return statement (since NRVO doesn't apply).
2976 if (LhsT->isObjectType() || LhsT->isFunctionType())
2977 LhsT = Self.Context.getRValueReferenceType(LhsT);
2978
2979 InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT));
Douglas Gregorc03a1082011-01-28 02:26:04 +00002980 OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
Douglas Gregor8006e762011-01-27 20:28:01 +00002981 Expr::getValueKindForType(LhsT));
2982 Expr *FromPtr = &From;
2983 InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc,
2984 SourceLocation()));
2985
Douglas Gregoredb76852011-01-27 22:31:44 +00002986 // Perform the initialization within a SFINAE trap at translation unit
2987 // scope.
2988 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
2989 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
Douglas Gregor8006e762011-01-27 20:28:01 +00002990 InitializationSequence Init(Self, To, Kind, &FromPtr, 1);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00002991 if (Init.Failed())
Douglas Gregor8006e762011-01-27 20:28:01 +00002992 return false;
Douglas Gregoredb76852011-01-27 22:31:44 +00002993
Douglas Gregor8006e762011-01-27 20:28:01 +00002994 ExprResult Result = Init.Perform(Self, To, Kind, MultiExprArg(&FromPtr, 1));
2995 return !Result.isInvalid() && !SFINAE.hasErrorOccurred();
2996 }
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00002997 }
2998 llvm_unreachable("Unknown type trait or not implemented");
2999}
3000
3001ExprResult Sema::BuildBinaryTypeTrait(BinaryTypeTrait BTT,
3002 SourceLocation KWLoc,
3003 TypeSourceInfo *LhsTSInfo,
3004 TypeSourceInfo *RhsTSInfo,
3005 SourceLocation RParen) {
3006 QualType LhsT = LhsTSInfo->getType();
3007 QualType RhsT = RhsTSInfo->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003008
John McCall388ef532011-01-28 22:02:36 +00003009 if (BTT == BTT_TypeCompatible) {
Francois Pichet34b21132010-12-08 22:35:30 +00003010 if (getLangOptions().CPlusPlus) {
3011 Diag(KWLoc, diag::err_types_compatible_p_in_cplusplus)
3012 << SourceRange(KWLoc, RParen);
3013 return ExprError();
3014 }
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00003015 }
3016
3017 bool Value = false;
3018 if (!LhsT->isDependentType() && !RhsT->isDependentType())
3019 Value = EvaluateBinaryTypeTrait(*this, BTT, LhsT, RhsT, KWLoc);
3020
Francois Pichet34b21132010-12-08 22:35:30 +00003021 // Select trait result type.
3022 QualType ResultType;
3023 switch (BTT) {
Francois Pichet34b21132010-12-08 22:35:30 +00003024 case BTT_IsBaseOf: ResultType = Context.BoolTy; break;
John Wiegley65497cc2011-04-27 23:09:49 +00003025 case BTT_IsConvertible: ResultType = Context.BoolTy; break;
3026 case BTT_IsSame: ResultType = Context.BoolTy; break;
Francois Pichet34b21132010-12-08 22:35:30 +00003027 case BTT_TypeCompatible: ResultType = Context.IntTy; break;
Douglas Gregor8006e762011-01-27 20:28:01 +00003028 case BTT_IsConvertibleTo: ResultType = Context.BoolTy; break;
Francois Pichet34b21132010-12-08 22:35:30 +00003029 }
3030
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00003031 return Owned(new (Context) BinaryTypeTraitExpr(KWLoc, BTT, LhsTSInfo,
3032 RhsTSInfo, Value, RParen,
Francois Pichet34b21132010-12-08 22:35:30 +00003033 ResultType));
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00003034}
3035
John Wiegley6242b6a2011-04-28 00:16:57 +00003036ExprResult Sema::ActOnArrayTypeTrait(ArrayTypeTrait ATT,
3037 SourceLocation KWLoc,
3038 ParsedType Ty,
3039 Expr* DimExpr,
3040 SourceLocation RParen) {
3041 TypeSourceInfo *TSInfo;
3042 QualType T = GetTypeFromParser(Ty, &TSInfo);
3043 if (!TSInfo)
3044 TSInfo = Context.getTrivialTypeSourceInfo(T);
3045
3046 return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen);
3047}
3048
3049static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT,
3050 QualType T, Expr *DimExpr,
3051 SourceLocation KeyLoc) {
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00003052 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
John Wiegley6242b6a2011-04-28 00:16:57 +00003053
3054 switch(ATT) {
3055 case ATT_ArrayRank:
3056 if (T->isArrayType()) {
3057 unsigned Dim = 0;
3058 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
3059 ++Dim;
3060 T = AT->getElementType();
3061 }
3062 return Dim;
John Wiegley6242b6a2011-04-28 00:16:57 +00003063 }
John Wiegleyd3522222011-04-28 02:06:46 +00003064 return 0;
3065
John Wiegley6242b6a2011-04-28 00:16:57 +00003066 case ATT_ArrayExtent: {
3067 llvm::APSInt Value;
3068 uint64_t Dim;
John Wiegleyd3522222011-04-28 02:06:46 +00003069 if (DimExpr->isIntegerConstantExpr(Value, Self.Context, 0, false)) {
3070 if (Value < llvm::APSInt(Value.getBitWidth(), Value.isUnsigned())) {
3071 Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer) <<
3072 DimExpr->getSourceRange();
3073 return false;
3074 }
John Wiegley6242b6a2011-04-28 00:16:57 +00003075 Dim = Value.getLimitedValue();
John Wiegleyd3522222011-04-28 02:06:46 +00003076 } else {
3077 Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer) <<
3078 DimExpr->getSourceRange();
3079 return false;
3080 }
John Wiegley6242b6a2011-04-28 00:16:57 +00003081
3082 if (T->isArrayType()) {
3083 unsigned D = 0;
3084 bool Matched = false;
3085 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
3086 if (Dim == D) {
3087 Matched = true;
3088 break;
3089 }
3090 ++D;
3091 T = AT->getElementType();
3092 }
3093
John Wiegleyd3522222011-04-28 02:06:46 +00003094 if (Matched && T->isArrayType()) {
3095 if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T))
3096 return CAT->getSize().getLimitedValue();
3097 }
John Wiegley6242b6a2011-04-28 00:16:57 +00003098 }
John Wiegleyd3522222011-04-28 02:06:46 +00003099 return 0;
John Wiegley6242b6a2011-04-28 00:16:57 +00003100 }
3101 }
3102 llvm_unreachable("Unknown type trait or not implemented");
3103}
3104
3105ExprResult Sema::BuildArrayTypeTrait(ArrayTypeTrait ATT,
3106 SourceLocation KWLoc,
3107 TypeSourceInfo *TSInfo,
3108 Expr* DimExpr,
3109 SourceLocation RParen) {
3110 QualType T = TSInfo->getType();
John Wiegley6242b6a2011-04-28 00:16:57 +00003111
Chandler Carruthc5276e52011-05-01 08:48:21 +00003112 // FIXME: This should likely be tracked as an APInt to remove any host
3113 // assumptions about the width of size_t on the target.
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00003114 uint64_t Value = 0;
3115 if (!T->isDependentType())
3116 Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc);
3117
Chandler Carruthc5276e52011-05-01 08:48:21 +00003118 // While the specification for these traits from the Embarcadero C++
3119 // compiler's documentation says the return type is 'unsigned int', Clang
3120 // returns 'size_t'. On Windows, the primary platform for the Embarcadero
3121 // compiler, there is no difference. On several other platforms this is an
3122 // important distinction.
John Wiegley6242b6a2011-04-28 00:16:57 +00003123 return Owned(new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value,
Chandler Carruth9cf632c2011-05-01 07:49:26 +00003124 DimExpr, RParen,
Chandler Carruthc5276e52011-05-01 08:48:21 +00003125 Context.getSizeType()));
John Wiegley6242b6a2011-04-28 00:16:57 +00003126}
3127
John Wiegleyf9f65842011-04-25 06:54:41 +00003128ExprResult Sema::ActOnExpressionTrait(ExpressionTrait ET,
Chandler Carruth20b9bc82011-05-01 07:44:20 +00003129 SourceLocation KWLoc,
3130 Expr *Queried,
3131 SourceLocation RParen) {
John Wiegleyf9f65842011-04-25 06:54:41 +00003132 // If error parsing the expression, ignore.
3133 if (!Queried)
Chandler Carruth20b9bc82011-05-01 07:44:20 +00003134 return ExprError();
John Wiegleyf9f65842011-04-25 06:54:41 +00003135
Chandler Carruth20b9bc82011-05-01 07:44:20 +00003136 ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen);
John Wiegleyf9f65842011-04-25 06:54:41 +00003137
3138 return move(Result);
3139}
3140
Chandler Carruth20b9bc82011-05-01 07:44:20 +00003141static bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E) {
3142 switch (ET) {
3143 case ET_IsLValueExpr: return E->isLValue();
3144 case ET_IsRValueExpr: return E->isRValue();
3145 }
3146 llvm_unreachable("Expression trait not covered by switch");
3147}
3148
John Wiegleyf9f65842011-04-25 06:54:41 +00003149ExprResult Sema::BuildExpressionTrait(ExpressionTrait ET,
Chandler Carruth20b9bc82011-05-01 07:44:20 +00003150 SourceLocation KWLoc,
3151 Expr *Queried,
3152 SourceLocation RParen) {
John Wiegleyf9f65842011-04-25 06:54:41 +00003153 if (Queried->isTypeDependent()) {
3154 // Delay type-checking for type-dependent expressions.
3155 } else if (Queried->getType()->isPlaceholderType()) {
3156 ExprResult PE = CheckPlaceholderExpr(Queried);
3157 if (PE.isInvalid()) return ExprError();
3158 return BuildExpressionTrait(ET, KWLoc, PE.take(), RParen);
3159 }
3160
Chandler Carruth20b9bc82011-05-01 07:44:20 +00003161 bool Value = EvaluateExpressionTrait(ET, Queried);
Chandler Carruthf57eba32011-05-01 08:48:19 +00003162
Chandler Carruth20b9bc82011-05-01 07:44:20 +00003163 return Owned(new (Context) ExpressionTraitExpr(KWLoc, ET, Queried, Value,
3164 RParen, Context.BoolTy));
John Wiegleyf9f65842011-04-25 06:54:41 +00003165}
3166
John Wiegley01296292011-04-08 18:41:53 +00003167QualType Sema::CheckPointerToMemberOperands(ExprResult &lex, ExprResult &rex,
John McCall7decc9e2010-11-18 06:31:45 +00003168 ExprValueKind &VK,
3169 SourceLocation Loc,
3170 bool isIndirect) {
Sebastian Redl5822f082009-02-07 20:10:22 +00003171 const char *OpSpelling = isIndirect ? "->*" : ".*";
3172 // C++ 5.5p2
3173 // The binary operator .* [p3: ->*] binds its second operand, which shall
3174 // be of type "pointer to member of T" (where T is a completely-defined
3175 // class type) [...]
John Wiegley01296292011-04-08 18:41:53 +00003176 QualType RType = rex.get()->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003177 const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
Douglas Gregorac1fb652009-03-24 19:52:54 +00003178 if (!MemPtr) {
Sebastian Redl5822f082009-02-07 20:10:22 +00003179 Diag(Loc, diag::err_bad_memptr_rhs)
John Wiegley01296292011-04-08 18:41:53 +00003180 << OpSpelling << RType << rex.get()->getSourceRange();
Sebastian Redl5822f082009-02-07 20:10:22 +00003181 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00003182 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00003183
Sebastian Redl5822f082009-02-07 20:10:22 +00003184 QualType Class(MemPtr->getClass(), 0);
3185
Douglas Gregord07ba342010-10-13 20:41:14 +00003186 // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
3187 // member pointer points must be completely-defined. However, there is no
3188 // reason for this semantic distinction, and the rule is not enforced by
3189 // other compilers. Therefore, we do not check this property, as it is
3190 // likely to be considered a defect.
Sebastian Redlc72350e2010-04-10 10:14:54 +00003191
Sebastian Redl5822f082009-02-07 20:10:22 +00003192 // C++ 5.5p2
3193 // [...] to its first operand, which shall be of class T or of a class of
3194 // which T is an unambiguous and accessible base class. [p3: a pointer to
3195 // such a class]
John Wiegley01296292011-04-08 18:41:53 +00003196 QualType LType = lex.get()->getType();
Sebastian Redl5822f082009-02-07 20:10:22 +00003197 if (isIndirect) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003198 if (const PointerType *Ptr = LType->getAs<PointerType>())
John McCall7decc9e2010-11-18 06:31:45 +00003199 LType = Ptr->getPointeeType();
Sebastian Redl5822f082009-02-07 20:10:22 +00003200 else {
3201 Diag(Loc, diag::err_bad_memptr_lhs)
Fariborz Jahanian59f64202009-10-26 20:45:27 +00003202 << OpSpelling << 1 << LType
Douglas Gregora771f462010-03-31 17:46:05 +00003203 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl5822f082009-02-07 20:10:22 +00003204 return QualType();
3205 }
3206 }
3207
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003208 if (!Context.hasSameUnqualifiedType(Class, LType)) {
Sebastian Redl26a0f1c2010-04-23 17:18:26 +00003209 // If we want to check the hierarchy, we need a complete type.
3210 if (RequireCompleteType(Loc, LType, PDiag(diag::err_bad_memptr_lhs)
3211 << OpSpelling << (int)isIndirect)) {
3212 return QualType();
3213 }
Anders Carlssona70cff62010-04-24 19:06:50 +00003214 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00003215 /*DetectVirtual=*/false);
Mike Stump87c57ac2009-05-16 07:39:55 +00003216 // FIXME: Would it be useful to print full ambiguity paths, or is that
3217 // overkill?
Sebastian Redl5822f082009-02-07 20:10:22 +00003218 if (!IsDerivedFrom(LType, Class, Paths) ||
3219 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
3220 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
John Wiegley01296292011-04-08 18:41:53 +00003221 << (int)isIndirect << lex.get()->getType();
Sebastian Redl5822f082009-02-07 20:10:22 +00003222 return QualType();
3223 }
Eli Friedman1fcf66b2010-01-16 00:00:48 +00003224 // Cast LHS to type of use.
3225 QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
John McCall2536c6d2010-08-25 10:28:54 +00003226 ExprValueKind VK =
John Wiegley01296292011-04-08 18:41:53 +00003227 isIndirect ? VK_RValue : CastCategory(lex.get());
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003228
John McCallcf142162010-08-07 06:22:56 +00003229 CXXCastPath BasePath;
Anders Carlssona70cff62010-04-24 19:06:50 +00003230 BuildBasePathArray(Paths, BasePath);
John Wiegley01296292011-04-08 18:41:53 +00003231 lex = ImpCastExprToType(lex.take(), UseType, CK_DerivedToBase, VK, &BasePath);
Sebastian Redl5822f082009-02-07 20:10:22 +00003232 }
3233
John Wiegley01296292011-04-08 18:41:53 +00003234 if (isa<CXXScalarValueInitExpr>(rex.get()->IgnoreParens())) {
Fariborz Jahanian1bc0f9a2009-11-18 21:54:48 +00003235 // Diagnose use of pointer-to-member type which when used as
3236 // the functional cast in a pointer-to-member expression.
3237 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
3238 return QualType();
3239 }
John McCall7decc9e2010-11-18 06:31:45 +00003240
Sebastian Redl5822f082009-02-07 20:10:22 +00003241 // C++ 5.5p2
3242 // The result is an object or a function of the type specified by the
3243 // second operand.
3244 // The cv qualifiers are the union of those in the pointer and the left side,
3245 // in accordance with 5.5p5 and 5.2.5.
Sebastian Redl5822f082009-02-07 20:10:22 +00003246 QualType Result = MemPtr->getPointeeType();
John McCall8ccfcb52009-09-24 19:53:00 +00003247 Result = Context.getCVRQualifiedType(Result, LType.getCVRQualifiers());
John McCall7decc9e2010-11-18 06:31:45 +00003248
Douglas Gregor1d042092011-01-26 16:40:18 +00003249 // C++0x [expr.mptr.oper]p6:
3250 // In a .* expression whose object expression is an rvalue, the program is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003251 // ill-formed if the second operand is a pointer to member function with
3252 // ref-qualifier &. In a ->* expression or in a .* expression whose object
3253 // expression is an lvalue, the program is ill-formed if the second operand
Douglas Gregor1d042092011-01-26 16:40:18 +00003254 // is a pointer to member function with ref-qualifier &&.
3255 if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
3256 switch (Proto->getRefQualifier()) {
3257 case RQ_None:
3258 // Do nothing
3259 break;
3260
3261 case RQ_LValue:
John Wiegley01296292011-04-08 18:41:53 +00003262 if (!isIndirect && !lex.get()->Classify(Context).isLValue())
Douglas Gregor1d042092011-01-26 16:40:18 +00003263 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
John Wiegley01296292011-04-08 18:41:53 +00003264 << RType << 1 << lex.get()->getSourceRange();
Douglas Gregor1d042092011-01-26 16:40:18 +00003265 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003266
Douglas Gregor1d042092011-01-26 16:40:18 +00003267 case RQ_RValue:
John Wiegley01296292011-04-08 18:41:53 +00003268 if (isIndirect || !lex.get()->Classify(Context).isRValue())
Douglas Gregor1d042092011-01-26 16:40:18 +00003269 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
John Wiegley01296292011-04-08 18:41:53 +00003270 << RType << 0 << lex.get()->getSourceRange();
Douglas Gregor1d042092011-01-26 16:40:18 +00003271 break;
3272 }
3273 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003274
John McCall7decc9e2010-11-18 06:31:45 +00003275 // C++ [expr.mptr.oper]p6:
3276 // The result of a .* expression whose second operand is a pointer
3277 // to a data member is of the same value category as its
3278 // first operand. The result of a .* expression whose second
3279 // operand is a pointer to a member function is a prvalue. The
3280 // result of an ->* expression is an lvalue if its second operand
3281 // is a pointer to data member and a prvalue otherwise.
John McCall0009fcc2011-04-26 20:42:42 +00003282 if (Result->isFunctionType()) {
John McCall7decc9e2010-11-18 06:31:45 +00003283 VK = VK_RValue;
John McCall0009fcc2011-04-26 20:42:42 +00003284 return Context.BoundMemberTy;
3285 } else if (isIndirect) {
John McCall7decc9e2010-11-18 06:31:45 +00003286 VK = VK_LValue;
John McCall0009fcc2011-04-26 20:42:42 +00003287 } else {
John Wiegley01296292011-04-08 18:41:53 +00003288 VK = lex.get()->getValueKind();
John McCall0009fcc2011-04-26 20:42:42 +00003289 }
John McCall7decc9e2010-11-18 06:31:45 +00003290
Sebastian Redl5822f082009-02-07 20:10:22 +00003291 return Result;
3292}
Sebastian Redl1a99f442009-04-16 17:51:27 +00003293
Sebastian Redl1a99f442009-04-16 17:51:27 +00003294/// \brief Try to convert a type to another according to C++0x 5.16p3.
3295///
3296/// This is part of the parameter validation for the ? operator. If either
3297/// value operand is a class type, the two operands are attempted to be
3298/// converted to each other. This function does the conversion in one direction.
Douglas Gregor838fcc32010-03-26 20:14:36 +00003299/// It returns true if the program is ill-formed and has already been diagnosed
3300/// as such.
Sebastian Redl1a99f442009-04-16 17:51:27 +00003301static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
3302 SourceLocation QuestionLoc,
Douglas Gregor838fcc32010-03-26 20:14:36 +00003303 bool &HaveConversion,
3304 QualType &ToType) {
3305 HaveConversion = false;
3306 ToType = To->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003307
3308 InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
Douglas Gregor838fcc32010-03-26 20:14:36 +00003309 SourceLocation());
Sebastian Redl1a99f442009-04-16 17:51:27 +00003310 // C++0x 5.16p3
3311 // The process for determining whether an operand expression E1 of type T1
3312 // can be converted to match an operand expression E2 of type T2 is defined
3313 // as follows:
3314 // -- If E2 is an lvalue:
John McCall086a4642010-11-24 05:12:34 +00003315 bool ToIsLvalue = To->isLValue();
Douglas Gregorf9edf802010-03-26 20:59:55 +00003316 if (ToIsLvalue) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00003317 // E1 can be converted to match E2 if E1 can be implicitly converted to
3318 // type "lvalue reference to T2", subject to the constraint that in the
3319 // conversion the reference must bind directly to E1.
Douglas Gregor838fcc32010-03-26 20:14:36 +00003320 QualType T = Self.Context.getLValueReferenceType(ToType);
3321 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003322
Douglas Gregor838fcc32010-03-26 20:14:36 +00003323 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
3324 if (InitSeq.isDirectReferenceBinding()) {
3325 ToType = T;
3326 HaveConversion = true;
3327 return false;
Sebastian Redl1a99f442009-04-16 17:51:27 +00003328 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003329
Douglas Gregor838fcc32010-03-26 20:14:36 +00003330 if (InitSeq.isAmbiguous())
3331 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
Sebastian Redl1a99f442009-04-16 17:51:27 +00003332 }
John McCall65eb8792010-02-25 01:37:24 +00003333
Sebastian Redl1a99f442009-04-16 17:51:27 +00003334 // -- If E2 is an rvalue, or if the conversion above cannot be done:
3335 // -- if E1 and E2 have class type, and the underlying class types are
3336 // the same or one is a base class of the other:
3337 QualType FTy = From->getType();
3338 QualType TTy = To->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003339 const RecordType *FRec = FTy->getAs<RecordType>();
3340 const RecordType *TRec = TTy->getAs<RecordType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003341 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
Douglas Gregor838fcc32010-03-26 20:14:36 +00003342 Self.IsDerivedFrom(FTy, TTy);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003343 if (FRec && TRec &&
Douglas Gregor838fcc32010-03-26 20:14:36 +00003344 (FRec == TRec || FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00003345 // E1 can be converted to match E2 if the class of T2 is the
3346 // same type as, or a base class of, the class of T1, and
3347 // [cv2 > cv1].
John McCall65eb8792010-02-25 01:37:24 +00003348 if (FRec == TRec || FDerivedFromT) {
3349 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00003350 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
3351 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00003352 if (InitSeq) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00003353 HaveConversion = true;
3354 return false;
3355 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003356
Douglas Gregor838fcc32010-03-26 20:14:36 +00003357 if (InitSeq.isAmbiguous())
3358 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003359 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00003360 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003361
Douglas Gregor838fcc32010-03-26 20:14:36 +00003362 return false;
Sebastian Redl1a99f442009-04-16 17:51:27 +00003363 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003364
Douglas Gregor838fcc32010-03-26 20:14:36 +00003365 // -- Otherwise: E1 can be converted to match E2 if E1 can be
3366 // implicitly converted to the type that expression E2 would have
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003367 // if E2 were converted to an rvalue (or the type it has, if E2 is
Douglas Gregorf9edf802010-03-26 20:59:55 +00003368 // an rvalue).
3369 //
3370 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
3371 // to the array-to-pointer or function-to-pointer conversions.
3372 if (!TTy->getAs<TagType>())
3373 TTy = TTy.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003374
Douglas Gregor838fcc32010-03-26 20:14:36 +00003375 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
3376 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00003377 HaveConversion = !InitSeq.Failed();
Douglas Gregor838fcc32010-03-26 20:14:36 +00003378 ToType = TTy;
3379 if (InitSeq.isAmbiguous())
3380 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
3381
Sebastian Redl1a99f442009-04-16 17:51:27 +00003382 return false;
3383}
3384
3385/// \brief Try to find a common type for two according to C++0x 5.16p5.
3386///
3387/// This is part of the parameter validation for the ? operator. If either
3388/// value operand is a class type, overload resolution is used to find a
3389/// conversion to a common type.
John Wiegley01296292011-04-08 18:41:53 +00003390static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS,
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003391 SourceLocation QuestionLoc) {
John Wiegley01296292011-04-08 18:41:53 +00003392 Expr *Args[2] = { LHS.get(), RHS.get() };
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003393 OverloadCandidateSet CandidateSet(QuestionLoc);
3394 Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args, 2,
3395 CandidateSet);
Sebastian Redl1a99f442009-04-16 17:51:27 +00003396
3397 OverloadCandidateSet::iterator Best;
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003398 switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
John Wiegley01296292011-04-08 18:41:53 +00003399 case OR_Success: {
Sebastian Redl1a99f442009-04-16 17:51:27 +00003400 // We found a match. Perform the conversions on the arguments and move on.
John Wiegley01296292011-04-08 18:41:53 +00003401 ExprResult LHSRes =
3402 Self.PerformImplicitConversion(LHS.get(), Best->BuiltinTypes.ParamTypes[0],
3403 Best->Conversions[0], Sema::AA_Converting);
3404 if (LHSRes.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00003405 break;
John Wiegley01296292011-04-08 18:41:53 +00003406 LHS = move(LHSRes);
3407
3408 ExprResult RHSRes =
3409 Self.PerformImplicitConversion(RHS.get(), Best->BuiltinTypes.ParamTypes[1],
3410 Best->Conversions[1], Sema::AA_Converting);
3411 if (RHSRes.isInvalid())
3412 break;
3413 RHS = move(RHSRes);
Chandler Carruth30141632011-02-25 19:41:05 +00003414 if (Best->Function)
3415 Self.MarkDeclarationReferenced(QuestionLoc, Best->Function);
Sebastian Redl1a99f442009-04-16 17:51:27 +00003416 return false;
John Wiegley01296292011-04-08 18:41:53 +00003417 }
3418
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003419 case OR_No_Viable_Function:
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003420
3421 // Emit a better diagnostic if one of the expressions is a null pointer
3422 // constant and the other is a pointer type. In this case, the user most
3423 // likely forgot to take the address of the other expression.
John Wiegley01296292011-04-08 18:41:53 +00003424 if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003425 return true;
3426
3427 Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley01296292011-04-08 18:41:53 +00003428 << LHS.get()->getType() << RHS.get()->getType()
3429 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00003430 return true;
3431
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003432 case OR_Ambiguous:
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003433 Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
John Wiegley01296292011-04-08 18:41:53 +00003434 << LHS.get()->getType() << RHS.get()->getType()
3435 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Mike Stump87c57ac2009-05-16 07:39:55 +00003436 // FIXME: Print the possible common types by printing the return types of
3437 // the viable candidates.
Sebastian Redl1a99f442009-04-16 17:51:27 +00003438 break;
3439
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003440 case OR_Deleted:
Sebastian Redl1a99f442009-04-16 17:51:27 +00003441 assert(false && "Conditional operator has only built-in overloads");
3442 break;
3443 }
3444 return true;
3445}
3446
Sebastian Redl5775af1a2009-04-17 16:30:52 +00003447/// \brief Perform an "extended" implicit conversion as returned by
3448/// TryClassUnification.
John Wiegley01296292011-04-08 18:41:53 +00003449static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00003450 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
John Wiegley01296292011-04-08 18:41:53 +00003451 InitializationKind Kind = InitializationKind::CreateCopy(E.get()->getLocStart(),
Douglas Gregor838fcc32010-03-26 20:14:36 +00003452 SourceLocation());
John Wiegley01296292011-04-08 18:41:53 +00003453 Expr *Arg = E.take();
3454 InitializationSequence InitSeq(Self, Entity, Kind, &Arg, 1);
3455 ExprResult Result = InitSeq.Perform(Self, Entity, Kind, MultiExprArg(&Arg, 1));
Douglas Gregor838fcc32010-03-26 20:14:36 +00003456 if (Result.isInvalid())
Sebastian Redl5775af1a2009-04-17 16:30:52 +00003457 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003458
John Wiegley01296292011-04-08 18:41:53 +00003459 E = Result;
Sebastian Redl5775af1a2009-04-17 16:30:52 +00003460 return false;
3461}
3462
Sebastian Redl1a99f442009-04-16 17:51:27 +00003463/// \brief Check the operands of ?: under C++ semantics.
3464///
3465/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
3466/// extension. In this case, LHS == Cond. (But they're not aliases.)
John Wiegley01296292011-04-08 18:41:53 +00003467QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
John McCallc07a0c72011-02-17 10:25:35 +00003468 ExprValueKind &VK, ExprObjectKind &OK,
Sebastian Redl1a99f442009-04-16 17:51:27 +00003469 SourceLocation QuestionLoc) {
Mike Stump87c57ac2009-05-16 07:39:55 +00003470 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
3471 // interface pointers.
Sebastian Redl1a99f442009-04-16 17:51:27 +00003472
3473 // C++0x 5.16p1
3474 // The first expression is contextually converted to bool.
John Wiegley01296292011-04-08 18:41:53 +00003475 if (!Cond.get()->isTypeDependent()) {
3476 ExprResult CondRes = CheckCXXBooleanCondition(Cond.take());
3477 if (CondRes.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00003478 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00003479 Cond = move(CondRes);
Sebastian Redl1a99f442009-04-16 17:51:27 +00003480 }
3481
John McCall7decc9e2010-11-18 06:31:45 +00003482 // Assume r-value.
3483 VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00003484 OK = OK_Ordinary;
John McCall7decc9e2010-11-18 06:31:45 +00003485
Sebastian Redl1a99f442009-04-16 17:51:27 +00003486 // Either of the arguments dependent?
John Wiegley01296292011-04-08 18:41:53 +00003487 if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent())
Sebastian Redl1a99f442009-04-16 17:51:27 +00003488 return Context.DependentTy;
3489
3490 // C++0x 5.16p2
3491 // If either the second or the third operand has type (cv) void, ...
John Wiegley01296292011-04-08 18:41:53 +00003492 QualType LTy = LHS.get()->getType();
3493 QualType RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00003494 bool LVoid = LTy->isVoidType();
3495 bool RVoid = RTy->isVoidType();
3496 if (LVoid || RVoid) {
3497 // ... then the [l2r] conversions are performed on the second and third
3498 // operands ...
John Wiegley01296292011-04-08 18:41:53 +00003499 LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
3500 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
3501 if (LHS.isInvalid() || RHS.isInvalid())
3502 return QualType();
3503 LTy = LHS.get()->getType();
3504 RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00003505
3506 // ... and one of the following shall hold:
3507 // -- The second or the third operand (but not both) is a throw-
3508 // expression; the result is of the type of the other and is an rvalue.
John Wiegley01296292011-04-08 18:41:53 +00003509 bool LThrow = isa<CXXThrowExpr>(LHS.get());
3510 bool RThrow = isa<CXXThrowExpr>(RHS.get());
Sebastian Redl1a99f442009-04-16 17:51:27 +00003511 if (LThrow && !RThrow)
3512 return RTy;
3513 if (RThrow && !LThrow)
3514 return LTy;
3515
3516 // -- Both the second and third operands have type void; the result is of
3517 // type void and is an rvalue.
3518 if (LVoid && RVoid)
3519 return Context.VoidTy;
3520
3521 // Neither holds, error.
3522 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
3523 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
John Wiegley01296292011-04-08 18:41:53 +00003524 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00003525 return QualType();
3526 }
3527
3528 // Neither is void.
3529
3530 // C++0x 5.16p3
3531 // Otherwise, if the second and third operand have different types, and
3532 // either has (cv) class type, and attempt is made to convert each of those
3533 // operands to the other.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003534 if (!Context.hasSameType(LTy, RTy) &&
Sebastian Redl1a99f442009-04-16 17:51:27 +00003535 (LTy->isRecordType() || RTy->isRecordType())) {
3536 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
3537 // These return true if a single direction is already ambiguous.
Douglas Gregor838fcc32010-03-26 20:14:36 +00003538 QualType L2RType, R2LType;
3539 bool HaveL2R, HaveR2L;
John Wiegley01296292011-04-08 18:41:53 +00003540 if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00003541 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00003542 if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00003543 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003544
Sebastian Redl1a99f442009-04-16 17:51:27 +00003545 // If both can be converted, [...] the program is ill-formed.
3546 if (HaveL2R && HaveR2L) {
3547 Diag(QuestionLoc, diag::err_conditional_ambiguous)
John Wiegley01296292011-04-08 18:41:53 +00003548 << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00003549 return QualType();
3550 }
3551
3552 // If exactly one conversion is possible, that conversion is applied to
3553 // the chosen operand and the converted operands are used in place of the
3554 // original operands for the remainder of this section.
3555 if (HaveL2R) {
John Wiegley01296292011-04-08 18:41:53 +00003556 if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00003557 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00003558 LTy = LHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00003559 } else if (HaveR2L) {
John Wiegley01296292011-04-08 18:41:53 +00003560 if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00003561 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00003562 RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00003563 }
3564 }
3565
3566 // C++0x 5.16p4
John McCall7decc9e2010-11-18 06:31:45 +00003567 // If the second and third operands are glvalues of the same value
3568 // category and have the same type, the result is of that type and
3569 // value category and it is a bit-field if the second or the third
3570 // operand is a bit-field, or if both are bit-fields.
John McCall4bc41ae2010-11-18 19:01:18 +00003571 // We only extend this to bitfields, not to the crazy other kinds of
3572 // l-values.
Douglas Gregor697a3912010-04-01 22:47:07 +00003573 bool Same = Context.hasSameType(LTy, RTy);
John McCall7decc9e2010-11-18 06:31:45 +00003574 if (Same &&
John Wiegley01296292011-04-08 18:41:53 +00003575 LHS.get()->isGLValue() &&
3576 LHS.get()->getValueKind() == RHS.get()->getValueKind() &&
3577 LHS.get()->isOrdinaryOrBitFieldObject() &&
3578 RHS.get()->isOrdinaryOrBitFieldObject()) {
3579 VK = LHS.get()->getValueKind();
3580 if (LHS.get()->getObjectKind() == OK_BitField ||
3581 RHS.get()->getObjectKind() == OK_BitField)
John McCall4bc41ae2010-11-18 19:01:18 +00003582 OK = OK_BitField;
John McCall7decc9e2010-11-18 06:31:45 +00003583 return LTy;
Fariborz Jahanianc60da032010-09-25 01:08:05 +00003584 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00003585
3586 // C++0x 5.16p5
3587 // Otherwise, the result is an rvalue. If the second and third operands
3588 // do not have the same type, and either has (cv) class type, ...
3589 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
3590 // ... overload resolution is used to determine the conversions (if any)
3591 // to be applied to the operands. If the overload resolution fails, the
3592 // program is ill-formed.
3593 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
3594 return QualType();
3595 }
3596
3597 // C++0x 5.16p6
3598 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
3599 // conversions are performed on the second and third operands.
John Wiegley01296292011-04-08 18:41:53 +00003600 LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
3601 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
3602 if (LHS.isInvalid() || RHS.isInvalid())
3603 return QualType();
3604 LTy = LHS.get()->getType();
3605 RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00003606
3607 // After those conversions, one of the following shall hold:
3608 // -- The second and third operands have the same type; the result
Douglas Gregorfa6010b2010-05-19 23:40:50 +00003609 // is of that type. If the operands have class type, the result
3610 // is a prvalue temporary of the result type, which is
3611 // copy-initialized from either the second operand or the third
3612 // operand depending on the value of the first operand.
3613 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
3614 if (LTy->isRecordType()) {
3615 // The operands have class type. Make a temporary copy.
3616 InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003617 ExprResult LHSCopy = PerformCopyInitialization(Entity,
3618 SourceLocation(),
John Wiegley01296292011-04-08 18:41:53 +00003619 LHS);
Douglas Gregorfa6010b2010-05-19 23:40:50 +00003620 if (LHSCopy.isInvalid())
3621 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003622
3623 ExprResult RHSCopy = PerformCopyInitialization(Entity,
3624 SourceLocation(),
John Wiegley01296292011-04-08 18:41:53 +00003625 RHS);
Douglas Gregorfa6010b2010-05-19 23:40:50 +00003626 if (RHSCopy.isInvalid())
3627 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003628
John Wiegley01296292011-04-08 18:41:53 +00003629 LHS = LHSCopy;
3630 RHS = RHSCopy;
Douglas Gregorfa6010b2010-05-19 23:40:50 +00003631 }
3632
Sebastian Redl1a99f442009-04-16 17:51:27 +00003633 return LTy;
Douglas Gregorfa6010b2010-05-19 23:40:50 +00003634 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00003635
Douglas Gregor46188682010-05-18 22:42:18 +00003636 // Extension: conditional operator involving vector types.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003637 if (LTy->isVectorType() || RTy->isVectorType())
Eli Friedman1408bc92011-06-23 18:10:35 +00003638 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
Douglas Gregor46188682010-05-18 22:42:18 +00003639
Sebastian Redl1a99f442009-04-16 17:51:27 +00003640 // -- The second and third operands have arithmetic or enumeration type;
3641 // the usual arithmetic conversions are performed to bring them to a
3642 // common type, and the result is of that type.
3643 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
3644 UsualArithmeticConversions(LHS, RHS);
John Wiegley01296292011-04-08 18:41:53 +00003645 if (LHS.isInvalid() || RHS.isInvalid())
3646 return QualType();
3647 return LHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00003648 }
3649
3650 // -- The second and third operands have pointer type, or one has pointer
3651 // type and the other is a null pointer constant; pointer conversions
3652 // and qualification conversions are performed to bring them to their
3653 // composite pointer type. The result is of the composite pointer type.
Eli Friedman81390df2010-01-02 22:56:07 +00003654 // -- The second and third operands have pointer to member type, or one has
3655 // pointer to member type and the other is a null pointer constant;
3656 // pointer to member conversions and qualification conversions are
3657 // performed to bring them to a common type, whose cv-qualification
3658 // shall match the cv-qualification of either the second or the third
3659 // operand. The result is of the common type.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00003660 bool NonStandardCompositeType = false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00003661 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00003662 isSFINAEContext()? 0 : &NonStandardCompositeType);
3663 if (!Composite.isNull()) {
3664 if (NonStandardCompositeType)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003665 Diag(QuestionLoc,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00003666 diag::ext_typecheck_cond_incompatible_operands_nonstandard)
3667 << LTy << RTy << Composite
John Wiegley01296292011-04-08 18:41:53 +00003668 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003669
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00003670 return Composite;
Douglas Gregor6f5f6422010-02-25 22:29:57 +00003671 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003672
Douglas Gregor697a3912010-04-01 22:47:07 +00003673 // Similarly, attempt to find composite type of two objective-c pointers.
Fariborz Jahanian798d2bd2009-12-10 20:46:08 +00003674 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
3675 if (!Composite.isNull())
3676 return Composite;
Sebastian Redl1a99f442009-04-16 17:51:27 +00003677
Chandler Carruth9c9127e2011-02-19 00:13:59 +00003678 // Check if we are using a null with a non-pointer type.
John Wiegley01296292011-04-08 18:41:53 +00003679 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carruth9c9127e2011-02-19 00:13:59 +00003680 return QualType();
3681
Sebastian Redl1a99f442009-04-16 17:51:27 +00003682 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley01296292011-04-08 18:41:53 +00003683 << LHS.get()->getType() << RHS.get()->getType()
3684 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00003685 return QualType();
3686}
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00003687
3688/// \brief Find a merged pointer type and convert the two expressions to it.
3689///
Douglas Gregorb00b10e2009-08-24 17:42:35 +00003690/// This finds the composite pointer type (or member pointer type) for @p E1
3691/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
3692/// type and returns it.
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00003693/// It does not emit diagnostics.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00003694///
Douglas Gregor19175ff2010-04-16 23:20:25 +00003695/// \param Loc The location of the operator requiring these two expressions to
3696/// be converted to the composite pointer type.
3697///
Douglas Gregor6f5f6422010-02-25 22:29:57 +00003698/// If \p NonStandardCompositeType is non-NULL, then we are permitted to find
3699/// a non-standard (but still sane) composite type to which both expressions
3700/// can be converted. When such a type is chosen, \c *NonStandardCompositeType
3701/// will be set true.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003702QualType Sema::FindCompositePointerType(SourceLocation Loc,
Douglas Gregor19175ff2010-04-16 23:20:25 +00003703 Expr *&E1, Expr *&E2,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00003704 bool *NonStandardCompositeType) {
3705 if (NonStandardCompositeType)
3706 *NonStandardCompositeType = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003707
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00003708 assert(getLangOptions().CPlusPlus && "This function assumes C++");
3709 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump11289f42009-09-09 15:08:12 +00003710
Fariborz Jahanian33e148f2009-12-08 20:04:24 +00003711 if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
3712 !T2->isAnyPointerType() && !T2->isMemberPointerType())
Douglas Gregorb00b10e2009-08-24 17:42:35 +00003713 return QualType();
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00003714
3715 // C++0x 5.9p2
3716 // Pointer conversions and qualification conversions are performed on
3717 // pointer operands to bring them to their composite pointer type. If
3718 // one operand is a null pointer constant, the composite pointer type is
3719 // the type of the other operand.
Douglas Gregor56751b52009-09-25 04:25:58 +00003720 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00003721 if (T2->isMemberPointerType())
John Wiegley01296292011-04-08 18:41:53 +00003722 E1 = ImpCastExprToType(E1, T2, CK_NullToMemberPointer).take();
Eli Friedman06ed2a52009-10-20 08:27:19 +00003723 else
John Wiegley01296292011-04-08 18:41:53 +00003724 E1 = ImpCastExprToType(E1, T2, CK_NullToPointer).take();
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00003725 return T2;
3726 }
Douglas Gregor56751b52009-09-25 04:25:58 +00003727 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00003728 if (T1->isMemberPointerType())
John Wiegley01296292011-04-08 18:41:53 +00003729 E2 = ImpCastExprToType(E2, T1, CK_NullToMemberPointer).take();
Eli Friedman06ed2a52009-10-20 08:27:19 +00003730 else
John Wiegley01296292011-04-08 18:41:53 +00003731 E2 = ImpCastExprToType(E2, T1, CK_NullToPointer).take();
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00003732 return T1;
3733 }
Mike Stump11289f42009-09-09 15:08:12 +00003734
Douglas Gregorb00b10e2009-08-24 17:42:35 +00003735 // Now both have to be pointers or member pointers.
Sebastian Redl658262f2009-11-16 21:03:45 +00003736 if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
3737 (!T2->isPointerType() && !T2->isMemberPointerType()))
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00003738 return QualType();
3739
3740 // Otherwise, of one of the operands has type "pointer to cv1 void," then
3741 // the other has type "pointer to cv2 T" and the composite pointer type is
3742 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
3743 // Otherwise, the composite pointer type is a pointer type similar to the
3744 // type of one of the operands, with a cv-qualification signature that is
3745 // the union of the cv-qualification signatures of the operand types.
3746 // In practice, the first part here is redundant; it's subsumed by the second.
3747 // What we do here is, we build the two possible composite types, and try the
3748 // conversions in both directions. If only one works, or if the two composite
3749 // types are the same, we have succeeded.
John McCall8ccfcb52009-09-24 19:53:00 +00003750 // FIXME: extended qualifiers?
Sebastian Redl658262f2009-11-16 21:03:45 +00003751 typedef llvm::SmallVector<unsigned, 4> QualifierVector;
3752 QualifierVector QualifierUnion;
3753 typedef llvm::SmallVector<std::pair<const Type *, const Type *>, 4>
3754 ContainingClassVector;
3755 ContainingClassVector MemberOfClass;
3756 QualType Composite1 = Context.getCanonicalType(T1),
3757 Composite2 = Context.getCanonicalType(T2);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003758 unsigned NeedConstBefore = 0;
Douglas Gregorb00b10e2009-08-24 17:42:35 +00003759 do {
3760 const PointerType *Ptr1, *Ptr2;
3761 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
3762 (Ptr2 = Composite2->getAs<PointerType>())) {
3763 Composite1 = Ptr1->getPointeeType();
3764 Composite2 = Ptr2->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003765
Douglas Gregor6f5f6422010-02-25 22:29:57 +00003766 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003767 // of where we need to fill in additional 'const' qualifiers.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00003768 if (NonStandardCompositeType &&
3769 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
3770 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003771
Douglas Gregorb00b10e2009-08-24 17:42:35 +00003772 QualifierUnion.push_back(
3773 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
3774 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
3775 continue;
3776 }
Mike Stump11289f42009-09-09 15:08:12 +00003777
Douglas Gregorb00b10e2009-08-24 17:42:35 +00003778 const MemberPointerType *MemPtr1, *MemPtr2;
3779 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
3780 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
3781 Composite1 = MemPtr1->getPointeeType();
3782 Composite2 = MemPtr2->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003783
Douglas Gregor6f5f6422010-02-25 22:29:57 +00003784 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003785 // of where we need to fill in additional 'const' qualifiers.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00003786 if (NonStandardCompositeType &&
3787 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
3788 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003789
Douglas Gregorb00b10e2009-08-24 17:42:35 +00003790 QualifierUnion.push_back(
3791 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
3792 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
3793 MemPtr2->getClass()));
3794 continue;
3795 }
Mike Stump11289f42009-09-09 15:08:12 +00003796
Douglas Gregorb00b10e2009-08-24 17:42:35 +00003797 // FIXME: block pointer types?
Mike Stump11289f42009-09-09 15:08:12 +00003798
Douglas Gregorb00b10e2009-08-24 17:42:35 +00003799 // Cannot unwrap any more types.
3800 break;
3801 } while (true);
Mike Stump11289f42009-09-09 15:08:12 +00003802
Douglas Gregor6f5f6422010-02-25 22:29:57 +00003803 if (NeedConstBefore && NonStandardCompositeType) {
3804 // Extension: Add 'const' to qualifiers that come before the first qualifier
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003805 // mismatch, so that our (non-standard!) composite type meets the
Douglas Gregor6f5f6422010-02-25 22:29:57 +00003806 // requirements of C++ [conv.qual]p4 bullet 3.
3807 for (unsigned I = 0; I != NeedConstBefore; ++I) {
3808 if ((QualifierUnion[I] & Qualifiers::Const) == 0) {
3809 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
3810 *NonStandardCompositeType = true;
3811 }
3812 }
3813 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003814
Douglas Gregorb00b10e2009-08-24 17:42:35 +00003815 // Rewrap the composites as pointers or member pointers with the union CVRs.
Sebastian Redl658262f2009-11-16 21:03:45 +00003816 ContainingClassVector::reverse_iterator MOC
3817 = MemberOfClass.rbegin();
3818 for (QualifierVector::reverse_iterator
3819 I = QualifierUnion.rbegin(),
3820 E = QualifierUnion.rend();
Douglas Gregorb00b10e2009-08-24 17:42:35 +00003821 I != E; (void)++I, ++MOC) {
John McCall8ccfcb52009-09-24 19:53:00 +00003822 Qualifiers Quals = Qualifiers::fromCVRMask(*I);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00003823 if (MOC->first && MOC->second) {
3824 // Rebuild member pointer type
John McCall8ccfcb52009-09-24 19:53:00 +00003825 Composite1 = Context.getMemberPointerType(
3826 Context.getQualifiedType(Composite1, Quals),
3827 MOC->first);
3828 Composite2 = Context.getMemberPointerType(
3829 Context.getQualifiedType(Composite2, Quals),
3830 MOC->second);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00003831 } else {
3832 // Rebuild pointer type
John McCall8ccfcb52009-09-24 19:53:00 +00003833 Composite1
3834 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
3835 Composite2
3836 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregorb00b10e2009-08-24 17:42:35 +00003837 }
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00003838 }
3839
Douglas Gregor19175ff2010-04-16 23:20:25 +00003840 // Try to convert to the first composite pointer type.
3841 InitializedEntity Entity1
3842 = InitializedEntity::InitializeTemporary(Composite1);
3843 InitializationKind Kind
3844 = InitializationKind::CreateCopy(Loc, SourceLocation());
3845 InitializationSequence E1ToC1(*this, Entity1, Kind, &E1, 1);
3846 InitializationSequence E2ToC1(*this, Entity1, Kind, &E2, 1);
Mike Stump11289f42009-09-09 15:08:12 +00003847
Douglas Gregor19175ff2010-04-16 23:20:25 +00003848 if (E1ToC1 && E2ToC1) {
3849 // Conversion to Composite1 is viable.
3850 if (!Context.hasSameType(Composite1, Composite2)) {
3851 // Composite2 is a different type from Composite1. Check whether
3852 // Composite2 is also viable.
3853 InitializedEntity Entity2
3854 = InitializedEntity::InitializeTemporary(Composite2);
3855 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
3856 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
3857 if (E1ToC2 && E2ToC2) {
3858 // Both Composite1 and Composite2 are viable and are different;
3859 // this is an ambiguity.
3860 return QualType();
3861 }
3862 }
3863
3864 // Convert E1 to Composite1
John McCalldadc5752010-08-24 06:29:42 +00003865 ExprResult E1Result
John McCall37ad5512010-08-23 06:44:23 +00003866 = E1ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E1,1));
Douglas Gregor19175ff2010-04-16 23:20:25 +00003867 if (E1Result.isInvalid())
3868 return QualType();
3869 E1 = E1Result.takeAs<Expr>();
3870
3871 // Convert E2 to Composite1
John McCalldadc5752010-08-24 06:29:42 +00003872 ExprResult E2Result
John McCall37ad5512010-08-23 06:44:23 +00003873 = E2ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E2,1));
Douglas Gregor19175ff2010-04-16 23:20:25 +00003874 if (E2Result.isInvalid())
3875 return QualType();
3876 E2 = E2Result.takeAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003877
Douglas Gregor19175ff2010-04-16 23:20:25 +00003878 return Composite1;
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00003879 }
3880
Douglas Gregor19175ff2010-04-16 23:20:25 +00003881 // Check whether Composite2 is viable.
3882 InitializedEntity Entity2
3883 = InitializedEntity::InitializeTemporary(Composite2);
3884 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
3885 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
3886 if (!E1ToC2 || !E2ToC2)
3887 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003888
Douglas Gregor19175ff2010-04-16 23:20:25 +00003889 // Convert E1 to Composite2
John McCalldadc5752010-08-24 06:29:42 +00003890 ExprResult E1Result
John McCall37ad5512010-08-23 06:44:23 +00003891 = E1ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E1, 1));
Douglas Gregor19175ff2010-04-16 23:20:25 +00003892 if (E1Result.isInvalid())
3893 return QualType();
3894 E1 = E1Result.takeAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003895
Douglas Gregor19175ff2010-04-16 23:20:25 +00003896 // Convert E2 to Composite2
John McCalldadc5752010-08-24 06:29:42 +00003897 ExprResult E2Result
John McCall37ad5512010-08-23 06:44:23 +00003898 = E2ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E2, 1));
Douglas Gregor19175ff2010-04-16 23:20:25 +00003899 if (E2Result.isInvalid())
3900 return QualType();
3901 E2 = E2Result.takeAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003902
Douglas Gregor19175ff2010-04-16 23:20:25 +00003903 return Composite2;
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00003904}
Anders Carlsson85a307d2009-05-17 18:41:29 +00003905
John McCalldadc5752010-08-24 06:29:42 +00003906ExprResult Sema::MaybeBindToTemporary(Expr *E) {
Douglas Gregor298087b2010-11-01 21:10:29 +00003907 if (!E)
3908 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003909
John McCall31168b02011-06-15 23:02:42 +00003910 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
3911
3912 // If the result is a glvalue, we shouldn't bind it.
3913 if (!E->isRValue())
Anders Carlssonf86a8d12009-08-15 23:41:35 +00003914 return Owned(E);
Mike Stump11289f42009-09-09 15:08:12 +00003915
John McCall31168b02011-06-15 23:02:42 +00003916 // In ARC, calls that return a retainable type can return retained,
3917 // in which case we have to insert a consuming cast.
3918 if (getLangOptions().ObjCAutoRefCount &&
3919 E->getType()->isObjCRetainableType()) {
3920
3921 bool ReturnsRetained;
3922
3923 // For actual calls, we compute this by examining the type of the
3924 // called value.
3925 if (CallExpr *Call = dyn_cast<CallExpr>(E)) {
3926 Expr *Callee = Call->getCallee()->IgnoreParens();
3927 QualType T = Callee->getType();
3928
3929 if (T == Context.BoundMemberTy) {
3930 // Handle pointer-to-members.
3931 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Callee))
3932 T = BinOp->getRHS()->getType();
3933 else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Callee))
3934 T = Mem->getMemberDecl()->getType();
3935 }
3936
3937 if (const PointerType *Ptr = T->getAs<PointerType>())
3938 T = Ptr->getPointeeType();
3939 else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>())
3940 T = Ptr->getPointeeType();
3941 else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>())
3942 T = MemPtr->getPointeeType();
3943
3944 const FunctionType *FTy = T->getAs<FunctionType>();
3945 assert(FTy && "call to value not of function type?");
3946 ReturnsRetained = FTy->getExtInfo().getProducesResult();
3947
3948 // ActOnStmtExpr arranges things so that StmtExprs of retainable
3949 // type always produce a +1 object.
3950 } else if (isa<StmtExpr>(E)) {
3951 ReturnsRetained = true;
3952
3953 // For message sends and property references, we try to find an
3954 // actual method. FIXME: we should infer retention by selector in
3955 // cases where we don't have an actual method.
3956 } else {
3957 Decl *D = 0;
3958 if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(E)) {
3959 D = Send->getMethodDecl();
3960 } else {
3961 CastExpr *CE = cast<CastExpr>(E);
3962 // FIXME. What other cast kinds to check for?
3963 if (CE->getCastKind() == CK_ObjCProduceObject ||
3964 CE->getCastKind() == CK_LValueToRValue)
3965 return MaybeBindToTemporary(CE->getSubExpr());
3966 assert(CE->getCastKind() == CK_GetObjCProperty);
3967 const ObjCPropertyRefExpr *PRE = CE->getSubExpr()->getObjCProperty();
3968 D = (PRE->isImplicitProperty() ? PRE->getImplicitPropertyGetter() : 0);
3969 }
3970
3971 ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>());
3972 }
3973
3974 if (ReturnsRetained) {
3975 ExprNeedsCleanups = true;
3976 E = ImplicitCastExpr::Create(Context, E->getType(),
3977 CK_ObjCConsumeObject, E, 0,
3978 VK_RValue);
3979 }
3980 return Owned(E);
3981 }
3982
3983 if (!getLangOptions().CPlusPlus)
3984 return Owned(E);
Douglas Gregor363b1512009-12-24 18:51:59 +00003985
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003986 const RecordType *RT = E->getType()->getAs<RecordType>();
Anders Carlsson2d4cada2009-05-30 20:36:53 +00003987 if (!RT)
3988 return Owned(E);
Mike Stump11289f42009-09-09 15:08:12 +00003989
John McCall67da35c2010-02-04 22:26:26 +00003990 // That should be enough to guarantee that this type is complete.
3991 // If it has a trivial destructor, we can avoid the extra copy.
Jeffrey Yasskinbbc4eea2011-01-27 19:17:54 +00003992 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
John McCallbdb989e2010-08-12 02:40:37 +00003993 if (RD->isInvalidDecl() || RD->hasTrivialDestructor())
John McCall67da35c2010-02-04 22:26:26 +00003994 return Owned(E);
3995
John McCall31168b02011-06-15 23:02:42 +00003996 CXXDestructorDecl *Destructor = LookupDestructor(RD);
3997
3998 CXXTemporary *Temp = CXXTemporary::Create(Context, Destructor);
3999 if (Destructor) {
Fariborz Jahanian67828442009-08-03 19:13:25 +00004000 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
John McCall8e36d532010-04-07 00:41:46 +00004001 CheckDestructorAccess(E->getExprLoc(), Destructor,
4002 PDiag(diag::err_access_dtor_temp)
4003 << E->getType());
John McCall31168b02011-06-15 23:02:42 +00004004
4005 ExprTemporaries.push_back(Temp);
4006 ExprNeedsCleanups = true;
John McCall8e36d532010-04-07 00:41:46 +00004007 }
Anders Carlsson2d4cada2009-05-30 20:36:53 +00004008 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
4009}
4010
John McCall5d413782010-12-06 08:20:24 +00004011Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) {
Anders Carlssonb3d05d62009-06-05 15:38:08 +00004012 assert(SubExpr && "sub expression can't be null!");
Mike Stump11289f42009-09-09 15:08:12 +00004013
Douglas Gregor580cd4a2009-12-03 17:10:37 +00004014 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
4015 assert(ExprTemporaries.size() >= FirstTemporary);
John McCall31168b02011-06-15 23:02:42 +00004016 assert(ExprNeedsCleanups || ExprTemporaries.size() == FirstTemporary);
4017 if (!ExprNeedsCleanups)
Anders Carlssonb3d05d62009-06-05 15:38:08 +00004018 return SubExpr;
Mike Stump11289f42009-09-09 15:08:12 +00004019
John McCall5d413782010-12-06 08:20:24 +00004020 Expr *E = ExprWithCleanups::Create(Context, SubExpr,
John McCall31168b02011-06-15 23:02:42 +00004021 ExprTemporaries.begin() + FirstTemporary,
John McCall5d413782010-12-06 08:20:24 +00004022 ExprTemporaries.size() - FirstTemporary);
Douglas Gregor580cd4a2009-12-03 17:10:37 +00004023 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
4024 ExprTemporaries.end());
John McCall31168b02011-06-15 23:02:42 +00004025 ExprNeedsCleanups = false;
Mike Stump11289f42009-09-09 15:08:12 +00004026
Anders Carlssonb3d05d62009-06-05 15:38:08 +00004027 return E;
4028}
4029
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004030ExprResult
John McCall5d413782010-12-06 08:20:24 +00004031Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) {
Douglas Gregorb6ea6082009-12-22 22:17:25 +00004032 if (SubExpr.isInvalid())
4033 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004034
John McCall5d413782010-12-06 08:20:24 +00004035 return Owned(MaybeCreateExprWithCleanups(SubExpr.take()));
Douglas Gregorb6ea6082009-12-22 22:17:25 +00004036}
4037
John McCall5d413782010-12-06 08:20:24 +00004038Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) {
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00004039 assert(SubStmt && "sub statement can't be null!");
4040
John McCall31168b02011-06-15 23:02:42 +00004041 if (!ExprNeedsCleanups)
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00004042 return SubStmt;
4043
4044 // FIXME: In order to attach the temporaries, wrap the statement into
4045 // a StmtExpr; currently this is only used for asm statements.
4046 // This is hacky, either create a new CXXStmtWithTemporaries statement or
4047 // a new AsmStmtWithTemporaries.
4048 CompoundStmt *CompStmt = new (Context) CompoundStmt(Context, &SubStmt, 1,
4049 SourceLocation(),
4050 SourceLocation());
4051 Expr *E = new (Context) StmtExpr(CompStmt, Context.VoidTy, SourceLocation(),
4052 SourceLocation());
John McCall5d413782010-12-06 08:20:24 +00004053 return MaybeCreateExprWithCleanups(E);
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00004054}
4055
John McCalldadc5752010-08-24 06:29:42 +00004056ExprResult
John McCallb268a282010-08-23 23:25:46 +00004057Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base, SourceLocation OpLoc,
John McCallba7bf592010-08-24 05:47:05 +00004058 tok::TokenKind OpKind, ParsedType &ObjectType,
Douglas Gregore610ada2010-02-24 18:44:31 +00004059 bool &MayBePseudoDestructor) {
Douglas Gregorb7bfe792009-09-02 22:59:36 +00004060 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00004061 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00004062 if (Result.isInvalid()) return ExprError();
4063 Base = Result.get();
Mike Stump11289f42009-09-09 15:08:12 +00004064
John McCallb268a282010-08-23 23:25:46 +00004065 QualType BaseType = Base->getType();
Douglas Gregore610ada2010-02-24 18:44:31 +00004066 MayBePseudoDestructor = false;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00004067 if (BaseType->isDependentType()) {
Douglas Gregor41127182009-11-04 22:49:18 +00004068 // If we have a pointer to a dependent type and are using the -> operator,
4069 // the object type is the type that the pointer points to. We might still
4070 // have enough information about that type to do something useful.
4071 if (OpKind == tok::arrow)
4072 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
4073 BaseType = Ptr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004074
John McCallba7bf592010-08-24 05:47:05 +00004075 ObjectType = ParsedType::make(BaseType);
Douglas Gregore610ada2010-02-24 18:44:31 +00004076 MayBePseudoDestructor = true;
John McCallb268a282010-08-23 23:25:46 +00004077 return Owned(Base);
Douglas Gregorb7bfe792009-09-02 22:59:36 +00004078 }
Mike Stump11289f42009-09-09 15:08:12 +00004079
Douglas Gregorb7bfe792009-09-02 22:59:36 +00004080 // C++ [over.match.oper]p8:
Mike Stump11289f42009-09-09 15:08:12 +00004081 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregorb7bfe792009-09-02 22:59:36 +00004082 // returned, with the original second operand.
4083 if (OpKind == tok::arrow) {
John McCallc1538c02009-09-30 01:01:30 +00004084 // The set of types we've considered so far.
John McCallbd0465b2009-09-30 01:30:54 +00004085 llvm::SmallPtrSet<CanQualType,8> CTypes;
Fariborz Jahanianac3005c2009-09-30 17:46:20 +00004086 llvm::SmallVector<SourceLocation, 8> Locations;
John McCallbd0465b2009-09-30 01:30:54 +00004087 CTypes.insert(Context.getCanonicalType(BaseType));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004088
Douglas Gregorb7bfe792009-09-02 22:59:36 +00004089 while (BaseType->isRecordType()) {
John McCallb268a282010-08-23 23:25:46 +00004090 Result = BuildOverloadedArrowExpr(S, Base, OpLoc);
4091 if (Result.isInvalid())
Douglas Gregorb7bfe792009-09-02 22:59:36 +00004092 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00004093 Base = Result.get();
4094 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
Anders Carlssonfbd2d492009-10-13 22:55:59 +00004095 Locations.push_back(OpCall->getDirectCallee()->getLocation());
John McCallb268a282010-08-23 23:25:46 +00004096 BaseType = Base->getType();
John McCallc1538c02009-09-30 01:01:30 +00004097 CanQualType CBaseType = Context.getCanonicalType(BaseType);
John McCallbd0465b2009-09-30 01:30:54 +00004098 if (!CTypes.insert(CBaseType)) {
Fariborz Jahanian10ce9582009-09-30 00:19:41 +00004099 Diag(OpLoc, diag::err_operator_arrow_circular);
Fariborz Jahanianac3005c2009-09-30 17:46:20 +00004100 for (unsigned i = 0; i < Locations.size(); i++)
4101 Diag(Locations[i], diag::note_declared_at);
Fariborz Jahanian10ce9582009-09-30 00:19:41 +00004102 return ExprError();
4103 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +00004104 }
Mike Stump11289f42009-09-09 15:08:12 +00004105
Douglas Gregore4f764f2009-11-20 19:58:21 +00004106 if (BaseType->isPointerType())
4107 BaseType = BaseType->getPointeeType();
4108 }
Mike Stump11289f42009-09-09 15:08:12 +00004109
4110 // We could end up with various non-record types here, such as extended
Douglas Gregorb7bfe792009-09-02 22:59:36 +00004111 // vector types or Objective-C interfaces. Just return early and let
4112 // ActOnMemberReferenceExpr do the work.
Douglas Gregor2b6ca462009-09-03 21:38:09 +00004113 if (!BaseType->isRecordType()) {
4114 // C++ [basic.lookup.classref]p2:
4115 // [...] If the type of the object expression is of pointer to scalar
4116 // type, the unqualified-id is looked up in the context of the complete
4117 // postfix-expression.
Douglas Gregore610ada2010-02-24 18:44:31 +00004118 //
4119 // This also indicates that we should be parsing a
4120 // pseudo-destructor-name.
John McCallba7bf592010-08-24 05:47:05 +00004121 ObjectType = ParsedType();
Douglas Gregore610ada2010-02-24 18:44:31 +00004122 MayBePseudoDestructor = true;
John McCallb268a282010-08-23 23:25:46 +00004123 return Owned(Base);
Douglas Gregor2b6ca462009-09-03 21:38:09 +00004124 }
Mike Stump11289f42009-09-09 15:08:12 +00004125
Douglas Gregor3fad6172009-11-17 05:17:33 +00004126 // The object type must be complete (or dependent).
4127 if (!BaseType->isDependentType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004128 RequireCompleteType(OpLoc, BaseType,
Douglas Gregor3fad6172009-11-17 05:17:33 +00004129 PDiag(diag::err_incomplete_member_access)))
4130 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004131
Douglas Gregor2b6ca462009-09-03 21:38:09 +00004132 // C++ [basic.lookup.classref]p2:
Mike Stump11289f42009-09-09 15:08:12 +00004133 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor3fad6172009-11-17 05:17:33 +00004134 // unqualified-id, and the type of the object expression is of a class
Douglas Gregor2b6ca462009-09-03 21:38:09 +00004135 // type C (or of pointer to a class type C), the unqualified-id is looked
4136 // up in the scope of class C. [...]
John McCallba7bf592010-08-24 05:47:05 +00004137 ObjectType = ParsedType::make(BaseType);
Mike Stump11289f42009-09-09 15:08:12 +00004138 return move(Base);
Douglas Gregorb7bfe792009-09-02 22:59:36 +00004139}
4140
John McCalldadc5752010-08-24 06:29:42 +00004141ExprResult Sema::DiagnoseDtorReference(SourceLocation NameLoc,
John McCallb268a282010-08-23 23:25:46 +00004142 Expr *MemExpr) {
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004143 SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(NameLoc);
John McCallb268a282010-08-23 23:25:46 +00004144 Diag(MemExpr->getLocStart(), diag::err_dtor_expr_without_call)
4145 << isa<CXXPseudoDestructorExpr>(MemExpr)
Douglas Gregora771f462010-03-31 17:46:05 +00004146 << FixItHint::CreateInsertion(ExpectedLParenLoc, "()");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004147
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004148 return ActOnCallExpr(/*Scope*/ 0,
John McCallb268a282010-08-23 23:25:46 +00004149 MemExpr,
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004150 /*LPLoc*/ ExpectedLParenLoc,
John McCallfaf5fb42010-08-26 23:41:50 +00004151 MultiExprArg(),
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004152 /*RPLoc*/ ExpectedLParenLoc);
4153}
Douglas Gregore610ada2010-02-24 18:44:31 +00004154
John McCalldadc5752010-08-24 06:29:42 +00004155ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
John McCalla2c4e722011-02-25 05:21:17 +00004156 SourceLocation OpLoc,
4157 tok::TokenKind OpKind,
4158 const CXXScopeSpec &SS,
4159 TypeSourceInfo *ScopeTypeInfo,
4160 SourceLocation CCLoc,
4161 SourceLocation TildeLoc,
Douglas Gregor678f90d2010-02-25 01:56:36 +00004162 PseudoDestructorTypeStorage Destructed,
John McCalla2c4e722011-02-25 05:21:17 +00004163 bool HasTrailingLParen) {
Douglas Gregor678f90d2010-02-25 01:56:36 +00004164 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004165
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004166 // C++ [expr.pseudo]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004167 // The left-hand side of the dot operator shall be of scalar type. The
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004168 // left-hand side of the arrow operator shall be of pointer to scalar type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004169 // This scalar type is the object type.
John McCallb268a282010-08-23 23:25:46 +00004170 QualType ObjectType = Base->getType();
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004171 if (OpKind == tok::arrow) {
4172 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
4173 ObjectType = Ptr->getPointeeType();
John McCallb268a282010-08-23 23:25:46 +00004174 } else if (!Base->isTypeDependent()) {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004175 // The user wrote "p->" when she probably meant "p."; fix it.
4176 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
4177 << ObjectType << true
Douglas Gregora771f462010-03-31 17:46:05 +00004178 << FixItHint::CreateReplacement(OpLoc, ".");
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004179 if (isSFINAEContext())
4180 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004181
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004182 OpKind = tok::period;
4183 }
4184 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004185
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004186 if (!ObjectType->isDependentType() && !ObjectType->isScalarType()) {
4187 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
John McCallb268a282010-08-23 23:25:46 +00004188 << ObjectType << Base->getSourceRange();
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004189 return ExprError();
4190 }
4191
4192 // C++ [expr.pseudo]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004193 // [...] The cv-unqualified versions of the object type and of the type
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004194 // designated by the pseudo-destructor-name shall be the same type.
Douglas Gregor678f90d2010-02-25 01:56:36 +00004195 if (DestructedTypeInfo) {
4196 QualType DestructedType = DestructedTypeInfo->getType();
4197 SourceLocation DestructedTypeStart
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00004198 = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
John McCall31168b02011-06-15 23:02:42 +00004199 if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) {
4200 if (!Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
4201 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
4202 << ObjectType << DestructedType << Base->getSourceRange()
4203 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004204
John McCall31168b02011-06-15 23:02:42 +00004205 // Recover by setting the destructed type to the object type.
4206 DestructedType = ObjectType;
4207 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
Douglas Gregor678f90d2010-02-25 01:56:36 +00004208 DestructedTypeStart);
John McCall31168b02011-06-15 23:02:42 +00004209 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
4210 } else if (DestructedType.getObjCLifetime() !=
4211 ObjectType.getObjCLifetime()) {
4212
4213 if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) {
4214 // Okay: just pretend that the user provided the correctly-qualified
4215 // type.
4216 } else {
4217 Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals)
4218 << ObjectType << DestructedType << Base->getSourceRange()
4219 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
4220 }
4221
4222 // Recover by setting the destructed type to the object type.
4223 DestructedType = ObjectType;
4224 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
4225 DestructedTypeStart);
4226 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
4227 }
Douglas Gregor678f90d2010-02-25 01:56:36 +00004228 }
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004229 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004230
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004231 // C++ [expr.pseudo]p2:
4232 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
4233 // form
4234 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004235 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004236 //
4237 // shall designate the same scalar type.
4238 if (ScopeTypeInfo) {
4239 QualType ScopeType = ScopeTypeInfo->getType();
4240 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
John McCallb86a6b82010-06-11 17:36:40 +00004241 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004242
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00004243 Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004244 diag::err_pseudo_dtor_type_mismatch)
John McCallb268a282010-08-23 23:25:46 +00004245 << ObjectType << ScopeType << Base->getSourceRange()
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00004246 << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004247
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004248 ScopeType = QualType();
4249 ScopeTypeInfo = 0;
4250 }
4251 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004252
John McCallb268a282010-08-23 23:25:46 +00004253 Expr *Result
4254 = new (Context) CXXPseudoDestructorExpr(Context, Base,
4255 OpKind == tok::arrow, OpLoc,
Douglas Gregora6ce6082011-02-25 18:19:59 +00004256 SS.getWithLocInContext(Context),
John McCallb268a282010-08-23 23:25:46 +00004257 ScopeTypeInfo,
4258 CCLoc,
4259 TildeLoc,
4260 Destructed);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004261
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004262 if (HasTrailingLParen)
John McCallb268a282010-08-23 23:25:46 +00004263 return Owned(Result);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004264
John McCallb268a282010-08-23 23:25:46 +00004265 return DiagnoseDtorReference(Destructed.getLocation(), Result);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004266}
4267
John McCalldadc5752010-08-24 06:29:42 +00004268ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
John McCalla2c4e722011-02-25 05:21:17 +00004269 SourceLocation OpLoc,
4270 tok::TokenKind OpKind,
4271 CXXScopeSpec &SS,
4272 UnqualifiedId &FirstTypeName,
4273 SourceLocation CCLoc,
4274 SourceLocation TildeLoc,
4275 UnqualifiedId &SecondTypeName,
4276 bool HasTrailingLParen) {
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004277 assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
4278 FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
4279 "Invalid first type name in pseudo-destructor");
4280 assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
4281 SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
4282 "Invalid second type name in pseudo-destructor");
4283
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004284 // C++ [expr.pseudo]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004285 // The left-hand side of the dot operator shall be of scalar type. The
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004286 // left-hand side of the arrow operator shall be of pointer to scalar type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004287 // This scalar type is the object type.
John McCallb268a282010-08-23 23:25:46 +00004288 QualType ObjectType = Base->getType();
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004289 if (OpKind == tok::arrow) {
4290 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
4291 ObjectType = Ptr->getPointeeType();
Douglas Gregor678f90d2010-02-25 01:56:36 +00004292 } else if (!ObjectType->isDependentType()) {
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004293 // The user wrote "p->" when she probably meant "p."; fix it.
4294 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
Douglas Gregor678f90d2010-02-25 01:56:36 +00004295 << ObjectType << true
Douglas Gregora771f462010-03-31 17:46:05 +00004296 << FixItHint::CreateReplacement(OpLoc, ".");
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004297 if (isSFINAEContext())
4298 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004299
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004300 OpKind = tok::period;
4301 }
4302 }
Douglas Gregor678f90d2010-02-25 01:56:36 +00004303
4304 // Compute the object type that we should use for name lookup purposes. Only
4305 // record types and dependent types matter.
John McCallba7bf592010-08-24 05:47:05 +00004306 ParsedType ObjectTypePtrForLookup;
Douglas Gregor678f90d2010-02-25 01:56:36 +00004307 if (!SS.isSet()) {
John McCalla2c4e722011-02-25 05:21:17 +00004308 if (ObjectType->isRecordType())
4309 ObjectTypePtrForLookup = ParsedType::make(ObjectType);
John McCallba7bf592010-08-24 05:47:05 +00004310 else if (ObjectType->isDependentType())
4311 ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
Douglas Gregor678f90d2010-02-25 01:56:36 +00004312 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004313
4314 // Convert the name of the type being destructed (following the ~) into a
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004315 // type (with source-location information).
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004316 QualType DestructedType;
4317 TypeSourceInfo *DestructedTypeInfo = 0;
Douglas Gregor678f90d2010-02-25 01:56:36 +00004318 PseudoDestructorTypeStorage Destructed;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004319 if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004320 ParsedType T = getTypeName(*SecondTypeName.Identifier,
John McCallba7bf592010-08-24 05:47:05 +00004321 SecondTypeName.StartLocation,
Fariborz Jahanian87967422011-02-08 18:05:59 +00004322 S, &SS, true, false, ObjectTypePtrForLookup);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004323 if (!T &&
Douglas Gregor678f90d2010-02-25 01:56:36 +00004324 ((SS.isSet() && !computeDeclContext(SS, false)) ||
4325 (!SS.isSet() && ObjectType->isDependentType()))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004326 // The name of the type being destroyed is a dependent name, and we
Douglas Gregor678f90d2010-02-25 01:56:36 +00004327 // couldn't find anything useful in scope. Just store the identifier and
4328 // it's location, and we'll perform (qualified) name lookup again at
4329 // template instantiation time.
4330 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
4331 SecondTypeName.StartLocation);
4332 } else if (!T) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004333 Diag(SecondTypeName.StartLocation,
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004334 diag::err_pseudo_dtor_destructor_non_type)
4335 << SecondTypeName.Identifier << ObjectType;
4336 if (isSFINAEContext())
4337 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004338
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004339 // Recover by assuming we had the right type all along.
4340 DestructedType = ObjectType;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004341 } else
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004342 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004343 } else {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004344 // Resolve the template-id to a type.
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004345 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004346 ASTTemplateArgsPtr TemplateArgsPtr(*this,
4347 TemplateId->getTemplateArgs(),
4348 TemplateId->NumArgs);
Douglas Gregore7c20652011-03-02 00:47:37 +00004349 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
4350 TemplateId->Template,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004351 TemplateId->TemplateNameLoc,
4352 TemplateId->LAngleLoc,
4353 TemplateArgsPtr,
4354 TemplateId->RAngleLoc);
4355 if (T.isInvalid() || !T.get()) {
4356 // Recover by assuming we had the right type all along.
4357 DestructedType = ObjectType;
4358 } else
4359 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004360 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004361
4362 // If we've performed some kind of recovery, (re-)build the type source
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004363 // information.
Douglas Gregor678f90d2010-02-25 01:56:36 +00004364 if (!DestructedType.isNull()) {
4365 if (!DestructedTypeInfo)
4366 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004367 SecondTypeName.StartLocation);
Douglas Gregor678f90d2010-02-25 01:56:36 +00004368 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
4369 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004370
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004371 // Convert the name of the scope type (the type prior to '::') into a type.
4372 TypeSourceInfo *ScopeTypeInfo = 0;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004373 QualType ScopeType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004374 if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004375 FirstTypeName.Identifier) {
4376 if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004377 ParsedType T = getTypeName(*FirstTypeName.Identifier,
John McCallba7bf592010-08-24 05:47:05 +00004378 FirstTypeName.StartLocation,
Douglas Gregora6ce6082011-02-25 18:19:59 +00004379 S, &SS, true, false, ObjectTypePtrForLookup);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004380 if (!T) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004381 Diag(FirstTypeName.StartLocation,
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004382 diag::err_pseudo_dtor_destructor_non_type)
4383 << FirstTypeName.Identifier << ObjectType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004384
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004385 if (isSFINAEContext())
4386 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004387
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004388 // Just drop this type. It's unnecessary anyway.
4389 ScopeType = QualType();
4390 } else
4391 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004392 } else {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004393 // Resolve the template-id to a type.
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004394 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004395 ASTTemplateArgsPtr TemplateArgsPtr(*this,
4396 TemplateId->getTemplateArgs(),
4397 TemplateId->NumArgs);
Douglas Gregore7c20652011-03-02 00:47:37 +00004398 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
4399 TemplateId->Template,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004400 TemplateId->TemplateNameLoc,
4401 TemplateId->LAngleLoc,
4402 TemplateArgsPtr,
4403 TemplateId->RAngleLoc);
4404 if (T.isInvalid() || !T.get()) {
4405 // Recover by dropping this type.
4406 ScopeType = QualType();
4407 } else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004408 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004409 }
4410 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004411
Douglas Gregor90ad9222010-02-24 23:02:30 +00004412 if (!ScopeType.isNull() && !ScopeTypeInfo)
4413 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
4414 FirstTypeName.StartLocation);
4415
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004416
John McCallb268a282010-08-23 23:25:46 +00004417 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
Douglas Gregorcdbd5152010-02-24 23:50:37 +00004418 ScopeTypeInfo, CCLoc, TildeLoc,
Douglas Gregor678f90d2010-02-25 01:56:36 +00004419 Destructed, HasTrailingLParen);
Douglas Gregore610ada2010-02-24 18:44:31 +00004420}
4421
John Wiegley01296292011-04-08 18:41:53 +00004422ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,
Douglas Gregor668443e2011-01-20 00:18:04 +00004423 CXXMethodDecl *Method) {
John Wiegley01296292011-04-08 18:41:53 +00004424 ExprResult Exp = PerformObjectArgumentInitialization(E, /*Qualifier=*/0,
4425 FoundDecl, Method);
4426 if (Exp.isInvalid())
Douglas Gregor668443e2011-01-20 00:18:04 +00004427 return true;
Eli Friedmanf7195532009-12-09 04:53:56 +00004428
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004429 MemberExpr *ME =
John Wiegley01296292011-04-08 18:41:53 +00004430 new (Context) MemberExpr(Exp.take(), /*IsArrow=*/false, Method,
John McCall7decc9e2010-11-18 06:31:45 +00004431 SourceLocation(), Method->getType(),
4432 VK_RValue, OK_Ordinary);
4433 QualType ResultType = Method->getResultType();
4434 ExprValueKind VK = Expr::getValueKindForType(ResultType);
4435 ResultType = ResultType.getNonLValueExprType(Context);
4436
John Wiegley01296292011-04-08 18:41:53 +00004437 MarkDeclarationReferenced(Exp.get()->getLocStart(), Method);
Douglas Gregor27381f32009-11-23 12:27:39 +00004438 CXXMemberCallExpr *CE =
John McCall7decc9e2010-11-18 06:31:45 +00004439 new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType, VK,
John Wiegley01296292011-04-08 18:41:53 +00004440 Exp.get()->getLocEnd());
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00004441 return CE;
4442}
4443
Sebastian Redl4202c0f2010-09-10 20:55:43 +00004444ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
4445 SourceLocation RParen) {
Sebastian Redl4202c0f2010-09-10 20:55:43 +00004446 return Owned(new (Context) CXXNoexceptExpr(Context.BoolTy, Operand,
4447 Operand->CanThrow(Context),
4448 KeyLoc, RParen));
4449}
4450
4451ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,
4452 Expr *Operand, SourceLocation RParen) {
4453 return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
Sebastian Redl22e3a932010-09-10 20:55:37 +00004454}
4455
John McCall34376a62010-12-04 03:47:34 +00004456/// Perform the conversions required for an expression used in a
4457/// context that ignores the result.
John Wiegley01296292011-04-08 18:41:53 +00004458ExprResult Sema::IgnoredValueConversions(Expr *E) {
John McCallfee942d2010-12-02 02:07:15 +00004459 // C99 6.3.2.1:
4460 // [Except in specific positions,] an lvalue that does not have
4461 // array type is converted to the value stored in the
4462 // designated object (and is no longer an lvalue).
John McCalld68b2d02011-06-27 21:24:11 +00004463 if (E->isRValue()) {
4464 // In C, function designators (i.e. expressions of function type)
4465 // are r-values, but we still want to do function-to-pointer decay
4466 // on them. This is both technically correct and convenient for
4467 // some clients.
4468 if (!getLangOptions().CPlusPlus && E->getType()->isFunctionType())
4469 return DefaultFunctionArrayConversion(E);
4470
4471 return Owned(E);
4472 }
John McCallfee942d2010-12-02 02:07:15 +00004473
John McCall34376a62010-12-04 03:47:34 +00004474 // We always want to do this on ObjC property references.
4475 if (E->getObjectKind() == OK_ObjCProperty) {
John Wiegley01296292011-04-08 18:41:53 +00004476 ExprResult Res = ConvertPropertyForRValue(E);
4477 if (Res.isInvalid()) return Owned(E);
4478 E = Res.take();
4479 if (E->isRValue()) return Owned(E);
John McCall34376a62010-12-04 03:47:34 +00004480 }
4481
4482 // Otherwise, this rule does not apply in C++, at least not for the moment.
John Wiegley01296292011-04-08 18:41:53 +00004483 if (getLangOptions().CPlusPlus) return Owned(E);
John McCall34376a62010-12-04 03:47:34 +00004484
4485 // GCC seems to also exclude expressions of incomplete enum type.
4486 if (const EnumType *T = E->getType()->getAs<EnumType>()) {
4487 if (!T->getDecl()->isComplete()) {
4488 // FIXME: stupid workaround for a codegen bug!
John Wiegley01296292011-04-08 18:41:53 +00004489 E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).take();
4490 return Owned(E);
John McCall34376a62010-12-04 03:47:34 +00004491 }
4492 }
4493
John Wiegley01296292011-04-08 18:41:53 +00004494 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
4495 if (Res.isInvalid())
4496 return Owned(E);
4497 E = Res.take();
4498
John McCallca61b652010-12-04 12:29:11 +00004499 if (!E->getType()->isVoidType())
4500 RequireCompleteType(E->getExprLoc(), E->getType(),
4501 diag::err_incomplete_type);
John Wiegley01296292011-04-08 18:41:53 +00004502 return Owned(E);
John McCall34376a62010-12-04 03:47:34 +00004503}
4504
John Wiegley01296292011-04-08 18:41:53 +00004505ExprResult Sema::ActOnFinishFullExpr(Expr *FE) {
4506 ExprResult FullExpr = Owned(FE);
4507
4508 if (!FullExpr.get())
Douglas Gregora6e053e2010-12-15 01:34:56 +00004509 return ExprError();
John McCall34376a62010-12-04 03:47:34 +00004510
John Wiegley01296292011-04-08 18:41:53 +00004511 if (DiagnoseUnexpandedParameterPack(FullExpr.get()))
Douglas Gregor506bd562010-12-13 22:49:22 +00004512 return ExprError();
4513
John McCall3aef3d82011-04-10 19:13:55 +00004514 FullExpr = CheckPlaceholderExpr(FullExpr.take());
4515 if (FullExpr.isInvalid())
4516 return ExprError();
Douglas Gregor0ec210b2011-03-07 02:05:23 +00004517
John Wiegley01296292011-04-08 18:41:53 +00004518 FullExpr = IgnoredValueConversions(FullExpr.take());
4519 if (FullExpr.isInvalid())
4520 return ExprError();
4521
4522 CheckImplicitConversions(FullExpr.get());
John McCall5d413782010-12-06 08:20:24 +00004523 return MaybeCreateExprWithCleanups(FullExpr);
Anders Carlsson85a307d2009-05-17 18:41:29 +00004524}
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00004525
4526StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) {
4527 if (!FullStmt) return StmtError();
4528
John McCall5d413782010-12-06 08:20:24 +00004529 return MaybeCreateStmtWithCleanups(FullStmt);
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00004530}
Francois Pichet4a7de3e2011-05-06 20:48:22 +00004531
4532bool Sema::CheckMicrosoftIfExistsSymbol(CXXScopeSpec &SS,
4533 UnqualifiedId &Name) {
4534 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
4535 DeclarationName TargetName = TargetNameInfo.getName();
4536 if (!TargetName)
4537 return false;
4538
4539 // Do the redeclaration lookup in the current scope.
4540 LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName,
4541 Sema::NotForRedeclaration);
4542 R.suppressDiagnostics();
4543 LookupParsedName(R, getCurScope(), &SS);
4544 return !R.empty();
4545}