blob: 4bc4ca1e94d68a722b3cba724492b0e3287ff505 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Douglas Gregor20093b42009-12-09 23:02:17 +000015#include "SemaInit.h"
John McCall7d384dd2009-11-18 07:57:50 +000016#include "Lookup.h"
Steve Naroff210679c2007-08-25 14:02:58 +000017#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000018#include "clang/AST/CXXInheritance.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000019#include "clang/AST/ExprCXX.h"
Douglas Gregorb57fb492010-02-24 22:38:50 +000020#include "clang/AST/TypeLoc.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000021#include "clang/Basic/PartialDiagnostic.h"
Sebastian Redlb5a57a62008-12-03 20:26:15 +000022#include "clang/Basic/TargetInfo.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000023#include "clang/Lex/Preprocessor.h"
24#include "clang/Parse/DeclSpec.h"
Douglas Gregord4dca082010-02-24 18:44:31 +000025#include "clang/Parse/Template.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000026#include "llvm/ADT/STLExtras.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000027using namespace clang;
28
Douglas Gregor124b8782010-02-16 19:09:40 +000029Action::TypeTy *Sema::getDestructorName(SourceLocation TildeLoc,
30 IdentifierInfo &II,
31 SourceLocation NameLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +000032 Scope *S, CXXScopeSpec &SS,
Douglas Gregor124b8782010-02-16 19:09:40 +000033 TypeTy *ObjectTypePtr,
34 bool EnteringContext) {
35 // Determine where to perform name lookup.
36
37 // FIXME: This area of the standard is very messy, and the current
38 // wording is rather unclear about which scopes we search for the
39 // destructor name; see core issues 399 and 555. Issue 399 in
40 // particular shows where the current description of destructor name
41 // lookup is completely out of line with existing practice, e.g.,
42 // this appears to be ill-formed:
43 //
44 // namespace N {
45 // template <typename T> struct S {
46 // ~S();
47 // };
48 // }
49 //
50 // void f(N::S<int>* s) {
51 // s->N::S<int>::~S();
52 // }
53 //
Douglas Gregor93649fd2010-02-23 00:15:22 +000054 // See also PR6358 and PR6359.
Douglas Gregor124b8782010-02-16 19:09:40 +000055 QualType SearchType;
56 DeclContext *LookupCtx = 0;
57 bool isDependent = false;
58 bool LookInScope = false;
59
60 // If we have an object type, it's because we are in a
61 // pseudo-destructor-expression or a member access expression, and
62 // we know what type we're looking for.
63 if (ObjectTypePtr)
64 SearchType = GetTypeFromParser(ObjectTypePtr);
65
66 if (SS.isSet()) {
Douglas Gregor93649fd2010-02-23 00:15:22 +000067 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
68
69 bool AlreadySearched = false;
70 bool LookAtPrefix = true;
71 if (!getLangOptions().CPlusPlus0x) {
72 // C++ [basic.lookup.qual]p6:
73 // If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier,
74 // the type-names are looked up as types in the scope designated by the
75 // nested-name-specifier. In a qualified-id of the form:
76 //
77 // ::[opt] nested-name-specifier ̃ class-name
78 //
79 // where the nested-name-specifier designates a namespace scope, and in
80 // a qualified-id of the form:
81 //
82 // ::opt nested-name-specifier class-name :: ̃ class-name
83 //
84 // the class-names are looked up as types in the scope designated by
85 // the nested-name-specifier.
86 //
87 // Here, we check the first case (completely) and determine whether the
88 // code below is permitted to look at the prefix of the
89 // nested-name-specifier (as we do in C++0x).
90 DeclContext *DC = computeDeclContext(SS, EnteringContext);
91 if (DC && DC->isFileContext()) {
92 AlreadySearched = true;
93 LookupCtx = DC;
94 isDependent = false;
95 } else if (DC && isa<CXXRecordDecl>(DC))
96 LookAtPrefix = false;
97 }
98
99 // C++0x [basic.lookup.qual]p6:
Douglas Gregor124b8782010-02-16 19:09:40 +0000100 // If a pseudo-destructor-name (5.2.4) contains a
101 // nested-name-specifier, the type-names are looked up as types
102 // in the scope designated by the nested-name-specifier. Similarly, in
Chandler Carruth5e895a82010-02-21 10:19:54 +0000103 // a qualified-id of the form:
Douglas Gregor124b8782010-02-16 19:09:40 +0000104 //
105 // :: [opt] nested-name-specifier[opt] class-name :: ~class-name
106 //
107 // the second class-name is looked up in the same scope as the first.
108 //
Douglas Gregor93649fd2010-02-23 00:15:22 +0000109 // To implement this, we look at the prefix of the
110 // nested-name-specifier we were given, and determine the lookup
111 // context from that.
112 //
113 // We also fold in the second case from the C++03 rules quoted further
114 // above.
115 NestedNameSpecifier *Prefix = 0;
116 if (AlreadySearched) {
117 // Nothing left to do.
118 } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) {
119 CXXScopeSpec PrefixSS;
120 PrefixSS.setScopeRep(Prefix);
121 LookupCtx = computeDeclContext(PrefixSS, EnteringContext);
122 isDependent = isDependentScopeSpecifier(PrefixSS);
123 } else if (getLangOptions().CPlusPlus0x &&
124 (LookupCtx = computeDeclContext(SS, EnteringContext))) {
125 if (!LookupCtx->isTranslationUnit())
126 LookupCtx = LookupCtx->getParent();
127 isDependent = LookupCtx && LookupCtx->isDependentContext();
128 } else if (ObjectTypePtr) {
Douglas Gregor124b8782010-02-16 19:09:40 +0000129 LookupCtx = computeDeclContext(SearchType);
130 isDependent = SearchType->isDependentType();
131 } else {
132 LookupCtx = computeDeclContext(SS, EnteringContext);
Douglas Gregor93649fd2010-02-23 00:15:22 +0000133 isDependent = LookupCtx && LookupCtx->isDependentContext();
Douglas Gregor124b8782010-02-16 19:09:40 +0000134 }
Douglas Gregor93649fd2010-02-23 00:15:22 +0000135
Douglas Gregoredc90502010-02-25 04:46:04 +0000136 LookInScope = false;
Douglas Gregor124b8782010-02-16 19:09:40 +0000137 } else if (ObjectTypePtr) {
138 // C++ [basic.lookup.classref]p3:
139 // If the unqualified-id is ~type-name, the type-name is looked up
140 // in the context of the entire postfix-expression. If the type T
141 // of the object expression is of a class type C, the type-name is
142 // also looked up in the scope of class C. At least one of the
143 // lookups shall find a name that refers to (possibly
144 // cv-qualified) T.
145 LookupCtx = computeDeclContext(SearchType);
146 isDependent = SearchType->isDependentType();
147 assert((isDependent || !SearchType->isIncompleteType()) &&
148 "Caller should have completed object type");
149
150 LookInScope = true;
151 } else {
152 // Perform lookup into the current scope (only).
153 LookInScope = true;
154 }
155
156 LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName);
157 for (unsigned Step = 0; Step != 2; ++Step) {
158 // Look for the name first in the computed lookup context (if we
159 // have one) and, if that fails to find a match, in the sope (if
160 // we're allowed to look there).
161 Found.clear();
162 if (Step == 0 && LookupCtx)
163 LookupQualifiedName(Found, LookupCtx);
Douglas Gregora2e7dd22010-02-25 01:56:36 +0000164 else if (Step == 1 && LookInScope && S)
Douglas Gregor124b8782010-02-16 19:09:40 +0000165 LookupName(Found, S);
166 else
167 continue;
168
169 // FIXME: Should we be suppressing ambiguities here?
170 if (Found.isAmbiguous())
171 return 0;
172
173 if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
174 QualType T = Context.getTypeDeclType(Type);
Douglas Gregor124b8782010-02-16 19:09:40 +0000175
176 if (SearchType.isNull() || SearchType->isDependentType() ||
177 Context.hasSameUnqualifiedType(T, SearchType)) {
178 // We found our type!
179
180 return T.getAsOpaquePtr();
181 }
182 }
183
184 // If the name that we found is a class template name, and it is
185 // the same name as the template name in the last part of the
186 // nested-name-specifier (if present) or the object type, then
187 // this is the destructor for that class.
188 // FIXME: This is a workaround until we get real drafting for core
189 // issue 399, for which there isn't even an obvious direction.
190 if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) {
191 QualType MemberOfType;
192 if (SS.isSet()) {
193 if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) {
194 // Figure out the type of the context, if it has one.
John McCall3cb0ebd2010-03-10 03:28:59 +0000195 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx))
196 MemberOfType = Context.getTypeDeclType(Record);
Douglas Gregor124b8782010-02-16 19:09:40 +0000197 }
198 }
199 if (MemberOfType.isNull())
200 MemberOfType = SearchType;
201
202 if (MemberOfType.isNull())
203 continue;
204
205 // We're referring into a class template specialization. If the
206 // class template we found is the same as the template being
207 // specialized, we found what we are looking for.
208 if (const RecordType *Record = MemberOfType->getAs<RecordType>()) {
209 if (ClassTemplateSpecializationDecl *Spec
210 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
211 if (Spec->getSpecializedTemplate()->getCanonicalDecl() ==
212 Template->getCanonicalDecl())
213 return MemberOfType.getAsOpaquePtr();
214 }
215
216 continue;
217 }
218
219 // We're referring to an unresolved class template
220 // specialization. Determine whether we class template we found
221 // is the same as the template being specialized or, if we don't
222 // know which template is being specialized, that it at least
223 // has the same name.
224 if (const TemplateSpecializationType *SpecType
225 = MemberOfType->getAs<TemplateSpecializationType>()) {
226 TemplateName SpecName = SpecType->getTemplateName();
227
228 // The class template we found is the same template being
229 // specialized.
230 if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) {
231 if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl())
232 return MemberOfType.getAsOpaquePtr();
233
234 continue;
235 }
236
237 // The class template we found has the same name as the
238 // (dependent) template name being specialized.
239 if (DependentTemplateName *DepTemplate
240 = SpecName.getAsDependentTemplateName()) {
241 if (DepTemplate->isIdentifier() &&
242 DepTemplate->getIdentifier() == Template->getIdentifier())
243 return MemberOfType.getAsOpaquePtr();
244
245 continue;
246 }
247 }
248 }
249 }
250
251 if (isDependent) {
252 // We didn't find our type, but that's okay: it's dependent
253 // anyway.
254 NestedNameSpecifier *NNS = 0;
255 SourceRange Range;
256 if (SS.isSet()) {
257 NNS = (NestedNameSpecifier *)SS.getScopeRep();
258 Range = SourceRange(SS.getRange().getBegin(), NameLoc);
259 } else {
260 NNS = NestedNameSpecifier::Create(Context, &II);
261 Range = SourceRange(NameLoc);
262 }
263
Abramo Bagnarae4da7a02010-05-19 21:37:53 +0000264 return CheckTypenameType(ETK_None, NNS, II, SourceLocation(),
265 Range, NameLoc).getAsOpaquePtr();
Douglas Gregor124b8782010-02-16 19:09:40 +0000266 }
267
268 if (ObjectTypePtr)
269 Diag(NameLoc, diag::err_ident_in_pseudo_dtor_not_a_type)
270 << &II;
271 else
272 Diag(NameLoc, diag::err_destructor_class_name);
273
274 return 0;
275}
276
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000277/// \brief Build a C++ typeid expression with a type operand.
278Sema::OwningExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
279 SourceLocation TypeidLoc,
280 TypeSourceInfo *Operand,
281 SourceLocation RParenLoc) {
282 // C++ [expr.typeid]p4:
283 // The top-level cv-qualifiers of the lvalue expression or the type-id
284 // that is the operand of typeid are always ignored.
285 // If the type of the type-id is a class type or a reference to a class
286 // type, the class shall be completely-defined.
287 QualType T = Operand->getType().getNonReferenceType();
288 if (T->getAs<RecordType>() &&
289 RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
290 return ExprError();
Daniel Dunbar380c2132010-05-11 21:32:35 +0000291
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000292 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
293 Operand,
294 SourceRange(TypeidLoc, RParenLoc)));
295}
296
297/// \brief Build a C++ typeid expression with an expression operand.
298Sema::OwningExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
299 SourceLocation TypeidLoc,
300 ExprArg Operand,
301 SourceLocation RParenLoc) {
302 bool isUnevaluatedOperand = true;
303 Expr *E = static_cast<Expr *>(Operand.get());
304 if (E && !E->isTypeDependent()) {
305 QualType T = E->getType();
306 if (const RecordType *RecordT = T->getAs<RecordType>()) {
307 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
308 // C++ [expr.typeid]p3:
309 // [...] If the type of the expression is a class type, the class
310 // shall be completely-defined.
311 if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
312 return ExprError();
313
314 // C++ [expr.typeid]p3:
315 // When typeid is applied to an expression other than an lvalue of a
316 // polymorphic class type [...] [the] expression is an unevaluated
317 // operand. [...]
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000318 if (RecordD->isPolymorphic() && E->isLvalue(Context) == Expr::LV_Valid) {
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000319 isUnevaluatedOperand = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000320
321 // We require a vtable to query the type at run time.
322 MarkVTableUsed(TypeidLoc, RecordD);
323 }
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000324 }
325
326 // C++ [expr.typeid]p4:
327 // [...] If the type of the type-id is a reference to a possibly
328 // cv-qualified type, the result of the typeid expression refers to a
329 // std::type_info object representing the cv-unqualified referenced
330 // type.
331 if (T.hasQualifiers()) {
332 ImpCastExprToType(E, T.getUnqualifiedType(), CastExpr::CK_NoOp,
333 E->isLvalue(Context));
334 Operand.release();
335 Operand = Owned(E);
336 }
337 }
338
339 // If this is an unevaluated operand, clear out the set of
340 // declaration references we have been computing and eliminate any
341 // temporaries introduced in its computation.
342 if (isUnevaluatedOperand)
343 ExprEvalContexts.back().Context = Unevaluated;
344
345 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
346 Operand.takeAs<Expr>(),
347 SourceRange(TypeidLoc, RParenLoc)));
348}
349
350/// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
Sebastian Redlf53597f2009-03-15 17:47:39 +0000351Action::OwningExprResult
Sebastian Redlc42e1182008-11-11 11:37:55 +0000352Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
353 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000354 // Find the std::type_info type.
Douglas Gregor7adb10f2009-09-15 22:30:29 +0000355 if (!StdNamespace)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000356 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000357
Chris Lattner572af492008-11-20 05:51:55 +0000358 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
John McCalla24dc2e2009-11-17 02:14:36 +0000359 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
360 LookupQualifiedName(R, StdNamespace);
John McCall1bcee0a2009-12-02 08:25:40 +0000361 RecordDecl *TypeInfoRecordDecl = R.getAsSingle<RecordDecl>();
Chris Lattner572af492008-11-20 05:51:55 +0000362 if (!TypeInfoRecordDecl)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000363 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000364
Sebastian Redlc42e1182008-11-11 11:37:55 +0000365 QualType TypeInfoType = Context.getTypeDeclType(TypeInfoRecordDecl);
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000366
367 if (isType) {
368 // The operand is a type; handle it as such.
369 TypeSourceInfo *TInfo = 0;
370 QualType T = GetTypeFromParser(TyOrExpr, &TInfo);
371 if (T.isNull())
372 return ExprError();
373
374 if (!TInfo)
375 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
Sebastian Redlc42e1182008-11-11 11:37:55 +0000376
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000377 return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000378 }
Mike Stump1eb44332009-09-09 15:08:12 +0000379
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000380 // The operand is an expression.
381 return BuildCXXTypeId(TypeInfoType, OpLoc, Owned((Expr*)TyOrExpr), RParenLoc);
Sebastian Redlc42e1182008-11-11 11:37:55 +0000382}
383
Steve Naroff1b273c42007-09-16 14:56:35 +0000384/// ActOnCXXBoolLiteral - Parse {true,false} literals.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000385Action::OwningExprResult
Steve Naroff1b273c42007-09-16 14:56:35 +0000386Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor2f639b92008-10-24 15:36:09 +0000387 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000388 "Unknown C++ Boolean value!");
Sebastian Redlf53597f2009-03-15 17:47:39 +0000389 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
390 Context.BoolTy, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000391}
Chris Lattner50dd2892008-02-26 00:51:44 +0000392
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000393/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
394Action::OwningExprResult
395Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
396 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
397}
398
Chris Lattner50dd2892008-02-26 00:51:44 +0000399/// ActOnCXXThrow - Parse throw expressions.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000400Action::OwningExprResult
401Sema::ActOnCXXThrow(SourceLocation OpLoc, ExprArg E) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000402 Expr *Ex = E.takeAs<Expr>();
403 if (Ex && !Ex->isTypeDependent() && CheckCXXThrowOperand(OpLoc, Ex))
404 return ExprError();
405 return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc));
406}
407
408/// CheckCXXThrowOperand - Validate the operand of a throw.
409bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *&E) {
410 // C++ [except.throw]p3:
Douglas Gregor154fe982009-12-23 22:04:40 +0000411 // A throw-expression initializes a temporary object, called the exception
412 // object, the type of which is determined by removing any top-level
413 // cv-qualifiers from the static type of the operand of throw and adjusting
414 // the type from "array of T" or "function returning T" to "pointer to T"
415 // or "pointer to function returning T", [...]
416 if (E->getType().hasQualifiers())
417 ImpCastExprToType(E, E->getType().getUnqualifiedType(), CastExpr::CK_NoOp,
418 E->isLvalue(Context) == Expr::LV_Valid);
419
Sebastian Redl972041f2009-04-27 20:27:31 +0000420 DefaultFunctionArrayConversion(E);
421
422 // If the type of the exception would be an incomplete type or a pointer
423 // to an incomplete type other than (cv) void the program is ill-formed.
424 QualType Ty = E->getType();
John McCallac418162010-04-22 01:10:34 +0000425 bool isPointer = false;
Ted Kremenek6217b802009-07-29 21:53:49 +0000426 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000427 Ty = Ptr->getPointeeType();
John McCallac418162010-04-22 01:10:34 +0000428 isPointer = true;
Sebastian Redl972041f2009-04-27 20:27:31 +0000429 }
430 if (!isPointer || !Ty->isVoidType()) {
431 if (RequireCompleteType(ThrowLoc, Ty,
Anders Carlssond497ba72009-08-26 22:59:12 +0000432 PDiag(isPointer ? diag::err_throw_incomplete_ptr
433 : diag::err_throw_incomplete)
434 << E->getSourceRange()))
Sebastian Redl972041f2009-04-27 20:27:31 +0000435 return true;
Rafael Espindola7b9a5aa2010-03-02 21:28:26 +0000436
Douglas Gregorbf422f92010-04-15 18:05:39 +0000437 if (RequireNonAbstractType(ThrowLoc, E->getType(),
438 PDiag(diag::err_throw_abstract_type)
439 << E->getSourceRange()))
440 return true;
Sebastian Redl972041f2009-04-27 20:27:31 +0000441 }
442
John McCallac418162010-04-22 01:10:34 +0000443 // Initialize the exception result. This implicitly weeds out
444 // abstract types or types with inaccessible copy constructors.
Douglas Gregor3c9034c2010-05-15 00:13:29 +0000445 // FIXME: Determine whether we can elide this copy per C++0x [class.copy]p34.
John McCallac418162010-04-22 01:10:34 +0000446 InitializedEntity Entity =
Douglas Gregor3c9034c2010-05-15 00:13:29 +0000447 InitializedEntity::InitializeException(ThrowLoc, E->getType(),
448 /*NRVO=*/false);
John McCallac418162010-04-22 01:10:34 +0000449 OwningExprResult Res = PerformCopyInitialization(Entity,
450 SourceLocation(),
451 Owned(E));
452 if (Res.isInvalid())
453 return true;
454 E = Res.takeAs<Expr>();
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000455
456 // If we are throwing a polymorphic class type or pointer thereof,
457 // exception handling will make use of the vtable.
458 if (const RecordType *RecordTy = Ty->getAs<RecordType>())
459 MarkVTableUsed(ThrowLoc, cast<CXXRecordDecl>(RecordTy->getDecl()));
460
Sebastian Redl972041f2009-04-27 20:27:31 +0000461 return false;
Chris Lattner50dd2892008-02-26 00:51:44 +0000462}
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000463
Sebastian Redlf53597f2009-03-15 17:47:39 +0000464Action::OwningExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000465 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
466 /// is a non-lvalue expression whose value is the address of the object for
467 /// which the function is called.
468
John McCallea1471e2010-05-20 01:18:31 +0000469 DeclContext *DC = getFunctionLevelDeclContext();
470 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC))
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000471 if (MD->isInstance())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000472 return Owned(new (Context) CXXThisExpr(ThisLoc,
Douglas Gregor828a1972010-01-07 23:12:05 +0000473 MD->getThisType(Context),
474 /*isImplicit=*/false));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000475
Sebastian Redlf53597f2009-03-15 17:47:39 +0000476 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000477}
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000478
479/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
480/// Can be interpreted either as function-style casting ("int(x)")
481/// or class type construction ("ClassType(x,y,z)")
482/// or creation of a value-initialized type ("int()").
Sebastian Redlf53597f2009-03-15 17:47:39 +0000483Action::OwningExprResult
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000484Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep,
485 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000486 MultiExprArg exprs,
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000487 SourceLocation *CommaLocs,
488 SourceLocation RParenLoc) {
Douglas Gregorae4c77d2010-02-05 19:11:37 +0000489 if (!TypeRep)
490 return ExprError();
491
John McCall9d125032010-01-15 18:39:57 +0000492 TypeSourceInfo *TInfo;
493 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
494 if (!TInfo)
495 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
Sebastian Redlf53597f2009-03-15 17:47:39 +0000496 unsigned NumExprs = exprs.size();
497 Expr **Exprs = (Expr**)exprs.get();
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000498 SourceLocation TyBeginLoc = TypeRange.getBegin();
499 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
500
Sebastian Redlf53597f2009-03-15 17:47:39 +0000501 if (Ty->isDependentType() ||
Douglas Gregorba498172009-03-13 21:01:28 +0000502 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
Sebastian Redlf53597f2009-03-15 17:47:39 +0000503 exprs.release();
Mike Stump1eb44332009-09-09 15:08:12 +0000504
505 return Owned(CXXUnresolvedConstructExpr::Create(Context,
506 TypeRange.getBegin(), Ty,
Douglas Gregord81e6ca2009-05-20 18:46:25 +0000507 LParenLoc,
508 Exprs, NumExprs,
509 RParenLoc));
Douglas Gregorba498172009-03-13 21:01:28 +0000510 }
511
Anders Carlssonbb60a502009-08-27 03:53:50 +0000512 if (Ty->isArrayType())
513 return ExprError(Diag(TyBeginLoc,
514 diag::err_value_init_for_array_type) << FullRange);
515 if (!Ty->isVoidType() &&
516 RequireCompleteType(TyBeginLoc, Ty,
517 PDiag(diag::err_invalid_incomplete_type_use)
518 << FullRange))
519 return ExprError();
Fariborz Jahanianf071e9b2009-10-23 21:01:39 +0000520
Anders Carlssonbb60a502009-08-27 03:53:50 +0000521 if (RequireNonAbstractType(TyBeginLoc, Ty,
522 diag::err_allocation_of_abstract_type))
523 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000524
525
Douglas Gregor506ae412009-01-16 18:33:17 +0000526 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000527 // If the expression list is a single expression, the type conversion
528 // expression is equivalent (in definedness, and if defined in meaning) to the
529 // corresponding cast expression.
530 //
531 if (NumExprs == 1) {
Anders Carlssoncdb61972009-08-07 22:21:05 +0000532 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Anders Carlsson41b2dcd2010-04-24 18:38:56 +0000533 CXXBaseSpecifierArray BasePath;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000534 if (CheckCastTypes(TypeRange, Ty, Exprs[0], Kind, BasePath,
535 /*FunctionalStyle=*/true))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000536 return ExprError();
Anders Carlsson0aebc812009-09-09 21:33:21 +0000537
538 exprs.release();
Anders Carlsson0aebc812009-09-09 21:33:21 +0000539
540 return Owned(new (Context) CXXFunctionalCastExpr(Ty.getNonReferenceType(),
John McCall9d125032010-01-15 18:39:57 +0000541 TInfo, TyBeginLoc, Kind,
Anders Carlsson41b2dcd2010-04-24 18:38:56 +0000542 Exprs[0], BasePath,
543 RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000544 }
545
Ted Kremenek6217b802009-07-29 21:53:49 +0000546 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Douglas Gregor506ae412009-01-16 18:33:17 +0000547 CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
Sebastian Redlf53597f2009-03-15 17:47:39 +0000548
Mike Stump1eb44332009-09-09 15:08:12 +0000549 if (NumExprs > 1 || !Record->hasTrivialConstructor() ||
Anders Carlssone7624a72009-08-27 05:08:22 +0000550 !Record->hasTrivialDestructor()) {
Eli Friedman6997aae2010-01-31 20:58:15 +0000551 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty);
552 InitializationKind Kind
553 = NumExprs ? InitializationKind::CreateDirect(TypeRange.getBegin(),
554 LParenLoc, RParenLoc)
555 : InitializationKind::CreateValue(TypeRange.getBegin(),
556 LParenLoc, RParenLoc);
557 InitializationSequence InitSeq(*this, Entity, Kind, Exprs, NumExprs);
558 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
559 move(exprs));
Douglas Gregor506ae412009-01-16 18:33:17 +0000560
Eli Friedman6997aae2010-01-31 20:58:15 +0000561 // FIXME: Improve AST representation?
562 return move(Result);
Douglas Gregor506ae412009-01-16 18:33:17 +0000563 }
564
565 // Fall through to value-initialize an object of class type that
566 // doesn't have a user-declared default constructor.
567 }
568
569 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000570 // If the expression list specifies more than a single value, the type shall
571 // be a class with a suitably declared constructor.
572 //
573 if (NumExprs > 1)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000574 return ExprError(Diag(CommaLocs[0],
575 diag::err_builtin_func_cast_more_than_one_arg)
576 << FullRange);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000577
578 assert(NumExprs == 0 && "Expected 0 expressions");
Douglas Gregor506ae412009-01-16 18:33:17 +0000579 // C++ [expr.type.conv]p2:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000580 // The expression T(), where T is a simple-type-specifier for a non-array
581 // complete object type or the (possibly cv-qualified) void type, creates an
582 // rvalue of the specified type, which is value-initialized.
583 //
Sebastian Redlf53597f2009-03-15 17:47:39 +0000584 exprs.release();
585 return Owned(new (Context) CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000586}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000587
588
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000589/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
590/// @code new (memory) int[size][4] @endcode
591/// or
592/// @code ::new Foo(23, "hello") @endcode
593/// For the interpretation of this heap of arguments, consult the base version.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000594Action::OwningExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000595Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000596 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000597 SourceLocation PlacementRParen, bool ParenTypeId,
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000598 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000599 MultiExprArg ConstructorArgs,
Mike Stump1eb44332009-09-09 15:08:12 +0000600 SourceLocation ConstructorRParen) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000601 Expr *ArraySize = 0;
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000602 // If the specified type is an array, unwrap it and save the expression.
603 if (D.getNumTypeObjects() > 0 &&
604 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
605 DeclaratorChunk &Chunk = D.getTypeObject(0);
606 if (Chunk.Arr.hasStatic)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000607 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
608 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000609 if (!Chunk.Arr.NumElts)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000610 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
611 << D.getSourceRange());
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000612
613 if (ParenTypeId) {
614 // Can't have dynamic array size when the type-id is in parentheses.
615 Expr *NumElts = (Expr *)Chunk.Arr.NumElts;
616 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
617 !NumElts->isIntegerConstantExpr(Context)) {
618 Diag(D.getTypeObject(0).Loc, diag::err_new_paren_array_nonconst)
619 << NumElts->getSourceRange();
620 return ExprError();
621 }
622 }
623
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000624 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000625 D.DropFirstTypeObject();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000626 }
627
Douglas Gregor043cad22009-09-11 00:18:58 +0000628 // Every dimension shall be of constant size.
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000629 if (ArraySize) {
630 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor043cad22009-09-11 00:18:58 +0000631 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
632 break;
633
634 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
635 if (Expr *NumElts = (Expr *)Array.NumElts) {
636 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
637 !NumElts->isIntegerConstantExpr(Context)) {
638 Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst)
639 << NumElts->getSourceRange();
640 return ExprError();
641 }
642 }
643 }
644 }
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000645
John McCalla93c9342009-12-07 02:54:59 +0000646 //FIXME: Store TypeSourceInfo in CXXNew expression.
647 TypeSourceInfo *TInfo = 0;
648 QualType AllocType = GetTypeForDeclarator(D, /*Scope=*/0, &TInfo);
Chris Lattnereaaebc72009-04-25 08:06:05 +0000649 if (D.isInvalidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000650 return ExprError();
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000651
Mike Stump1eb44332009-09-09 15:08:12 +0000652 return BuildCXXNew(StartLoc, UseGlobal,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000653 PlacementLParen,
Mike Stump1eb44332009-09-09 15:08:12 +0000654 move(PlacementArgs),
Douglas Gregor3433cf72009-05-21 00:00:09 +0000655 PlacementRParen,
656 ParenTypeId,
Mike Stump1eb44332009-09-09 15:08:12 +0000657 AllocType,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000658 D.getSourceRange().getBegin(),
659 D.getSourceRange(),
660 Owned(ArraySize),
661 ConstructorLParen,
662 move(ConstructorArgs),
663 ConstructorRParen);
664}
665
Mike Stump1eb44332009-09-09 15:08:12 +0000666Sema::OwningExprResult
Douglas Gregor3433cf72009-05-21 00:00:09 +0000667Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
668 SourceLocation PlacementLParen,
669 MultiExprArg PlacementArgs,
670 SourceLocation PlacementRParen,
Mike Stump1eb44332009-09-09 15:08:12 +0000671 bool ParenTypeId,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000672 QualType AllocType,
673 SourceLocation TypeLoc,
674 SourceRange TypeRange,
675 ExprArg ArraySizeE,
676 SourceLocation ConstructorLParen,
677 MultiExprArg ConstructorArgs,
678 SourceLocation ConstructorRParen) {
679 if (CheckAllocatedType(AllocType, TypeLoc, TypeRange))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000680 return ExprError();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000681
Douglas Gregor3caf04e2010-05-16 16:01:03 +0000682 // Per C++0x [expr.new]p5, the type being constructed may be a
683 // typedef of an array type.
684 if (!ArraySizeE.get()) {
685 if (const ConstantArrayType *Array
686 = Context.getAsConstantArrayType(AllocType)) {
687 ArraySizeE = Owned(new (Context) IntegerLiteral(Array->getSize(),
688 Context.getSizeType(),
689 TypeRange.getEnd()));
690 AllocType = Array->getElementType();
691 }
692 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000693
Douglas Gregor3caf04e2010-05-16 16:01:03 +0000694 QualType ResultType = Context.getPointerType(AllocType);
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000695
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000696 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
697 // or enumeration type with a non-negative value."
Douglas Gregor3433cf72009-05-21 00:00:09 +0000698 Expr *ArraySize = (Expr *)ArraySizeE.get();
Sebastian Redl28507842009-02-26 14:39:58 +0000699 if (ArraySize && !ArraySize->isTypeDependent()) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000700 QualType SizeType = ArraySize->getType();
701 if (!SizeType->isIntegralType() && !SizeType->isEnumeralType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000702 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
703 diag::err_array_size_not_integral)
704 << SizeType << ArraySize->getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000705 // Let's see if this is a constant < 0. If so, we reject it out of hand.
706 // We don't care about special rules, so we tell the machinery it's not
707 // evaluated - it gives us a result in more cases.
Sebastian Redl28507842009-02-26 14:39:58 +0000708 if (!ArraySize->isValueDependent()) {
709 llvm::APSInt Value;
710 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
711 if (Value < llvm::APSInt(
Anders Carlssonac18b2e2009-09-23 00:37:25 +0000712 llvm::APInt::getNullValue(Value.getBitWidth()),
713 Value.isUnsigned()))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000714 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
715 diag::err_typecheck_negative_array_size)
716 << ArraySize->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +0000717 }
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000718 }
Anders Carlssonac18b2e2009-09-23 00:37:25 +0000719
Eli Friedman73c39ab2009-10-20 08:27:19 +0000720 ImpCastExprToType(ArraySize, Context.getSizeType(),
721 CastExpr::CK_IntegralCast);
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000722 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000723
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000724 FunctionDecl *OperatorNew = 0;
725 FunctionDecl *OperatorDelete = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000726 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
727 unsigned NumPlaceArgs = PlacementArgs.size();
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000728
Sebastian Redl28507842009-02-26 14:39:58 +0000729 if (!AllocType->isDependentType() &&
730 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
731 FindAllocationFunctions(StartLoc,
Sebastian Redl00e68e22009-02-09 18:24:27 +0000732 SourceRange(PlacementLParen, PlacementRParen),
733 UseGlobal, AllocType, ArraySize, PlaceArgs,
734 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000735 return ExprError();
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000736 llvm::SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000737 if (OperatorNew) {
738 // Add default arguments, if any.
739 const FunctionProtoType *Proto =
740 OperatorNew->getType()->getAs<FunctionProtoType>();
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +0000741 VariadicCallType CallType =
742 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
Anders Carlsson28e94832010-05-03 02:07:56 +0000743
744 if (GatherArgumentsForCall(PlacementLParen, OperatorNew,
745 Proto, 1, PlaceArgs, NumPlaceArgs,
746 AllPlaceArgs, CallType))
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000747 return ExprError();
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000748
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000749 NumPlaceArgs = AllPlaceArgs.size();
750 if (NumPlaceArgs > 0)
751 PlaceArgs = &AllPlaceArgs[0];
752 }
753
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000754 bool Init = ConstructorLParen.isValid();
755 // --- Choosing a constructor ---
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000756 CXXConstructorDecl *Constructor = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000757 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
758 unsigned NumConsArgs = ConstructorArgs.size();
Eli Friedmana8ce9ec2009-11-08 22:15:39 +0000759 ASTOwningVector<&ActionBase::DeleteExpr> ConvertedConstructorArgs(*this);
760
Anders Carlsson48c95012010-05-03 15:45:23 +0000761 // Array 'new' can't have any initializers.
Anders Carlsson55cbd6e2010-05-16 16:24:20 +0000762 if (NumConsArgs && (ResultType->isArrayType() || ArraySize)) {
Anders Carlsson48c95012010-05-03 15:45:23 +0000763 SourceRange InitRange(ConsArgs[0]->getLocStart(),
764 ConsArgs[NumConsArgs - 1]->getLocEnd());
765
766 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
767 return ExprError();
768 }
769
Douglas Gregor99a2e602009-12-16 01:38:02 +0000770 if (!AllocType->isDependentType() &&
771 !Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) {
772 // C++0x [expr.new]p15:
773 // A new-expression that creates an object of type T initializes that
774 // object as follows:
775 InitializationKind Kind
776 // - If the new-initializer is omitted, the object is default-
777 // initialized (8.5); if no initialization is performed,
778 // the object has indeterminate value
779 = !Init? InitializationKind::CreateDefault(TypeLoc)
780 // - Otherwise, the new-initializer is interpreted according to the
781 // initialization rules of 8.5 for direct-initialization.
782 : InitializationKind::CreateDirect(TypeLoc,
783 ConstructorLParen,
784 ConstructorRParen);
785
Douglas Gregor99a2e602009-12-16 01:38:02 +0000786 InitializedEntity Entity
Douglas Gregord6542d82009-12-22 15:35:07 +0000787 = InitializedEntity::InitializeNew(StartLoc, AllocType);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000788 InitializationSequence InitSeq(*this, Entity, Kind, ConsArgs, NumConsArgs);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000789 OwningExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
790 move(ConstructorArgs));
791 if (FullInit.isInvalid())
792 return ExprError();
793
794 // FullInit is our initializer; walk through it to determine if it's a
795 // constructor call, which CXXNewExpr handles directly.
796 if (Expr *FullInitExpr = (Expr *)FullInit.get()) {
797 if (CXXBindTemporaryExpr *Binder
798 = dyn_cast<CXXBindTemporaryExpr>(FullInitExpr))
799 FullInitExpr = Binder->getSubExpr();
800 if (CXXConstructExpr *Construct
801 = dyn_cast<CXXConstructExpr>(FullInitExpr)) {
802 Constructor = Construct->getConstructor();
803 for (CXXConstructExpr::arg_iterator A = Construct->arg_begin(),
804 AEnd = Construct->arg_end();
805 A != AEnd; ++A)
806 ConvertedConstructorArgs.push_back(A->Retain());
807 } else {
808 // Take the converted initializer.
809 ConvertedConstructorArgs.push_back(FullInit.release());
810 }
811 } else {
812 // No initialization required.
813 }
814
815 // Take the converted arguments and use them for the new expression.
Douglas Gregor39da0b82009-09-09 23:08:42 +0000816 NumConsArgs = ConvertedConstructorArgs.size();
817 ConsArgs = (Expr **)ConvertedConstructorArgs.take();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000818 }
Douglas Gregor99a2e602009-12-16 01:38:02 +0000819
Douglas Gregor6d908702010-02-26 05:06:18 +0000820 // Mark the new and delete operators as referenced.
821 if (OperatorNew)
822 MarkDeclarationReferenced(StartLoc, OperatorNew);
823 if (OperatorDelete)
824 MarkDeclarationReferenced(StartLoc, OperatorDelete);
825
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000826 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
Douglas Gregor089407b2009-10-17 21:40:42 +0000827
Sebastian Redlf53597f2009-03-15 17:47:39 +0000828 PlacementArgs.release();
829 ConstructorArgs.release();
Douglas Gregor3433cf72009-05-21 00:00:09 +0000830 ArraySizeE.release();
Ted Kremenekad7fe862010-02-11 22:51:03 +0000831 return Owned(new (Context) CXXNewExpr(Context, UseGlobal, OperatorNew,
832 PlaceArgs, NumPlaceArgs, ParenTypeId,
833 ArraySize, Constructor, Init,
834 ConsArgs, NumConsArgs, OperatorDelete,
835 ResultType, StartLoc,
836 Init ? ConstructorRParen :
837 SourceLocation()));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000838}
839
840/// CheckAllocatedType - Checks that a type is suitable as the allocated type
841/// in a new-expression.
842/// dimension off and stores the size expression in ArraySize.
Douglas Gregor3433cf72009-05-21 00:00:09 +0000843bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +0000844 SourceRange R) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000845 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
846 // abstract class type or array thereof.
Douglas Gregore7450f52009-03-24 19:52:54 +0000847 if (AllocType->isFunctionType())
Douglas Gregor3433cf72009-05-21 00:00:09 +0000848 return Diag(Loc, diag::err_bad_new_type)
849 << AllocType << 0 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +0000850 else if (AllocType->isReferenceType())
Douglas Gregor3433cf72009-05-21 00:00:09 +0000851 return Diag(Loc, diag::err_bad_new_type)
852 << AllocType << 1 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +0000853 else if (!AllocType->isDependentType() &&
Douglas Gregor3433cf72009-05-21 00:00:09 +0000854 RequireCompleteType(Loc, AllocType,
Anders Carlssonb7906612009-08-26 23:45:07 +0000855 PDiag(diag::err_new_incomplete_type)
856 << R))
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000857 return true;
Douglas Gregor3433cf72009-05-21 00:00:09 +0000858 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregore7450f52009-03-24 19:52:54 +0000859 diag::err_allocation_of_abstract_type))
860 return true;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000861
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000862 return false;
863}
864
Douglas Gregor6d908702010-02-26 05:06:18 +0000865/// \brief Determine whether the given function is a non-placement
866/// deallocation function.
867static bool isNonPlacementDeallocationFunction(FunctionDecl *FD) {
868 if (FD->isInvalidDecl())
869 return false;
870
871 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
872 return Method->isUsualDeallocationFunction();
873
874 return ((FD->getOverloadedOperator() == OO_Delete ||
875 FD->getOverloadedOperator() == OO_Array_Delete) &&
876 FD->getNumParams() == 1);
877}
878
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000879/// FindAllocationFunctions - Finds the overloads of operator new and delete
880/// that are appropriate for the allocation.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000881bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
882 bool UseGlobal, QualType AllocType,
883 bool IsArray, Expr **PlaceArgs,
884 unsigned NumPlaceArgs,
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000885 FunctionDecl *&OperatorNew,
Mike Stump1eb44332009-09-09 15:08:12 +0000886 FunctionDecl *&OperatorDelete) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000887 // --- Choosing an allocation function ---
888 // C++ 5.3.4p8 - 14 & 18
889 // 1) If UseGlobal is true, only look in the global scope. Else, also look
890 // in the scope of the allocated class.
891 // 2) If an array size is given, look for operator new[], else look for
892 // operator new.
893 // 3) The first argument is always size_t. Append the arguments from the
894 // placement form.
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000895
896 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
897 // We don't care about the actual value of this argument.
898 // FIXME: Should the Sema create the expression and embed it in the syntax
899 // tree? Or should the consumer just recalculate the value?
Anders Carlssond67c4c32009-08-16 20:29:29 +0000900 IntegerLiteral Size(llvm::APInt::getNullValue(
901 Context.Target.getPointerWidth(0)),
902 Context.getSizeType(),
903 SourceLocation());
904 AllocArgs[0] = &Size;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000905 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
906
Douglas Gregor6d908702010-02-26 05:06:18 +0000907 // C++ [expr.new]p8:
908 // If the allocated type is a non-array type, the allocation
909 // function’s name is operator new and the deallocation function’s
910 // name is operator delete. If the allocated type is an array
911 // type, the allocation function’s name is operator new[] and the
912 // deallocation function’s name is operator delete[].
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000913 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
914 IsArray ? OO_Array_New : OO_New);
Douglas Gregor6d908702010-02-26 05:06:18 +0000915 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
916 IsArray ? OO_Array_Delete : OO_Delete);
917
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000918 if (AllocType->isRecordType() && !UseGlobal) {
Mike Stump1eb44332009-09-09 15:08:12 +0000919 CXXRecordDecl *Record
Ted Kremenek6217b802009-07-29 21:53:49 +0000920 = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl());
Sebastian Redl00e68e22009-02-09 18:24:27 +0000921 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000922 AllocArgs.size(), Record, /*AllowMissing=*/true,
923 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000924 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000925 }
926 if (!OperatorNew) {
927 // Didn't find a member overload. Look for a global one.
928 DeclareGlobalNewDelete();
Sebastian Redl7f662392008-12-04 22:20:51 +0000929 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl00e68e22009-02-09 18:24:27 +0000930 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000931 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
932 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000933 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000934 }
935
John McCall9c82afc2010-04-20 02:18:25 +0000936 // We don't need an operator delete if we're running under
937 // -fno-exceptions.
938 if (!getLangOptions().Exceptions) {
939 OperatorDelete = 0;
940 return false;
941 }
942
Anders Carlssond9583892009-05-31 20:26:12 +0000943 // FindAllocationOverload can change the passed in arguments, so we need to
944 // copy them back.
945 if (NumPlaceArgs > 0)
946 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
Mike Stump1eb44332009-09-09 15:08:12 +0000947
Douglas Gregor6d908702010-02-26 05:06:18 +0000948 // C++ [expr.new]p19:
949 //
950 // If the new-expression begins with a unary :: operator, the
951 // deallocation function’s name is looked up in the global
952 // scope. Otherwise, if the allocated type is a class type T or an
953 // array thereof, the deallocation function’s name is looked up in
954 // the scope of T. If this lookup fails to find the name, or if
955 // the allocated type is not a class type or array thereof, the
956 // deallocation function’s name is looked up in the global scope.
957 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
958 if (AllocType->isRecordType() && !UseGlobal) {
959 CXXRecordDecl *RD
960 = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl());
961 LookupQualifiedName(FoundDelete, RD);
962 }
John McCall90c8c572010-03-18 08:19:33 +0000963 if (FoundDelete.isAmbiguous())
964 return true; // FIXME: clean up expressions?
Douglas Gregor6d908702010-02-26 05:06:18 +0000965
966 if (FoundDelete.empty()) {
967 DeclareGlobalNewDelete();
968 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
969 }
970
971 FoundDelete.suppressDiagnostics();
John McCall9aa472c2010-03-19 07:35:19 +0000972
973 llvm::SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
974
John McCall90c8c572010-03-18 08:19:33 +0000975 if (NumPlaceArgs > 0) {
Douglas Gregor6d908702010-02-26 05:06:18 +0000976 // C++ [expr.new]p20:
977 // A declaration of a placement deallocation function matches the
978 // declaration of a placement allocation function if it has the
979 // same number of parameters and, after parameter transformations
980 // (8.3.5), all parameter types except the first are
981 // identical. [...]
982 //
983 // To perform this comparison, we compute the function type that
984 // the deallocation function should have, and use that type both
985 // for template argument deduction and for comparison purposes.
986 QualType ExpectedFunctionType;
987 {
988 const FunctionProtoType *Proto
989 = OperatorNew->getType()->getAs<FunctionProtoType>();
990 llvm::SmallVector<QualType, 4> ArgTypes;
991 ArgTypes.push_back(Context.VoidPtrTy);
992 for (unsigned I = 1, N = Proto->getNumArgs(); I < N; ++I)
993 ArgTypes.push_back(Proto->getArgType(I));
994
995 ExpectedFunctionType
996 = Context.getFunctionType(Context.VoidTy, ArgTypes.data(),
997 ArgTypes.size(),
998 Proto->isVariadic(),
Rafael Espindola264ba482010-03-30 20:24:48 +0000999 0, false, false, 0, 0,
1000 FunctionType::ExtInfo());
Douglas Gregor6d908702010-02-26 05:06:18 +00001001 }
1002
1003 for (LookupResult::iterator D = FoundDelete.begin(),
1004 DEnd = FoundDelete.end();
1005 D != DEnd; ++D) {
1006 FunctionDecl *Fn = 0;
1007 if (FunctionTemplateDecl *FnTmpl
1008 = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
1009 // Perform template argument deduction to try to match the
1010 // expected function type.
1011 TemplateDeductionInfo Info(Context, StartLoc);
1012 if (DeduceTemplateArguments(FnTmpl, 0, ExpectedFunctionType, Fn, Info))
1013 continue;
1014 } else
1015 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
1016
1017 if (Context.hasSameType(Fn->getType(), ExpectedFunctionType))
John McCall9aa472c2010-03-19 07:35:19 +00001018 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6d908702010-02-26 05:06:18 +00001019 }
1020 } else {
1021 // C++ [expr.new]p20:
1022 // [...] Any non-placement deallocation function matches a
1023 // non-placement allocation function. [...]
1024 for (LookupResult::iterator D = FoundDelete.begin(),
1025 DEnd = FoundDelete.end();
1026 D != DEnd; ++D) {
1027 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>((*D)->getUnderlyingDecl()))
1028 if (isNonPlacementDeallocationFunction(Fn))
John McCall9aa472c2010-03-19 07:35:19 +00001029 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6d908702010-02-26 05:06:18 +00001030 }
1031 }
1032
1033 // C++ [expr.new]p20:
1034 // [...] If the lookup finds a single matching deallocation
1035 // function, that function will be called; otherwise, no
1036 // deallocation function will be called.
1037 if (Matches.size() == 1) {
John McCall9aa472c2010-03-19 07:35:19 +00001038 OperatorDelete = Matches[0].second;
Douglas Gregor6d908702010-02-26 05:06:18 +00001039
1040 // C++0x [expr.new]p20:
1041 // If the lookup finds the two-parameter form of a usual
1042 // deallocation function (3.7.4.2) and that function, considered
1043 // as a placement deallocation function, would have been
1044 // selected as a match for the allocation function, the program
1045 // is ill-formed.
1046 if (NumPlaceArgs && getLangOptions().CPlusPlus0x &&
1047 isNonPlacementDeallocationFunction(OperatorDelete)) {
1048 Diag(StartLoc, diag::err_placement_new_non_placement_delete)
1049 << SourceRange(PlaceArgs[0]->getLocStart(),
1050 PlaceArgs[NumPlaceArgs - 1]->getLocEnd());
1051 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
1052 << DeleteName;
John McCall90c8c572010-03-18 08:19:33 +00001053 } else {
1054 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
John McCall9aa472c2010-03-19 07:35:19 +00001055 Matches[0].first);
Douglas Gregor6d908702010-02-26 05:06:18 +00001056 }
1057 }
1058
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001059 return false;
1060}
1061
Sebastian Redl7f662392008-12-04 22:20:51 +00001062/// FindAllocationOverload - Find an fitting overload for the allocation
1063/// function in the specified scope.
Sebastian Redl00e68e22009-02-09 18:24:27 +00001064bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
1065 DeclarationName Name, Expr** Args,
1066 unsigned NumArgs, DeclContext *Ctx,
Mike Stump1eb44332009-09-09 15:08:12 +00001067 bool AllowMissing, FunctionDecl *&Operator) {
John McCalla24dc2e2009-11-17 02:14:36 +00001068 LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
1069 LookupQualifiedName(R, Ctx);
John McCallf36e02d2009-10-09 21:13:30 +00001070 if (R.empty()) {
Sebastian Redl7f662392008-12-04 22:20:51 +00001071 if (AllowMissing)
1072 return false;
Sebastian Redl7f662392008-12-04 22:20:51 +00001073 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +00001074 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +00001075 }
1076
John McCall90c8c572010-03-18 08:19:33 +00001077 if (R.isAmbiguous())
1078 return true;
1079
1080 R.suppressDiagnostics();
John McCallf36e02d2009-10-09 21:13:30 +00001081
John McCall5769d612010-02-08 23:07:23 +00001082 OverloadCandidateSet Candidates(StartLoc);
Douglas Gregor5d64e5b2009-09-30 00:03:47 +00001083 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
1084 Alloc != AllocEnd; ++Alloc) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001085 // Even member operator new/delete are implicitly treated as
1086 // static, so don't use AddMemberCandidate.
John McCall9aa472c2010-03-19 07:35:19 +00001087 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001088
John McCall9aa472c2010-03-19 07:35:19 +00001089 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
1090 AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001091 /*ExplicitTemplateArgs=*/0, Args, NumArgs,
1092 Candidates,
1093 /*SuppressUserConversions=*/false);
Douglas Gregor90916562009-09-29 18:16:17 +00001094 continue;
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001095 }
1096
John McCall9aa472c2010-03-19 07:35:19 +00001097 FunctionDecl *Fn = cast<FunctionDecl>(D);
1098 AddOverloadCandidate(Fn, Alloc.getPair(), Args, NumArgs, Candidates,
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001099 /*SuppressUserConversions=*/false);
Sebastian Redl7f662392008-12-04 22:20:51 +00001100 }
1101
1102 // Do the resolution.
1103 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00001104 switch(BestViableFunction(Candidates, StartLoc, Best)) {
Sebastian Redl7f662392008-12-04 22:20:51 +00001105 case OR_Success: {
1106 // Got one!
1107 FunctionDecl *FnDecl = Best->Function;
1108 // The first argument is size_t, and the first parameter must be size_t,
1109 // too. This is checked on declaration and can be assumed. (It can't be
1110 // asserted on, though, since invalid decls are left in there.)
John McCall90c8c572010-03-18 08:19:33 +00001111 // Watch out for variadic allocator function.
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00001112 unsigned NumArgsInFnDecl = FnDecl->getNumParams();
1113 for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) {
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001114 OwningExprResult Result
1115 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
1116 FnDecl->getParamDecl(i)),
1117 SourceLocation(),
1118 Owned(Args[i]->Retain()));
1119 if (Result.isInvalid())
Sebastian Redl7f662392008-12-04 22:20:51 +00001120 return true;
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001121
1122 Args[i] = Result.takeAs<Expr>();
Sebastian Redl7f662392008-12-04 22:20:51 +00001123 }
1124 Operator = FnDecl;
John McCall9aa472c2010-03-19 07:35:19 +00001125 CheckAllocationAccess(StartLoc, Range, R.getNamingClass(), Best->FoundDecl);
Sebastian Redl7f662392008-12-04 22:20:51 +00001126 return false;
1127 }
1128
1129 case OR_No_Viable_Function:
Sebastian Redl7f662392008-12-04 22:20:51 +00001130 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +00001131 << Name << Range;
John McCallcbce6062010-01-12 07:18:19 +00001132 PrintOverloadCandidates(Candidates, OCD_AllCandidates, Args, NumArgs);
Sebastian Redl7f662392008-12-04 22:20:51 +00001133 return true;
1134
1135 case OR_Ambiguous:
Sebastian Redl7f662392008-12-04 22:20:51 +00001136 Diag(StartLoc, diag::err_ovl_ambiguous_call)
Sebastian Redl00e68e22009-02-09 18:24:27 +00001137 << Name << Range;
John McCallcbce6062010-01-12 07:18:19 +00001138 PrintOverloadCandidates(Candidates, OCD_ViableCandidates, Args, NumArgs);
Sebastian Redl7f662392008-12-04 22:20:51 +00001139 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001140
1141 case OR_Deleted:
1142 Diag(StartLoc, diag::err_ovl_deleted_call)
1143 << Best->Function->isDeleted()
1144 << Name << Range;
John McCallcbce6062010-01-12 07:18:19 +00001145 PrintOverloadCandidates(Candidates, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001146 return true;
Sebastian Redl7f662392008-12-04 22:20:51 +00001147 }
1148 assert(false && "Unreachable, bad result from BestViableFunction");
1149 return true;
1150}
1151
1152
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001153/// DeclareGlobalNewDelete - Declare the global forms of operator new and
1154/// delete. These are:
1155/// @code
1156/// void* operator new(std::size_t) throw(std::bad_alloc);
1157/// void* operator new[](std::size_t) throw(std::bad_alloc);
1158/// void operator delete(void *) throw();
1159/// void operator delete[](void *) throw();
1160/// @endcode
1161/// Note that the placement and nothrow forms of new are *not* implicitly
1162/// declared. Their use requires including \<new\>.
Mike Stump1eb44332009-09-09 15:08:12 +00001163void Sema::DeclareGlobalNewDelete() {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001164 if (GlobalNewDeleteDeclared)
1165 return;
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001166
1167 // C++ [basic.std.dynamic]p2:
1168 // [...] The following allocation and deallocation functions (18.4) are
1169 // implicitly declared in global scope in each translation unit of a
1170 // program
1171 //
1172 // void* operator new(std::size_t) throw(std::bad_alloc);
1173 // void* operator new[](std::size_t) throw(std::bad_alloc);
1174 // void operator delete(void*) throw();
1175 // void operator delete[](void*) throw();
1176 //
1177 // These implicit declarations introduce only the function names operator
1178 // new, operator new[], operator delete, operator delete[].
1179 //
1180 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
1181 // "std" or "bad_alloc" as necessary to form the exception specification.
1182 // However, we do not make these implicit declarations visible to name
1183 // lookup.
1184 if (!StdNamespace) {
1185 // The "std" namespace has not yet been defined, so build one implicitly.
1186 StdNamespace = NamespaceDecl::Create(Context,
1187 Context.getTranslationUnitDecl(),
1188 SourceLocation(),
1189 &PP.getIdentifierTable().get("std"));
1190 StdNamespace->setImplicit(true);
1191 }
1192
1193 if (!StdBadAlloc) {
1194 // The "std::bad_alloc" class has not yet been declared, so build it
1195 // implicitly.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001196 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001197 StdNamespace,
1198 SourceLocation(),
1199 &PP.getIdentifierTable().get("bad_alloc"),
1200 SourceLocation(), 0);
1201 StdBadAlloc->setImplicit(true);
1202 }
1203
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001204 GlobalNewDeleteDeclared = true;
1205
1206 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
1207 QualType SizeT = Context.getSizeType();
Nuno Lopesfc284482009-12-16 16:59:22 +00001208 bool AssumeSaneOperatorNew = getLangOptions().AssumeSaneOperatorNew;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001209
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001210 DeclareGlobalAllocationFunction(
1211 Context.DeclarationNames.getCXXOperatorName(OO_New),
Nuno Lopesfc284482009-12-16 16:59:22 +00001212 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001213 DeclareGlobalAllocationFunction(
1214 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
Nuno Lopesfc284482009-12-16 16:59:22 +00001215 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001216 DeclareGlobalAllocationFunction(
1217 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
1218 Context.VoidTy, VoidPtr);
1219 DeclareGlobalAllocationFunction(
1220 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
1221 Context.VoidTy, VoidPtr);
1222}
1223
1224/// DeclareGlobalAllocationFunction - Declares a single implicit global
1225/// allocation function if it doesn't already exist.
1226void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Nuno Lopesfc284482009-12-16 16:59:22 +00001227 QualType Return, QualType Argument,
1228 bool AddMallocAttr) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001229 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
1230
1231 // Check if this function is already declared.
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001232 {
Douglas Gregor5cc37092008-12-23 22:05:29 +00001233 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001234 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001235 Alloc != AllocEnd; ++Alloc) {
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001236 // Only look at non-template functions, as it is the predefined,
1237 // non-templated allocation function we are trying to declare here.
1238 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
1239 QualType InitialParamType =
Douglas Gregor6e790ab2009-12-22 23:42:49 +00001240 Context.getCanonicalType(
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001241 Func->getParamDecl(0)->getType().getUnqualifiedType());
1242 // FIXME: Do we need to check for default arguments here?
1243 if (Func->getNumParams() == 1 && InitialParamType == Argument)
1244 return;
1245 }
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001246 }
1247 }
1248
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001249 QualType BadAllocType;
1250 bool HasBadAllocExceptionSpec
1251 = (Name.getCXXOverloadedOperator() == OO_New ||
1252 Name.getCXXOverloadedOperator() == OO_Array_New);
1253 if (HasBadAllocExceptionSpec) {
1254 assert(StdBadAlloc && "Must have std::bad_alloc declared");
1255 BadAllocType = Context.getTypeDeclType(StdBadAlloc);
1256 }
1257
1258 QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0,
1259 true, false,
1260 HasBadAllocExceptionSpec? 1 : 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00001261 &BadAllocType,
1262 FunctionType::ExtInfo());
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001263 FunctionDecl *Alloc =
1264 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001265 FnType, /*TInfo=*/0, FunctionDecl::None,
1266 FunctionDecl::None, false, true);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001267 Alloc->setImplicit();
Nuno Lopesfc284482009-12-16 16:59:22 +00001268
1269 if (AddMallocAttr)
1270 Alloc->addAttr(::new (Context) MallocAttr());
1271
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001272 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
John McCalla93c9342009-12-07 02:54:59 +00001273 0, Argument, /*TInfo=*/0,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001274 VarDecl::None,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001275 VarDecl::None, 0);
Douglas Gregor838db382010-02-11 01:19:42 +00001276 Alloc->setParams(&Param, 1);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001277
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001278 // FIXME: Also add this declaration to the IdentifierResolver, but
1279 // make sure it is at the end of the chain to coincide with the
1280 // global scope.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001281 ((DeclContext *)TUScope->getEntity())->addDecl(Alloc);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001282}
1283
Anders Carlsson78f74552009-11-15 18:45:20 +00001284bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
1285 DeclarationName Name,
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00001286 FunctionDecl* &Operator) {
John McCalla24dc2e2009-11-17 02:14:36 +00001287 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlsson78f74552009-11-15 18:45:20 +00001288 // Try to find operator delete/operator delete[] in class scope.
John McCalla24dc2e2009-11-17 02:14:36 +00001289 LookupQualifiedName(Found, RD);
Anders Carlsson78f74552009-11-15 18:45:20 +00001290
John McCalla24dc2e2009-11-17 02:14:36 +00001291 if (Found.isAmbiguous())
Anders Carlsson78f74552009-11-15 18:45:20 +00001292 return true;
Anders Carlsson78f74552009-11-15 18:45:20 +00001293
1294 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1295 F != FEnd; ++F) {
1296 if (CXXMethodDecl *Delete = dyn_cast<CXXMethodDecl>(*F))
1297 if (Delete->isUsualDeallocationFunction()) {
1298 Operator = Delete;
1299 return false;
1300 }
1301 }
1302
1303 // We did find operator delete/operator delete[] declarations, but
1304 // none of them were suitable.
1305 if (!Found.empty()) {
1306 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
1307 << Name << RD;
1308
1309 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1310 F != FEnd; ++F) {
Douglas Gregorb0fd4832010-04-25 20:55:08 +00001311 Diag((*F)->getLocation(), diag::note_member_declared_here)
Anders Carlsson78f74552009-11-15 18:45:20 +00001312 << Name;
1313 }
1314
1315 return true;
1316 }
1317
1318 // Look for a global declaration.
1319 DeclareGlobalNewDelete();
1320 DeclContext *TUDecl = Context.getTranslationUnitDecl();
1321
1322 CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation());
1323 Expr* DeallocArgs[1];
1324 DeallocArgs[0] = &Null;
1325 if (FindAllocationOverload(StartLoc, SourceRange(), Name,
1326 DeallocArgs, 1, TUDecl, /*AllowMissing=*/false,
1327 Operator))
1328 return true;
1329
1330 assert(Operator && "Did not find a deallocation function!");
1331 return false;
1332}
1333
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001334/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
1335/// @code ::delete ptr; @endcode
1336/// or
1337/// @code delete [] ptr; @endcode
Sebastian Redlf53597f2009-03-15 17:47:39 +00001338Action::OwningExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001339Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
Mike Stump1eb44332009-09-09 15:08:12 +00001340 bool ArrayForm, ExprArg Operand) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001341 // C++ [expr.delete]p1:
1342 // The operand shall have a pointer type, or a class type having a single
1343 // conversion function to a pointer type. The result has type void.
1344 //
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001345 // DR599 amends "pointer type" to "pointer to object type" in both cases.
1346
Anders Carlssond67c4c32009-08-16 20:29:29 +00001347 FunctionDecl *OperatorDelete = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001348
Sebastian Redlf53597f2009-03-15 17:47:39 +00001349 Expr *Ex = (Expr *)Operand.get();
Sebastian Redl28507842009-02-26 14:39:58 +00001350 if (!Ex->isTypeDependent()) {
1351 QualType Type = Ex->getType();
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001352
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001353 if (const RecordType *Record = Type->getAs<RecordType>()) {
John McCall32daa422010-03-31 01:36:47 +00001354 llvm::SmallVector<CXXConversionDecl*, 4> ObjectPtrConversions;
1355
Fariborz Jahanian53462782009-09-11 21:44:33 +00001356 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
John McCall32daa422010-03-31 01:36:47 +00001357 const UnresolvedSetImpl *Conversions = RD->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00001358 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00001359 E = Conversions->end(); I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00001360 NamedDecl *D = I.getDecl();
1361 if (isa<UsingShadowDecl>(D))
1362 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1363
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001364 // Skip over templated conversion functions; they aren't considered.
John McCall32daa422010-03-31 01:36:47 +00001365 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001366 continue;
1367
John McCall32daa422010-03-31 01:36:47 +00001368 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001369
1370 QualType ConvType = Conv->getConversionType().getNonReferenceType();
1371 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
1372 if (ConvPtrType->getPointeeType()->isObjectType())
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001373 ObjectPtrConversions.push_back(Conv);
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001374 }
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001375 if (ObjectPtrConversions.size() == 1) {
1376 // We have a single conversion to a pointer-to-object type. Perform
1377 // that conversion.
John McCall32daa422010-03-31 01:36:47 +00001378 // TODO: don't redo the conversion calculation.
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001379 Operand.release();
John McCall32daa422010-03-31 01:36:47 +00001380 if (!PerformImplicitConversion(Ex,
1381 ObjectPtrConversions.front()->getConversionType(),
Douglas Gregor68647482009-12-16 03:45:30 +00001382 AA_Converting)) {
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001383 Operand = Owned(Ex);
1384 Type = Ex->getType();
1385 }
1386 }
1387 else if (ObjectPtrConversions.size() > 1) {
1388 Diag(StartLoc, diag::err_ambiguous_delete_operand)
1389 << Type << Ex->getSourceRange();
John McCall32daa422010-03-31 01:36:47 +00001390 for (unsigned i= 0; i < ObjectPtrConversions.size(); i++)
1391 NoteOverloadCandidate(ObjectPtrConversions[i]);
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001392 return ExprError();
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001393 }
Sebastian Redl28507842009-02-26 14:39:58 +00001394 }
1395
Sebastian Redlf53597f2009-03-15 17:47:39 +00001396 if (!Type->isPointerType())
1397 return ExprError(Diag(StartLoc, diag::err_delete_operand)
1398 << Type << Ex->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +00001399
Ted Kremenek6217b802009-07-29 21:53:49 +00001400 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Douglas Gregor8dcb29d2009-03-24 20:13:58 +00001401 if (Pointee->isFunctionType() || Pointee->isVoidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +00001402 return ExprError(Diag(StartLoc, diag::err_delete_operand)
1403 << Type << Ex->getSourceRange());
Douglas Gregor8dcb29d2009-03-24 20:13:58 +00001404 else if (!Pointee->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00001405 RequireCompleteType(StartLoc, Pointee,
Anders Carlssonb7906612009-08-26 23:45:07 +00001406 PDiag(diag::warn_delete_incomplete)
1407 << Ex->getSourceRange()))
Douglas Gregor8dcb29d2009-03-24 20:13:58 +00001408 return ExprError();
Sebastian Redl28507842009-02-26 14:39:58 +00001409
Douglas Gregor1070c9f2009-09-29 21:38:53 +00001410 // C++ [expr.delete]p2:
1411 // [Note: a pointer to a const type can be the operand of a
1412 // delete-expression; it is not necessary to cast away the constness
1413 // (5.2.11) of the pointer expression before it is used as the operand
1414 // of the delete-expression. ]
1415 ImpCastExprToType(Ex, Context.getPointerType(Context.VoidTy),
1416 CastExpr::CK_NoOp);
1417
1418 // Update the operand.
1419 Operand.take();
1420 Operand = ExprArg(*this, Ex);
1421
Anders Carlssond67c4c32009-08-16 20:29:29 +00001422 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1423 ArrayForm ? OO_Array_Delete : OO_Delete);
1424
Anders Carlsson78f74552009-11-15 18:45:20 +00001425 if (const RecordType *RT = Pointee->getAs<RecordType>()) {
1426 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1427
1428 if (!UseGlobal &&
1429 FindDeallocationFunction(StartLoc, RD, DeleteName, OperatorDelete))
Anders Carlsson0ba63ea2009-11-14 03:17:38 +00001430 return ExprError();
Anders Carlsson0ba63ea2009-11-14 03:17:38 +00001431
Anders Carlsson78f74552009-11-15 18:45:20 +00001432 if (!RD->hasTrivialDestructor())
1433 if (const CXXDestructorDecl *Dtor = RD->getDestructor(Context))
Mike Stump1eb44332009-09-09 15:08:12 +00001434 MarkDeclarationReferenced(StartLoc,
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001435 const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssond67c4c32009-08-16 20:29:29 +00001436 }
Anders Carlsson78f74552009-11-15 18:45:20 +00001437
Anders Carlssond67c4c32009-08-16 20:29:29 +00001438 if (!OperatorDelete) {
Anders Carlsson78f74552009-11-15 18:45:20 +00001439 // Look for a global declaration.
Anders Carlssond67c4c32009-08-16 20:29:29 +00001440 DeclareGlobalNewDelete();
1441 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001442 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
Douglas Gregor90916562009-09-29 18:16:17 +00001443 &Ex, 1, TUDecl, /*AllowMissing=*/false,
Anders Carlssond67c4c32009-08-16 20:29:29 +00001444 OperatorDelete))
1445 return ExprError();
1446 }
Mike Stump1eb44332009-09-09 15:08:12 +00001447
John McCall9c82afc2010-04-20 02:18:25 +00001448 MarkDeclarationReferenced(StartLoc, OperatorDelete);
1449
Sebastian Redl28507842009-02-26 14:39:58 +00001450 // FIXME: Check access and ambiguity of operator delete and destructor.
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001451 }
1452
Sebastian Redlf53597f2009-03-15 17:47:39 +00001453 Operand.release();
1454 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
Anders Carlssond67c4c32009-08-16 20:29:29 +00001455 OperatorDelete, Ex, StartLoc));
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001456}
1457
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001458/// \brief Check the use of the given variable as a C++ condition in an if,
1459/// while, do-while, or switch statement.
Douglas Gregor586596f2010-05-06 17:25:47 +00001460Action::OwningExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
1461 SourceLocation StmtLoc,
1462 bool ConvertToBoolean) {
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001463 QualType T = ConditionVar->getType();
1464
1465 // C++ [stmt.select]p2:
1466 // The declarator shall not specify a function or an array.
1467 if (T->isFunctionType())
1468 return ExprError(Diag(ConditionVar->getLocation(),
1469 diag::err_invalid_use_of_function_type)
1470 << ConditionVar->getSourceRange());
1471 else if (T->isArrayType())
1472 return ExprError(Diag(ConditionVar->getLocation(),
1473 diag::err_invalid_use_of_array_type)
1474 << ConditionVar->getSourceRange());
Douglas Gregora7605db2009-11-24 16:07:02 +00001475
Douglas Gregor586596f2010-05-06 17:25:47 +00001476 Expr *Condition = DeclRefExpr::Create(Context, 0, SourceRange(), ConditionVar,
1477 ConditionVar->getLocation(),
1478 ConditionVar->getType().getNonReferenceType());
1479 if (ConvertToBoolean && CheckBooleanCondition(Condition, StmtLoc)) {
1480 Condition->Destroy(Context);
1481 return ExprError();
1482 }
1483
1484 return Owned(Condition);
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001485}
1486
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001487/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
1488bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
1489 // C++ 6.4p4:
1490 // The value of a condition that is an initialized declaration in a statement
1491 // other than a switch statement is the value of the declared variable
1492 // implicitly converted to type bool. If that conversion is ill-formed, the
1493 // program is ill-formed.
1494 // The value of a condition that is an expression is the value of the
1495 // expression, implicitly converted to bool.
1496 //
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001497 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001498}
Douglas Gregor77a52232008-09-12 00:47:35 +00001499
1500/// Helper function to determine whether this is the (deprecated) C++
1501/// conversion from a string literal to a pointer to non-const char or
1502/// non-const wchar_t (for narrow and wide string literals,
1503/// respectively).
Mike Stump1eb44332009-09-09 15:08:12 +00001504bool
Douglas Gregor77a52232008-09-12 00:47:35 +00001505Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
1506 // Look inside the implicit cast, if it exists.
1507 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
1508 From = Cast->getSubExpr();
1509
1510 // A string literal (2.13.4) that is not a wide string literal can
1511 // be converted to an rvalue of type "pointer to char"; a wide
1512 // string literal can be converted to an rvalue of type "pointer
1513 // to wchar_t" (C++ 4.2p2).
1514 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From))
Ted Kremenek6217b802009-07-29 21:53:49 +00001515 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump1eb44332009-09-09 15:08:12 +00001516 if (const BuiltinType *ToPointeeType
John McCall183700f2009-09-21 23:43:11 +00001517 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregor77a52232008-09-12 00:47:35 +00001518 // This conversion is considered only when there is an
1519 // explicit appropriate pointer target type (C++ 4.2p2).
John McCall0953e762009-09-24 19:53:00 +00001520 if (!ToPtrType->getPointeeType().hasQualifiers() &&
Douglas Gregor77a52232008-09-12 00:47:35 +00001521 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
1522 (!StrLit->isWide() &&
1523 (ToPointeeType->getKind() == BuiltinType::Char_U ||
1524 ToPointeeType->getKind() == BuiltinType::Char_S))))
1525 return true;
1526 }
1527
1528 return false;
1529}
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001530
Douglas Gregorba70ab62010-04-16 22:17:36 +00001531static Sema::OwningExprResult BuildCXXCastArgument(Sema &S,
1532 SourceLocation CastLoc,
1533 QualType Ty,
1534 CastExpr::CastKind Kind,
1535 CXXMethodDecl *Method,
1536 Sema::ExprArg Arg) {
1537 Expr *From = Arg.takeAs<Expr>();
1538
1539 switch (Kind) {
1540 default: assert(0 && "Unhandled cast kind!");
1541 case CastExpr::CK_ConstructorConversion: {
1542 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(S);
1543
1544 if (S.CompleteConstructorCall(cast<CXXConstructorDecl>(Method),
1545 Sema::MultiExprArg(S, (void **)&From, 1),
1546 CastLoc, ConstructorArgs))
1547 return S.ExprError();
1548
1549 Sema::OwningExprResult Result =
1550 S.BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
1551 move_arg(ConstructorArgs));
1552 if (Result.isInvalid())
1553 return S.ExprError();
1554
1555 return S.MaybeBindToTemporary(Result.takeAs<Expr>());
1556 }
1557
1558 case CastExpr::CK_UserDefinedConversion: {
1559 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
1560
1561 // Create an implicit call expr that calls it.
1562 // FIXME: pass the FoundDecl for the user-defined conversion here
1563 CXXMemberCallExpr *CE = S.BuildCXXMemberCallExpr(From, Method, Method);
1564 return S.MaybeBindToTemporary(CE);
1565 }
1566 }
1567}
1568
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001569/// PerformImplicitConversion - Perform an implicit conversion of the
1570/// expression From to the type ToType using the pre-computed implicit
1571/// conversion sequence ICS. Returns true if there was an error, false
1572/// otherwise. The expression From is replaced with the converted
Douglas Gregor68647482009-12-16 03:45:30 +00001573/// expression. Action is the kind of conversion we're performing,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001574/// used in the error message.
1575bool
1576Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
1577 const ImplicitConversionSequence &ICS,
Douglas Gregor68647482009-12-16 03:45:30 +00001578 AssignmentAction Action, bool IgnoreBaseAccess) {
John McCall1d318332010-01-12 00:44:57 +00001579 switch (ICS.getKind()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001580 case ImplicitConversionSequence::StandardConversion:
Douglas Gregor68647482009-12-16 03:45:30 +00001581 if (PerformImplicitConversion(From, ToType, ICS.Standard, Action,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001582 IgnoreBaseAccess))
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001583 return true;
1584 break;
1585
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001586 case ImplicitConversionSequence::UserDefinedConversion: {
1587
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00001588 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
1589 CastExpr::CastKind CastKind = CastExpr::CK_Unknown;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001590 QualType BeforeToType;
1591 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00001592 CastKind = CastExpr::CK_UserDefinedConversion;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001593
1594 // If the user-defined conversion is specified by a conversion function,
1595 // the initial standard conversion sequence converts the source type to
1596 // the implicit object parameter of the conversion function.
1597 BeforeToType = Context.getTagDeclType(Conv->getParent());
1598 } else if (const CXXConstructorDecl *Ctor =
1599 dyn_cast<CXXConstructorDecl>(FD)) {
Anders Carlsson0aebc812009-09-09 21:33:21 +00001600 CastKind = CastExpr::CK_ConstructorConversion;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001601 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregore44201a2009-11-20 02:31:03 +00001602 if (!ICS.UserDefined.EllipsisConversion) {
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001603 // If the user-defined conversion is specified by a constructor, the
1604 // initial standard conversion sequence converts the source type to the
1605 // type required by the argument of the constructor
Douglas Gregore44201a2009-11-20 02:31:03 +00001606 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
1607 }
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001608 }
Anders Carlsson0aebc812009-09-09 21:33:21 +00001609 else
1610 assert(0 && "Unknown conversion function kind!");
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001611 // Whatch out for elipsis conversion.
Fariborz Jahanian4c0cea22009-11-06 00:55:14 +00001612 if (!ICS.UserDefined.EllipsisConversion) {
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001613 if (PerformImplicitConversion(From, BeforeToType,
Douglas Gregor68647482009-12-16 03:45:30 +00001614 ICS.UserDefined.Before, AA_Converting,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001615 IgnoreBaseAccess))
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001616 return true;
1617 }
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001618
Anders Carlsson0aebc812009-09-09 21:33:21 +00001619 OwningExprResult CastArg
Douglas Gregorba70ab62010-04-16 22:17:36 +00001620 = BuildCXXCastArgument(*this,
1621 From->getLocStart(),
Anders Carlsson0aebc812009-09-09 21:33:21 +00001622 ToType.getNonReferenceType(),
1623 CastKind, cast<CXXMethodDecl>(FD),
1624 Owned(From));
1625
1626 if (CastArg.isInvalid())
1627 return true;
Eli Friedmand8889622009-11-27 04:41:50 +00001628
1629 From = CastArg.takeAs<Expr>();
1630
Eli Friedmand8889622009-11-27 04:41:50 +00001631 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
Douglas Gregor68647482009-12-16 03:45:30 +00001632 AA_Converting, IgnoreBaseAccess);
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001633 }
John McCall1d318332010-01-12 00:44:57 +00001634
1635 case ImplicitConversionSequence::AmbiguousConversion:
1636 DiagnoseAmbiguousConversion(ICS, From->getExprLoc(),
1637 PDiag(diag::err_typecheck_ambiguous_condition)
1638 << From->getSourceRange());
1639 return true;
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001640
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001641 case ImplicitConversionSequence::EllipsisConversion:
1642 assert(false && "Cannot perform an ellipsis conversion");
Douglas Gregor60d62c22008-10-31 16:23:19 +00001643 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001644
1645 case ImplicitConversionSequence::BadConversion:
1646 return true;
1647 }
1648
1649 // Everything went well.
1650 return false;
1651}
1652
1653/// PerformImplicitConversion - Perform an implicit conversion of the
1654/// expression From to the type ToType by following the standard
1655/// conversion sequence SCS. Returns true if there was an error, false
1656/// otherwise. The expression From is replaced with the converted
Douglas Gregor45920e82008-12-19 17:40:08 +00001657/// expression. Flavor is the context in which we're performing this
1658/// conversion, for use in error messages.
Mike Stump1eb44332009-09-09 15:08:12 +00001659bool
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001660Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor45920e82008-12-19 17:40:08 +00001661 const StandardConversionSequence& SCS,
Douglas Gregor68647482009-12-16 03:45:30 +00001662 AssignmentAction Action, bool IgnoreBaseAccess) {
Mike Stump390b4cc2009-05-16 07:39:55 +00001663 // Overall FIXME: we are recomputing too many types here and doing far too
1664 // much extra work. What this means is that we need to keep track of more
1665 // information that is computed when we try the implicit conversion initially,
1666 // so that we don't need to recompute anything here.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001667 QualType FromType = From->getType();
1668
Douglas Gregor225c41e2008-11-03 19:09:14 +00001669 if (SCS.CopyConstructor) {
Anders Carlsson7c3e8a12009-05-19 04:45:15 +00001670 // FIXME: When can ToType be a reference type?
1671 assert(!ToType->isReferenceType());
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00001672 if (SCS.Second == ICK_Derived_To_Base) {
1673 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1674 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
1675 MultiExprArg(*this, (void **)&From, 1),
1676 /*FIXME:ConstructLoc*/SourceLocation(),
1677 ConstructorArgs))
1678 return true;
1679 OwningExprResult FromResult =
1680 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1681 ToType, SCS.CopyConstructor,
1682 move_arg(ConstructorArgs));
1683 if (FromResult.isInvalid())
1684 return true;
1685 From = FromResult.takeAs<Expr>();
1686 return false;
1687 }
Mike Stump1eb44332009-09-09 15:08:12 +00001688 OwningExprResult FromResult =
1689 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1690 ToType, SCS.CopyConstructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00001691 MultiExprArg(*this, (void**)&From, 1));
Mike Stump1eb44332009-09-09 15:08:12 +00001692
Anders Carlssonda3f4e22009-08-25 05:12:04 +00001693 if (FromResult.isInvalid())
1694 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001695
Anders Carlssonda3f4e22009-08-25 05:12:04 +00001696 From = FromResult.takeAs<Expr>();
Douglas Gregor225c41e2008-11-03 19:09:14 +00001697 return false;
1698 }
1699
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001700 // Resolve overloaded function references.
1701 if (Context.hasSameType(FromType, Context.OverloadTy)) {
1702 DeclAccessPair Found;
1703 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
1704 true, Found);
1705 if (!Fn)
1706 return true;
1707
1708 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
1709 return true;
1710
1711 From = FixOverloadedFunctionReference(From, Found, Fn);
1712 FromType = From->getType();
1713 }
1714
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001715 // Perform the first implicit conversion.
1716 switch (SCS.First) {
1717 case ICK_Identity:
1718 case ICK_Lvalue_To_Rvalue:
1719 // Nothing to do.
1720 break;
1721
1722 case ICK_Array_To_Pointer:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001723 FromType = Context.getArrayDecayedType(FromType);
Anders Carlsson82495762009-08-08 21:04:35 +00001724 ImpCastExprToType(From, FromType, CastExpr::CK_ArrayToPointerDecay);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001725 break;
1726
1727 case ICK_Function_To_Pointer:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001728 FromType = Context.getPointerType(FromType);
Anders Carlssonb633c4e2009-09-01 20:37:18 +00001729 ImpCastExprToType(From, FromType, CastExpr::CK_FunctionToPointerDecay);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001730 break;
1731
1732 default:
1733 assert(false && "Improper first standard conversion");
1734 break;
1735 }
1736
1737 // Perform the second implicit conversion
1738 switch (SCS.Second) {
1739 case ICK_Identity:
Sebastian Redl2c7588f2009-10-10 12:04:10 +00001740 // If both sides are functions (or pointers/references to them), there could
1741 // be incompatible exception declarations.
1742 if (CheckExceptionSpecCompatibility(From, ToType))
1743 return true;
1744 // Nothing else to do.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001745 break;
1746
Douglas Gregor43c79c22009-12-09 00:47:37 +00001747 case ICK_NoReturn_Adjustment:
1748 // If both sides are functions (or pointers/references to them), there could
1749 // be incompatible exception declarations.
1750 if (CheckExceptionSpecCompatibility(From, ToType))
1751 return true;
1752
1753 ImpCastExprToType(From, Context.getNoReturnType(From->getType(), false),
1754 CastExpr::CK_NoOp);
1755 break;
1756
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001757 case ICK_Integral_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001758 case ICK_Integral_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001759 ImpCastExprToType(From, ToType, CastExpr::CK_IntegralCast);
1760 break;
1761
1762 case ICK_Floating_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001763 case ICK_Floating_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001764 ImpCastExprToType(From, ToType, CastExpr::CK_FloatingCast);
1765 break;
1766
1767 case ICK_Complex_Promotion:
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001768 case ICK_Complex_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001769 ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1770 break;
1771
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001772 case ICK_Floating_Integral:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001773 if (ToType->isFloatingType())
1774 ImpCastExprToType(From, ToType, CastExpr::CK_IntegralToFloating);
1775 else
1776 ImpCastExprToType(From, ToType, CastExpr::CK_FloatingToIntegral);
1777 break;
1778
Douglas Gregorf9201e02009-02-11 23:02:49 +00001779 case ICK_Compatible_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001780 ImpCastExprToType(From, ToType, CastExpr::CK_NoOp);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001781 break;
1782
Anders Carlsson61faec12009-09-12 04:46:44 +00001783 case ICK_Pointer_Conversion: {
Douglas Gregor45920e82008-12-19 17:40:08 +00001784 if (SCS.IncompatibleObjC) {
1785 // Diagnose incompatible Objective-C conversions
Mike Stump1eb44332009-09-09 15:08:12 +00001786 Diag(From->getSourceRange().getBegin(),
Douglas Gregor45920e82008-12-19 17:40:08 +00001787 diag::ext_typecheck_convert_incompatible_pointer)
Douglas Gregor68647482009-12-16 03:45:30 +00001788 << From->getType() << ToType << Action
Douglas Gregor45920e82008-12-19 17:40:08 +00001789 << From->getSourceRange();
1790 }
1791
Anders Carlsson61faec12009-09-12 04:46:44 +00001792
1793 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001794 CXXBaseSpecifierArray BasePath;
1795 if (CheckPointerConversion(From, ToType, Kind, BasePath, IgnoreBaseAccess))
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001796 return true;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001797 ImpCastExprToType(From, ToType, Kind, /*isLvalue=*/false, BasePath);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001798 break;
Anders Carlsson61faec12009-09-12 04:46:44 +00001799 }
1800
1801 case ICK_Pointer_Member: {
1802 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Anders Carlssonf9d68e12010-04-24 19:36:51 +00001803 CXXBaseSpecifierArray BasePath;
1804 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath,
1805 IgnoreBaseAccess))
Anders Carlsson61faec12009-09-12 04:46:44 +00001806 return true;
Sebastian Redl2c7588f2009-10-10 12:04:10 +00001807 if (CheckExceptionSpecCompatibility(From, ToType))
1808 return true;
Anders Carlssonf9d68e12010-04-24 19:36:51 +00001809 ImpCastExprToType(From, ToType, Kind, /*isLvalue=*/false, BasePath);
Anders Carlsson61faec12009-09-12 04:46:44 +00001810 break;
1811 }
Anders Carlssonbc0e0782009-11-23 20:04:44 +00001812 case ICK_Boolean_Conversion: {
1813 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
1814 if (FromType->isMemberPointerType())
1815 Kind = CastExpr::CK_MemberPointerToBoolean;
1816
1817 ImpCastExprToType(From, Context.BoolTy, Kind);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001818 break;
Anders Carlssonbc0e0782009-11-23 20:04:44 +00001819 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001820
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001821 case ICK_Derived_To_Base: {
1822 CXXBaseSpecifierArray BasePath;
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001823 if (CheckDerivedToBaseConversion(From->getType(),
1824 ToType.getNonReferenceType(),
1825 From->getLocStart(),
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001826 From->getSourceRange(),
1827 &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001828 IgnoreBaseAccess))
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001829 return true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001830
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001831 ImpCastExprToType(From, ToType.getNonReferenceType(),
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001832 CastExpr::CK_DerivedToBase,
1833 /*isLvalue=*/(From->getType()->isRecordType() &&
1834 From->isLvalue(Context) == Expr::LV_Valid),
1835 BasePath);
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001836 break;
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001837 }
1838
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001839 case ICK_Vector_Conversion:
1840 ImpCastExprToType(From, ToType, CastExpr::CK_BitCast);
1841 break;
1842
1843 case ICK_Vector_Splat:
1844 ImpCastExprToType(From, ToType, CastExpr::CK_VectorSplat);
1845 break;
1846
1847 case ICK_Complex_Real:
1848 ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1849 break;
1850
1851 case ICK_Lvalue_To_Rvalue:
1852 case ICK_Array_To_Pointer:
1853 case ICK_Function_To_Pointer:
1854 case ICK_Qualification:
1855 case ICK_Num_Conversion_Kinds:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001856 assert(false && "Improper second standard conversion");
1857 break;
1858 }
1859
1860 switch (SCS.Third) {
1861 case ICK_Identity:
1862 // Nothing to do.
1863 break;
1864
1865 case ICK_Qualification:
Mike Stump390b4cc2009-05-16 07:39:55 +00001866 // FIXME: Not sure about lvalue vs rvalue here in the presence of rvalue
1867 // references.
Mike Stump1eb44332009-09-09 15:08:12 +00001868 ImpCastExprToType(From, ToType.getNonReferenceType(),
Anders Carlssonf1b48b72010-04-24 16:57:13 +00001869 CastExpr::CK_NoOp, ToType->isLValueReferenceType());
Douglas Gregora9bff302010-02-28 18:30:25 +00001870
1871 if (SCS.DeprecatedStringLiteralToCharPtr)
1872 Diag(From->getLocStart(), diag::warn_deprecated_string_literal_conversion)
1873 << ToType.getNonReferenceType();
1874
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001875 break;
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001876
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001877 default:
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001878 assert(false && "Improper third standard conversion");
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001879 break;
1880 }
1881
1882 return false;
1883}
1884
Sebastian Redl64b45f72009-01-05 20:52:13 +00001885Sema::OwningExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
1886 SourceLocation KWLoc,
1887 SourceLocation LParen,
1888 TypeTy *Ty,
1889 SourceLocation RParen) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00001890 QualType T = GetTypeFromParser(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00001891
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001892 // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
1893 // all traits except __is_class, __is_enum and __is_union require a the type
1894 // to be complete.
1895 if (OTT != UTT_IsClass && OTT != UTT_IsEnum && OTT != UTT_IsUnion) {
Mike Stump1eb44332009-09-09 15:08:12 +00001896 if (RequireCompleteType(KWLoc, T,
Anders Carlssond497ba72009-08-26 22:59:12 +00001897 diag::err_incomplete_type_used_in_type_trait_expr))
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001898 return ExprError();
1899 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00001900
1901 // There is no point in eagerly computing the value. The traits are designed
1902 // to be used from type trait templates, so Ty will be a template parameter
1903 // 99% of the time.
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001904 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT, T,
1905 RParen, Context.BoolTy));
Sebastian Redl64b45f72009-01-05 20:52:13 +00001906}
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001907
1908QualType Sema::CheckPointerToMemberOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00001909 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001910 const char *OpSpelling = isIndirect ? "->*" : ".*";
1911 // C++ 5.5p2
1912 // The binary operator .* [p3: ->*] binds its second operand, which shall
1913 // be of type "pointer to member of T" (where T is a completely-defined
1914 // class type) [...]
1915 QualType RType = rex->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001916 const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
Douglas Gregore7450f52009-03-24 19:52:54 +00001917 if (!MemPtr) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001918 Diag(Loc, diag::err_bad_memptr_rhs)
1919 << OpSpelling << RType << rex->getSourceRange();
1920 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00001921 }
Douglas Gregore7450f52009-03-24 19:52:54 +00001922
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001923 QualType Class(MemPtr->getClass(), 0);
1924
Sebastian Redl59fc2692010-04-10 10:14:54 +00001925 if (RequireCompleteType(Loc, Class, diag::err_memptr_rhs_to_incomplete))
1926 return QualType();
1927
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001928 // C++ 5.5p2
1929 // [...] to its first operand, which shall be of class T or of a class of
1930 // which T is an unambiguous and accessible base class. [p3: a pointer to
1931 // such a class]
1932 QualType LType = lex->getType();
1933 if (isIndirect) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001934 if (const PointerType *Ptr = LType->getAs<PointerType>())
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001935 LType = Ptr->getPointeeType().getNonReferenceType();
1936 else {
1937 Diag(Loc, diag::err_bad_memptr_lhs)
Fariborz Jahanianef78ac62009-10-26 20:45:27 +00001938 << OpSpelling << 1 << LType
Douglas Gregor849b2432010-03-31 17:46:05 +00001939 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001940 return QualType();
1941 }
1942 }
1943
Douglas Gregora4923eb2009-11-16 21:35:15 +00001944 if (!Context.hasSameUnqualifiedType(Class, LType)) {
Sebastian Redl17e1d352010-04-23 17:18:26 +00001945 // If we want to check the hierarchy, we need a complete type.
1946 if (RequireCompleteType(Loc, LType, PDiag(diag::err_bad_memptr_lhs)
1947 << OpSpelling << (int)isIndirect)) {
1948 return QualType();
1949 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001950 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001951 /*DetectVirtual=*/false);
Mike Stump390b4cc2009-05-16 07:39:55 +00001952 // FIXME: Would it be useful to print full ambiguity paths, or is that
1953 // overkill?
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001954 if (!IsDerivedFrom(LType, Class, Paths) ||
1955 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
1956 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Eli Friedman3005efe2010-01-16 00:00:48 +00001957 << (int)isIndirect << lex->getType();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001958 return QualType();
1959 }
Eli Friedman3005efe2010-01-16 00:00:48 +00001960 // Cast LHS to type of use.
1961 QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
1962 bool isLValue = !isIndirect && lex->isLvalue(Context) == Expr::LV_Valid;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001963
1964 CXXBaseSpecifierArray BasePath;
1965 BuildBasePathArray(Paths, BasePath);
1966 ImpCastExprToType(lex, UseType, CastExpr::CK_DerivedToBase, isLValue,
1967 BasePath);
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001968 }
1969
Fariborz Jahanian19d70732009-11-18 22:16:17 +00001970 if (isa<CXXZeroInitValueExpr>(rex->IgnoreParens())) {
Fariborz Jahanian05ebda92009-11-18 21:54:48 +00001971 // Diagnose use of pointer-to-member type which when used as
1972 // the functional cast in a pointer-to-member expression.
1973 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
1974 return QualType();
1975 }
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001976 // C++ 5.5p2
1977 // The result is an object or a function of the type specified by the
1978 // second operand.
1979 // The cv qualifiers are the union of those in the pointer and the left side,
1980 // in accordance with 5.5p5 and 5.2.5.
1981 // FIXME: This returns a dereferenced member function pointer as a normal
1982 // function type. However, the only operation valid on such functions is
Mike Stump390b4cc2009-05-16 07:39:55 +00001983 // calling them. There's also a GCC extension to get a function pointer to the
1984 // thing, which is another complication, because this type - unlike the type
1985 // that is the result of this expression - takes the class as the first
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001986 // argument.
1987 // We probably need a "MemberFunctionClosureType" or something like that.
1988 QualType Result = MemPtr->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00001989 Result = Context.getCVRQualifiedType(Result, LType.getCVRQualifiers());
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001990 return Result;
1991}
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001992
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001993/// \brief Try to convert a type to another according to C++0x 5.16p3.
1994///
1995/// This is part of the parameter validation for the ? operator. If either
1996/// value operand is a class type, the two operands are attempted to be
1997/// converted to each other. This function does the conversion in one direction.
Douglas Gregorb70cf442010-03-26 20:14:36 +00001998/// It returns true if the program is ill-formed and has already been diagnosed
1999/// as such.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002000static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
2001 SourceLocation QuestionLoc,
Douglas Gregorb70cf442010-03-26 20:14:36 +00002002 bool &HaveConversion,
2003 QualType &ToType) {
2004 HaveConversion = false;
2005 ToType = To->getType();
2006
2007 InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
2008 SourceLocation());
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002009 // C++0x 5.16p3
2010 // The process for determining whether an operand expression E1 of type T1
2011 // can be converted to match an operand expression E2 of type T2 is defined
2012 // as follows:
2013 // -- If E2 is an lvalue:
Douglas Gregor0fd8ff72010-03-26 20:59:55 +00002014 bool ToIsLvalue = (To->isLvalue(Self.Context) == Expr::LV_Valid);
2015 if (ToIsLvalue) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002016 // E1 can be converted to match E2 if E1 can be implicitly converted to
2017 // type "lvalue reference to T2", subject to the constraint that in the
2018 // conversion the reference must bind directly to E1.
Douglas Gregorb70cf442010-03-26 20:14:36 +00002019 QualType T = Self.Context.getLValueReferenceType(ToType);
2020 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
2021
2022 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2023 if (InitSeq.isDirectReferenceBinding()) {
2024 ToType = T;
2025 HaveConversion = true;
2026 return false;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002027 }
Douglas Gregorb70cf442010-03-26 20:14:36 +00002028
2029 if (InitSeq.isAmbiguous())
2030 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002031 }
John McCallb1bdc622010-02-25 01:37:24 +00002032
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002033 // -- If E2 is an rvalue, or if the conversion above cannot be done:
2034 // -- if E1 and E2 have class type, and the underlying class types are
2035 // the same or one is a base class of the other:
2036 QualType FTy = From->getType();
2037 QualType TTy = To->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002038 const RecordType *FRec = FTy->getAs<RecordType>();
2039 const RecordType *TRec = TTy->getAs<RecordType>();
Douglas Gregorb70cf442010-03-26 20:14:36 +00002040 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
2041 Self.IsDerivedFrom(FTy, TTy);
2042 if (FRec && TRec &&
2043 (FRec == TRec || FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002044 // E1 can be converted to match E2 if the class of T2 is the
2045 // same type as, or a base class of, the class of T1, and
2046 // [cv2 > cv1].
John McCallb1bdc622010-02-25 01:37:24 +00002047 if (FRec == TRec || FDerivedFromT) {
2048 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00002049 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
2050 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2051 if (InitSeq.getKind() != InitializationSequence::FailedSequence) {
2052 HaveConversion = true;
2053 return false;
2054 }
2055
2056 if (InitSeq.isAmbiguous())
2057 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
2058 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002059 }
Douglas Gregorb70cf442010-03-26 20:14:36 +00002060
2061 return false;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002062 }
Douglas Gregorb70cf442010-03-26 20:14:36 +00002063
2064 // -- Otherwise: E1 can be converted to match E2 if E1 can be
2065 // implicitly converted to the type that expression E2 would have
Douglas Gregor0fd8ff72010-03-26 20:59:55 +00002066 // if E2 were converted to an rvalue (or the type it has, if E2 is
2067 // an rvalue).
2068 //
2069 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
2070 // to the array-to-pointer or function-to-pointer conversions.
2071 if (!TTy->getAs<TagType>())
2072 TTy = TTy.getUnqualifiedType();
Douglas Gregorb70cf442010-03-26 20:14:36 +00002073
2074 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
2075 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2076 HaveConversion = InitSeq.getKind() != InitializationSequence::FailedSequence;
2077 ToType = TTy;
2078 if (InitSeq.isAmbiguous())
2079 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
2080
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002081 return false;
2082}
2083
2084/// \brief Try to find a common type for two according to C++0x 5.16p5.
2085///
2086/// This is part of the parameter validation for the ? operator. If either
2087/// value operand is a class type, overload resolution is used to find a
2088/// conversion to a common type.
2089static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
2090 SourceLocation Loc) {
2091 Expr *Args[2] = { LHS, RHS };
John McCall5769d612010-02-08 23:07:23 +00002092 OverloadCandidateSet CandidateSet(Loc);
Douglas Gregor573d9c32009-10-21 23:19:44 +00002093 Self.AddBuiltinOperatorCandidates(OO_Conditional, Loc, Args, 2, CandidateSet);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002094
2095 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00002096 switch (Self.BestViableFunction(CandidateSet, Loc, Best)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002097 case OR_Success:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002098 // We found a match. Perform the conversions on the arguments and move on.
2099 if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00002100 Best->Conversions[0], Sema::AA_Converting) ||
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002101 Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor68647482009-12-16 03:45:30 +00002102 Best->Conversions[1], Sema::AA_Converting))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002103 break;
2104 return false;
2105
Douglas Gregor20093b42009-12-09 23:02:17 +00002106 case OR_No_Viable_Function:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002107 Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
2108 << LHS->getType() << RHS->getType()
2109 << LHS->getSourceRange() << RHS->getSourceRange();
2110 return true;
2111
Douglas Gregor20093b42009-12-09 23:02:17 +00002112 case OR_Ambiguous:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002113 Self.Diag(Loc, diag::err_conditional_ambiguous_ovl)
2114 << LHS->getType() << RHS->getType()
2115 << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stump390b4cc2009-05-16 07:39:55 +00002116 // FIXME: Print the possible common types by printing the return types of
2117 // the viable candidates.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002118 break;
2119
Douglas Gregor20093b42009-12-09 23:02:17 +00002120 case OR_Deleted:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002121 assert(false && "Conditional operator has only built-in overloads");
2122 break;
2123 }
2124 return true;
2125}
2126
Sebastian Redl76458502009-04-17 16:30:52 +00002127/// \brief Perform an "extended" implicit conversion as returned by
2128/// TryClassUnification.
Douglas Gregorb70cf442010-03-26 20:14:36 +00002129static bool ConvertForConditional(Sema &Self, Expr *&E, QualType T) {
2130 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
2131 InitializationKind Kind = InitializationKind::CreateCopy(E->getLocStart(),
2132 SourceLocation());
2133 InitializationSequence InitSeq(Self, Entity, Kind, &E, 1);
2134 Sema::OwningExprResult Result = InitSeq.Perform(Self, Entity, Kind,
2135 Sema::MultiExprArg(Self, (void **)&E, 1));
2136 if (Result.isInvalid())
Sebastian Redl76458502009-04-17 16:30:52 +00002137 return true;
Douglas Gregorb70cf442010-03-26 20:14:36 +00002138
2139 E = Result.takeAs<Expr>();
Sebastian Redl76458502009-04-17 16:30:52 +00002140 return false;
2141}
2142
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002143/// \brief Check the operands of ?: under C++ semantics.
2144///
2145/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
2146/// extension. In this case, LHS == Cond. (But they're not aliases.)
2147QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
2148 SourceLocation QuestionLoc) {
Mike Stump390b4cc2009-05-16 07:39:55 +00002149 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
2150 // interface pointers.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002151
2152 // C++0x 5.16p1
2153 // The first expression is contextually converted to bool.
2154 if (!Cond->isTypeDependent()) {
2155 if (CheckCXXBooleanCondition(Cond))
2156 return QualType();
2157 }
2158
2159 // Either of the arguments dependent?
2160 if (LHS->isTypeDependent() || RHS->isTypeDependent())
2161 return Context.DependentTy;
2162
2163 // C++0x 5.16p2
2164 // If either the second or the third operand has type (cv) void, ...
2165 QualType LTy = LHS->getType();
2166 QualType RTy = RHS->getType();
2167 bool LVoid = LTy->isVoidType();
2168 bool RVoid = RTy->isVoidType();
2169 if (LVoid || RVoid) {
2170 // ... then the [l2r] conversions are performed on the second and third
2171 // operands ...
Douglas Gregora873dfc2010-02-03 00:27:59 +00002172 DefaultFunctionArrayLvalueConversion(LHS);
2173 DefaultFunctionArrayLvalueConversion(RHS);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002174 LTy = LHS->getType();
2175 RTy = RHS->getType();
2176
2177 // ... and one of the following shall hold:
2178 // -- The second or the third operand (but not both) is a throw-
2179 // expression; the result is of the type of the other and is an rvalue.
2180 bool LThrow = isa<CXXThrowExpr>(LHS);
2181 bool RThrow = isa<CXXThrowExpr>(RHS);
2182 if (LThrow && !RThrow)
2183 return RTy;
2184 if (RThrow && !LThrow)
2185 return LTy;
2186
2187 // -- Both the second and third operands have type void; the result is of
2188 // type void and is an rvalue.
2189 if (LVoid && RVoid)
2190 return Context.VoidTy;
2191
2192 // Neither holds, error.
2193 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
2194 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
2195 << LHS->getSourceRange() << RHS->getSourceRange();
2196 return QualType();
2197 }
2198
2199 // Neither is void.
2200
2201 // C++0x 5.16p3
2202 // Otherwise, if the second and third operand have different types, and
2203 // either has (cv) class type, and attempt is made to convert each of those
2204 // operands to the other.
Douglas Gregorb70cf442010-03-26 20:14:36 +00002205 if (!Context.hasSameType(LTy, RTy) &&
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002206 (LTy->isRecordType() || RTy->isRecordType())) {
2207 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
2208 // These return true if a single direction is already ambiguous.
Douglas Gregorb70cf442010-03-26 20:14:36 +00002209 QualType L2RType, R2LType;
2210 bool HaveL2R, HaveR2L;
2211 if (TryClassUnification(*this, LHS, RHS, QuestionLoc, HaveL2R, L2RType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002212 return QualType();
Douglas Gregorb70cf442010-03-26 20:14:36 +00002213 if (TryClassUnification(*this, RHS, LHS, QuestionLoc, HaveR2L, R2LType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002214 return QualType();
Douglas Gregorb70cf442010-03-26 20:14:36 +00002215
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002216 // If both can be converted, [...] the program is ill-formed.
2217 if (HaveL2R && HaveR2L) {
2218 Diag(QuestionLoc, diag::err_conditional_ambiguous)
2219 << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
2220 return QualType();
2221 }
2222
2223 // If exactly one conversion is possible, that conversion is applied to
2224 // the chosen operand and the converted operands are used in place of the
2225 // original operands for the remainder of this section.
2226 if (HaveL2R) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00002227 if (ConvertForConditional(*this, LHS, L2RType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002228 return QualType();
2229 LTy = LHS->getType();
2230 } else if (HaveR2L) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00002231 if (ConvertForConditional(*this, RHS, R2LType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002232 return QualType();
2233 RTy = RHS->getType();
2234 }
2235 }
2236
2237 // C++0x 5.16p4
2238 // If the second and third operands are lvalues and have the same type,
2239 // the result is of that type [...]
Douglas Gregor1927b1f2010-04-01 22:47:07 +00002240 bool Same = Context.hasSameType(LTy, RTy);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002241 if (Same && LHS->isLvalue(Context) == Expr::LV_Valid &&
2242 RHS->isLvalue(Context) == Expr::LV_Valid)
2243 return LTy;
2244
2245 // C++0x 5.16p5
2246 // Otherwise, the result is an rvalue. If the second and third operands
2247 // do not have the same type, and either has (cv) class type, ...
2248 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
2249 // ... overload resolution is used to determine the conversions (if any)
2250 // to be applied to the operands. If the overload resolution fails, the
2251 // program is ill-formed.
2252 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
2253 return QualType();
2254 }
2255
2256 // C++0x 5.16p6
2257 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
2258 // conversions are performed on the second and third operands.
Douglas Gregora873dfc2010-02-03 00:27:59 +00002259 DefaultFunctionArrayLvalueConversion(LHS);
2260 DefaultFunctionArrayLvalueConversion(RHS);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002261 LTy = LHS->getType();
2262 RTy = RHS->getType();
2263
2264 // After those conversions, one of the following shall hold:
2265 // -- The second and third operands have the same type; the result
Douglas Gregorb65a4582010-05-19 23:40:50 +00002266 // is of that type. If the operands have class type, the result
2267 // is a prvalue temporary of the result type, which is
2268 // copy-initialized from either the second operand or the third
2269 // operand depending on the value of the first operand.
2270 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
2271 if (LTy->isRecordType()) {
2272 // The operands have class type. Make a temporary copy.
2273 InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
2274 OwningExprResult LHSCopy = PerformCopyInitialization(Entity,
2275 SourceLocation(),
2276 Owned(LHS));
2277 if (LHSCopy.isInvalid())
2278 return QualType();
2279
2280 OwningExprResult RHSCopy = PerformCopyInitialization(Entity,
2281 SourceLocation(),
2282 Owned(RHS));
2283 if (RHSCopy.isInvalid())
2284 return QualType();
2285
2286 LHS = LHSCopy.takeAs<Expr>();
2287 RHS = RHSCopy.takeAs<Expr>();
2288 }
2289
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002290 return LTy;
Douglas Gregorb65a4582010-05-19 23:40:50 +00002291 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002292
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002293 // Extension: conditional operator involving vector types.
2294 if (LTy->isVectorType() || RTy->isVectorType())
2295 return CheckVectorOperands(QuestionLoc, LHS, RHS);
2296
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002297 // -- The second and third operands have arithmetic or enumeration type;
2298 // the usual arithmetic conversions are performed to bring them to a
2299 // common type, and the result is of that type.
2300 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
2301 UsualArithmeticConversions(LHS, RHS);
2302 return LHS->getType();
2303 }
2304
2305 // -- The second and third operands have pointer type, or one has pointer
2306 // type and the other is a null pointer constant; pointer conversions
2307 // and qualification conversions are performed to bring them to their
2308 // composite pointer type. The result is of the composite pointer type.
Eli Friedmande8ac492010-01-02 22:56:07 +00002309 // -- The second and third operands have pointer to member type, or one has
2310 // pointer to member type and the other is a null pointer constant;
2311 // pointer to member conversions and qualification conversions are
2312 // performed to bring them to a common type, whose cv-qualification
2313 // shall match the cv-qualification of either the second or the third
2314 // operand. The result is of the common type.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002315 bool NonStandardCompositeType = false;
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002316 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002317 isSFINAEContext()? 0 : &NonStandardCompositeType);
2318 if (!Composite.isNull()) {
2319 if (NonStandardCompositeType)
2320 Diag(QuestionLoc,
2321 diag::ext_typecheck_cond_incompatible_operands_nonstandard)
2322 << LTy << RTy << Composite
2323 << LHS->getSourceRange() << RHS->getSourceRange();
2324
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002325 return Composite;
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002326 }
Fariborz Jahanian55016362009-12-10 20:46:08 +00002327
Douglas Gregor1927b1f2010-04-01 22:47:07 +00002328 // Similarly, attempt to find composite type of two objective-c pointers.
Fariborz Jahanian55016362009-12-10 20:46:08 +00002329 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
2330 if (!Composite.isNull())
2331 return Composite;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002332
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002333 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
2334 << LHS->getType() << RHS->getType()
2335 << LHS->getSourceRange() << RHS->getSourceRange();
2336 return QualType();
2337}
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002338
2339/// \brief Find a merged pointer type and convert the two expressions to it.
2340///
Douglas Gregor20b3e992009-08-24 17:42:35 +00002341/// This finds the composite pointer type (or member pointer type) for @p E1
2342/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
2343/// type and returns it.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002344/// It does not emit diagnostics.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002345///
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002346/// \param Loc The location of the operator requiring these two expressions to
2347/// be converted to the composite pointer type.
2348///
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002349/// If \p NonStandardCompositeType is non-NULL, then we are permitted to find
2350/// a non-standard (but still sane) composite type to which both expressions
2351/// can be converted. When such a type is chosen, \c *NonStandardCompositeType
2352/// will be set true.
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002353QualType Sema::FindCompositePointerType(SourceLocation Loc,
2354 Expr *&E1, Expr *&E2,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002355 bool *NonStandardCompositeType) {
2356 if (NonStandardCompositeType)
2357 *NonStandardCompositeType = false;
2358
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002359 assert(getLangOptions().CPlusPlus && "This function assumes C++");
2360 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002361
Fariborz Jahanian0cedfbd2009-12-08 20:04:24 +00002362 if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
2363 !T2->isAnyPointerType() && !T2->isMemberPointerType())
Douglas Gregor20b3e992009-08-24 17:42:35 +00002364 return QualType();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002365
2366 // C++0x 5.9p2
2367 // Pointer conversions and qualification conversions are performed on
2368 // pointer operands to bring them to their composite pointer type. If
2369 // one operand is a null pointer constant, the composite pointer type is
2370 // the type of the other operand.
Douglas Gregorce940492009-09-25 04:25:58 +00002371 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00002372 if (T2->isMemberPointerType())
2373 ImpCastExprToType(E1, T2, CastExpr::CK_NullToMemberPointer);
2374 else
2375 ImpCastExprToType(E1, T2, CastExpr::CK_IntegralToPointer);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002376 return T2;
2377 }
Douglas Gregorce940492009-09-25 04:25:58 +00002378 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00002379 if (T1->isMemberPointerType())
2380 ImpCastExprToType(E2, T1, CastExpr::CK_NullToMemberPointer);
2381 else
2382 ImpCastExprToType(E2, T1, CastExpr::CK_IntegralToPointer);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002383 return T1;
2384 }
Mike Stump1eb44332009-09-09 15:08:12 +00002385
Douglas Gregor20b3e992009-08-24 17:42:35 +00002386 // Now both have to be pointers or member pointers.
Sebastian Redla439e6f2009-11-16 21:03:45 +00002387 if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
2388 (!T2->isPointerType() && !T2->isMemberPointerType()))
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002389 return QualType();
2390
2391 // Otherwise, of one of the operands has type "pointer to cv1 void," then
2392 // the other has type "pointer to cv2 T" and the composite pointer type is
2393 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
2394 // Otherwise, the composite pointer type is a pointer type similar to the
2395 // type of one of the operands, with a cv-qualification signature that is
2396 // the union of the cv-qualification signatures of the operand types.
2397 // In practice, the first part here is redundant; it's subsumed by the second.
2398 // What we do here is, we build the two possible composite types, and try the
2399 // conversions in both directions. If only one works, or if the two composite
2400 // types are the same, we have succeeded.
John McCall0953e762009-09-24 19:53:00 +00002401 // FIXME: extended qualifiers?
Sebastian Redla439e6f2009-11-16 21:03:45 +00002402 typedef llvm::SmallVector<unsigned, 4> QualifierVector;
2403 QualifierVector QualifierUnion;
2404 typedef llvm::SmallVector<std::pair<const Type *, const Type *>, 4>
2405 ContainingClassVector;
2406 ContainingClassVector MemberOfClass;
2407 QualType Composite1 = Context.getCanonicalType(T1),
2408 Composite2 = Context.getCanonicalType(T2);
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002409 unsigned NeedConstBefore = 0;
Douglas Gregor20b3e992009-08-24 17:42:35 +00002410 do {
2411 const PointerType *Ptr1, *Ptr2;
2412 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
2413 (Ptr2 = Composite2->getAs<PointerType>())) {
2414 Composite1 = Ptr1->getPointeeType();
2415 Composite2 = Ptr2->getPointeeType();
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002416
2417 // If we're allowed to create a non-standard composite type, keep track
2418 // of where we need to fill in additional 'const' qualifiers.
2419 if (NonStandardCompositeType &&
2420 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
2421 NeedConstBefore = QualifierUnion.size();
2422
Douglas Gregor20b3e992009-08-24 17:42:35 +00002423 QualifierUnion.push_back(
2424 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
2425 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
2426 continue;
2427 }
Mike Stump1eb44332009-09-09 15:08:12 +00002428
Douglas Gregor20b3e992009-08-24 17:42:35 +00002429 const MemberPointerType *MemPtr1, *MemPtr2;
2430 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
2431 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
2432 Composite1 = MemPtr1->getPointeeType();
2433 Composite2 = MemPtr2->getPointeeType();
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002434
2435 // If we're allowed to create a non-standard composite type, keep track
2436 // of where we need to fill in additional 'const' qualifiers.
2437 if (NonStandardCompositeType &&
2438 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
2439 NeedConstBefore = QualifierUnion.size();
2440
Douglas Gregor20b3e992009-08-24 17:42:35 +00002441 QualifierUnion.push_back(
2442 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
2443 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
2444 MemPtr2->getClass()));
2445 continue;
2446 }
Mike Stump1eb44332009-09-09 15:08:12 +00002447
Douglas Gregor20b3e992009-08-24 17:42:35 +00002448 // FIXME: block pointer types?
Mike Stump1eb44332009-09-09 15:08:12 +00002449
Douglas Gregor20b3e992009-08-24 17:42:35 +00002450 // Cannot unwrap any more types.
2451 break;
2452 } while (true);
Mike Stump1eb44332009-09-09 15:08:12 +00002453
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002454 if (NeedConstBefore && NonStandardCompositeType) {
2455 // Extension: Add 'const' to qualifiers that come before the first qualifier
2456 // mismatch, so that our (non-standard!) composite type meets the
2457 // requirements of C++ [conv.qual]p4 bullet 3.
2458 for (unsigned I = 0; I != NeedConstBefore; ++I) {
2459 if ((QualifierUnion[I] & Qualifiers::Const) == 0) {
2460 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
2461 *NonStandardCompositeType = true;
2462 }
2463 }
2464 }
2465
Douglas Gregor20b3e992009-08-24 17:42:35 +00002466 // Rewrap the composites as pointers or member pointers with the union CVRs.
Sebastian Redla439e6f2009-11-16 21:03:45 +00002467 ContainingClassVector::reverse_iterator MOC
2468 = MemberOfClass.rbegin();
2469 for (QualifierVector::reverse_iterator
2470 I = QualifierUnion.rbegin(),
2471 E = QualifierUnion.rend();
Douglas Gregor20b3e992009-08-24 17:42:35 +00002472 I != E; (void)++I, ++MOC) {
John McCall0953e762009-09-24 19:53:00 +00002473 Qualifiers Quals = Qualifiers::fromCVRMask(*I);
Douglas Gregor20b3e992009-08-24 17:42:35 +00002474 if (MOC->first && MOC->second) {
2475 // Rebuild member pointer type
John McCall0953e762009-09-24 19:53:00 +00002476 Composite1 = Context.getMemberPointerType(
2477 Context.getQualifiedType(Composite1, Quals),
2478 MOC->first);
2479 Composite2 = Context.getMemberPointerType(
2480 Context.getQualifiedType(Composite2, Quals),
2481 MOC->second);
Douglas Gregor20b3e992009-08-24 17:42:35 +00002482 } else {
2483 // Rebuild pointer type
John McCall0953e762009-09-24 19:53:00 +00002484 Composite1
2485 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
2486 Composite2
2487 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregor20b3e992009-08-24 17:42:35 +00002488 }
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002489 }
2490
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002491 // Try to convert to the first composite pointer type.
2492 InitializedEntity Entity1
2493 = InitializedEntity::InitializeTemporary(Composite1);
2494 InitializationKind Kind
2495 = InitializationKind::CreateCopy(Loc, SourceLocation());
2496 InitializationSequence E1ToC1(*this, Entity1, Kind, &E1, 1);
2497 InitializationSequence E2ToC1(*this, Entity1, Kind, &E2, 1);
Mike Stump1eb44332009-09-09 15:08:12 +00002498
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002499 if (E1ToC1 && E2ToC1) {
2500 // Conversion to Composite1 is viable.
2501 if (!Context.hasSameType(Composite1, Composite2)) {
2502 // Composite2 is a different type from Composite1. Check whether
2503 // Composite2 is also viable.
2504 InitializedEntity Entity2
2505 = InitializedEntity::InitializeTemporary(Composite2);
2506 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
2507 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
2508 if (E1ToC2 && E2ToC2) {
2509 // Both Composite1 and Composite2 are viable and are different;
2510 // this is an ambiguity.
2511 return QualType();
2512 }
2513 }
2514
2515 // Convert E1 to Composite1
2516 OwningExprResult E1Result
2517 = E1ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,(void**)&E1,1));
2518 if (E1Result.isInvalid())
2519 return QualType();
2520 E1 = E1Result.takeAs<Expr>();
2521
2522 // Convert E2 to Composite1
2523 OwningExprResult E2Result
2524 = E2ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,(void**)&E2,1));
2525 if (E2Result.isInvalid())
2526 return QualType();
2527 E2 = E2Result.takeAs<Expr>();
2528
2529 return Composite1;
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002530 }
2531
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002532 // Check whether Composite2 is viable.
2533 InitializedEntity Entity2
2534 = InitializedEntity::InitializeTemporary(Composite2);
2535 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
2536 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
2537 if (!E1ToC2 || !E2ToC2)
2538 return QualType();
2539
2540 // Convert E1 to Composite2
2541 OwningExprResult E1Result
2542 = E1ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, (void**)&E1, 1));
2543 if (E1Result.isInvalid())
2544 return QualType();
2545 E1 = E1Result.takeAs<Expr>();
2546
2547 // Convert E2 to Composite2
2548 OwningExprResult E2Result
2549 = E2ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, (void**)&E2, 1));
2550 if (E2Result.isInvalid())
2551 return QualType();
2552 E2 = E2Result.takeAs<Expr>();
2553
2554 return Composite2;
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002555}
Anders Carlsson165a0a02009-05-17 18:41:29 +00002556
Anders Carlssondef11992009-05-30 20:36:53 +00002557Sema::OwningExprResult Sema::MaybeBindToTemporary(Expr *E) {
Anders Carlsson089c2602009-08-15 23:41:35 +00002558 if (!Context.getLangOptions().CPlusPlus)
2559 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002560
Douglas Gregor51326552009-12-24 18:51:59 +00002561 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
2562
Ted Kremenek6217b802009-07-29 21:53:49 +00002563 const RecordType *RT = E->getType()->getAs<RecordType>();
Anders Carlssondef11992009-05-30 20:36:53 +00002564 if (!RT)
2565 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002566
John McCall86ff3082010-02-04 22:26:26 +00002567 // If this is the result of a call expression, our source might
2568 // actually be a reference, in which case we shouldn't bind.
Anders Carlsson283e4d52009-09-14 01:30:44 +00002569 if (CallExpr *CE = dyn_cast<CallExpr>(E)) {
2570 QualType Ty = CE->getCallee()->getType();
2571 if (const PointerType *PT = Ty->getAs<PointerType>())
2572 Ty = PT->getPointeeType();
Fariborz Jahanianb372b0f2010-02-18 20:31:02 +00002573 else if (const BlockPointerType *BPT = Ty->getAs<BlockPointerType>())
2574 Ty = BPT->getPointeeType();
2575
John McCall183700f2009-09-21 23:43:11 +00002576 const FunctionType *FTy = Ty->getAs<FunctionType>();
Anders Carlsson283e4d52009-09-14 01:30:44 +00002577 if (FTy->getResultType()->isReferenceType())
2578 return Owned(E);
2579 }
John McCall86ff3082010-02-04 22:26:26 +00002580
2581 // That should be enough to guarantee that this type is complete.
2582 // If it has a trivial destructor, we can avoid the extra copy.
2583 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2584 if (RD->hasTrivialDestructor())
2585 return Owned(E);
2586
Mike Stump1eb44332009-09-09 15:08:12 +00002587 CXXTemporary *Temp = CXXTemporary::Create(Context,
Anders Carlssondef11992009-05-30 20:36:53 +00002588 RD->getDestructor(Context));
Anders Carlsson860306e2009-05-30 21:21:49 +00002589 ExprTemporaries.push_back(Temp);
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00002590 if (CXXDestructorDecl *Destructor =
John McCallc91cc662010-04-07 00:41:46 +00002591 const_cast<CXXDestructorDecl*>(RD->getDestructor(Context))) {
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00002592 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
John McCallc91cc662010-04-07 00:41:46 +00002593 CheckDestructorAccess(E->getExprLoc(), Destructor,
2594 PDiag(diag::err_access_dtor_temp)
2595 << E->getType());
2596 }
Anders Carlssondef11992009-05-30 20:36:53 +00002597 // FIXME: Add the temporary to the temporaries vector.
2598 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
2599}
2600
Anders Carlsson0ece4912009-12-15 20:51:39 +00002601Expr *Sema::MaybeCreateCXXExprWithTemporaries(Expr *SubExpr) {
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002602 assert(SubExpr && "sub expression can't be null!");
Mike Stump1eb44332009-09-09 15:08:12 +00002603
John McCall323ed742010-05-06 08:58:33 +00002604 // Check any implicit conversions within the expression.
2605 CheckImplicitConversions(SubExpr);
2606
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00002607 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
2608 assert(ExprTemporaries.size() >= FirstTemporary);
2609 if (ExprTemporaries.size() == FirstTemporary)
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002610 return SubExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00002611
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002612 Expr *E = CXXExprWithTemporaries::Create(Context, SubExpr,
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00002613 &ExprTemporaries[FirstTemporary],
Anders Carlsson0ece4912009-12-15 20:51:39 +00002614 ExprTemporaries.size() - FirstTemporary);
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00002615 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
2616 ExprTemporaries.end());
Mike Stump1eb44332009-09-09 15:08:12 +00002617
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002618 return E;
2619}
2620
Douglas Gregor90f93822009-12-22 22:17:25 +00002621Sema::OwningExprResult
2622Sema::MaybeCreateCXXExprWithTemporaries(OwningExprResult SubExpr) {
2623 if (SubExpr.isInvalid())
2624 return ExprError();
2625
2626 return Owned(MaybeCreateCXXExprWithTemporaries(SubExpr.takeAs<Expr>()));
2627}
2628
Anders Carlsson5ee56e92009-12-16 02:09:40 +00002629FullExpr Sema::CreateFullExpr(Expr *SubExpr) {
2630 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
2631 assert(ExprTemporaries.size() >= FirstTemporary);
2632
2633 unsigned NumTemporaries = ExprTemporaries.size() - FirstTemporary;
2634 CXXTemporary **Temporaries =
2635 NumTemporaries == 0 ? 0 : &ExprTemporaries[FirstTemporary];
2636
2637 FullExpr E = FullExpr::Create(Context, SubExpr, Temporaries, NumTemporaries);
2638
2639 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
2640 ExprTemporaries.end());
2641
2642 return E;
2643}
2644
Mike Stump1eb44332009-09-09 15:08:12 +00002645Sema::OwningExprResult
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002646Sema::ActOnStartCXXMemberReference(Scope *S, ExprArg Base, SourceLocation OpLoc,
Douglas Gregord4dca082010-02-24 18:44:31 +00002647 tok::TokenKind OpKind, TypeTy *&ObjectType,
2648 bool &MayBePseudoDestructor) {
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002649 // Since this might be a postfix expression, get rid of ParenListExprs.
2650 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
Mike Stump1eb44332009-09-09 15:08:12 +00002651
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002652 Expr *BaseExpr = (Expr*)Base.get();
2653 assert(BaseExpr && "no record expansion");
Mike Stump1eb44332009-09-09 15:08:12 +00002654
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002655 QualType BaseType = BaseExpr->getType();
Douglas Gregord4dca082010-02-24 18:44:31 +00002656 MayBePseudoDestructor = false;
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002657 if (BaseType->isDependentType()) {
Douglas Gregor43d88632009-11-04 22:49:18 +00002658 // If we have a pointer to a dependent type and are using the -> operator,
2659 // the object type is the type that the pointer points to. We might still
2660 // have enough information about that type to do something useful.
2661 if (OpKind == tok::arrow)
2662 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
2663 BaseType = Ptr->getPointeeType();
2664
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002665 ObjectType = BaseType.getAsOpaquePtr();
Douglas Gregord4dca082010-02-24 18:44:31 +00002666 MayBePseudoDestructor = true;
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002667 return move(Base);
2668 }
Mike Stump1eb44332009-09-09 15:08:12 +00002669
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002670 // C++ [over.match.oper]p8:
Mike Stump1eb44332009-09-09 15:08:12 +00002671 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002672 // returned, with the original second operand.
2673 if (OpKind == tok::arrow) {
John McCallc4e83212009-09-30 01:01:30 +00002674 // The set of types we've considered so far.
John McCall432887f2009-09-30 01:30:54 +00002675 llvm::SmallPtrSet<CanQualType,8> CTypes;
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002676 llvm::SmallVector<SourceLocation, 8> Locations;
John McCall432887f2009-09-30 01:30:54 +00002677 CTypes.insert(Context.getCanonicalType(BaseType));
John McCallc4e83212009-09-30 01:01:30 +00002678
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002679 while (BaseType->isRecordType()) {
Anders Carlsson15ea3782009-10-13 22:43:21 +00002680 Base = BuildOverloadedArrowExpr(S, move(Base), OpLoc);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002681 BaseExpr = (Expr*)Base.get();
2682 if (BaseExpr == NULL)
2683 return ExprError();
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002684 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(BaseExpr))
Anders Carlssonde699e52009-10-13 22:55:59 +00002685 Locations.push_back(OpCall->getDirectCallee()->getLocation());
John McCallc4e83212009-09-30 01:01:30 +00002686 BaseType = BaseExpr->getType();
2687 CanQualType CBaseType = Context.getCanonicalType(BaseType);
John McCall432887f2009-09-30 01:30:54 +00002688 if (!CTypes.insert(CBaseType)) {
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00002689 Diag(OpLoc, diag::err_operator_arrow_circular);
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002690 for (unsigned i = 0; i < Locations.size(); i++)
2691 Diag(Locations[i], diag::note_declared_at);
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00002692 return ExprError();
2693 }
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002694 }
Mike Stump1eb44332009-09-09 15:08:12 +00002695
Douglas Gregor31658df2009-11-20 19:58:21 +00002696 if (BaseType->isPointerType())
2697 BaseType = BaseType->getPointeeType();
2698 }
Mike Stump1eb44332009-09-09 15:08:12 +00002699
2700 // We could end up with various non-record types here, such as extended
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002701 // vector types or Objective-C interfaces. Just return early and let
2702 // ActOnMemberReferenceExpr do the work.
Douglas Gregorc68afe22009-09-03 21:38:09 +00002703 if (!BaseType->isRecordType()) {
2704 // C++ [basic.lookup.classref]p2:
2705 // [...] If the type of the object expression is of pointer to scalar
2706 // type, the unqualified-id is looked up in the context of the complete
2707 // postfix-expression.
Douglas Gregord4dca082010-02-24 18:44:31 +00002708 //
2709 // This also indicates that we should be parsing a
2710 // pseudo-destructor-name.
Douglas Gregorc68afe22009-09-03 21:38:09 +00002711 ObjectType = 0;
Douglas Gregord4dca082010-02-24 18:44:31 +00002712 MayBePseudoDestructor = true;
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002713 return move(Base);
Douglas Gregorc68afe22009-09-03 21:38:09 +00002714 }
Mike Stump1eb44332009-09-09 15:08:12 +00002715
Douglas Gregor03c57052009-11-17 05:17:33 +00002716 // The object type must be complete (or dependent).
2717 if (!BaseType->isDependentType() &&
2718 RequireCompleteType(OpLoc, BaseType,
2719 PDiag(diag::err_incomplete_member_access)))
2720 return ExprError();
2721
Douglas Gregorc68afe22009-09-03 21:38:09 +00002722 // C++ [basic.lookup.classref]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00002723 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor03c57052009-11-17 05:17:33 +00002724 // unqualified-id, and the type of the object expression is of a class
Douglas Gregorc68afe22009-09-03 21:38:09 +00002725 // type C (or of pointer to a class type C), the unqualified-id is looked
2726 // up in the scope of class C. [...]
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002727 ObjectType = BaseType.getAsOpaquePtr();
Mike Stump1eb44332009-09-09 15:08:12 +00002728 return move(Base);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002729}
2730
Douglas Gregor77549082010-02-24 21:29:12 +00002731Sema::OwningExprResult Sema::DiagnoseDtorReference(SourceLocation NameLoc,
2732 ExprArg MemExpr) {
2733 Expr *E = (Expr *) MemExpr.get();
2734 SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(NameLoc);
2735 Diag(E->getLocStart(), diag::err_dtor_expr_without_call)
2736 << isa<CXXPseudoDestructorExpr>(E)
Douglas Gregor849b2432010-03-31 17:46:05 +00002737 << FixItHint::CreateInsertion(ExpectedLParenLoc, "()");
Douglas Gregor77549082010-02-24 21:29:12 +00002738
2739 return ActOnCallExpr(/*Scope*/ 0,
2740 move(MemExpr),
2741 /*LPLoc*/ ExpectedLParenLoc,
2742 Sema::MultiExprArg(*this, 0, 0),
2743 /*CommaLocs*/ 0,
2744 /*RPLoc*/ ExpectedLParenLoc);
2745}
Douglas Gregord4dca082010-02-24 18:44:31 +00002746
Douglas Gregorb57fb492010-02-24 22:38:50 +00002747Sema::OwningExprResult Sema::BuildPseudoDestructorExpr(ExprArg Base,
2748 SourceLocation OpLoc,
2749 tok::TokenKind OpKind,
2750 const CXXScopeSpec &SS,
Douglas Gregor26d4ac92010-02-24 23:40:28 +00002751 TypeSourceInfo *ScopeTypeInfo,
Douglas Gregorb57fb492010-02-24 22:38:50 +00002752 SourceLocation CCLoc,
Douglas Gregorfce46ee2010-02-24 23:50:37 +00002753 SourceLocation TildeLoc,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002754 PseudoDestructorTypeStorage Destructed,
Douglas Gregorb57fb492010-02-24 22:38:50 +00002755 bool HasTrailingLParen) {
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002756 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
Douglas Gregorb57fb492010-02-24 22:38:50 +00002757
2758 // C++ [expr.pseudo]p2:
2759 // The left-hand side of the dot operator shall be of scalar type. The
2760 // left-hand side of the arrow operator shall be of pointer to scalar type.
2761 // This scalar type is the object type.
2762 Expr *BaseE = (Expr *)Base.get();
2763 QualType ObjectType = BaseE->getType();
2764 if (OpKind == tok::arrow) {
2765 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
2766 ObjectType = Ptr->getPointeeType();
2767 } else if (!BaseE->isTypeDependent()) {
2768 // The user wrote "p->" when she probably meant "p."; fix it.
2769 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
2770 << ObjectType << true
Douglas Gregor849b2432010-03-31 17:46:05 +00002771 << FixItHint::CreateReplacement(OpLoc, ".");
Douglas Gregorb57fb492010-02-24 22:38:50 +00002772 if (isSFINAEContext())
2773 return ExprError();
2774
2775 OpKind = tok::period;
2776 }
2777 }
2778
2779 if (!ObjectType->isDependentType() && !ObjectType->isScalarType()) {
2780 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
2781 << ObjectType << BaseE->getSourceRange();
2782 return ExprError();
2783 }
2784
2785 // C++ [expr.pseudo]p2:
2786 // [...] The cv-unqualified versions of the object type and of the type
2787 // designated by the pseudo-destructor-name shall be the same type.
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002788 if (DestructedTypeInfo) {
2789 QualType DestructedType = DestructedTypeInfo->getType();
2790 SourceLocation DestructedTypeStart
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002791 = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002792 if (!DestructedType->isDependentType() && !ObjectType->isDependentType() &&
2793 !Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
2794 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
2795 << ObjectType << DestructedType << BaseE->getSourceRange()
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002796 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002797
2798 // Recover by setting the destructed type to the object type.
2799 DestructedType = ObjectType;
2800 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
2801 DestructedTypeStart);
2802 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
2803 }
Douglas Gregorb57fb492010-02-24 22:38:50 +00002804 }
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002805
Douglas Gregorb57fb492010-02-24 22:38:50 +00002806 // C++ [expr.pseudo]p2:
2807 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
2808 // form
2809 //
2810 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
2811 //
2812 // shall designate the same scalar type.
2813 if (ScopeTypeInfo) {
2814 QualType ScopeType = ScopeTypeInfo->getType();
2815 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
2816 !Context.hasSameType(ScopeType, ObjectType)) {
2817
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002818 Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
Douglas Gregorb57fb492010-02-24 22:38:50 +00002819 diag::err_pseudo_dtor_type_mismatch)
2820 << ObjectType << ScopeType << BaseE->getSourceRange()
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002821 << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregorb57fb492010-02-24 22:38:50 +00002822
2823 ScopeType = QualType();
2824 ScopeTypeInfo = 0;
2825 }
2826 }
2827
2828 OwningExprResult Result
2829 = Owned(new (Context) CXXPseudoDestructorExpr(Context,
2830 Base.takeAs<Expr>(),
2831 OpKind == tok::arrow,
2832 OpLoc,
2833 (NestedNameSpecifier *) SS.getScopeRep(),
2834 SS.getRange(),
2835 ScopeTypeInfo,
2836 CCLoc,
Douglas Gregorfce46ee2010-02-24 23:50:37 +00002837 TildeLoc,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002838 Destructed));
2839
Douglas Gregorb57fb492010-02-24 22:38:50 +00002840 if (HasTrailingLParen)
2841 return move(Result);
2842
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002843 return DiagnoseDtorReference(Destructed.getLocation(), move(Result));
Douglas Gregor77549082010-02-24 21:29:12 +00002844}
2845
2846Sema::OwningExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, ExprArg Base,
2847 SourceLocation OpLoc,
2848 tok::TokenKind OpKind,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00002849 CXXScopeSpec &SS,
Douglas Gregor77549082010-02-24 21:29:12 +00002850 UnqualifiedId &FirstTypeName,
2851 SourceLocation CCLoc,
2852 SourceLocation TildeLoc,
2853 UnqualifiedId &SecondTypeName,
2854 bool HasTrailingLParen) {
2855 assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
2856 FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
2857 "Invalid first type name in pseudo-destructor");
2858 assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
2859 SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
2860 "Invalid second type name in pseudo-destructor");
2861
2862 Expr *BaseE = (Expr *)Base.get();
Douglas Gregor77549082010-02-24 21:29:12 +00002863
2864 // C++ [expr.pseudo]p2:
2865 // The left-hand side of the dot operator shall be of scalar type. The
2866 // left-hand side of the arrow operator shall be of pointer to scalar type.
2867 // This scalar type is the object type.
2868 QualType ObjectType = BaseE->getType();
2869 if (OpKind == tok::arrow) {
2870 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
2871 ObjectType = Ptr->getPointeeType();
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002872 } else if (!ObjectType->isDependentType()) {
Douglas Gregor77549082010-02-24 21:29:12 +00002873 // The user wrote "p->" when she probably meant "p."; fix it.
2874 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002875 << ObjectType << true
Douglas Gregor849b2432010-03-31 17:46:05 +00002876 << FixItHint::CreateReplacement(OpLoc, ".");
Douglas Gregor77549082010-02-24 21:29:12 +00002877 if (isSFINAEContext())
2878 return ExprError();
2879
2880 OpKind = tok::period;
2881 }
2882 }
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002883
2884 // Compute the object type that we should use for name lookup purposes. Only
2885 // record types and dependent types matter.
2886 void *ObjectTypePtrForLookup = 0;
2887 if (!SS.isSet()) {
2888 ObjectTypePtrForLookup = (void *)ObjectType->getAs<RecordType>();
2889 if (!ObjectTypePtrForLookup && ObjectType->isDependentType())
2890 ObjectTypePtrForLookup = Context.DependentTy.getAsOpaquePtr();
2891 }
Douglas Gregor77549082010-02-24 21:29:12 +00002892
Douglas Gregorb57fb492010-02-24 22:38:50 +00002893 // Convert the name of the type being destructed (following the ~) into a
2894 // type (with source-location information).
Douglas Gregor77549082010-02-24 21:29:12 +00002895 QualType DestructedType;
2896 TypeSourceInfo *DestructedTypeInfo = 0;
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002897 PseudoDestructorTypeStorage Destructed;
Douglas Gregor77549082010-02-24 21:29:12 +00002898 if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
2899 TypeTy *T = getTypeName(*SecondTypeName.Identifier,
2900 SecondTypeName.StartLocation,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002901 S, &SS, true, ObjectTypePtrForLookup);
2902 if (!T &&
2903 ((SS.isSet() && !computeDeclContext(SS, false)) ||
2904 (!SS.isSet() && ObjectType->isDependentType()))) {
2905 // The name of the type being destroyed is a dependent name, and we
2906 // couldn't find anything useful in scope. Just store the identifier and
2907 // it's location, and we'll perform (qualified) name lookup again at
2908 // template instantiation time.
2909 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
2910 SecondTypeName.StartLocation);
2911 } else if (!T) {
Douglas Gregor77549082010-02-24 21:29:12 +00002912 Diag(SecondTypeName.StartLocation,
2913 diag::err_pseudo_dtor_destructor_non_type)
2914 << SecondTypeName.Identifier << ObjectType;
2915 if (isSFINAEContext())
2916 return ExprError();
2917
2918 // Recover by assuming we had the right type all along.
2919 DestructedType = ObjectType;
Douglas Gregorb57fb492010-02-24 22:38:50 +00002920 } else
Douglas Gregor77549082010-02-24 21:29:12 +00002921 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00002922 } else {
Douglas Gregorb57fb492010-02-24 22:38:50 +00002923 // Resolve the template-id to a type.
Douglas Gregor77549082010-02-24 21:29:12 +00002924 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
Douglas Gregorb57fb492010-02-24 22:38:50 +00002925 ASTTemplateArgsPtr TemplateArgsPtr(*this,
2926 TemplateId->getTemplateArgs(),
2927 TemplateId->NumArgs);
2928 TypeResult T = ActOnTemplateIdType(TemplateTy::make(TemplateId->Template),
2929 TemplateId->TemplateNameLoc,
2930 TemplateId->LAngleLoc,
2931 TemplateArgsPtr,
2932 TemplateId->RAngleLoc);
2933 if (T.isInvalid() || !T.get()) {
2934 // Recover by assuming we had the right type all along.
2935 DestructedType = ObjectType;
2936 } else
2937 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00002938 }
2939
Douglas Gregorb57fb492010-02-24 22:38:50 +00002940 // If we've performed some kind of recovery, (re-)build the type source
2941 // information.
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002942 if (!DestructedType.isNull()) {
2943 if (!DestructedTypeInfo)
2944 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
Douglas Gregorb57fb492010-02-24 22:38:50 +00002945 SecondTypeName.StartLocation);
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002946 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
2947 }
Douglas Gregorb57fb492010-02-24 22:38:50 +00002948
2949 // Convert the name of the scope type (the type prior to '::') into a type.
2950 TypeSourceInfo *ScopeTypeInfo = 0;
Douglas Gregor77549082010-02-24 21:29:12 +00002951 QualType ScopeType;
2952 if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
2953 FirstTypeName.Identifier) {
2954 if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
2955 TypeTy *T = getTypeName(*FirstTypeName.Identifier,
2956 FirstTypeName.StartLocation,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002957 S, &SS, false, ObjectTypePtrForLookup);
Douglas Gregor77549082010-02-24 21:29:12 +00002958 if (!T) {
2959 Diag(FirstTypeName.StartLocation,
2960 diag::err_pseudo_dtor_destructor_non_type)
2961 << FirstTypeName.Identifier << ObjectType;
Douglas Gregor77549082010-02-24 21:29:12 +00002962
Douglas Gregorb57fb492010-02-24 22:38:50 +00002963 if (isSFINAEContext())
2964 return ExprError();
2965
2966 // Just drop this type. It's unnecessary anyway.
2967 ScopeType = QualType();
2968 } else
2969 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00002970 } else {
Douglas Gregorb57fb492010-02-24 22:38:50 +00002971 // Resolve the template-id to a type.
Douglas Gregor77549082010-02-24 21:29:12 +00002972 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
Douglas Gregorb57fb492010-02-24 22:38:50 +00002973 ASTTemplateArgsPtr TemplateArgsPtr(*this,
2974 TemplateId->getTemplateArgs(),
2975 TemplateId->NumArgs);
2976 TypeResult T = ActOnTemplateIdType(TemplateTy::make(TemplateId->Template),
2977 TemplateId->TemplateNameLoc,
2978 TemplateId->LAngleLoc,
2979 TemplateArgsPtr,
2980 TemplateId->RAngleLoc);
2981 if (T.isInvalid() || !T.get()) {
2982 // Recover by dropping this type.
2983 ScopeType = QualType();
2984 } else
2985 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00002986 }
2987 }
Douglas Gregorb4a418f2010-02-24 23:02:30 +00002988
2989 if (!ScopeType.isNull() && !ScopeTypeInfo)
2990 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
2991 FirstTypeName.StartLocation);
2992
2993
Douglas Gregorb57fb492010-02-24 22:38:50 +00002994 return BuildPseudoDestructorExpr(move(Base), OpLoc, OpKind, SS,
Douglas Gregorfce46ee2010-02-24 23:50:37 +00002995 ScopeTypeInfo, CCLoc, TildeLoc,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002996 Destructed, HasTrailingLParen);
Douglas Gregord4dca082010-02-24 18:44:31 +00002997}
2998
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002999CXXMemberCallExpr *Sema::BuildCXXMemberCallExpr(Expr *Exp,
John McCall6bb80172010-03-30 21:47:33 +00003000 NamedDecl *FoundDecl,
Fariborz Jahanianb7400232009-09-28 23:23:40 +00003001 CXXMethodDecl *Method) {
John McCall6bb80172010-03-30 21:47:33 +00003002 if (PerformObjectArgumentInitialization(Exp, /*Qualifier=*/0,
3003 FoundDecl, Method))
Eli Friedman772fffa2009-12-09 04:53:56 +00003004 assert(0 && "Calling BuildCXXMemberCallExpr with invalid call?");
3005
Fariborz Jahanianb7400232009-09-28 23:23:40 +00003006 MemberExpr *ME =
3007 new (Context) MemberExpr(Exp, /*IsArrow=*/false, Method,
3008 SourceLocation(), Method->getType());
Eli Friedman772fffa2009-12-09 04:53:56 +00003009 QualType ResultType = Method->getResultType().getNonReferenceType();
Douglas Gregor7edfb692009-11-23 12:27:39 +00003010 MarkDeclarationReferenced(Exp->getLocStart(), Method);
3011 CXXMemberCallExpr *CE =
3012 new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType,
3013 Exp->getLocEnd());
Fariborz Jahanianb7400232009-09-28 23:23:40 +00003014 return CE;
3015}
3016
Anders Carlsson165a0a02009-05-17 18:41:29 +00003017Sema::OwningExprResult Sema::ActOnFinishFullExpr(ExprArg Arg) {
3018 Expr *FullExpr = Arg.takeAs<Expr>();
Anders Carlsson99ba36d2009-06-05 15:38:08 +00003019 if (FullExpr)
Anders Carlsson0ece4912009-12-15 20:51:39 +00003020 FullExpr = MaybeCreateCXXExprWithTemporaries(FullExpr);
Douglas Gregoreecf38f2010-05-06 21:39:56 +00003021 else
3022 return ExprError();
3023
Anders Carlsson165a0a02009-05-17 18:41:29 +00003024 return Owned(FullExpr);
3025}