blob: 7df1c5683c381a3314cd930000fcb77dbb818817 [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
264 return CheckTypenameType(NNS, II, Range).getAsOpaquePtr();
265 }
266
267 if (ObjectTypePtr)
268 Diag(NameLoc, diag::err_ident_in_pseudo_dtor_not_a_type)
269 << &II;
270 else
271 Diag(NameLoc, diag::err_destructor_class_name);
272
273 return 0;
274}
275
Sebastian Redlc42e1182008-11-11 11:37:55 +0000276/// ActOnCXXTypeidOfType - Parse typeid( type-id ).
Sebastian Redlf53597f2009-03-15 17:47:39 +0000277Action::OwningExprResult
Sebastian Redlc42e1182008-11-11 11:37:55 +0000278Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
279 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +0000280 if (!StdNamespace)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000281 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000282
Douglas Gregorf57f2072009-12-23 20:51:04 +0000283 if (isType) {
284 // C++ [expr.typeid]p4:
285 // The top-level cv-qualifiers of the lvalue expression or the type-id
286 // that is the operand of typeid are always ignored.
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000287 // FIXME: Preserve type source info.
Douglas Gregorf57f2072009-12-23 20:51:04 +0000288 // FIXME: Preserve the type before we stripped the cv-qualifiers?
Douglas Gregor765ccba2009-12-23 21:06:06 +0000289 QualType T = GetTypeFromParser(TyOrExpr);
290 if (T.isNull())
291 return ExprError();
292
293 // C++ [expr.typeid]p4:
294 // If the type of the type-id is a class type or a reference to a class
295 // type, the class shall be completely-defined.
296 QualType CheckT = T;
297 if (const ReferenceType *RefType = CheckT->getAs<ReferenceType>())
298 CheckT = RefType->getPointeeType();
299
300 if (CheckT->getAs<RecordType>() &&
301 RequireCompleteType(OpLoc, CheckT, diag::err_incomplete_typeid))
302 return ExprError();
303
304 TyOrExpr = T.getUnqualifiedType().getAsOpaquePtr();
Douglas Gregorf57f2072009-12-23 20:51:04 +0000305 }
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000306
Chris Lattner572af492008-11-20 05:51:55 +0000307 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
John McCalla24dc2e2009-11-17 02:14:36 +0000308 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
309 LookupQualifiedName(R, StdNamespace);
John McCall1bcee0a2009-12-02 08:25:40 +0000310 RecordDecl *TypeInfoRecordDecl = R.getAsSingle<RecordDecl>();
Chris Lattner572af492008-11-20 05:51:55 +0000311 if (!TypeInfoRecordDecl)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000312 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Sebastian Redlc42e1182008-11-11 11:37:55 +0000313
314 QualType TypeInfoType = Context.getTypeDeclType(TypeInfoRecordDecl);
315
Douglas Gregorac7610d2009-06-22 20:57:11 +0000316 if (!isType) {
Douglas Gregorac7610d2009-06-22 20:57:11 +0000317 bool isUnevaluatedOperand = true;
318 Expr *E = static_cast<Expr *>(TyOrExpr);
Douglas Gregorf57f2072009-12-23 20:51:04 +0000319 if (E && !E->isTypeDependent()) {
Douglas Gregorac7610d2009-06-22 20:57:11 +0000320 QualType T = E->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000321 if (const RecordType *RecordT = T->getAs<RecordType>()) {
Douglas Gregorac7610d2009-06-22 20:57:11 +0000322 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
Douglas Gregorf57f2072009-12-23 20:51:04 +0000323 // C++ [expr.typeid]p3:
John McCall86ff3082010-02-04 22:26:26 +0000324 // [...] If the type of the expression is a class type, the class
325 // shall be completely-defined.
326 if (RequireCompleteType(OpLoc, T, diag::err_incomplete_typeid))
327 return ExprError();
328
329 // C++ [expr.typeid]p3:
Douglas Gregorf57f2072009-12-23 20:51:04 +0000330 // When typeid is applied to an expression other than an lvalue of a
331 // polymorphic class type [...] [the] expression is an unevaluated
332 // operand. [...]
333 if (RecordD->isPolymorphic() && E->isLvalue(Context) == Expr::LV_Valid)
Douglas Gregorac7610d2009-06-22 20:57:11 +0000334 isUnevaluatedOperand = false;
Douglas Gregorf57f2072009-12-23 20:51:04 +0000335 }
336
337 // C++ [expr.typeid]p4:
338 // [...] If the type of the type-id is a reference to a possibly
339 // cv-qualified type, the result of the typeid expression refers to a
340 // std::type_info object representing the cv-unqualified referenced
341 // type.
342 if (T.hasQualifiers()) {
343 ImpCastExprToType(E, T.getUnqualifiedType(), CastExpr::CK_NoOp,
344 E->isLvalue(Context));
345 TyOrExpr = E;
Douglas Gregorac7610d2009-06-22 20:57:11 +0000346 }
347 }
Mike Stump1eb44332009-09-09 15:08:12 +0000348
Douglas Gregor2afce722009-11-26 00:44:06 +0000349 // If this is an unevaluated operand, clear out the set of
350 // declaration references we have been computing and eliminate any
351 // temporaries introduced in its computation.
Douglas Gregorac7610d2009-06-22 20:57:11 +0000352 if (isUnevaluatedOperand)
Douglas Gregor2afce722009-11-26 00:44:06 +0000353 ExprEvalContexts.back().Context = Unevaluated;
Douglas Gregorac7610d2009-06-22 20:57:11 +0000354 }
Mike Stump1eb44332009-09-09 15:08:12 +0000355
Sebastian Redlf53597f2009-03-15 17:47:39 +0000356 return Owned(new (Context) CXXTypeidExpr(isType, TyOrExpr,
357 TypeInfoType.withConst(),
358 SourceRange(OpLoc, RParenLoc)));
Sebastian Redlc42e1182008-11-11 11:37:55 +0000359}
360
Steve Naroff1b273c42007-09-16 14:56:35 +0000361/// ActOnCXXBoolLiteral - Parse {true,false} literals.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000362Action::OwningExprResult
Steve Naroff1b273c42007-09-16 14:56:35 +0000363Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor2f639b92008-10-24 15:36:09 +0000364 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000365 "Unknown C++ Boolean value!");
Sebastian Redlf53597f2009-03-15 17:47:39 +0000366 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
367 Context.BoolTy, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000368}
Chris Lattner50dd2892008-02-26 00:51:44 +0000369
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000370/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
371Action::OwningExprResult
372Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
373 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
374}
375
Chris Lattner50dd2892008-02-26 00:51:44 +0000376/// ActOnCXXThrow - Parse throw expressions.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000377Action::OwningExprResult
378Sema::ActOnCXXThrow(SourceLocation OpLoc, ExprArg E) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000379 Expr *Ex = E.takeAs<Expr>();
380 if (Ex && !Ex->isTypeDependent() && CheckCXXThrowOperand(OpLoc, Ex))
381 return ExprError();
382 return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc));
383}
384
385/// CheckCXXThrowOperand - Validate the operand of a throw.
386bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *&E) {
387 // C++ [except.throw]p3:
Douglas Gregor154fe982009-12-23 22:04:40 +0000388 // A throw-expression initializes a temporary object, called the exception
389 // object, the type of which is determined by removing any top-level
390 // cv-qualifiers from the static type of the operand of throw and adjusting
391 // the type from "array of T" or "function returning T" to "pointer to T"
392 // or "pointer to function returning T", [...]
393 if (E->getType().hasQualifiers())
394 ImpCastExprToType(E, E->getType().getUnqualifiedType(), CastExpr::CK_NoOp,
395 E->isLvalue(Context) == Expr::LV_Valid);
396
Sebastian Redl972041f2009-04-27 20:27:31 +0000397 DefaultFunctionArrayConversion(E);
398
399 // If the type of the exception would be an incomplete type or a pointer
400 // to an incomplete type other than (cv) void the program is ill-formed.
401 QualType Ty = E->getType();
John McCallac418162010-04-22 01:10:34 +0000402 bool isPointer = false;
Ted Kremenek6217b802009-07-29 21:53:49 +0000403 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000404 Ty = Ptr->getPointeeType();
John McCallac418162010-04-22 01:10:34 +0000405 isPointer = true;
Sebastian Redl972041f2009-04-27 20:27:31 +0000406 }
407 if (!isPointer || !Ty->isVoidType()) {
408 if (RequireCompleteType(ThrowLoc, Ty,
Anders Carlssond497ba72009-08-26 22:59:12 +0000409 PDiag(isPointer ? diag::err_throw_incomplete_ptr
410 : diag::err_throw_incomplete)
411 << E->getSourceRange()))
Sebastian Redl972041f2009-04-27 20:27:31 +0000412 return true;
Rafael Espindola7b9a5aa2010-03-02 21:28:26 +0000413
Douglas Gregorbf422f92010-04-15 18:05:39 +0000414 if (RequireNonAbstractType(ThrowLoc, E->getType(),
415 PDiag(diag::err_throw_abstract_type)
416 << E->getSourceRange()))
417 return true;
Sebastian Redl972041f2009-04-27 20:27:31 +0000418 }
419
John McCallac418162010-04-22 01:10:34 +0000420 // Initialize the exception result. This implicitly weeds out
421 // abstract types or types with inaccessible copy constructors.
422 InitializedEntity Entity =
423 InitializedEntity::InitializeException(ThrowLoc, E->getType());
424 OwningExprResult Res = PerformCopyInitialization(Entity,
425 SourceLocation(),
426 Owned(E));
427 if (Res.isInvalid())
428 return true;
429 E = Res.takeAs<Expr>();
Sebastian Redl972041f2009-04-27 20:27:31 +0000430 return false;
Chris Lattner50dd2892008-02-26 00:51:44 +0000431}
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000432
Sebastian Redlf53597f2009-03-15 17:47:39 +0000433Action::OwningExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000434 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
435 /// is a non-lvalue expression whose value is the address of the object for
436 /// which the function is called.
437
Sebastian Redlf53597f2009-03-15 17:47:39 +0000438 if (!isa<FunctionDecl>(CurContext))
439 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000440
441 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext))
442 if (MD->isInstance())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000443 return Owned(new (Context) CXXThisExpr(ThisLoc,
Douglas Gregor828a1972010-01-07 23:12:05 +0000444 MD->getThisType(Context),
445 /*isImplicit=*/false));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000446
Sebastian Redlf53597f2009-03-15 17:47:39 +0000447 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000448}
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000449
450/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
451/// Can be interpreted either as function-style casting ("int(x)")
452/// or class type construction ("ClassType(x,y,z)")
453/// or creation of a value-initialized type ("int()").
Sebastian Redlf53597f2009-03-15 17:47:39 +0000454Action::OwningExprResult
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000455Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep,
456 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000457 MultiExprArg exprs,
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000458 SourceLocation *CommaLocs,
459 SourceLocation RParenLoc) {
Douglas Gregorae4c77d2010-02-05 19:11:37 +0000460 if (!TypeRep)
461 return ExprError();
462
John McCall9d125032010-01-15 18:39:57 +0000463 TypeSourceInfo *TInfo;
464 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
465 if (!TInfo)
466 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
Sebastian Redlf53597f2009-03-15 17:47:39 +0000467 unsigned NumExprs = exprs.size();
468 Expr **Exprs = (Expr**)exprs.get();
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000469 SourceLocation TyBeginLoc = TypeRange.getBegin();
470 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
471
Sebastian Redlf53597f2009-03-15 17:47:39 +0000472 if (Ty->isDependentType() ||
Douglas Gregorba498172009-03-13 21:01:28 +0000473 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
Sebastian Redlf53597f2009-03-15 17:47:39 +0000474 exprs.release();
Mike Stump1eb44332009-09-09 15:08:12 +0000475
476 return Owned(CXXUnresolvedConstructExpr::Create(Context,
477 TypeRange.getBegin(), Ty,
Douglas Gregord81e6ca2009-05-20 18:46:25 +0000478 LParenLoc,
479 Exprs, NumExprs,
480 RParenLoc));
Douglas Gregorba498172009-03-13 21:01:28 +0000481 }
482
Anders Carlssonbb60a502009-08-27 03:53:50 +0000483 if (Ty->isArrayType())
484 return ExprError(Diag(TyBeginLoc,
485 diag::err_value_init_for_array_type) << FullRange);
486 if (!Ty->isVoidType() &&
487 RequireCompleteType(TyBeginLoc, Ty,
488 PDiag(diag::err_invalid_incomplete_type_use)
489 << FullRange))
490 return ExprError();
Fariborz Jahanianf071e9b2009-10-23 21:01:39 +0000491
Anders Carlssonbb60a502009-08-27 03:53:50 +0000492 if (RequireNonAbstractType(TyBeginLoc, Ty,
493 diag::err_allocation_of_abstract_type))
494 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000495
496
Douglas Gregor506ae412009-01-16 18:33:17 +0000497 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000498 // If the expression list is a single expression, the type conversion
499 // expression is equivalent (in definedness, and if defined in meaning) to the
500 // corresponding cast expression.
501 //
502 if (NumExprs == 1) {
Anders Carlssoncdb61972009-08-07 22:21:05 +0000503 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Douglas Gregord6e44a32010-04-16 22:09:46 +0000504 if (CheckCastTypes(TypeRange, Ty, Exprs[0], Kind, /*FunctionalStyle=*/true))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000505 return ExprError();
Anders Carlsson0aebc812009-09-09 21:33:21 +0000506
507 exprs.release();
Anders Carlsson0aebc812009-09-09 21:33:21 +0000508
509 return Owned(new (Context) CXXFunctionalCastExpr(Ty.getNonReferenceType(),
John McCall9d125032010-01-15 18:39:57 +0000510 TInfo, TyBeginLoc, Kind,
Anders Carlsson0aebc812009-09-09 21:33:21 +0000511 Exprs[0], RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000512 }
513
Ted Kremenek6217b802009-07-29 21:53:49 +0000514 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Douglas Gregor506ae412009-01-16 18:33:17 +0000515 CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
Sebastian Redlf53597f2009-03-15 17:47:39 +0000516
Mike Stump1eb44332009-09-09 15:08:12 +0000517 if (NumExprs > 1 || !Record->hasTrivialConstructor() ||
Anders Carlssone7624a72009-08-27 05:08:22 +0000518 !Record->hasTrivialDestructor()) {
Eli Friedman6997aae2010-01-31 20:58:15 +0000519 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty);
520 InitializationKind Kind
521 = NumExprs ? InitializationKind::CreateDirect(TypeRange.getBegin(),
522 LParenLoc, RParenLoc)
523 : InitializationKind::CreateValue(TypeRange.getBegin(),
524 LParenLoc, RParenLoc);
525 InitializationSequence InitSeq(*this, Entity, Kind, Exprs, NumExprs);
526 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
527 move(exprs));
Douglas Gregor506ae412009-01-16 18:33:17 +0000528
Eli Friedman6997aae2010-01-31 20:58:15 +0000529 // FIXME: Improve AST representation?
530 return move(Result);
Douglas Gregor506ae412009-01-16 18:33:17 +0000531 }
532
533 // Fall through to value-initialize an object of class type that
534 // doesn't have a user-declared default constructor.
535 }
536
537 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000538 // If the expression list specifies more than a single value, the type shall
539 // be a class with a suitably declared constructor.
540 //
541 if (NumExprs > 1)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000542 return ExprError(Diag(CommaLocs[0],
543 diag::err_builtin_func_cast_more_than_one_arg)
544 << FullRange);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000545
546 assert(NumExprs == 0 && "Expected 0 expressions");
Douglas Gregor506ae412009-01-16 18:33:17 +0000547 // C++ [expr.type.conv]p2:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000548 // The expression T(), where T is a simple-type-specifier for a non-array
549 // complete object type or the (possibly cv-qualified) void type, creates an
550 // rvalue of the specified type, which is value-initialized.
551 //
Sebastian Redlf53597f2009-03-15 17:47:39 +0000552 exprs.release();
553 return Owned(new (Context) CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000554}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000555
556
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000557/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
558/// @code new (memory) int[size][4] @endcode
559/// or
560/// @code ::new Foo(23, "hello") @endcode
561/// For the interpretation of this heap of arguments, consult the base version.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000562Action::OwningExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000563Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000564 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000565 SourceLocation PlacementRParen, bool ParenTypeId,
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000566 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000567 MultiExprArg ConstructorArgs,
Mike Stump1eb44332009-09-09 15:08:12 +0000568 SourceLocation ConstructorRParen) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000569 Expr *ArraySize = 0;
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000570 // If the specified type is an array, unwrap it and save the expression.
571 if (D.getNumTypeObjects() > 0 &&
572 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
573 DeclaratorChunk &Chunk = D.getTypeObject(0);
574 if (Chunk.Arr.hasStatic)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000575 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
576 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000577 if (!Chunk.Arr.NumElts)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000578 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
579 << D.getSourceRange());
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000580
581 if (ParenTypeId) {
582 // Can't have dynamic array size when the type-id is in parentheses.
583 Expr *NumElts = (Expr *)Chunk.Arr.NumElts;
584 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
585 !NumElts->isIntegerConstantExpr(Context)) {
586 Diag(D.getTypeObject(0).Loc, diag::err_new_paren_array_nonconst)
587 << NumElts->getSourceRange();
588 return ExprError();
589 }
590 }
591
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000592 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000593 D.DropFirstTypeObject();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000594 }
595
Douglas Gregor043cad22009-09-11 00:18:58 +0000596 // Every dimension shall be of constant size.
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000597 if (ArraySize) {
598 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor043cad22009-09-11 00:18:58 +0000599 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
600 break;
601
602 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
603 if (Expr *NumElts = (Expr *)Array.NumElts) {
604 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
605 !NumElts->isIntegerConstantExpr(Context)) {
606 Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst)
607 << NumElts->getSourceRange();
608 return ExprError();
609 }
610 }
611 }
612 }
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000613
John McCalla93c9342009-12-07 02:54:59 +0000614 //FIXME: Store TypeSourceInfo in CXXNew expression.
615 TypeSourceInfo *TInfo = 0;
616 QualType AllocType = GetTypeForDeclarator(D, /*Scope=*/0, &TInfo);
Chris Lattnereaaebc72009-04-25 08:06:05 +0000617 if (D.isInvalidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000618 return ExprError();
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000619
Mike Stump1eb44332009-09-09 15:08:12 +0000620 return BuildCXXNew(StartLoc, UseGlobal,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000621 PlacementLParen,
Mike Stump1eb44332009-09-09 15:08:12 +0000622 move(PlacementArgs),
Douglas Gregor3433cf72009-05-21 00:00:09 +0000623 PlacementRParen,
624 ParenTypeId,
Mike Stump1eb44332009-09-09 15:08:12 +0000625 AllocType,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000626 D.getSourceRange().getBegin(),
627 D.getSourceRange(),
628 Owned(ArraySize),
629 ConstructorLParen,
630 move(ConstructorArgs),
631 ConstructorRParen);
632}
633
Mike Stump1eb44332009-09-09 15:08:12 +0000634Sema::OwningExprResult
Douglas Gregor3433cf72009-05-21 00:00:09 +0000635Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
636 SourceLocation PlacementLParen,
637 MultiExprArg PlacementArgs,
638 SourceLocation PlacementRParen,
Mike Stump1eb44332009-09-09 15:08:12 +0000639 bool ParenTypeId,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000640 QualType AllocType,
641 SourceLocation TypeLoc,
642 SourceRange TypeRange,
643 ExprArg ArraySizeE,
644 SourceLocation ConstructorLParen,
645 MultiExprArg ConstructorArgs,
646 SourceLocation ConstructorRParen) {
647 if (CheckAllocatedType(AllocType, TypeLoc, TypeRange))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000648 return ExprError();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000649
Douglas Gregor3433cf72009-05-21 00:00:09 +0000650 QualType ResultType = Context.getPointerType(AllocType);
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000651
652 // That every array dimension except the first is constant was already
653 // checked by the type check above.
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000654
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000655 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
656 // or enumeration type with a non-negative value."
Douglas Gregor3433cf72009-05-21 00:00:09 +0000657 Expr *ArraySize = (Expr *)ArraySizeE.get();
Sebastian Redl28507842009-02-26 14:39:58 +0000658 if (ArraySize && !ArraySize->isTypeDependent()) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000659 QualType SizeType = ArraySize->getType();
660 if (!SizeType->isIntegralType() && !SizeType->isEnumeralType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000661 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
662 diag::err_array_size_not_integral)
663 << SizeType << ArraySize->getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000664 // Let's see if this is a constant < 0. If so, we reject it out of hand.
665 // We don't care about special rules, so we tell the machinery it's not
666 // evaluated - it gives us a result in more cases.
Sebastian Redl28507842009-02-26 14:39:58 +0000667 if (!ArraySize->isValueDependent()) {
668 llvm::APSInt Value;
669 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
670 if (Value < llvm::APSInt(
Anders Carlssonac18b2e2009-09-23 00:37:25 +0000671 llvm::APInt::getNullValue(Value.getBitWidth()),
672 Value.isUnsigned()))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000673 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
674 diag::err_typecheck_negative_array_size)
675 << ArraySize->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +0000676 }
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000677 }
Anders Carlssonac18b2e2009-09-23 00:37:25 +0000678
Eli Friedman73c39ab2009-10-20 08:27:19 +0000679 ImpCastExprToType(ArraySize, Context.getSizeType(),
680 CastExpr::CK_IntegralCast);
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000681 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000682
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000683 FunctionDecl *OperatorNew = 0;
684 FunctionDecl *OperatorDelete = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000685 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
686 unsigned NumPlaceArgs = PlacementArgs.size();
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000687
Sebastian Redl28507842009-02-26 14:39:58 +0000688 if (!AllocType->isDependentType() &&
689 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
690 FindAllocationFunctions(StartLoc,
Sebastian Redl00e68e22009-02-09 18:24:27 +0000691 SourceRange(PlacementLParen, PlacementRParen),
692 UseGlobal, AllocType, ArraySize, PlaceArgs,
693 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000694 return ExprError();
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000695 llvm::SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000696 if (OperatorNew) {
697 // Add default arguments, if any.
698 const FunctionProtoType *Proto =
699 OperatorNew->getType()->getAs<FunctionProtoType>();
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +0000700 VariadicCallType CallType =
701 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000702 bool Invalid = GatherArgumentsForCall(PlacementLParen, OperatorNew,
703 Proto, 1, PlaceArgs, NumPlaceArgs,
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +0000704 AllPlaceArgs, CallType);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000705 if (Invalid)
706 return ExprError();
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000707
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000708 NumPlaceArgs = AllPlaceArgs.size();
709 if (NumPlaceArgs > 0)
710 PlaceArgs = &AllPlaceArgs[0];
711 }
712
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000713 bool Init = ConstructorLParen.isValid();
714 // --- Choosing a constructor ---
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000715 CXXConstructorDecl *Constructor = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000716 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
717 unsigned NumConsArgs = ConstructorArgs.size();
Eli Friedmana8ce9ec2009-11-08 22:15:39 +0000718 ASTOwningVector<&ActionBase::DeleteExpr> ConvertedConstructorArgs(*this);
719
Douglas Gregor99a2e602009-12-16 01:38:02 +0000720 if (!AllocType->isDependentType() &&
721 !Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) {
722 // C++0x [expr.new]p15:
723 // A new-expression that creates an object of type T initializes that
724 // object as follows:
725 InitializationKind Kind
726 // - If the new-initializer is omitted, the object is default-
727 // initialized (8.5); if no initialization is performed,
728 // the object has indeterminate value
729 = !Init? InitializationKind::CreateDefault(TypeLoc)
730 // - Otherwise, the new-initializer is interpreted according to the
731 // initialization rules of 8.5 for direct-initialization.
732 : InitializationKind::CreateDirect(TypeLoc,
733 ConstructorLParen,
734 ConstructorRParen);
735
Douglas Gregor99a2e602009-12-16 01:38:02 +0000736 InitializedEntity Entity
Douglas Gregord6542d82009-12-22 15:35:07 +0000737 = InitializedEntity::InitializeNew(StartLoc, AllocType);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000738 InitializationSequence InitSeq(*this, Entity, Kind, ConsArgs, NumConsArgs);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000739 OwningExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
740 move(ConstructorArgs));
741 if (FullInit.isInvalid())
742 return ExprError();
743
744 // FullInit is our initializer; walk through it to determine if it's a
745 // constructor call, which CXXNewExpr handles directly.
746 if (Expr *FullInitExpr = (Expr *)FullInit.get()) {
747 if (CXXBindTemporaryExpr *Binder
748 = dyn_cast<CXXBindTemporaryExpr>(FullInitExpr))
749 FullInitExpr = Binder->getSubExpr();
750 if (CXXConstructExpr *Construct
751 = dyn_cast<CXXConstructExpr>(FullInitExpr)) {
752 Constructor = Construct->getConstructor();
753 for (CXXConstructExpr::arg_iterator A = Construct->arg_begin(),
754 AEnd = Construct->arg_end();
755 A != AEnd; ++A)
756 ConvertedConstructorArgs.push_back(A->Retain());
757 } else {
758 // Take the converted initializer.
759 ConvertedConstructorArgs.push_back(FullInit.release());
760 }
761 } else {
762 // No initialization required.
763 }
764
765 // Take the converted arguments and use them for the new expression.
Douglas Gregor39da0b82009-09-09 23:08:42 +0000766 NumConsArgs = ConvertedConstructorArgs.size();
767 ConsArgs = (Expr **)ConvertedConstructorArgs.take();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000768 }
Douglas Gregor99a2e602009-12-16 01:38:02 +0000769
Douglas Gregor6d908702010-02-26 05:06:18 +0000770 // Mark the new and delete operators as referenced.
771 if (OperatorNew)
772 MarkDeclarationReferenced(StartLoc, OperatorNew);
773 if (OperatorDelete)
774 MarkDeclarationReferenced(StartLoc, OperatorDelete);
775
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000776 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
Douglas Gregor089407b2009-10-17 21:40:42 +0000777
Sebastian Redlf53597f2009-03-15 17:47:39 +0000778 PlacementArgs.release();
779 ConstructorArgs.release();
Douglas Gregor3433cf72009-05-21 00:00:09 +0000780 ArraySizeE.release();
Ted Kremenekad7fe862010-02-11 22:51:03 +0000781 return Owned(new (Context) CXXNewExpr(Context, UseGlobal, OperatorNew,
782 PlaceArgs, NumPlaceArgs, ParenTypeId,
783 ArraySize, Constructor, Init,
784 ConsArgs, NumConsArgs, OperatorDelete,
785 ResultType, StartLoc,
786 Init ? ConstructorRParen :
787 SourceLocation()));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000788}
789
790/// CheckAllocatedType - Checks that a type is suitable as the allocated type
791/// in a new-expression.
792/// dimension off and stores the size expression in ArraySize.
Douglas Gregor3433cf72009-05-21 00:00:09 +0000793bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +0000794 SourceRange R) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000795 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
796 // abstract class type or array thereof.
Douglas Gregore7450f52009-03-24 19:52:54 +0000797 if (AllocType->isFunctionType())
Douglas Gregor3433cf72009-05-21 00:00:09 +0000798 return Diag(Loc, diag::err_bad_new_type)
799 << AllocType << 0 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +0000800 else if (AllocType->isReferenceType())
Douglas Gregor3433cf72009-05-21 00:00:09 +0000801 return Diag(Loc, diag::err_bad_new_type)
802 << AllocType << 1 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +0000803 else if (!AllocType->isDependentType() &&
Douglas Gregor3433cf72009-05-21 00:00:09 +0000804 RequireCompleteType(Loc, AllocType,
Anders Carlssonb7906612009-08-26 23:45:07 +0000805 PDiag(diag::err_new_incomplete_type)
806 << R))
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000807 return true;
Douglas Gregor3433cf72009-05-21 00:00:09 +0000808 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregore7450f52009-03-24 19:52:54 +0000809 diag::err_allocation_of_abstract_type))
810 return true;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000811
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000812 return false;
813}
814
Douglas Gregor6d908702010-02-26 05:06:18 +0000815/// \brief Determine whether the given function is a non-placement
816/// deallocation function.
817static bool isNonPlacementDeallocationFunction(FunctionDecl *FD) {
818 if (FD->isInvalidDecl())
819 return false;
820
821 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
822 return Method->isUsualDeallocationFunction();
823
824 return ((FD->getOverloadedOperator() == OO_Delete ||
825 FD->getOverloadedOperator() == OO_Array_Delete) &&
826 FD->getNumParams() == 1);
827}
828
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000829/// FindAllocationFunctions - Finds the overloads of operator new and delete
830/// that are appropriate for the allocation.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000831bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
832 bool UseGlobal, QualType AllocType,
833 bool IsArray, Expr **PlaceArgs,
834 unsigned NumPlaceArgs,
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000835 FunctionDecl *&OperatorNew,
Mike Stump1eb44332009-09-09 15:08:12 +0000836 FunctionDecl *&OperatorDelete) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000837 // --- Choosing an allocation function ---
838 // C++ 5.3.4p8 - 14 & 18
839 // 1) If UseGlobal is true, only look in the global scope. Else, also look
840 // in the scope of the allocated class.
841 // 2) If an array size is given, look for operator new[], else look for
842 // operator new.
843 // 3) The first argument is always size_t. Append the arguments from the
844 // placement form.
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000845
846 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
847 // We don't care about the actual value of this argument.
848 // FIXME: Should the Sema create the expression and embed it in the syntax
849 // tree? Or should the consumer just recalculate the value?
Anders Carlssond67c4c32009-08-16 20:29:29 +0000850 IntegerLiteral Size(llvm::APInt::getNullValue(
851 Context.Target.getPointerWidth(0)),
852 Context.getSizeType(),
853 SourceLocation());
854 AllocArgs[0] = &Size;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000855 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
856
Douglas Gregor6d908702010-02-26 05:06:18 +0000857 // C++ [expr.new]p8:
858 // If the allocated type is a non-array type, the allocation
859 // function’s name is operator new and the deallocation function’s
860 // name is operator delete. If the allocated type is an array
861 // type, the allocation function’s name is operator new[] and the
862 // deallocation function’s name is operator delete[].
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000863 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
864 IsArray ? OO_Array_New : OO_New);
Douglas Gregor6d908702010-02-26 05:06:18 +0000865 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
866 IsArray ? OO_Array_Delete : OO_Delete);
867
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000868 if (AllocType->isRecordType() && !UseGlobal) {
Mike Stump1eb44332009-09-09 15:08:12 +0000869 CXXRecordDecl *Record
Ted Kremenek6217b802009-07-29 21:53:49 +0000870 = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl());
Sebastian Redl00e68e22009-02-09 18:24:27 +0000871 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000872 AllocArgs.size(), Record, /*AllowMissing=*/true,
873 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000874 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000875 }
876 if (!OperatorNew) {
877 // Didn't find a member overload. Look for a global one.
878 DeclareGlobalNewDelete();
Sebastian Redl7f662392008-12-04 22:20:51 +0000879 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl00e68e22009-02-09 18:24:27 +0000880 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000881 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
882 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000883 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000884 }
885
John McCall9c82afc2010-04-20 02:18:25 +0000886 // We don't need an operator delete if we're running under
887 // -fno-exceptions.
888 if (!getLangOptions().Exceptions) {
889 OperatorDelete = 0;
890 return false;
891 }
892
Anders Carlssond9583892009-05-31 20:26:12 +0000893 // FindAllocationOverload can change the passed in arguments, so we need to
894 // copy them back.
895 if (NumPlaceArgs > 0)
896 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
Mike Stump1eb44332009-09-09 15:08:12 +0000897
Douglas Gregor6d908702010-02-26 05:06:18 +0000898 // C++ [expr.new]p19:
899 //
900 // If the new-expression begins with a unary :: operator, the
901 // deallocation function’s name is looked up in the global
902 // scope. Otherwise, if the allocated type is a class type T or an
903 // array thereof, the deallocation function’s name is looked up in
904 // the scope of T. If this lookup fails to find the name, or if
905 // the allocated type is not a class type or array thereof, the
906 // deallocation function’s name is looked up in the global scope.
907 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
908 if (AllocType->isRecordType() && !UseGlobal) {
909 CXXRecordDecl *RD
910 = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl());
911 LookupQualifiedName(FoundDelete, RD);
912 }
John McCall90c8c572010-03-18 08:19:33 +0000913 if (FoundDelete.isAmbiguous())
914 return true; // FIXME: clean up expressions?
Douglas Gregor6d908702010-02-26 05:06:18 +0000915
916 if (FoundDelete.empty()) {
917 DeclareGlobalNewDelete();
918 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
919 }
920
921 FoundDelete.suppressDiagnostics();
John McCall9aa472c2010-03-19 07:35:19 +0000922
923 llvm::SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
924
John McCall90c8c572010-03-18 08:19:33 +0000925 if (NumPlaceArgs > 0) {
Douglas Gregor6d908702010-02-26 05:06:18 +0000926 // C++ [expr.new]p20:
927 // A declaration of a placement deallocation function matches the
928 // declaration of a placement allocation function if it has the
929 // same number of parameters and, after parameter transformations
930 // (8.3.5), all parameter types except the first are
931 // identical. [...]
932 //
933 // To perform this comparison, we compute the function type that
934 // the deallocation function should have, and use that type both
935 // for template argument deduction and for comparison purposes.
936 QualType ExpectedFunctionType;
937 {
938 const FunctionProtoType *Proto
939 = OperatorNew->getType()->getAs<FunctionProtoType>();
940 llvm::SmallVector<QualType, 4> ArgTypes;
941 ArgTypes.push_back(Context.VoidPtrTy);
942 for (unsigned I = 1, N = Proto->getNumArgs(); I < N; ++I)
943 ArgTypes.push_back(Proto->getArgType(I));
944
945 ExpectedFunctionType
946 = Context.getFunctionType(Context.VoidTy, ArgTypes.data(),
947 ArgTypes.size(),
948 Proto->isVariadic(),
Rafael Espindola264ba482010-03-30 20:24:48 +0000949 0, false, false, 0, 0,
950 FunctionType::ExtInfo());
Douglas Gregor6d908702010-02-26 05:06:18 +0000951 }
952
953 for (LookupResult::iterator D = FoundDelete.begin(),
954 DEnd = FoundDelete.end();
955 D != DEnd; ++D) {
956 FunctionDecl *Fn = 0;
957 if (FunctionTemplateDecl *FnTmpl
958 = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
959 // Perform template argument deduction to try to match the
960 // expected function type.
961 TemplateDeductionInfo Info(Context, StartLoc);
962 if (DeduceTemplateArguments(FnTmpl, 0, ExpectedFunctionType, Fn, Info))
963 continue;
964 } else
965 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
966
967 if (Context.hasSameType(Fn->getType(), ExpectedFunctionType))
John McCall9aa472c2010-03-19 07:35:19 +0000968 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6d908702010-02-26 05:06:18 +0000969 }
970 } else {
971 // C++ [expr.new]p20:
972 // [...] Any non-placement deallocation function matches a
973 // non-placement allocation function. [...]
974 for (LookupResult::iterator D = FoundDelete.begin(),
975 DEnd = FoundDelete.end();
976 D != DEnd; ++D) {
977 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>((*D)->getUnderlyingDecl()))
978 if (isNonPlacementDeallocationFunction(Fn))
John McCall9aa472c2010-03-19 07:35:19 +0000979 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6d908702010-02-26 05:06:18 +0000980 }
981 }
982
983 // C++ [expr.new]p20:
984 // [...] If the lookup finds a single matching deallocation
985 // function, that function will be called; otherwise, no
986 // deallocation function will be called.
987 if (Matches.size() == 1) {
John McCall9aa472c2010-03-19 07:35:19 +0000988 OperatorDelete = Matches[0].second;
Douglas Gregor6d908702010-02-26 05:06:18 +0000989
990 // C++0x [expr.new]p20:
991 // If the lookup finds the two-parameter form of a usual
992 // deallocation function (3.7.4.2) and that function, considered
993 // as a placement deallocation function, would have been
994 // selected as a match for the allocation function, the program
995 // is ill-formed.
996 if (NumPlaceArgs && getLangOptions().CPlusPlus0x &&
997 isNonPlacementDeallocationFunction(OperatorDelete)) {
998 Diag(StartLoc, diag::err_placement_new_non_placement_delete)
999 << SourceRange(PlaceArgs[0]->getLocStart(),
1000 PlaceArgs[NumPlaceArgs - 1]->getLocEnd());
1001 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
1002 << DeleteName;
John McCall90c8c572010-03-18 08:19:33 +00001003 } else {
1004 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
John McCall9aa472c2010-03-19 07:35:19 +00001005 Matches[0].first);
Douglas Gregor6d908702010-02-26 05:06:18 +00001006 }
1007 }
1008
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001009 return false;
1010}
1011
Sebastian Redl7f662392008-12-04 22:20:51 +00001012/// FindAllocationOverload - Find an fitting overload for the allocation
1013/// function in the specified scope.
Sebastian Redl00e68e22009-02-09 18:24:27 +00001014bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
1015 DeclarationName Name, Expr** Args,
1016 unsigned NumArgs, DeclContext *Ctx,
Mike Stump1eb44332009-09-09 15:08:12 +00001017 bool AllowMissing, FunctionDecl *&Operator) {
John McCalla24dc2e2009-11-17 02:14:36 +00001018 LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
1019 LookupQualifiedName(R, Ctx);
John McCallf36e02d2009-10-09 21:13:30 +00001020 if (R.empty()) {
Sebastian Redl7f662392008-12-04 22:20:51 +00001021 if (AllowMissing)
1022 return false;
Sebastian Redl7f662392008-12-04 22:20:51 +00001023 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +00001024 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +00001025 }
1026
John McCall90c8c572010-03-18 08:19:33 +00001027 if (R.isAmbiguous())
1028 return true;
1029
1030 R.suppressDiagnostics();
John McCallf36e02d2009-10-09 21:13:30 +00001031
John McCall5769d612010-02-08 23:07:23 +00001032 OverloadCandidateSet Candidates(StartLoc);
Douglas Gregor5d64e5b2009-09-30 00:03:47 +00001033 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
1034 Alloc != AllocEnd; ++Alloc) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001035 // Even member operator new/delete are implicitly treated as
1036 // static, so don't use AddMemberCandidate.
John McCall9aa472c2010-03-19 07:35:19 +00001037 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001038
John McCall9aa472c2010-03-19 07:35:19 +00001039 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
1040 AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001041 /*ExplicitTemplateArgs=*/0, Args, NumArgs,
1042 Candidates,
1043 /*SuppressUserConversions=*/false);
Douglas Gregor90916562009-09-29 18:16:17 +00001044 continue;
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001045 }
1046
John McCall9aa472c2010-03-19 07:35:19 +00001047 FunctionDecl *Fn = cast<FunctionDecl>(D);
1048 AddOverloadCandidate(Fn, Alloc.getPair(), Args, NumArgs, Candidates,
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001049 /*SuppressUserConversions=*/false);
Sebastian Redl7f662392008-12-04 22:20:51 +00001050 }
1051
1052 // Do the resolution.
1053 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00001054 switch(BestViableFunction(Candidates, StartLoc, Best)) {
Sebastian Redl7f662392008-12-04 22:20:51 +00001055 case OR_Success: {
1056 // Got one!
1057 FunctionDecl *FnDecl = Best->Function;
1058 // The first argument is size_t, and the first parameter must be size_t,
1059 // too. This is checked on declaration and can be assumed. (It can't be
1060 // asserted on, though, since invalid decls are left in there.)
John McCall90c8c572010-03-18 08:19:33 +00001061 // Watch out for variadic allocator function.
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00001062 unsigned NumArgsInFnDecl = FnDecl->getNumParams();
1063 for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) {
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001064 OwningExprResult Result
1065 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
1066 FnDecl->getParamDecl(i)),
1067 SourceLocation(),
1068 Owned(Args[i]->Retain()));
1069 if (Result.isInvalid())
Sebastian Redl7f662392008-12-04 22:20:51 +00001070 return true;
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001071
1072 Args[i] = Result.takeAs<Expr>();
Sebastian Redl7f662392008-12-04 22:20:51 +00001073 }
1074 Operator = FnDecl;
John McCall9aa472c2010-03-19 07:35:19 +00001075 CheckAllocationAccess(StartLoc, Range, R.getNamingClass(), Best->FoundDecl);
Sebastian Redl7f662392008-12-04 22:20:51 +00001076 return false;
1077 }
1078
1079 case OR_No_Viable_Function:
Sebastian Redl7f662392008-12-04 22:20:51 +00001080 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +00001081 << Name << Range;
John McCallcbce6062010-01-12 07:18:19 +00001082 PrintOverloadCandidates(Candidates, OCD_AllCandidates, Args, NumArgs);
Sebastian Redl7f662392008-12-04 22:20:51 +00001083 return true;
1084
1085 case OR_Ambiguous:
Sebastian Redl7f662392008-12-04 22:20:51 +00001086 Diag(StartLoc, diag::err_ovl_ambiguous_call)
Sebastian Redl00e68e22009-02-09 18:24:27 +00001087 << Name << Range;
John McCallcbce6062010-01-12 07:18:19 +00001088 PrintOverloadCandidates(Candidates, OCD_ViableCandidates, Args, NumArgs);
Sebastian Redl7f662392008-12-04 22:20:51 +00001089 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001090
1091 case OR_Deleted:
1092 Diag(StartLoc, diag::err_ovl_deleted_call)
1093 << Best->Function->isDeleted()
1094 << Name << Range;
John McCallcbce6062010-01-12 07:18:19 +00001095 PrintOverloadCandidates(Candidates, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001096 return true;
Sebastian Redl7f662392008-12-04 22:20:51 +00001097 }
1098 assert(false && "Unreachable, bad result from BestViableFunction");
1099 return true;
1100}
1101
1102
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001103/// DeclareGlobalNewDelete - Declare the global forms of operator new and
1104/// delete. These are:
1105/// @code
1106/// void* operator new(std::size_t) throw(std::bad_alloc);
1107/// void* operator new[](std::size_t) throw(std::bad_alloc);
1108/// void operator delete(void *) throw();
1109/// void operator delete[](void *) throw();
1110/// @endcode
1111/// Note that the placement and nothrow forms of new are *not* implicitly
1112/// declared. Their use requires including \<new\>.
Mike Stump1eb44332009-09-09 15:08:12 +00001113void Sema::DeclareGlobalNewDelete() {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001114 if (GlobalNewDeleteDeclared)
1115 return;
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001116
1117 // C++ [basic.std.dynamic]p2:
1118 // [...] The following allocation and deallocation functions (18.4) are
1119 // implicitly declared in global scope in each translation unit of a
1120 // program
1121 //
1122 // void* operator new(std::size_t) throw(std::bad_alloc);
1123 // void* operator new[](std::size_t) throw(std::bad_alloc);
1124 // void operator delete(void*) throw();
1125 // void operator delete[](void*) throw();
1126 //
1127 // These implicit declarations introduce only the function names operator
1128 // new, operator new[], operator delete, operator delete[].
1129 //
1130 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
1131 // "std" or "bad_alloc" as necessary to form the exception specification.
1132 // However, we do not make these implicit declarations visible to name
1133 // lookup.
1134 if (!StdNamespace) {
1135 // The "std" namespace has not yet been defined, so build one implicitly.
1136 StdNamespace = NamespaceDecl::Create(Context,
1137 Context.getTranslationUnitDecl(),
1138 SourceLocation(),
1139 &PP.getIdentifierTable().get("std"));
1140 StdNamespace->setImplicit(true);
1141 }
1142
1143 if (!StdBadAlloc) {
1144 // The "std::bad_alloc" class has not yet been declared, so build it
1145 // implicitly.
1146 StdBadAlloc = CXXRecordDecl::Create(Context, TagDecl::TK_class,
1147 StdNamespace,
1148 SourceLocation(),
1149 &PP.getIdentifierTable().get("bad_alloc"),
1150 SourceLocation(), 0);
1151 StdBadAlloc->setImplicit(true);
1152 }
1153
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001154 GlobalNewDeleteDeclared = true;
1155
1156 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
1157 QualType SizeT = Context.getSizeType();
Nuno Lopesfc284482009-12-16 16:59:22 +00001158 bool AssumeSaneOperatorNew = getLangOptions().AssumeSaneOperatorNew;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001159
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001160 DeclareGlobalAllocationFunction(
1161 Context.DeclarationNames.getCXXOperatorName(OO_New),
Nuno Lopesfc284482009-12-16 16:59:22 +00001162 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001163 DeclareGlobalAllocationFunction(
1164 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
Nuno Lopesfc284482009-12-16 16:59:22 +00001165 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001166 DeclareGlobalAllocationFunction(
1167 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
1168 Context.VoidTy, VoidPtr);
1169 DeclareGlobalAllocationFunction(
1170 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
1171 Context.VoidTy, VoidPtr);
1172}
1173
1174/// DeclareGlobalAllocationFunction - Declares a single implicit global
1175/// allocation function if it doesn't already exist.
1176void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Nuno Lopesfc284482009-12-16 16:59:22 +00001177 QualType Return, QualType Argument,
1178 bool AddMallocAttr) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001179 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
1180
1181 // Check if this function is already declared.
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001182 {
Douglas Gregor5cc37092008-12-23 22:05:29 +00001183 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001184 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001185 Alloc != AllocEnd; ++Alloc) {
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001186 // Only look at non-template functions, as it is the predefined,
1187 // non-templated allocation function we are trying to declare here.
1188 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
1189 QualType InitialParamType =
Douglas Gregor6e790ab2009-12-22 23:42:49 +00001190 Context.getCanonicalType(
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001191 Func->getParamDecl(0)->getType().getUnqualifiedType());
1192 // FIXME: Do we need to check for default arguments here?
1193 if (Func->getNumParams() == 1 && InitialParamType == Argument)
1194 return;
1195 }
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001196 }
1197 }
1198
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001199 QualType BadAllocType;
1200 bool HasBadAllocExceptionSpec
1201 = (Name.getCXXOverloadedOperator() == OO_New ||
1202 Name.getCXXOverloadedOperator() == OO_Array_New);
1203 if (HasBadAllocExceptionSpec) {
1204 assert(StdBadAlloc && "Must have std::bad_alloc declared");
1205 BadAllocType = Context.getTypeDeclType(StdBadAlloc);
1206 }
1207
1208 QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0,
1209 true, false,
1210 HasBadAllocExceptionSpec? 1 : 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00001211 &BadAllocType,
1212 FunctionType::ExtInfo());
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001213 FunctionDecl *Alloc =
1214 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001215 FnType, /*TInfo=*/0, FunctionDecl::None,
1216 FunctionDecl::None, false, true);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001217 Alloc->setImplicit();
Nuno Lopesfc284482009-12-16 16:59:22 +00001218
1219 if (AddMallocAttr)
1220 Alloc->addAttr(::new (Context) MallocAttr());
1221
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001222 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
John McCalla93c9342009-12-07 02:54:59 +00001223 0, Argument, /*TInfo=*/0,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001224 VarDecl::None,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001225 VarDecl::None, 0);
Douglas Gregor838db382010-02-11 01:19:42 +00001226 Alloc->setParams(&Param, 1);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001227
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001228 // FIXME: Also add this declaration to the IdentifierResolver, but
1229 // make sure it is at the end of the chain to coincide with the
1230 // global scope.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001231 ((DeclContext *)TUScope->getEntity())->addDecl(Alloc);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001232}
1233
Anders Carlsson78f74552009-11-15 18:45:20 +00001234bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
1235 DeclarationName Name,
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00001236 FunctionDecl* &Operator) {
John McCalla24dc2e2009-11-17 02:14:36 +00001237 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlsson78f74552009-11-15 18:45:20 +00001238 // Try to find operator delete/operator delete[] in class scope.
John McCalla24dc2e2009-11-17 02:14:36 +00001239 LookupQualifiedName(Found, RD);
Anders Carlsson78f74552009-11-15 18:45:20 +00001240
John McCalla24dc2e2009-11-17 02:14:36 +00001241 if (Found.isAmbiguous())
Anders Carlsson78f74552009-11-15 18:45:20 +00001242 return true;
Anders Carlsson78f74552009-11-15 18:45:20 +00001243
1244 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1245 F != FEnd; ++F) {
1246 if (CXXMethodDecl *Delete = dyn_cast<CXXMethodDecl>(*F))
1247 if (Delete->isUsualDeallocationFunction()) {
1248 Operator = Delete;
1249 return false;
1250 }
1251 }
1252
1253 // We did find operator delete/operator delete[] declarations, but
1254 // none of them were suitable.
1255 if (!Found.empty()) {
1256 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
1257 << Name << RD;
1258
1259 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1260 F != FEnd; ++F) {
1261 Diag((*F)->getLocation(),
1262 diag::note_delete_member_function_declared_here)
1263 << Name;
1264 }
1265
1266 return true;
1267 }
1268
1269 // Look for a global declaration.
1270 DeclareGlobalNewDelete();
1271 DeclContext *TUDecl = Context.getTranslationUnitDecl();
1272
1273 CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation());
1274 Expr* DeallocArgs[1];
1275 DeallocArgs[0] = &Null;
1276 if (FindAllocationOverload(StartLoc, SourceRange(), Name,
1277 DeallocArgs, 1, TUDecl, /*AllowMissing=*/false,
1278 Operator))
1279 return true;
1280
1281 assert(Operator && "Did not find a deallocation function!");
1282 return false;
1283}
1284
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001285/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
1286/// @code ::delete ptr; @endcode
1287/// or
1288/// @code delete [] ptr; @endcode
Sebastian Redlf53597f2009-03-15 17:47:39 +00001289Action::OwningExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001290Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
Mike Stump1eb44332009-09-09 15:08:12 +00001291 bool ArrayForm, ExprArg Operand) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001292 // C++ [expr.delete]p1:
1293 // The operand shall have a pointer type, or a class type having a single
1294 // conversion function to a pointer type. The result has type void.
1295 //
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001296 // DR599 amends "pointer type" to "pointer to object type" in both cases.
1297
Anders Carlssond67c4c32009-08-16 20:29:29 +00001298 FunctionDecl *OperatorDelete = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001299
Sebastian Redlf53597f2009-03-15 17:47:39 +00001300 Expr *Ex = (Expr *)Operand.get();
Sebastian Redl28507842009-02-26 14:39:58 +00001301 if (!Ex->isTypeDependent()) {
1302 QualType Type = Ex->getType();
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001303
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001304 if (const RecordType *Record = Type->getAs<RecordType>()) {
John McCall32daa422010-03-31 01:36:47 +00001305 llvm::SmallVector<CXXConversionDecl*, 4> ObjectPtrConversions;
1306
Fariborz Jahanian53462782009-09-11 21:44:33 +00001307 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
John McCall32daa422010-03-31 01:36:47 +00001308 const UnresolvedSetImpl *Conversions = RD->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00001309 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00001310 E = Conversions->end(); I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00001311 NamedDecl *D = I.getDecl();
1312 if (isa<UsingShadowDecl>(D))
1313 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1314
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001315 // Skip over templated conversion functions; they aren't considered.
John McCall32daa422010-03-31 01:36:47 +00001316 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001317 continue;
1318
John McCall32daa422010-03-31 01:36:47 +00001319 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001320
1321 QualType ConvType = Conv->getConversionType().getNonReferenceType();
1322 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
1323 if (ConvPtrType->getPointeeType()->isObjectType())
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001324 ObjectPtrConversions.push_back(Conv);
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001325 }
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001326 if (ObjectPtrConversions.size() == 1) {
1327 // We have a single conversion to a pointer-to-object type. Perform
1328 // that conversion.
John McCall32daa422010-03-31 01:36:47 +00001329 // TODO: don't redo the conversion calculation.
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001330 Operand.release();
John McCall32daa422010-03-31 01:36:47 +00001331 if (!PerformImplicitConversion(Ex,
1332 ObjectPtrConversions.front()->getConversionType(),
Douglas Gregor68647482009-12-16 03:45:30 +00001333 AA_Converting)) {
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001334 Operand = Owned(Ex);
1335 Type = Ex->getType();
1336 }
1337 }
1338 else if (ObjectPtrConversions.size() > 1) {
1339 Diag(StartLoc, diag::err_ambiguous_delete_operand)
1340 << Type << Ex->getSourceRange();
John McCall32daa422010-03-31 01:36:47 +00001341 for (unsigned i= 0; i < ObjectPtrConversions.size(); i++)
1342 NoteOverloadCandidate(ObjectPtrConversions[i]);
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001343 return ExprError();
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001344 }
Sebastian Redl28507842009-02-26 14:39:58 +00001345 }
1346
Sebastian Redlf53597f2009-03-15 17:47:39 +00001347 if (!Type->isPointerType())
1348 return ExprError(Diag(StartLoc, diag::err_delete_operand)
1349 << Type << Ex->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +00001350
Ted Kremenek6217b802009-07-29 21:53:49 +00001351 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Douglas Gregor8dcb29d2009-03-24 20:13:58 +00001352 if (Pointee->isFunctionType() || Pointee->isVoidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +00001353 return ExprError(Diag(StartLoc, diag::err_delete_operand)
1354 << Type << Ex->getSourceRange());
Douglas Gregor8dcb29d2009-03-24 20:13:58 +00001355 else if (!Pointee->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00001356 RequireCompleteType(StartLoc, Pointee,
Anders Carlssonb7906612009-08-26 23:45:07 +00001357 PDiag(diag::warn_delete_incomplete)
1358 << Ex->getSourceRange()))
Douglas Gregor8dcb29d2009-03-24 20:13:58 +00001359 return ExprError();
Sebastian Redl28507842009-02-26 14:39:58 +00001360
Douglas Gregor1070c9f2009-09-29 21:38:53 +00001361 // C++ [expr.delete]p2:
1362 // [Note: a pointer to a const type can be the operand of a
1363 // delete-expression; it is not necessary to cast away the constness
1364 // (5.2.11) of the pointer expression before it is used as the operand
1365 // of the delete-expression. ]
1366 ImpCastExprToType(Ex, Context.getPointerType(Context.VoidTy),
1367 CastExpr::CK_NoOp);
1368
1369 // Update the operand.
1370 Operand.take();
1371 Operand = ExprArg(*this, Ex);
1372
Anders Carlssond67c4c32009-08-16 20:29:29 +00001373 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1374 ArrayForm ? OO_Array_Delete : OO_Delete);
1375
Anders Carlsson78f74552009-11-15 18:45:20 +00001376 if (const RecordType *RT = Pointee->getAs<RecordType>()) {
1377 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1378
1379 if (!UseGlobal &&
1380 FindDeallocationFunction(StartLoc, RD, DeleteName, OperatorDelete))
Anders Carlsson0ba63ea2009-11-14 03:17:38 +00001381 return ExprError();
Anders Carlsson0ba63ea2009-11-14 03:17:38 +00001382
Anders Carlsson78f74552009-11-15 18:45:20 +00001383 if (!RD->hasTrivialDestructor())
1384 if (const CXXDestructorDecl *Dtor = RD->getDestructor(Context))
Mike Stump1eb44332009-09-09 15:08:12 +00001385 MarkDeclarationReferenced(StartLoc,
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001386 const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssond67c4c32009-08-16 20:29:29 +00001387 }
Anders Carlsson78f74552009-11-15 18:45:20 +00001388
Anders Carlssond67c4c32009-08-16 20:29:29 +00001389 if (!OperatorDelete) {
Anders Carlsson78f74552009-11-15 18:45:20 +00001390 // Look for a global declaration.
Anders Carlssond67c4c32009-08-16 20:29:29 +00001391 DeclareGlobalNewDelete();
1392 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001393 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
Douglas Gregor90916562009-09-29 18:16:17 +00001394 &Ex, 1, TUDecl, /*AllowMissing=*/false,
Anders Carlssond67c4c32009-08-16 20:29:29 +00001395 OperatorDelete))
1396 return ExprError();
1397 }
Mike Stump1eb44332009-09-09 15:08:12 +00001398
John McCall9c82afc2010-04-20 02:18:25 +00001399 MarkDeclarationReferenced(StartLoc, OperatorDelete);
1400
Sebastian Redl28507842009-02-26 14:39:58 +00001401 // FIXME: Check access and ambiguity of operator delete and destructor.
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001402 }
1403
Sebastian Redlf53597f2009-03-15 17:47:39 +00001404 Operand.release();
1405 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
Anders Carlssond67c4c32009-08-16 20:29:29 +00001406 OperatorDelete, Ex, StartLoc));
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001407}
1408
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001409/// \brief Check the use of the given variable as a C++ condition in an if,
1410/// while, do-while, or switch statement.
1411Action::OwningExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar) {
1412 QualType T = ConditionVar->getType();
1413
1414 // C++ [stmt.select]p2:
1415 // The declarator shall not specify a function or an array.
1416 if (T->isFunctionType())
1417 return ExprError(Diag(ConditionVar->getLocation(),
1418 diag::err_invalid_use_of_function_type)
1419 << ConditionVar->getSourceRange());
1420 else if (T->isArrayType())
1421 return ExprError(Diag(ConditionVar->getLocation(),
1422 diag::err_invalid_use_of_array_type)
1423 << ConditionVar->getSourceRange());
Douglas Gregora7605db2009-11-24 16:07:02 +00001424
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001425 return Owned(DeclRefExpr::Create(Context, 0, SourceRange(), ConditionVar,
1426 ConditionVar->getLocation(),
1427 ConditionVar->getType().getNonReferenceType()));
1428}
1429
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001430/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
1431bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
1432 // C++ 6.4p4:
1433 // The value of a condition that is an initialized declaration in a statement
1434 // other than a switch statement is the value of the declared variable
1435 // implicitly converted to type bool. If that conversion is ill-formed, the
1436 // program is ill-formed.
1437 // The value of a condition that is an expression is the value of the
1438 // expression, implicitly converted to bool.
1439 //
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001440 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001441}
Douglas Gregor77a52232008-09-12 00:47:35 +00001442
1443/// Helper function to determine whether this is the (deprecated) C++
1444/// conversion from a string literal to a pointer to non-const char or
1445/// non-const wchar_t (for narrow and wide string literals,
1446/// respectively).
Mike Stump1eb44332009-09-09 15:08:12 +00001447bool
Douglas Gregor77a52232008-09-12 00:47:35 +00001448Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
1449 // Look inside the implicit cast, if it exists.
1450 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
1451 From = Cast->getSubExpr();
1452
1453 // A string literal (2.13.4) that is not a wide string literal can
1454 // be converted to an rvalue of type "pointer to char"; a wide
1455 // string literal can be converted to an rvalue of type "pointer
1456 // to wchar_t" (C++ 4.2p2).
1457 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From))
Ted Kremenek6217b802009-07-29 21:53:49 +00001458 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump1eb44332009-09-09 15:08:12 +00001459 if (const BuiltinType *ToPointeeType
John McCall183700f2009-09-21 23:43:11 +00001460 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregor77a52232008-09-12 00:47:35 +00001461 // This conversion is considered only when there is an
1462 // explicit appropriate pointer target type (C++ 4.2p2).
John McCall0953e762009-09-24 19:53:00 +00001463 if (!ToPtrType->getPointeeType().hasQualifiers() &&
Douglas Gregor77a52232008-09-12 00:47:35 +00001464 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
1465 (!StrLit->isWide() &&
1466 (ToPointeeType->getKind() == BuiltinType::Char_U ||
1467 ToPointeeType->getKind() == BuiltinType::Char_S))))
1468 return true;
1469 }
1470
1471 return false;
1472}
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001473
Douglas Gregorba70ab62010-04-16 22:17:36 +00001474static Sema::OwningExprResult BuildCXXCastArgument(Sema &S,
1475 SourceLocation CastLoc,
1476 QualType Ty,
1477 CastExpr::CastKind Kind,
1478 CXXMethodDecl *Method,
1479 Sema::ExprArg Arg) {
1480 Expr *From = Arg.takeAs<Expr>();
1481
1482 switch (Kind) {
1483 default: assert(0 && "Unhandled cast kind!");
1484 case CastExpr::CK_ConstructorConversion: {
1485 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(S);
1486
1487 if (S.CompleteConstructorCall(cast<CXXConstructorDecl>(Method),
1488 Sema::MultiExprArg(S, (void **)&From, 1),
1489 CastLoc, ConstructorArgs))
1490 return S.ExprError();
1491
1492 Sema::OwningExprResult Result =
1493 S.BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
1494 move_arg(ConstructorArgs));
1495 if (Result.isInvalid())
1496 return S.ExprError();
1497
1498 return S.MaybeBindToTemporary(Result.takeAs<Expr>());
1499 }
1500
1501 case CastExpr::CK_UserDefinedConversion: {
1502 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
1503
1504 // Create an implicit call expr that calls it.
1505 // FIXME: pass the FoundDecl for the user-defined conversion here
1506 CXXMemberCallExpr *CE = S.BuildCXXMemberCallExpr(From, Method, Method);
1507 return S.MaybeBindToTemporary(CE);
1508 }
1509 }
1510}
1511
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001512/// PerformImplicitConversion - Perform an implicit conversion of the
1513/// expression From to the type ToType using the pre-computed implicit
1514/// conversion sequence ICS. Returns true if there was an error, false
1515/// otherwise. The expression From is replaced with the converted
Douglas Gregor68647482009-12-16 03:45:30 +00001516/// expression. Action is the kind of conversion we're performing,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001517/// used in the error message.
1518bool
1519Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
1520 const ImplicitConversionSequence &ICS,
Douglas Gregor68647482009-12-16 03:45:30 +00001521 AssignmentAction Action, bool IgnoreBaseAccess) {
John McCall1d318332010-01-12 00:44:57 +00001522 switch (ICS.getKind()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001523 case ImplicitConversionSequence::StandardConversion:
Douglas Gregor68647482009-12-16 03:45:30 +00001524 if (PerformImplicitConversion(From, ToType, ICS.Standard, Action,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001525 IgnoreBaseAccess))
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001526 return true;
1527 break;
1528
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001529 case ImplicitConversionSequence::UserDefinedConversion: {
1530
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00001531 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
1532 CastExpr::CastKind CastKind = CastExpr::CK_Unknown;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001533 QualType BeforeToType;
1534 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00001535 CastKind = CastExpr::CK_UserDefinedConversion;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001536
1537 // If the user-defined conversion is specified by a conversion function,
1538 // the initial standard conversion sequence converts the source type to
1539 // the implicit object parameter of the conversion function.
1540 BeforeToType = Context.getTagDeclType(Conv->getParent());
1541 } else if (const CXXConstructorDecl *Ctor =
1542 dyn_cast<CXXConstructorDecl>(FD)) {
Anders Carlsson0aebc812009-09-09 21:33:21 +00001543 CastKind = CastExpr::CK_ConstructorConversion;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001544 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregore44201a2009-11-20 02:31:03 +00001545 if (!ICS.UserDefined.EllipsisConversion) {
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001546 // If the user-defined conversion is specified by a constructor, the
1547 // initial standard conversion sequence converts the source type to the
1548 // type required by the argument of the constructor
Douglas Gregore44201a2009-11-20 02:31:03 +00001549 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
1550 }
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001551 }
Anders Carlsson0aebc812009-09-09 21:33:21 +00001552 else
1553 assert(0 && "Unknown conversion function kind!");
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001554 // Whatch out for elipsis conversion.
Fariborz Jahanian4c0cea22009-11-06 00:55:14 +00001555 if (!ICS.UserDefined.EllipsisConversion) {
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001556 if (PerformImplicitConversion(From, BeforeToType,
Douglas Gregor68647482009-12-16 03:45:30 +00001557 ICS.UserDefined.Before, AA_Converting,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001558 IgnoreBaseAccess))
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001559 return true;
1560 }
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001561
Anders Carlsson0aebc812009-09-09 21:33:21 +00001562 OwningExprResult CastArg
Douglas Gregorba70ab62010-04-16 22:17:36 +00001563 = BuildCXXCastArgument(*this,
1564 From->getLocStart(),
Anders Carlsson0aebc812009-09-09 21:33:21 +00001565 ToType.getNonReferenceType(),
1566 CastKind, cast<CXXMethodDecl>(FD),
1567 Owned(From));
1568
1569 if (CastArg.isInvalid())
1570 return true;
Eli Friedmand8889622009-11-27 04:41:50 +00001571
1572 From = CastArg.takeAs<Expr>();
1573
Eli Friedmand8889622009-11-27 04:41:50 +00001574 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
Douglas Gregor68647482009-12-16 03:45:30 +00001575 AA_Converting, IgnoreBaseAccess);
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001576 }
John McCall1d318332010-01-12 00:44:57 +00001577
1578 case ImplicitConversionSequence::AmbiguousConversion:
1579 DiagnoseAmbiguousConversion(ICS, From->getExprLoc(),
1580 PDiag(diag::err_typecheck_ambiguous_condition)
1581 << From->getSourceRange());
1582 return true;
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001583
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001584 case ImplicitConversionSequence::EllipsisConversion:
1585 assert(false && "Cannot perform an ellipsis conversion");
Douglas Gregor60d62c22008-10-31 16:23:19 +00001586 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001587
1588 case ImplicitConversionSequence::BadConversion:
1589 return true;
1590 }
1591
1592 // Everything went well.
1593 return false;
1594}
1595
1596/// PerformImplicitConversion - Perform an implicit conversion of the
1597/// expression From to the type ToType by following the standard
1598/// conversion sequence SCS. Returns true if there was an error, false
1599/// otherwise. The expression From is replaced with the converted
Douglas Gregor45920e82008-12-19 17:40:08 +00001600/// expression. Flavor is the context in which we're performing this
1601/// conversion, for use in error messages.
Mike Stump1eb44332009-09-09 15:08:12 +00001602bool
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001603Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor45920e82008-12-19 17:40:08 +00001604 const StandardConversionSequence& SCS,
Douglas Gregor68647482009-12-16 03:45:30 +00001605 AssignmentAction Action, bool IgnoreBaseAccess) {
Mike Stump390b4cc2009-05-16 07:39:55 +00001606 // Overall FIXME: we are recomputing too many types here and doing far too
1607 // much extra work. What this means is that we need to keep track of more
1608 // information that is computed when we try the implicit conversion initially,
1609 // so that we don't need to recompute anything here.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001610 QualType FromType = From->getType();
1611
Douglas Gregor225c41e2008-11-03 19:09:14 +00001612 if (SCS.CopyConstructor) {
Anders Carlsson7c3e8a12009-05-19 04:45:15 +00001613 // FIXME: When can ToType be a reference type?
1614 assert(!ToType->isReferenceType());
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00001615 if (SCS.Second == ICK_Derived_To_Base) {
1616 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1617 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
1618 MultiExprArg(*this, (void **)&From, 1),
1619 /*FIXME:ConstructLoc*/SourceLocation(),
1620 ConstructorArgs))
1621 return true;
1622 OwningExprResult FromResult =
1623 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1624 ToType, SCS.CopyConstructor,
1625 move_arg(ConstructorArgs));
1626 if (FromResult.isInvalid())
1627 return true;
1628 From = FromResult.takeAs<Expr>();
1629 return false;
1630 }
Mike Stump1eb44332009-09-09 15:08:12 +00001631 OwningExprResult FromResult =
1632 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1633 ToType, SCS.CopyConstructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00001634 MultiExprArg(*this, (void**)&From, 1));
Mike Stump1eb44332009-09-09 15:08:12 +00001635
Anders Carlssonda3f4e22009-08-25 05:12:04 +00001636 if (FromResult.isInvalid())
1637 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001638
Anders Carlssonda3f4e22009-08-25 05:12:04 +00001639 From = FromResult.takeAs<Expr>();
Douglas Gregor225c41e2008-11-03 19:09:14 +00001640 return false;
1641 }
1642
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001643 // Perform the first implicit conversion.
1644 switch (SCS.First) {
1645 case ICK_Identity:
1646 case ICK_Lvalue_To_Rvalue:
1647 // Nothing to do.
1648 break;
1649
1650 case ICK_Array_To_Pointer:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001651 FromType = Context.getArrayDecayedType(FromType);
Anders Carlsson82495762009-08-08 21:04:35 +00001652 ImpCastExprToType(From, FromType, CastExpr::CK_ArrayToPointerDecay);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001653 break;
1654
1655 case ICK_Function_To_Pointer:
Douglas Gregor063daf62009-03-13 18:40:31 +00001656 if (Context.getCanonicalType(FromType) == Context.OverloadTy) {
John McCall6bb80172010-03-30 21:47:33 +00001657 DeclAccessPair Found;
1658 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
1659 true, Found);
Douglas Gregor904eed32008-11-10 20:40:00 +00001660 if (!Fn)
1661 return true;
1662
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001663 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
1664 return true;
1665
John McCall6bb80172010-03-30 21:47:33 +00001666 From = FixOverloadedFunctionReference(From, Found, Fn);
Douglas Gregor904eed32008-11-10 20:40:00 +00001667 FromType = From->getType();
Anders Carlsson96ad5332009-10-21 17:16:23 +00001668
Sebastian Redl759986e2009-10-17 20:50:27 +00001669 // If there's already an address-of operator in the expression, we have
1670 // the right type already, and the code below would just introduce an
1671 // invalid additional pointer level.
Anders Carlsson96ad5332009-10-21 17:16:23 +00001672 if (FromType->isPointerType() || FromType->isMemberFunctionPointerType())
Sebastian Redl759986e2009-10-17 20:50:27 +00001673 break;
Douglas Gregor904eed32008-11-10 20:40:00 +00001674 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001675 FromType = Context.getPointerType(FromType);
Anders Carlssonb633c4e2009-09-01 20:37:18 +00001676 ImpCastExprToType(From, FromType, CastExpr::CK_FunctionToPointerDecay);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001677 break;
1678
1679 default:
1680 assert(false && "Improper first standard conversion");
1681 break;
1682 }
1683
1684 // Perform the second implicit conversion
1685 switch (SCS.Second) {
1686 case ICK_Identity:
Sebastian Redl2c7588f2009-10-10 12:04:10 +00001687 // If both sides are functions (or pointers/references to them), there could
1688 // be incompatible exception declarations.
1689 if (CheckExceptionSpecCompatibility(From, ToType))
1690 return true;
1691 // Nothing else to do.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001692 break;
1693
Douglas Gregor43c79c22009-12-09 00:47:37 +00001694 case ICK_NoReturn_Adjustment:
1695 // If both sides are functions (or pointers/references to them), there could
1696 // be incompatible exception declarations.
1697 if (CheckExceptionSpecCompatibility(From, ToType))
1698 return true;
1699
1700 ImpCastExprToType(From, Context.getNoReturnType(From->getType(), false),
1701 CastExpr::CK_NoOp);
1702 break;
1703
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001704 case ICK_Integral_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001705 case ICK_Integral_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001706 ImpCastExprToType(From, ToType, CastExpr::CK_IntegralCast);
1707 break;
1708
1709 case ICK_Floating_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001710 case ICK_Floating_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001711 ImpCastExprToType(From, ToType, CastExpr::CK_FloatingCast);
1712 break;
1713
1714 case ICK_Complex_Promotion:
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001715 case ICK_Complex_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001716 ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1717 break;
1718
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001719 case ICK_Floating_Integral:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001720 if (ToType->isFloatingType())
1721 ImpCastExprToType(From, ToType, CastExpr::CK_IntegralToFloating);
1722 else
1723 ImpCastExprToType(From, ToType, CastExpr::CK_FloatingToIntegral);
1724 break;
1725
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001726 case ICK_Complex_Real:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001727 ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1728 break;
1729
Douglas Gregorf9201e02009-02-11 23:02:49 +00001730 case ICK_Compatible_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001731 ImpCastExprToType(From, ToType, CastExpr::CK_NoOp);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001732 break;
1733
Anders Carlsson61faec12009-09-12 04:46:44 +00001734 case ICK_Pointer_Conversion: {
Douglas Gregor45920e82008-12-19 17:40:08 +00001735 if (SCS.IncompatibleObjC) {
1736 // Diagnose incompatible Objective-C conversions
Mike Stump1eb44332009-09-09 15:08:12 +00001737 Diag(From->getSourceRange().getBegin(),
Douglas Gregor45920e82008-12-19 17:40:08 +00001738 diag::ext_typecheck_convert_incompatible_pointer)
Douglas Gregor68647482009-12-16 03:45:30 +00001739 << From->getType() << ToType << Action
Douglas Gregor45920e82008-12-19 17:40:08 +00001740 << From->getSourceRange();
1741 }
1742
Anders Carlsson61faec12009-09-12 04:46:44 +00001743
1744 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001745 if (CheckPointerConversion(From, ToType, Kind, IgnoreBaseAccess))
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001746 return true;
Anders Carlsson61faec12009-09-12 04:46:44 +00001747 ImpCastExprToType(From, ToType, Kind);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001748 break;
Anders Carlsson61faec12009-09-12 04:46:44 +00001749 }
1750
1751 case ICK_Pointer_Member: {
1752 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001753 if (CheckMemberPointerConversion(From, ToType, Kind, IgnoreBaseAccess))
Anders Carlsson61faec12009-09-12 04:46:44 +00001754 return true;
Sebastian Redl2c7588f2009-10-10 12:04:10 +00001755 if (CheckExceptionSpecCompatibility(From, ToType))
1756 return true;
Anders Carlsson61faec12009-09-12 04:46:44 +00001757 ImpCastExprToType(From, ToType, Kind);
1758 break;
1759 }
Anders Carlssonbc0e0782009-11-23 20:04:44 +00001760 case ICK_Boolean_Conversion: {
1761 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
1762 if (FromType->isMemberPointerType())
1763 Kind = CastExpr::CK_MemberPointerToBoolean;
1764
1765 ImpCastExprToType(From, Context.BoolTy, Kind);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001766 break;
Anders Carlssonbc0e0782009-11-23 20:04:44 +00001767 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001768
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001769 case ICK_Derived_To_Base:
1770 if (CheckDerivedToBaseConversion(From->getType(),
1771 ToType.getNonReferenceType(),
1772 From->getLocStart(),
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001773 From->getSourceRange(),
1774 IgnoreBaseAccess))
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001775 return true;
1776 ImpCastExprToType(From, ToType.getNonReferenceType(),
1777 CastExpr::CK_DerivedToBase);
1778 break;
1779
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001780 default:
1781 assert(false && "Improper second standard conversion");
1782 break;
1783 }
1784
1785 switch (SCS.Third) {
1786 case ICK_Identity:
1787 // Nothing to do.
1788 break;
1789
1790 case ICK_Qualification:
Mike Stump390b4cc2009-05-16 07:39:55 +00001791 // FIXME: Not sure about lvalue vs rvalue here in the presence of rvalue
1792 // references.
Mike Stump1eb44332009-09-09 15:08:12 +00001793 ImpCastExprToType(From, ToType.getNonReferenceType(),
Eli Friedman73c39ab2009-10-20 08:27:19 +00001794 CastExpr::CK_NoOp,
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001795 ToType->isLValueReferenceType());
Douglas Gregora9bff302010-02-28 18:30:25 +00001796
1797 if (SCS.DeprecatedStringLiteralToCharPtr)
1798 Diag(From->getLocStart(), diag::warn_deprecated_string_literal_conversion)
1799 << ToType.getNonReferenceType();
1800
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001801 break;
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001802
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001803 default:
1804 assert(false && "Improper second standard conversion");
1805 break;
1806 }
1807
1808 return false;
1809}
1810
Sebastian Redl64b45f72009-01-05 20:52:13 +00001811Sema::OwningExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
1812 SourceLocation KWLoc,
1813 SourceLocation LParen,
1814 TypeTy *Ty,
1815 SourceLocation RParen) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00001816 QualType T = GetTypeFromParser(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00001817
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001818 // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
1819 // all traits except __is_class, __is_enum and __is_union require a the type
1820 // to be complete.
1821 if (OTT != UTT_IsClass && OTT != UTT_IsEnum && OTT != UTT_IsUnion) {
Mike Stump1eb44332009-09-09 15:08:12 +00001822 if (RequireCompleteType(KWLoc, T,
Anders Carlssond497ba72009-08-26 22:59:12 +00001823 diag::err_incomplete_type_used_in_type_trait_expr))
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001824 return ExprError();
1825 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00001826
1827 // There is no point in eagerly computing the value. The traits are designed
1828 // to be used from type trait templates, so Ty will be a template parameter
1829 // 99% of the time.
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001830 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT, T,
1831 RParen, Context.BoolTy));
Sebastian Redl64b45f72009-01-05 20:52:13 +00001832}
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001833
1834QualType Sema::CheckPointerToMemberOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00001835 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001836 const char *OpSpelling = isIndirect ? "->*" : ".*";
1837 // C++ 5.5p2
1838 // The binary operator .* [p3: ->*] binds its second operand, which shall
1839 // be of type "pointer to member of T" (where T is a completely-defined
1840 // class type) [...]
1841 QualType RType = rex->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001842 const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
Douglas Gregore7450f52009-03-24 19:52:54 +00001843 if (!MemPtr) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001844 Diag(Loc, diag::err_bad_memptr_rhs)
1845 << OpSpelling << RType << rex->getSourceRange();
1846 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00001847 }
Douglas Gregore7450f52009-03-24 19:52:54 +00001848
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001849 QualType Class(MemPtr->getClass(), 0);
1850
Sebastian Redl59fc2692010-04-10 10:14:54 +00001851 if (RequireCompleteType(Loc, Class, diag::err_memptr_rhs_to_incomplete))
1852 return QualType();
1853
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001854 // C++ 5.5p2
1855 // [...] to its first operand, which shall be of class T or of a class of
1856 // which T is an unambiguous and accessible base class. [p3: a pointer to
1857 // such a class]
1858 QualType LType = lex->getType();
1859 if (isIndirect) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001860 if (const PointerType *Ptr = LType->getAs<PointerType>())
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001861 LType = Ptr->getPointeeType().getNonReferenceType();
1862 else {
1863 Diag(Loc, diag::err_bad_memptr_lhs)
Fariborz Jahanianef78ac62009-10-26 20:45:27 +00001864 << OpSpelling << 1 << LType
Douglas Gregor849b2432010-03-31 17:46:05 +00001865 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001866 return QualType();
1867 }
1868 }
1869
Douglas Gregora4923eb2009-11-16 21:35:15 +00001870 if (!Context.hasSameUnqualifiedType(Class, LType)) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001871 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1872 /*DetectVirtual=*/false);
Mike Stump390b4cc2009-05-16 07:39:55 +00001873 // FIXME: Would it be useful to print full ambiguity paths, or is that
1874 // overkill?
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001875 if (!IsDerivedFrom(LType, Class, Paths) ||
1876 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
1877 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Eli Friedman3005efe2010-01-16 00:00:48 +00001878 << (int)isIndirect << lex->getType();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001879 return QualType();
1880 }
Eli Friedman3005efe2010-01-16 00:00:48 +00001881 // Cast LHS to type of use.
1882 QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
1883 bool isLValue = !isIndirect && lex->isLvalue(Context) == Expr::LV_Valid;
1884 ImpCastExprToType(lex, UseType, CastExpr::CK_DerivedToBase, isLValue);
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001885 }
1886
Fariborz Jahanian19d70732009-11-18 22:16:17 +00001887 if (isa<CXXZeroInitValueExpr>(rex->IgnoreParens())) {
Fariborz Jahanian05ebda92009-11-18 21:54:48 +00001888 // Diagnose use of pointer-to-member type which when used as
1889 // the functional cast in a pointer-to-member expression.
1890 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
1891 return QualType();
1892 }
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001893 // C++ 5.5p2
1894 // The result is an object or a function of the type specified by the
1895 // second operand.
1896 // The cv qualifiers are the union of those in the pointer and the left side,
1897 // in accordance with 5.5p5 and 5.2.5.
1898 // FIXME: This returns a dereferenced member function pointer as a normal
1899 // function type. However, the only operation valid on such functions is
Mike Stump390b4cc2009-05-16 07:39:55 +00001900 // calling them. There's also a GCC extension to get a function pointer to the
1901 // thing, which is another complication, because this type - unlike the type
1902 // that is the result of this expression - takes the class as the first
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001903 // argument.
1904 // We probably need a "MemberFunctionClosureType" or something like that.
1905 QualType Result = MemPtr->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00001906 Result = Context.getCVRQualifiedType(Result, LType.getCVRQualifiers());
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001907 return Result;
1908}
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001909
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001910/// \brief Try to convert a type to another according to C++0x 5.16p3.
1911///
1912/// This is part of the parameter validation for the ? operator. If either
1913/// value operand is a class type, the two operands are attempted to be
1914/// converted to each other. This function does the conversion in one direction.
Douglas Gregorb70cf442010-03-26 20:14:36 +00001915/// It returns true if the program is ill-formed and has already been diagnosed
1916/// as such.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001917static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
1918 SourceLocation QuestionLoc,
Douglas Gregorb70cf442010-03-26 20:14:36 +00001919 bool &HaveConversion,
1920 QualType &ToType) {
1921 HaveConversion = false;
1922 ToType = To->getType();
1923
1924 InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
1925 SourceLocation());
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001926 // C++0x 5.16p3
1927 // The process for determining whether an operand expression E1 of type T1
1928 // can be converted to match an operand expression E2 of type T2 is defined
1929 // as follows:
1930 // -- If E2 is an lvalue:
Douglas Gregor0fd8ff72010-03-26 20:59:55 +00001931 bool ToIsLvalue = (To->isLvalue(Self.Context) == Expr::LV_Valid);
1932 if (ToIsLvalue) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001933 // E1 can be converted to match E2 if E1 can be implicitly converted to
1934 // type "lvalue reference to T2", subject to the constraint that in the
1935 // conversion the reference must bind directly to E1.
Douglas Gregorb70cf442010-03-26 20:14:36 +00001936 QualType T = Self.Context.getLValueReferenceType(ToType);
1937 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
1938
1939 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
1940 if (InitSeq.isDirectReferenceBinding()) {
1941 ToType = T;
1942 HaveConversion = true;
1943 return false;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001944 }
Douglas Gregorb70cf442010-03-26 20:14:36 +00001945
1946 if (InitSeq.isAmbiguous())
1947 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001948 }
John McCallb1bdc622010-02-25 01:37:24 +00001949
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001950 // -- If E2 is an rvalue, or if the conversion above cannot be done:
1951 // -- if E1 and E2 have class type, and the underlying class types are
1952 // the same or one is a base class of the other:
1953 QualType FTy = From->getType();
1954 QualType TTy = To->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001955 const RecordType *FRec = FTy->getAs<RecordType>();
1956 const RecordType *TRec = TTy->getAs<RecordType>();
Douglas Gregorb70cf442010-03-26 20:14:36 +00001957 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
1958 Self.IsDerivedFrom(FTy, TTy);
1959 if (FRec && TRec &&
1960 (FRec == TRec || FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001961 // E1 can be converted to match E2 if the class of T2 is the
1962 // same type as, or a base class of, the class of T1, and
1963 // [cv2 > cv1].
John McCallb1bdc622010-02-25 01:37:24 +00001964 if (FRec == TRec || FDerivedFromT) {
1965 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00001966 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
1967 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
1968 if (InitSeq.getKind() != InitializationSequence::FailedSequence) {
1969 HaveConversion = true;
1970 return false;
1971 }
1972
1973 if (InitSeq.isAmbiguous())
1974 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
1975 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001976 }
Douglas Gregorb70cf442010-03-26 20:14:36 +00001977
1978 return false;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001979 }
Douglas Gregorb70cf442010-03-26 20:14:36 +00001980
1981 // -- Otherwise: E1 can be converted to match E2 if E1 can be
1982 // implicitly converted to the type that expression E2 would have
Douglas Gregor0fd8ff72010-03-26 20:59:55 +00001983 // if E2 were converted to an rvalue (or the type it has, if E2 is
1984 // an rvalue).
1985 //
1986 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
1987 // to the array-to-pointer or function-to-pointer conversions.
1988 if (!TTy->getAs<TagType>())
1989 TTy = TTy.getUnqualifiedType();
Douglas Gregorb70cf442010-03-26 20:14:36 +00001990
1991 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
1992 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
1993 HaveConversion = InitSeq.getKind() != InitializationSequence::FailedSequence;
1994 ToType = TTy;
1995 if (InitSeq.isAmbiguous())
1996 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
1997
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001998 return false;
1999}
2000
2001/// \brief Try to find a common type for two according to C++0x 5.16p5.
2002///
2003/// This is part of the parameter validation for the ? operator. If either
2004/// value operand is a class type, overload resolution is used to find a
2005/// conversion to a common type.
2006static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
2007 SourceLocation Loc) {
2008 Expr *Args[2] = { LHS, RHS };
John McCall5769d612010-02-08 23:07:23 +00002009 OverloadCandidateSet CandidateSet(Loc);
Douglas Gregor573d9c32009-10-21 23:19:44 +00002010 Self.AddBuiltinOperatorCandidates(OO_Conditional, Loc, Args, 2, CandidateSet);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002011
2012 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00002013 switch (Self.BestViableFunction(CandidateSet, Loc, Best)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002014 case OR_Success:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002015 // We found a match. Perform the conversions on the arguments and move on.
2016 if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00002017 Best->Conversions[0], Sema::AA_Converting) ||
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002018 Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor68647482009-12-16 03:45:30 +00002019 Best->Conversions[1], Sema::AA_Converting))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002020 break;
2021 return false;
2022
Douglas Gregor20093b42009-12-09 23:02:17 +00002023 case OR_No_Viable_Function:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002024 Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
2025 << LHS->getType() << RHS->getType()
2026 << LHS->getSourceRange() << RHS->getSourceRange();
2027 return true;
2028
Douglas Gregor20093b42009-12-09 23:02:17 +00002029 case OR_Ambiguous:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002030 Self.Diag(Loc, diag::err_conditional_ambiguous_ovl)
2031 << LHS->getType() << RHS->getType()
2032 << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stump390b4cc2009-05-16 07:39:55 +00002033 // FIXME: Print the possible common types by printing the return types of
2034 // the viable candidates.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002035 break;
2036
Douglas Gregor20093b42009-12-09 23:02:17 +00002037 case OR_Deleted:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002038 assert(false && "Conditional operator has only built-in overloads");
2039 break;
2040 }
2041 return true;
2042}
2043
Sebastian Redl76458502009-04-17 16:30:52 +00002044/// \brief Perform an "extended" implicit conversion as returned by
2045/// TryClassUnification.
Douglas Gregorb70cf442010-03-26 20:14:36 +00002046static bool ConvertForConditional(Sema &Self, Expr *&E, QualType T) {
2047 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
2048 InitializationKind Kind = InitializationKind::CreateCopy(E->getLocStart(),
2049 SourceLocation());
2050 InitializationSequence InitSeq(Self, Entity, Kind, &E, 1);
2051 Sema::OwningExprResult Result = InitSeq.Perform(Self, Entity, Kind,
2052 Sema::MultiExprArg(Self, (void **)&E, 1));
2053 if (Result.isInvalid())
Sebastian Redl76458502009-04-17 16:30:52 +00002054 return true;
Douglas Gregorb70cf442010-03-26 20:14:36 +00002055
2056 E = Result.takeAs<Expr>();
Sebastian Redl76458502009-04-17 16:30:52 +00002057 return false;
2058}
2059
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002060/// \brief Check the operands of ?: under C++ semantics.
2061///
2062/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
2063/// extension. In this case, LHS == Cond. (But they're not aliases.)
2064QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
2065 SourceLocation QuestionLoc) {
Mike Stump390b4cc2009-05-16 07:39:55 +00002066 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
2067 // interface pointers.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002068
2069 // C++0x 5.16p1
2070 // The first expression is contextually converted to bool.
2071 if (!Cond->isTypeDependent()) {
2072 if (CheckCXXBooleanCondition(Cond))
2073 return QualType();
2074 }
2075
2076 // Either of the arguments dependent?
2077 if (LHS->isTypeDependent() || RHS->isTypeDependent())
2078 return Context.DependentTy;
2079
John McCalld1b47bf2010-03-11 19:43:18 +00002080 CheckSignCompare(LHS, RHS, QuestionLoc);
John McCallb13c87f2009-11-05 09:23:39 +00002081
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002082 // C++0x 5.16p2
2083 // If either the second or the third operand has type (cv) void, ...
2084 QualType LTy = LHS->getType();
2085 QualType RTy = RHS->getType();
2086 bool LVoid = LTy->isVoidType();
2087 bool RVoid = RTy->isVoidType();
2088 if (LVoid || RVoid) {
2089 // ... then the [l2r] conversions are performed on the second and third
2090 // operands ...
Douglas Gregora873dfc2010-02-03 00:27:59 +00002091 DefaultFunctionArrayLvalueConversion(LHS);
2092 DefaultFunctionArrayLvalueConversion(RHS);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002093 LTy = LHS->getType();
2094 RTy = RHS->getType();
2095
2096 // ... and one of the following shall hold:
2097 // -- The second or the third operand (but not both) is a throw-
2098 // expression; the result is of the type of the other and is an rvalue.
2099 bool LThrow = isa<CXXThrowExpr>(LHS);
2100 bool RThrow = isa<CXXThrowExpr>(RHS);
2101 if (LThrow && !RThrow)
2102 return RTy;
2103 if (RThrow && !LThrow)
2104 return LTy;
2105
2106 // -- Both the second and third operands have type void; the result is of
2107 // type void and is an rvalue.
2108 if (LVoid && RVoid)
2109 return Context.VoidTy;
2110
2111 // Neither holds, error.
2112 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
2113 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
2114 << LHS->getSourceRange() << RHS->getSourceRange();
2115 return QualType();
2116 }
2117
2118 // Neither is void.
2119
2120 // C++0x 5.16p3
2121 // Otherwise, if the second and third operand have different types, and
2122 // either has (cv) class type, and attempt is made to convert each of those
2123 // operands to the other.
Douglas Gregorb70cf442010-03-26 20:14:36 +00002124 if (!Context.hasSameType(LTy, RTy) &&
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002125 (LTy->isRecordType() || RTy->isRecordType())) {
2126 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
2127 // These return true if a single direction is already ambiguous.
Douglas Gregorb70cf442010-03-26 20:14:36 +00002128 QualType L2RType, R2LType;
2129 bool HaveL2R, HaveR2L;
2130 if (TryClassUnification(*this, LHS, RHS, QuestionLoc, HaveL2R, L2RType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002131 return QualType();
Douglas Gregorb70cf442010-03-26 20:14:36 +00002132 if (TryClassUnification(*this, RHS, LHS, QuestionLoc, HaveR2L, R2LType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002133 return QualType();
Douglas Gregorb70cf442010-03-26 20:14:36 +00002134
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002135 // If both can be converted, [...] the program is ill-formed.
2136 if (HaveL2R && HaveR2L) {
2137 Diag(QuestionLoc, diag::err_conditional_ambiguous)
2138 << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
2139 return QualType();
2140 }
2141
2142 // If exactly one conversion is possible, that conversion is applied to
2143 // the chosen operand and the converted operands are used in place of the
2144 // original operands for the remainder of this section.
2145 if (HaveL2R) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00002146 if (ConvertForConditional(*this, LHS, L2RType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002147 return QualType();
2148 LTy = LHS->getType();
2149 } else if (HaveR2L) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00002150 if (ConvertForConditional(*this, RHS, R2LType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002151 return QualType();
2152 RTy = RHS->getType();
2153 }
2154 }
2155
2156 // C++0x 5.16p4
2157 // If the second and third operands are lvalues and have the same type,
2158 // the result is of that type [...]
Douglas Gregor1927b1f2010-04-01 22:47:07 +00002159 bool Same = Context.hasSameType(LTy, RTy);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002160 if (Same && LHS->isLvalue(Context) == Expr::LV_Valid &&
2161 RHS->isLvalue(Context) == Expr::LV_Valid)
2162 return LTy;
2163
2164 // C++0x 5.16p5
2165 // Otherwise, the result is an rvalue. If the second and third operands
2166 // do not have the same type, and either has (cv) class type, ...
2167 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
2168 // ... overload resolution is used to determine the conversions (if any)
2169 // to be applied to the operands. If the overload resolution fails, the
2170 // program is ill-formed.
2171 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
2172 return QualType();
2173 }
2174
2175 // C++0x 5.16p6
2176 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
2177 // conversions are performed on the second and third operands.
Douglas Gregora873dfc2010-02-03 00:27:59 +00002178 DefaultFunctionArrayLvalueConversion(LHS);
2179 DefaultFunctionArrayLvalueConversion(RHS);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002180 LTy = LHS->getType();
2181 RTy = RHS->getType();
2182
2183 // After those conversions, one of the following shall hold:
2184 // -- The second and third operands have the same type; the result
2185 // is of that type.
2186 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy))
2187 return LTy;
2188
2189 // -- The second and third operands have arithmetic or enumeration type;
2190 // the usual arithmetic conversions are performed to bring them to a
2191 // common type, and the result is of that type.
2192 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
2193 UsualArithmeticConversions(LHS, RHS);
2194 return LHS->getType();
2195 }
2196
2197 // -- The second and third operands have pointer type, or one has pointer
2198 // type and the other is a null pointer constant; pointer conversions
2199 // and qualification conversions are performed to bring them to their
2200 // composite pointer type. The result is of the composite pointer type.
Eli Friedmande8ac492010-01-02 22:56:07 +00002201 // -- The second and third operands have pointer to member type, or one has
2202 // pointer to member type and the other is a null pointer constant;
2203 // pointer to member conversions and qualification conversions are
2204 // performed to bring them to a common type, whose cv-qualification
2205 // shall match the cv-qualification of either the second or the third
2206 // operand. The result is of the common type.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002207 bool NonStandardCompositeType = false;
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002208 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002209 isSFINAEContext()? 0 : &NonStandardCompositeType);
2210 if (!Composite.isNull()) {
2211 if (NonStandardCompositeType)
2212 Diag(QuestionLoc,
2213 diag::ext_typecheck_cond_incompatible_operands_nonstandard)
2214 << LTy << RTy << Composite
2215 << LHS->getSourceRange() << RHS->getSourceRange();
2216
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002217 return Composite;
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002218 }
Fariborz Jahanian55016362009-12-10 20:46:08 +00002219
Douglas Gregor1927b1f2010-04-01 22:47:07 +00002220 // Similarly, attempt to find composite type of two objective-c pointers.
Fariborz Jahanian55016362009-12-10 20:46:08 +00002221 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
2222 if (!Composite.isNull())
2223 return Composite;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002224
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002225 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
2226 << LHS->getType() << RHS->getType()
2227 << LHS->getSourceRange() << RHS->getSourceRange();
2228 return QualType();
2229}
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002230
2231/// \brief Find a merged pointer type and convert the two expressions to it.
2232///
Douglas Gregor20b3e992009-08-24 17:42:35 +00002233/// This finds the composite pointer type (or member pointer type) for @p E1
2234/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
2235/// type and returns it.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002236/// It does not emit diagnostics.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002237///
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002238/// \param Loc The location of the operator requiring these two expressions to
2239/// be converted to the composite pointer type.
2240///
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002241/// If \p NonStandardCompositeType is non-NULL, then we are permitted to find
2242/// a non-standard (but still sane) composite type to which both expressions
2243/// can be converted. When such a type is chosen, \c *NonStandardCompositeType
2244/// will be set true.
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002245QualType Sema::FindCompositePointerType(SourceLocation Loc,
2246 Expr *&E1, Expr *&E2,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002247 bool *NonStandardCompositeType) {
2248 if (NonStandardCompositeType)
2249 *NonStandardCompositeType = false;
2250
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002251 assert(getLangOptions().CPlusPlus && "This function assumes C++");
2252 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002253
Fariborz Jahanian0cedfbd2009-12-08 20:04:24 +00002254 if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
2255 !T2->isAnyPointerType() && !T2->isMemberPointerType())
Douglas Gregor20b3e992009-08-24 17:42:35 +00002256 return QualType();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002257
2258 // C++0x 5.9p2
2259 // Pointer conversions and qualification conversions are performed on
2260 // pointer operands to bring them to their composite pointer type. If
2261 // one operand is a null pointer constant, the composite pointer type is
2262 // the type of the other operand.
Douglas Gregorce940492009-09-25 04:25:58 +00002263 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00002264 if (T2->isMemberPointerType())
2265 ImpCastExprToType(E1, T2, CastExpr::CK_NullToMemberPointer);
2266 else
2267 ImpCastExprToType(E1, T2, CastExpr::CK_IntegralToPointer);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002268 return T2;
2269 }
Douglas Gregorce940492009-09-25 04:25:58 +00002270 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00002271 if (T1->isMemberPointerType())
2272 ImpCastExprToType(E2, T1, CastExpr::CK_NullToMemberPointer);
2273 else
2274 ImpCastExprToType(E2, T1, CastExpr::CK_IntegralToPointer);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002275 return T1;
2276 }
Mike Stump1eb44332009-09-09 15:08:12 +00002277
Douglas Gregor20b3e992009-08-24 17:42:35 +00002278 // Now both have to be pointers or member pointers.
Sebastian Redla439e6f2009-11-16 21:03:45 +00002279 if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
2280 (!T2->isPointerType() && !T2->isMemberPointerType()))
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002281 return QualType();
2282
2283 // Otherwise, of one of the operands has type "pointer to cv1 void," then
2284 // the other has type "pointer to cv2 T" and the composite pointer type is
2285 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
2286 // Otherwise, the composite pointer type is a pointer type similar to the
2287 // type of one of the operands, with a cv-qualification signature that is
2288 // the union of the cv-qualification signatures of the operand types.
2289 // In practice, the first part here is redundant; it's subsumed by the second.
2290 // What we do here is, we build the two possible composite types, and try the
2291 // conversions in both directions. If only one works, or if the two composite
2292 // types are the same, we have succeeded.
John McCall0953e762009-09-24 19:53:00 +00002293 // FIXME: extended qualifiers?
Sebastian Redla439e6f2009-11-16 21:03:45 +00002294 typedef llvm::SmallVector<unsigned, 4> QualifierVector;
2295 QualifierVector QualifierUnion;
2296 typedef llvm::SmallVector<std::pair<const Type *, const Type *>, 4>
2297 ContainingClassVector;
2298 ContainingClassVector MemberOfClass;
2299 QualType Composite1 = Context.getCanonicalType(T1),
2300 Composite2 = Context.getCanonicalType(T2);
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002301 unsigned NeedConstBefore = 0;
Douglas Gregor20b3e992009-08-24 17:42:35 +00002302 do {
2303 const PointerType *Ptr1, *Ptr2;
2304 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
2305 (Ptr2 = Composite2->getAs<PointerType>())) {
2306 Composite1 = Ptr1->getPointeeType();
2307 Composite2 = Ptr2->getPointeeType();
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002308
2309 // If we're allowed to create a non-standard composite type, keep track
2310 // of where we need to fill in additional 'const' qualifiers.
2311 if (NonStandardCompositeType &&
2312 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
2313 NeedConstBefore = QualifierUnion.size();
2314
Douglas Gregor20b3e992009-08-24 17:42:35 +00002315 QualifierUnion.push_back(
2316 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
2317 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
2318 continue;
2319 }
Mike Stump1eb44332009-09-09 15:08:12 +00002320
Douglas Gregor20b3e992009-08-24 17:42:35 +00002321 const MemberPointerType *MemPtr1, *MemPtr2;
2322 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
2323 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
2324 Composite1 = MemPtr1->getPointeeType();
2325 Composite2 = MemPtr2->getPointeeType();
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002326
2327 // If we're allowed to create a non-standard composite type, keep track
2328 // of where we need to fill in additional 'const' qualifiers.
2329 if (NonStandardCompositeType &&
2330 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
2331 NeedConstBefore = QualifierUnion.size();
2332
Douglas Gregor20b3e992009-08-24 17:42:35 +00002333 QualifierUnion.push_back(
2334 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
2335 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
2336 MemPtr2->getClass()));
2337 continue;
2338 }
Mike Stump1eb44332009-09-09 15:08:12 +00002339
Douglas Gregor20b3e992009-08-24 17:42:35 +00002340 // FIXME: block pointer types?
Mike Stump1eb44332009-09-09 15:08:12 +00002341
Douglas Gregor20b3e992009-08-24 17:42:35 +00002342 // Cannot unwrap any more types.
2343 break;
2344 } while (true);
Mike Stump1eb44332009-09-09 15:08:12 +00002345
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002346 if (NeedConstBefore && NonStandardCompositeType) {
2347 // Extension: Add 'const' to qualifiers that come before the first qualifier
2348 // mismatch, so that our (non-standard!) composite type meets the
2349 // requirements of C++ [conv.qual]p4 bullet 3.
2350 for (unsigned I = 0; I != NeedConstBefore; ++I) {
2351 if ((QualifierUnion[I] & Qualifiers::Const) == 0) {
2352 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
2353 *NonStandardCompositeType = true;
2354 }
2355 }
2356 }
2357
Douglas Gregor20b3e992009-08-24 17:42:35 +00002358 // Rewrap the composites as pointers or member pointers with the union CVRs.
Sebastian Redla439e6f2009-11-16 21:03:45 +00002359 ContainingClassVector::reverse_iterator MOC
2360 = MemberOfClass.rbegin();
2361 for (QualifierVector::reverse_iterator
2362 I = QualifierUnion.rbegin(),
2363 E = QualifierUnion.rend();
Douglas Gregor20b3e992009-08-24 17:42:35 +00002364 I != E; (void)++I, ++MOC) {
John McCall0953e762009-09-24 19:53:00 +00002365 Qualifiers Quals = Qualifiers::fromCVRMask(*I);
Douglas Gregor20b3e992009-08-24 17:42:35 +00002366 if (MOC->first && MOC->second) {
2367 // Rebuild member pointer type
John McCall0953e762009-09-24 19:53:00 +00002368 Composite1 = Context.getMemberPointerType(
2369 Context.getQualifiedType(Composite1, Quals),
2370 MOC->first);
2371 Composite2 = Context.getMemberPointerType(
2372 Context.getQualifiedType(Composite2, Quals),
2373 MOC->second);
Douglas Gregor20b3e992009-08-24 17:42:35 +00002374 } else {
2375 // Rebuild pointer type
John McCall0953e762009-09-24 19:53:00 +00002376 Composite1
2377 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
2378 Composite2
2379 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregor20b3e992009-08-24 17:42:35 +00002380 }
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002381 }
2382
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002383 // Try to convert to the first composite pointer type.
2384 InitializedEntity Entity1
2385 = InitializedEntity::InitializeTemporary(Composite1);
2386 InitializationKind Kind
2387 = InitializationKind::CreateCopy(Loc, SourceLocation());
2388 InitializationSequence E1ToC1(*this, Entity1, Kind, &E1, 1);
2389 InitializationSequence E2ToC1(*this, Entity1, Kind, &E2, 1);
Mike Stump1eb44332009-09-09 15:08:12 +00002390
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002391 if (E1ToC1 && E2ToC1) {
2392 // Conversion to Composite1 is viable.
2393 if (!Context.hasSameType(Composite1, Composite2)) {
2394 // Composite2 is a different type from Composite1. Check whether
2395 // Composite2 is also viable.
2396 InitializedEntity Entity2
2397 = InitializedEntity::InitializeTemporary(Composite2);
2398 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
2399 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
2400 if (E1ToC2 && E2ToC2) {
2401 // Both Composite1 and Composite2 are viable and are different;
2402 // this is an ambiguity.
2403 return QualType();
2404 }
2405 }
2406
2407 // Convert E1 to Composite1
2408 OwningExprResult E1Result
2409 = E1ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,(void**)&E1,1));
2410 if (E1Result.isInvalid())
2411 return QualType();
2412 E1 = E1Result.takeAs<Expr>();
2413
2414 // Convert E2 to Composite1
2415 OwningExprResult E2Result
2416 = E2ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,(void**)&E2,1));
2417 if (E2Result.isInvalid())
2418 return QualType();
2419 E2 = E2Result.takeAs<Expr>();
2420
2421 return Composite1;
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002422 }
2423
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002424 // Check whether Composite2 is viable.
2425 InitializedEntity Entity2
2426 = InitializedEntity::InitializeTemporary(Composite2);
2427 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
2428 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
2429 if (!E1ToC2 || !E2ToC2)
2430 return QualType();
2431
2432 // Convert E1 to Composite2
2433 OwningExprResult E1Result
2434 = E1ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, (void**)&E1, 1));
2435 if (E1Result.isInvalid())
2436 return QualType();
2437 E1 = E1Result.takeAs<Expr>();
2438
2439 // Convert E2 to Composite2
2440 OwningExprResult E2Result
2441 = E2ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, (void**)&E2, 1));
2442 if (E2Result.isInvalid())
2443 return QualType();
2444 E2 = E2Result.takeAs<Expr>();
2445
2446 return Composite2;
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002447}
Anders Carlsson165a0a02009-05-17 18:41:29 +00002448
Anders Carlssondef11992009-05-30 20:36:53 +00002449Sema::OwningExprResult Sema::MaybeBindToTemporary(Expr *E) {
Anders Carlsson089c2602009-08-15 23:41:35 +00002450 if (!Context.getLangOptions().CPlusPlus)
2451 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002452
Douglas Gregor51326552009-12-24 18:51:59 +00002453 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
2454
Ted Kremenek6217b802009-07-29 21:53:49 +00002455 const RecordType *RT = E->getType()->getAs<RecordType>();
Anders Carlssondef11992009-05-30 20:36:53 +00002456 if (!RT)
2457 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002458
John McCall86ff3082010-02-04 22:26:26 +00002459 // If this is the result of a call expression, our source might
2460 // actually be a reference, in which case we shouldn't bind.
Anders Carlsson283e4d52009-09-14 01:30:44 +00002461 if (CallExpr *CE = dyn_cast<CallExpr>(E)) {
2462 QualType Ty = CE->getCallee()->getType();
2463 if (const PointerType *PT = Ty->getAs<PointerType>())
2464 Ty = PT->getPointeeType();
Fariborz Jahanianb372b0f2010-02-18 20:31:02 +00002465 else if (const BlockPointerType *BPT = Ty->getAs<BlockPointerType>())
2466 Ty = BPT->getPointeeType();
2467
John McCall183700f2009-09-21 23:43:11 +00002468 const FunctionType *FTy = Ty->getAs<FunctionType>();
Anders Carlsson283e4d52009-09-14 01:30:44 +00002469 if (FTy->getResultType()->isReferenceType())
2470 return Owned(E);
2471 }
John McCall86ff3082010-02-04 22:26:26 +00002472
2473 // That should be enough to guarantee that this type is complete.
2474 // If it has a trivial destructor, we can avoid the extra copy.
2475 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2476 if (RD->hasTrivialDestructor())
2477 return Owned(E);
2478
Mike Stump1eb44332009-09-09 15:08:12 +00002479 CXXTemporary *Temp = CXXTemporary::Create(Context,
Anders Carlssondef11992009-05-30 20:36:53 +00002480 RD->getDestructor(Context));
Anders Carlsson860306e2009-05-30 21:21:49 +00002481 ExprTemporaries.push_back(Temp);
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00002482 if (CXXDestructorDecl *Destructor =
John McCallc91cc662010-04-07 00:41:46 +00002483 const_cast<CXXDestructorDecl*>(RD->getDestructor(Context))) {
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00002484 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
John McCallc91cc662010-04-07 00:41:46 +00002485 CheckDestructorAccess(E->getExprLoc(), Destructor,
2486 PDiag(diag::err_access_dtor_temp)
2487 << E->getType());
2488 }
Anders Carlssondef11992009-05-30 20:36:53 +00002489 // FIXME: Add the temporary to the temporaries vector.
2490 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
2491}
2492
Anders Carlsson0ece4912009-12-15 20:51:39 +00002493Expr *Sema::MaybeCreateCXXExprWithTemporaries(Expr *SubExpr) {
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002494 assert(SubExpr && "sub expression can't be null!");
Mike Stump1eb44332009-09-09 15:08:12 +00002495
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00002496 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
2497 assert(ExprTemporaries.size() >= FirstTemporary);
2498 if (ExprTemporaries.size() == FirstTemporary)
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002499 return SubExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00002500
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002501 Expr *E = CXXExprWithTemporaries::Create(Context, SubExpr,
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00002502 &ExprTemporaries[FirstTemporary],
Anders Carlsson0ece4912009-12-15 20:51:39 +00002503 ExprTemporaries.size() - FirstTemporary);
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00002504 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
2505 ExprTemporaries.end());
Mike Stump1eb44332009-09-09 15:08:12 +00002506
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002507 return E;
2508}
2509
Douglas Gregor90f93822009-12-22 22:17:25 +00002510Sema::OwningExprResult
2511Sema::MaybeCreateCXXExprWithTemporaries(OwningExprResult SubExpr) {
2512 if (SubExpr.isInvalid())
2513 return ExprError();
2514
2515 return Owned(MaybeCreateCXXExprWithTemporaries(SubExpr.takeAs<Expr>()));
2516}
2517
Anders Carlsson5ee56e92009-12-16 02:09:40 +00002518FullExpr Sema::CreateFullExpr(Expr *SubExpr) {
2519 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
2520 assert(ExprTemporaries.size() >= FirstTemporary);
2521
2522 unsigned NumTemporaries = ExprTemporaries.size() - FirstTemporary;
2523 CXXTemporary **Temporaries =
2524 NumTemporaries == 0 ? 0 : &ExprTemporaries[FirstTemporary];
2525
2526 FullExpr E = FullExpr::Create(Context, SubExpr, Temporaries, NumTemporaries);
2527
2528 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
2529 ExprTemporaries.end());
2530
2531 return E;
2532}
2533
Mike Stump1eb44332009-09-09 15:08:12 +00002534Sema::OwningExprResult
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002535Sema::ActOnStartCXXMemberReference(Scope *S, ExprArg Base, SourceLocation OpLoc,
Douglas Gregord4dca082010-02-24 18:44:31 +00002536 tok::TokenKind OpKind, TypeTy *&ObjectType,
2537 bool &MayBePseudoDestructor) {
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002538 // Since this might be a postfix expression, get rid of ParenListExprs.
2539 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
Mike Stump1eb44332009-09-09 15:08:12 +00002540
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002541 Expr *BaseExpr = (Expr*)Base.get();
2542 assert(BaseExpr && "no record expansion");
Mike Stump1eb44332009-09-09 15:08:12 +00002543
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002544 QualType BaseType = BaseExpr->getType();
Douglas Gregord4dca082010-02-24 18:44:31 +00002545 MayBePseudoDestructor = false;
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002546 if (BaseType->isDependentType()) {
Douglas Gregor43d88632009-11-04 22:49:18 +00002547 // If we have a pointer to a dependent type and are using the -> operator,
2548 // the object type is the type that the pointer points to. We might still
2549 // have enough information about that type to do something useful.
2550 if (OpKind == tok::arrow)
2551 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
2552 BaseType = Ptr->getPointeeType();
2553
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002554 ObjectType = BaseType.getAsOpaquePtr();
Douglas Gregord4dca082010-02-24 18:44:31 +00002555 MayBePseudoDestructor = true;
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002556 return move(Base);
2557 }
Mike Stump1eb44332009-09-09 15:08:12 +00002558
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002559 // C++ [over.match.oper]p8:
Mike Stump1eb44332009-09-09 15:08:12 +00002560 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002561 // returned, with the original second operand.
2562 if (OpKind == tok::arrow) {
John McCallc4e83212009-09-30 01:01:30 +00002563 // The set of types we've considered so far.
John McCall432887f2009-09-30 01:30:54 +00002564 llvm::SmallPtrSet<CanQualType,8> CTypes;
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002565 llvm::SmallVector<SourceLocation, 8> Locations;
John McCall432887f2009-09-30 01:30:54 +00002566 CTypes.insert(Context.getCanonicalType(BaseType));
John McCallc4e83212009-09-30 01:01:30 +00002567
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002568 while (BaseType->isRecordType()) {
Anders Carlsson15ea3782009-10-13 22:43:21 +00002569 Base = BuildOverloadedArrowExpr(S, move(Base), OpLoc);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002570 BaseExpr = (Expr*)Base.get();
2571 if (BaseExpr == NULL)
2572 return ExprError();
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002573 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(BaseExpr))
Anders Carlssonde699e52009-10-13 22:55:59 +00002574 Locations.push_back(OpCall->getDirectCallee()->getLocation());
John McCallc4e83212009-09-30 01:01:30 +00002575 BaseType = BaseExpr->getType();
2576 CanQualType CBaseType = Context.getCanonicalType(BaseType);
John McCall432887f2009-09-30 01:30:54 +00002577 if (!CTypes.insert(CBaseType)) {
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00002578 Diag(OpLoc, diag::err_operator_arrow_circular);
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002579 for (unsigned i = 0; i < Locations.size(); i++)
2580 Diag(Locations[i], diag::note_declared_at);
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00002581 return ExprError();
2582 }
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002583 }
Mike Stump1eb44332009-09-09 15:08:12 +00002584
Douglas Gregor31658df2009-11-20 19:58:21 +00002585 if (BaseType->isPointerType())
2586 BaseType = BaseType->getPointeeType();
2587 }
Mike Stump1eb44332009-09-09 15:08:12 +00002588
2589 // We could end up with various non-record types here, such as extended
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002590 // vector types or Objective-C interfaces. Just return early and let
2591 // ActOnMemberReferenceExpr do the work.
Douglas Gregorc68afe22009-09-03 21:38:09 +00002592 if (!BaseType->isRecordType()) {
2593 // C++ [basic.lookup.classref]p2:
2594 // [...] If the type of the object expression is of pointer to scalar
2595 // type, the unqualified-id is looked up in the context of the complete
2596 // postfix-expression.
Douglas Gregord4dca082010-02-24 18:44:31 +00002597 //
2598 // This also indicates that we should be parsing a
2599 // pseudo-destructor-name.
Douglas Gregorc68afe22009-09-03 21:38:09 +00002600 ObjectType = 0;
Douglas Gregord4dca082010-02-24 18:44:31 +00002601 MayBePseudoDestructor = true;
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002602 return move(Base);
Douglas Gregorc68afe22009-09-03 21:38:09 +00002603 }
Mike Stump1eb44332009-09-09 15:08:12 +00002604
Douglas Gregor03c57052009-11-17 05:17:33 +00002605 // The object type must be complete (or dependent).
2606 if (!BaseType->isDependentType() &&
2607 RequireCompleteType(OpLoc, BaseType,
2608 PDiag(diag::err_incomplete_member_access)))
2609 return ExprError();
2610
Douglas Gregorc68afe22009-09-03 21:38:09 +00002611 // C++ [basic.lookup.classref]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00002612 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor03c57052009-11-17 05:17:33 +00002613 // unqualified-id, and the type of the object expression is of a class
Douglas Gregorc68afe22009-09-03 21:38:09 +00002614 // type C (or of pointer to a class type C), the unqualified-id is looked
2615 // up in the scope of class C. [...]
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002616 ObjectType = BaseType.getAsOpaquePtr();
Mike Stump1eb44332009-09-09 15:08:12 +00002617 return move(Base);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002618}
2619
Douglas Gregor77549082010-02-24 21:29:12 +00002620Sema::OwningExprResult Sema::DiagnoseDtorReference(SourceLocation NameLoc,
2621 ExprArg MemExpr) {
2622 Expr *E = (Expr *) MemExpr.get();
2623 SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(NameLoc);
2624 Diag(E->getLocStart(), diag::err_dtor_expr_without_call)
2625 << isa<CXXPseudoDestructorExpr>(E)
Douglas Gregor849b2432010-03-31 17:46:05 +00002626 << FixItHint::CreateInsertion(ExpectedLParenLoc, "()");
Douglas Gregor77549082010-02-24 21:29:12 +00002627
2628 return ActOnCallExpr(/*Scope*/ 0,
2629 move(MemExpr),
2630 /*LPLoc*/ ExpectedLParenLoc,
2631 Sema::MultiExprArg(*this, 0, 0),
2632 /*CommaLocs*/ 0,
2633 /*RPLoc*/ ExpectedLParenLoc);
2634}
Douglas Gregord4dca082010-02-24 18:44:31 +00002635
Douglas Gregorb57fb492010-02-24 22:38:50 +00002636Sema::OwningExprResult Sema::BuildPseudoDestructorExpr(ExprArg Base,
2637 SourceLocation OpLoc,
2638 tok::TokenKind OpKind,
2639 const CXXScopeSpec &SS,
Douglas Gregor26d4ac92010-02-24 23:40:28 +00002640 TypeSourceInfo *ScopeTypeInfo,
Douglas Gregorb57fb492010-02-24 22:38:50 +00002641 SourceLocation CCLoc,
Douglas Gregorfce46ee2010-02-24 23:50:37 +00002642 SourceLocation TildeLoc,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002643 PseudoDestructorTypeStorage Destructed,
Douglas Gregorb57fb492010-02-24 22:38:50 +00002644 bool HasTrailingLParen) {
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002645 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
Douglas Gregorb57fb492010-02-24 22:38:50 +00002646
2647 // C++ [expr.pseudo]p2:
2648 // The left-hand side of the dot operator shall be of scalar type. The
2649 // left-hand side of the arrow operator shall be of pointer to scalar type.
2650 // This scalar type is the object type.
2651 Expr *BaseE = (Expr *)Base.get();
2652 QualType ObjectType = BaseE->getType();
2653 if (OpKind == tok::arrow) {
2654 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
2655 ObjectType = Ptr->getPointeeType();
2656 } else if (!BaseE->isTypeDependent()) {
2657 // The user wrote "p->" when she probably meant "p."; fix it.
2658 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
2659 << ObjectType << true
Douglas Gregor849b2432010-03-31 17:46:05 +00002660 << FixItHint::CreateReplacement(OpLoc, ".");
Douglas Gregorb57fb492010-02-24 22:38:50 +00002661 if (isSFINAEContext())
2662 return ExprError();
2663
2664 OpKind = tok::period;
2665 }
2666 }
2667
2668 if (!ObjectType->isDependentType() && !ObjectType->isScalarType()) {
2669 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
2670 << ObjectType << BaseE->getSourceRange();
2671 return ExprError();
2672 }
2673
2674 // C++ [expr.pseudo]p2:
2675 // [...] The cv-unqualified versions of the object type and of the type
2676 // designated by the pseudo-destructor-name shall be the same type.
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002677 if (DestructedTypeInfo) {
2678 QualType DestructedType = DestructedTypeInfo->getType();
2679 SourceLocation DestructedTypeStart
2680 = DestructedTypeInfo->getTypeLoc().getSourceRange().getBegin();
2681 if (!DestructedType->isDependentType() && !ObjectType->isDependentType() &&
2682 !Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
2683 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
2684 << ObjectType << DestructedType << BaseE->getSourceRange()
2685 << DestructedTypeInfo->getTypeLoc().getSourceRange();
2686
2687 // Recover by setting the destructed type to the object type.
2688 DestructedType = ObjectType;
2689 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
2690 DestructedTypeStart);
2691 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
2692 }
Douglas Gregorb57fb492010-02-24 22:38:50 +00002693 }
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002694
Douglas Gregorb57fb492010-02-24 22:38:50 +00002695 // C++ [expr.pseudo]p2:
2696 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
2697 // form
2698 //
2699 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
2700 //
2701 // shall designate the same scalar type.
2702 if (ScopeTypeInfo) {
2703 QualType ScopeType = ScopeTypeInfo->getType();
2704 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
2705 !Context.hasSameType(ScopeType, ObjectType)) {
2706
2707 Diag(ScopeTypeInfo->getTypeLoc().getSourceRange().getBegin(),
2708 diag::err_pseudo_dtor_type_mismatch)
2709 << ObjectType << ScopeType << BaseE->getSourceRange()
2710 << ScopeTypeInfo->getTypeLoc().getSourceRange();
2711
2712 ScopeType = QualType();
2713 ScopeTypeInfo = 0;
2714 }
2715 }
2716
2717 OwningExprResult Result
2718 = Owned(new (Context) CXXPseudoDestructorExpr(Context,
2719 Base.takeAs<Expr>(),
2720 OpKind == tok::arrow,
2721 OpLoc,
2722 (NestedNameSpecifier *) SS.getScopeRep(),
2723 SS.getRange(),
2724 ScopeTypeInfo,
2725 CCLoc,
Douglas Gregorfce46ee2010-02-24 23:50:37 +00002726 TildeLoc,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002727 Destructed));
2728
Douglas Gregorb57fb492010-02-24 22:38:50 +00002729 if (HasTrailingLParen)
2730 return move(Result);
2731
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002732 return DiagnoseDtorReference(Destructed.getLocation(), move(Result));
Douglas Gregor77549082010-02-24 21:29:12 +00002733}
2734
2735Sema::OwningExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, ExprArg Base,
2736 SourceLocation OpLoc,
2737 tok::TokenKind OpKind,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00002738 CXXScopeSpec &SS,
Douglas Gregor77549082010-02-24 21:29:12 +00002739 UnqualifiedId &FirstTypeName,
2740 SourceLocation CCLoc,
2741 SourceLocation TildeLoc,
2742 UnqualifiedId &SecondTypeName,
2743 bool HasTrailingLParen) {
2744 assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
2745 FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
2746 "Invalid first type name in pseudo-destructor");
2747 assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
2748 SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
2749 "Invalid second type name in pseudo-destructor");
2750
2751 Expr *BaseE = (Expr *)Base.get();
Douglas Gregor77549082010-02-24 21:29:12 +00002752
2753 // C++ [expr.pseudo]p2:
2754 // The left-hand side of the dot operator shall be of scalar type. The
2755 // left-hand side of the arrow operator shall be of pointer to scalar type.
2756 // This scalar type is the object type.
2757 QualType ObjectType = BaseE->getType();
2758 if (OpKind == tok::arrow) {
2759 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
2760 ObjectType = Ptr->getPointeeType();
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002761 } else if (!ObjectType->isDependentType()) {
Douglas Gregor77549082010-02-24 21:29:12 +00002762 // The user wrote "p->" when she probably meant "p."; fix it.
2763 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002764 << ObjectType << true
Douglas Gregor849b2432010-03-31 17:46:05 +00002765 << FixItHint::CreateReplacement(OpLoc, ".");
Douglas Gregor77549082010-02-24 21:29:12 +00002766 if (isSFINAEContext())
2767 return ExprError();
2768
2769 OpKind = tok::period;
2770 }
2771 }
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002772
2773 // Compute the object type that we should use for name lookup purposes. Only
2774 // record types and dependent types matter.
2775 void *ObjectTypePtrForLookup = 0;
2776 if (!SS.isSet()) {
2777 ObjectTypePtrForLookup = (void *)ObjectType->getAs<RecordType>();
2778 if (!ObjectTypePtrForLookup && ObjectType->isDependentType())
2779 ObjectTypePtrForLookup = Context.DependentTy.getAsOpaquePtr();
2780 }
Douglas Gregor77549082010-02-24 21:29:12 +00002781
Douglas Gregorb57fb492010-02-24 22:38:50 +00002782 // Convert the name of the type being destructed (following the ~) into a
2783 // type (with source-location information).
Douglas Gregor77549082010-02-24 21:29:12 +00002784 QualType DestructedType;
2785 TypeSourceInfo *DestructedTypeInfo = 0;
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002786 PseudoDestructorTypeStorage Destructed;
Douglas Gregor77549082010-02-24 21:29:12 +00002787 if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
2788 TypeTy *T = getTypeName(*SecondTypeName.Identifier,
2789 SecondTypeName.StartLocation,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002790 S, &SS, true, ObjectTypePtrForLookup);
2791 if (!T &&
2792 ((SS.isSet() && !computeDeclContext(SS, false)) ||
2793 (!SS.isSet() && ObjectType->isDependentType()))) {
2794 // The name of the type being destroyed is a dependent name, and we
2795 // couldn't find anything useful in scope. Just store the identifier and
2796 // it's location, and we'll perform (qualified) name lookup again at
2797 // template instantiation time.
2798 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
2799 SecondTypeName.StartLocation);
2800 } else if (!T) {
Douglas Gregor77549082010-02-24 21:29:12 +00002801 Diag(SecondTypeName.StartLocation,
2802 diag::err_pseudo_dtor_destructor_non_type)
2803 << SecondTypeName.Identifier << ObjectType;
2804 if (isSFINAEContext())
2805 return ExprError();
2806
2807 // Recover by assuming we had the right type all along.
2808 DestructedType = ObjectType;
Douglas Gregorb57fb492010-02-24 22:38:50 +00002809 } else
Douglas Gregor77549082010-02-24 21:29:12 +00002810 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00002811 } else {
Douglas Gregorb57fb492010-02-24 22:38:50 +00002812 // Resolve the template-id to a type.
Douglas Gregor77549082010-02-24 21:29:12 +00002813 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
Douglas Gregorb57fb492010-02-24 22:38:50 +00002814 ASTTemplateArgsPtr TemplateArgsPtr(*this,
2815 TemplateId->getTemplateArgs(),
2816 TemplateId->NumArgs);
2817 TypeResult T = ActOnTemplateIdType(TemplateTy::make(TemplateId->Template),
2818 TemplateId->TemplateNameLoc,
2819 TemplateId->LAngleLoc,
2820 TemplateArgsPtr,
2821 TemplateId->RAngleLoc);
2822 if (T.isInvalid() || !T.get()) {
2823 // Recover by assuming we had the right type all along.
2824 DestructedType = ObjectType;
2825 } else
2826 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00002827 }
2828
Douglas Gregorb57fb492010-02-24 22:38:50 +00002829 // If we've performed some kind of recovery, (re-)build the type source
2830 // information.
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002831 if (!DestructedType.isNull()) {
2832 if (!DestructedTypeInfo)
2833 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
Douglas Gregorb57fb492010-02-24 22:38:50 +00002834 SecondTypeName.StartLocation);
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002835 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
2836 }
Douglas Gregorb57fb492010-02-24 22:38:50 +00002837
2838 // Convert the name of the scope type (the type prior to '::') into a type.
2839 TypeSourceInfo *ScopeTypeInfo = 0;
Douglas Gregor77549082010-02-24 21:29:12 +00002840 QualType ScopeType;
2841 if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
2842 FirstTypeName.Identifier) {
2843 if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
2844 TypeTy *T = getTypeName(*FirstTypeName.Identifier,
2845 FirstTypeName.StartLocation,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002846 S, &SS, false, ObjectTypePtrForLookup);
Douglas Gregor77549082010-02-24 21:29:12 +00002847 if (!T) {
2848 Diag(FirstTypeName.StartLocation,
2849 diag::err_pseudo_dtor_destructor_non_type)
2850 << FirstTypeName.Identifier << ObjectType;
Douglas Gregor77549082010-02-24 21:29:12 +00002851
Douglas Gregorb57fb492010-02-24 22:38:50 +00002852 if (isSFINAEContext())
2853 return ExprError();
2854
2855 // Just drop this type. It's unnecessary anyway.
2856 ScopeType = QualType();
2857 } else
2858 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00002859 } else {
Douglas Gregorb57fb492010-02-24 22:38:50 +00002860 // Resolve the template-id to a type.
Douglas Gregor77549082010-02-24 21:29:12 +00002861 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
Douglas Gregorb57fb492010-02-24 22:38:50 +00002862 ASTTemplateArgsPtr TemplateArgsPtr(*this,
2863 TemplateId->getTemplateArgs(),
2864 TemplateId->NumArgs);
2865 TypeResult T = ActOnTemplateIdType(TemplateTy::make(TemplateId->Template),
2866 TemplateId->TemplateNameLoc,
2867 TemplateId->LAngleLoc,
2868 TemplateArgsPtr,
2869 TemplateId->RAngleLoc);
2870 if (T.isInvalid() || !T.get()) {
2871 // Recover by dropping this type.
2872 ScopeType = QualType();
2873 } else
2874 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00002875 }
2876 }
Douglas Gregorb4a418f2010-02-24 23:02:30 +00002877
2878 if (!ScopeType.isNull() && !ScopeTypeInfo)
2879 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
2880 FirstTypeName.StartLocation);
2881
2882
Douglas Gregorb57fb492010-02-24 22:38:50 +00002883 return BuildPseudoDestructorExpr(move(Base), OpLoc, OpKind, SS,
Douglas Gregorfce46ee2010-02-24 23:50:37 +00002884 ScopeTypeInfo, CCLoc, TildeLoc,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002885 Destructed, HasTrailingLParen);
Douglas Gregord4dca082010-02-24 18:44:31 +00002886}
2887
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002888CXXMemberCallExpr *Sema::BuildCXXMemberCallExpr(Expr *Exp,
John McCall6bb80172010-03-30 21:47:33 +00002889 NamedDecl *FoundDecl,
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002890 CXXMethodDecl *Method) {
John McCall6bb80172010-03-30 21:47:33 +00002891 if (PerformObjectArgumentInitialization(Exp, /*Qualifier=*/0,
2892 FoundDecl, Method))
Eli Friedman772fffa2009-12-09 04:53:56 +00002893 assert(0 && "Calling BuildCXXMemberCallExpr with invalid call?");
2894
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002895 MemberExpr *ME =
2896 new (Context) MemberExpr(Exp, /*IsArrow=*/false, Method,
2897 SourceLocation(), Method->getType());
Eli Friedman772fffa2009-12-09 04:53:56 +00002898 QualType ResultType = Method->getResultType().getNonReferenceType();
Douglas Gregor7edfb692009-11-23 12:27:39 +00002899 MarkDeclarationReferenced(Exp->getLocStart(), Method);
2900 CXXMemberCallExpr *CE =
2901 new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType,
2902 Exp->getLocEnd());
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002903 return CE;
2904}
2905
Anders Carlsson165a0a02009-05-17 18:41:29 +00002906Sema::OwningExprResult Sema::ActOnFinishFullExpr(ExprArg Arg) {
2907 Expr *FullExpr = Arg.takeAs<Expr>();
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002908 if (FullExpr)
Anders Carlsson0ece4912009-12-15 20:51:39 +00002909 FullExpr = MaybeCreateCXXExprWithTemporaries(FullExpr);
Anders Carlssonec773872009-08-25 23:46:41 +00002910
Anders Carlsson165a0a02009-05-17 18:41:29 +00002911 return Owned(FullExpr);
2912}