blob: be3ef83d9944c842f1c3cacaccfbc655f010c27b [file] [log] [blame]
Chris Lattner29375652006-12-04 18:06:35 +00001//===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner29375652006-12-04 18:06:35 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Douglas Gregor3e1e5272009-12-09 23:02:17 +000015#include "SemaInit.h"
John McCall5cebab12009-11-18 07:57:50 +000016#include "Lookup.h"
Steve Naroffaac94152007-08-25 14:02:58 +000017#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000018#include "clang/AST/CXXInheritance.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000019#include "clang/AST/ExprCXX.h"
Douglas Gregorb1dd23f2010-02-24 22:38:50 +000020#include "clang/AST/TypeLoc.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000021#include "clang/Basic/PartialDiagnostic.h"
Sebastian Redlfaf68082008-12-03 20:26:15 +000022#include "clang/Basic/TargetInfo.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000023#include "clang/Lex/Preprocessor.h"
24#include "clang/Parse/DeclSpec.h"
Douglas Gregore610ada2010-02-24 18:44:31 +000025#include "clang/Parse/Template.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000026#include "llvm/ADT/STLExtras.h"
Chris Lattner29375652006-12-04 18:06:35 +000027using namespace clang;
28
Douglas Gregorfe17d252010-02-16 19:09:40 +000029Action::TypeTy *Sema::getDestructorName(SourceLocation TildeLoc,
30 IdentifierInfo &II,
31 SourceLocation NameLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +000032 Scope *S, CXXScopeSpec &SS,
Douglas Gregorfe17d252010-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 Gregor46841e12010-02-23 00:15:22 +000054 // See also PR6358 and PR6359.
Douglas Gregorfe17d252010-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 Gregor46841e12010-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 Gregorfe17d252010-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 Carruth8f254812010-02-21 10:19:54 +0000103 // a qualified-id of the form:
Douglas Gregorfe17d252010-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 Gregor46841e12010-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 Gregorfe17d252010-02-16 19:09:40 +0000129 LookupCtx = computeDeclContext(SearchType);
130 isDependent = SearchType->isDependentType();
131 } else {
132 LookupCtx = computeDeclContext(SS, EnteringContext);
Douglas Gregor46841e12010-02-23 00:15:22 +0000133 isDependent = LookupCtx && LookupCtx->isDependentContext();
Douglas Gregorfe17d252010-02-16 19:09:40 +0000134 }
Douglas Gregor46841e12010-02-23 00:15:22 +0000135
Douglas Gregorcd3f49f2010-02-25 04:46:04 +0000136 LookInScope = false;
Douglas Gregorfe17d252010-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 Gregor678f90d2010-02-25 01:56:36 +0000164 else if (Step == 1 && LookInScope && S)
Douglas Gregorfe17d252010-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 Gregorfe17d252010-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 McCalle78aac42010-03-10 03:28:59 +0000195 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx))
196 MemberOfType = Context.getTypeDeclType(Record);
Douglas Gregorfe17d252010-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 Redlc4704762008-11-11 11:37:55 +0000276/// ActOnCXXTypeidOfType - Parse typeid( type-id ).
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000277Action::OwningExprResult
Sebastian Redlc4704762008-11-11 11:37:55 +0000278Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
279 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Douglas Gregor87f54062009-09-15 22:30:29 +0000280 if (!StdNamespace)
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000281 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000282
Douglas Gregorf45f6822009-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 Kyrtzidisc7148c92009-08-19 01:28:28 +0000287 // FIXME: Preserve type source info.
Douglas Gregorf45f6822009-12-23 20:51:04 +0000288 // FIXME: Preserve the type before we stripped the cv-qualifiers?
Douglas Gregor721fb2b2009-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 Gregorf45f6822009-12-23 20:51:04 +0000305 }
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000306
Chris Lattnerec7f7732008-11-20 05:51:55 +0000307 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
John McCall27b18f82009-11-17 02:14:36 +0000308 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
309 LookupQualifiedName(R, StdNamespace);
John McCall67c00872009-12-02 08:25:40 +0000310 RecordDecl *TypeInfoRecordDecl = R.getAsSingle<RecordDecl>();
Chris Lattnerec7f7732008-11-20 05:51:55 +0000311 if (!TypeInfoRecordDecl)
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000312 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Sebastian Redlc4704762008-11-11 11:37:55 +0000313
314 QualType TypeInfoType = Context.getTypeDeclType(TypeInfoRecordDecl);
315
Douglas Gregor0b6a6242009-06-22 20:57:11 +0000316 if (!isType) {
Douglas Gregor0b6a6242009-06-22 20:57:11 +0000317 bool isUnevaluatedOperand = true;
318 Expr *E = static_cast<Expr *>(TyOrExpr);
Douglas Gregorf45f6822009-12-23 20:51:04 +0000319 if (E && !E->isTypeDependent()) {
Douglas Gregor0b6a6242009-06-22 20:57:11 +0000320 QualType T = E->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000321 if (const RecordType *RecordT = T->getAs<RecordType>()) {
Douglas Gregor0b6a6242009-06-22 20:57:11 +0000322 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
Douglas Gregorf45f6822009-12-23 20:51:04 +0000323 // C++ [expr.typeid]p3:
John McCall67da35c2010-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 Gregorf45f6822009-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 Gregor0b6a6242009-06-22 20:57:11 +0000334 isUnevaluatedOperand = false;
Douglas Gregorf45f6822009-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 Gregor0b6a6242009-06-22 20:57:11 +0000346 }
347 }
Mike Stump11289f42009-09-09 15:08:12 +0000348
Douglas Gregorff790f12009-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 Gregor0b6a6242009-06-22 20:57:11 +0000352 if (isUnevaluatedOperand)
Douglas Gregorff790f12009-11-26 00:44:06 +0000353 ExprEvalContexts.back().Context = Unevaluated;
Douglas Gregor0b6a6242009-06-22 20:57:11 +0000354 }
Mike Stump11289f42009-09-09 15:08:12 +0000355
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000356 return Owned(new (Context) CXXTypeidExpr(isType, TyOrExpr,
357 TypeInfoType.withConst(),
358 SourceRange(OpLoc, RParenLoc)));
Sebastian Redlc4704762008-11-11 11:37:55 +0000359}
360
Steve Naroff66356bd2007-09-16 14:56:35 +0000361/// ActOnCXXBoolLiteral - Parse {true,false} literals.
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000362Action::OwningExprResult
Steve Naroff66356bd2007-09-16 14:56:35 +0000363Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor08d918a2008-10-24 15:36:09 +0000364 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Bill Wendlingbf313b02007-02-13 20:09:46 +0000365 "Unknown C++ Boolean value!");
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000366 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
367 Context.BoolTy, OpLoc));
Bill Wendling4073ed52007-02-13 01:51:42 +0000368}
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000369
Sebastian Redl576fd422009-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 Lattnerb7e656b2008-02-26 00:51:44 +0000376/// ActOnCXXThrow - Parse throw expressions.
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000377Action::OwningExprResult
378Sema::ActOnCXXThrow(SourceLocation OpLoc, ExprArg E) {
Sebastian Redl4de47b42009-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 Gregor247894b2009-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 Redl4de47b42009-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();
402 int isPointer = 0;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000403 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl4de47b42009-04-27 20:27:31 +0000404 Ty = Ptr->getPointeeType();
405 isPointer = 1;
406 }
407 if (!isPointer || !Ty->isVoidType()) {
408 if (RequireCompleteType(ThrowLoc, Ty,
Anders Carlsson029fc692009-08-26 22:59:12 +0000409 PDiag(isPointer ? diag::err_throw_incomplete_ptr
410 : diag::err_throw_incomplete)
411 << E->getSourceRange()))
Sebastian Redl4de47b42009-04-27 20:27:31 +0000412 return true;
Rafael Espindola70e040d2010-03-02 21:28:26 +0000413
Douglas Gregore8154332010-04-15 18:05:39 +0000414 if (RequireNonAbstractType(ThrowLoc, E->getType(),
415 PDiag(diag::err_throw_abstract_type)
416 << E->getSourceRange()))
417 return true;
418
Rafael Espindola70e040d2010-03-02 21:28:26 +0000419 // FIXME: This is just a hack to mark the copy constructor referenced.
420 // This should go away when the next FIXME is fixed.
421 const RecordType *RT = Ty->getAs<RecordType>();
422 if (!RT)
423 return false;
424
425 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
426 if (RD->hasTrivialCopyConstructor())
427 return false;
428 CXXConstructorDecl *CopyCtor = RD->getCopyConstructor(Context, 0);
429 MarkDeclarationReferenced(ThrowLoc, CopyCtor);
Sebastian Redl4de47b42009-04-27 20:27:31 +0000430 }
431
432 // FIXME: Construct a temporary here.
433 return false;
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000434}
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000435
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000436Action::OwningExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000437 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
438 /// is a non-lvalue expression whose value is the address of the object for
439 /// which the function is called.
440
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000441 if (!isa<FunctionDecl>(CurContext))
442 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000443
444 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext))
445 if (MD->isInstance())
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000446 return Owned(new (Context) CXXThisExpr(ThisLoc,
Douglas Gregorb15af892010-01-07 23:12:05 +0000447 MD->getThisType(Context),
448 /*isImplicit=*/false));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000449
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000450 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000451}
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000452
453/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
454/// Can be interpreted either as function-style casting ("int(x)")
455/// or class type construction ("ClassType(x,y,z)")
456/// or creation of a value-initialized type ("int()").
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000457Action::OwningExprResult
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000458Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep,
459 SourceLocation LParenLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000460 MultiExprArg exprs,
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000461 SourceLocation *CommaLocs,
462 SourceLocation RParenLoc) {
Douglas Gregor7df89f52010-02-05 19:11:37 +0000463 if (!TypeRep)
464 return ExprError();
465
John McCall97513962010-01-15 18:39:57 +0000466 TypeSourceInfo *TInfo;
467 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
468 if (!TInfo)
469 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000470 unsigned NumExprs = exprs.size();
471 Expr **Exprs = (Expr**)exprs.get();
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000472 SourceLocation TyBeginLoc = TypeRange.getBegin();
473 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
474
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000475 if (Ty->isDependentType() ||
Douglas Gregor0950e412009-03-13 21:01:28 +0000476 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000477 exprs.release();
Mike Stump11289f42009-09-09 15:08:12 +0000478
479 return Owned(CXXUnresolvedConstructExpr::Create(Context,
480 TypeRange.getBegin(), Ty,
Douglas Gregorce934142009-05-20 18:46:25 +0000481 LParenLoc,
482 Exprs, NumExprs,
483 RParenLoc));
Douglas Gregor0950e412009-03-13 21:01:28 +0000484 }
485
Anders Carlsson55243162009-08-27 03:53:50 +0000486 if (Ty->isArrayType())
487 return ExprError(Diag(TyBeginLoc,
488 diag::err_value_init_for_array_type) << FullRange);
489 if (!Ty->isVoidType() &&
490 RequireCompleteType(TyBeginLoc, Ty,
491 PDiag(diag::err_invalid_incomplete_type_use)
492 << FullRange))
493 return ExprError();
Fariborz Jahanian9a14b842009-10-23 21:01:39 +0000494
Anders Carlsson55243162009-08-27 03:53:50 +0000495 if (RequireNonAbstractType(TyBeginLoc, Ty,
496 diag::err_allocation_of_abstract_type))
497 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +0000498
499
Douglas Gregordd04d332009-01-16 18:33:17 +0000500 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000501 // If the expression list is a single expression, the type conversion
502 // expression is equivalent (in definedness, and if defined in meaning) to the
503 // corresponding cast expression.
504 //
505 if (NumExprs == 1) {
Anders Carlssonf10e4142009-08-07 22:21:05 +0000506 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Anders Carlssone9766d52009-09-09 21:33:21 +0000507 CXXMethodDecl *Method = 0;
508 if (CheckCastTypes(TypeRange, Ty, Exprs[0], Kind, Method,
509 /*FunctionalStyle=*/true))
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000510 return ExprError();
Anders Carlssone9766d52009-09-09 21:33:21 +0000511
512 exprs.release();
513 if (Method) {
514 OwningExprResult CastArg
515 = BuildCXXCastArgument(TypeRange.getBegin(), Ty.getNonReferenceType(),
516 Kind, Method, Owned(Exprs[0]));
517 if (CastArg.isInvalid())
518 return ExprError();
519
520 Exprs[0] = CastArg.takeAs<Expr>();
Fariborz Jahanian8b899e42009-08-28 15:11:24 +0000521 }
Anders Carlssone9766d52009-09-09 21:33:21 +0000522
523 return Owned(new (Context) CXXFunctionalCastExpr(Ty.getNonReferenceType(),
John McCall97513962010-01-15 18:39:57 +0000524 TInfo, TyBeginLoc, Kind,
Anders Carlssone9766d52009-09-09 21:33:21 +0000525 Exprs[0], RParenLoc));
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000526 }
527
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000528 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Douglas Gregordd04d332009-01-16 18:33:17 +0000529 CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000530
Mike Stump11289f42009-09-09 15:08:12 +0000531 if (NumExprs > 1 || !Record->hasTrivialConstructor() ||
Anders Carlsson574315a2009-08-27 05:08:22 +0000532 !Record->hasTrivialDestructor()) {
Eli Friedmana6824272010-01-31 20:58:15 +0000533 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty);
534 InitializationKind Kind
535 = NumExprs ? InitializationKind::CreateDirect(TypeRange.getBegin(),
536 LParenLoc, RParenLoc)
537 : InitializationKind::CreateValue(TypeRange.getBegin(),
538 LParenLoc, RParenLoc);
539 InitializationSequence InitSeq(*this, Entity, Kind, Exprs, NumExprs);
540 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
541 move(exprs));
Douglas Gregordd04d332009-01-16 18:33:17 +0000542
Eli Friedmana6824272010-01-31 20:58:15 +0000543 // FIXME: Improve AST representation?
544 return move(Result);
Douglas Gregordd04d332009-01-16 18:33:17 +0000545 }
546
547 // Fall through to value-initialize an object of class type that
548 // doesn't have a user-declared default constructor.
549 }
550
551 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000552 // If the expression list specifies more than a single value, the type shall
553 // be a class with a suitably declared constructor.
554 //
555 if (NumExprs > 1)
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000556 return ExprError(Diag(CommaLocs[0],
557 diag::err_builtin_func_cast_more_than_one_arg)
558 << FullRange);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000559
560 assert(NumExprs == 0 && "Expected 0 expressions");
Douglas Gregordd04d332009-01-16 18:33:17 +0000561 // C++ [expr.type.conv]p2:
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000562 // The expression T(), where T is a simple-type-specifier for a non-array
563 // complete object type or the (possibly cv-qualified) void type, creates an
564 // rvalue of the specified type, which is value-initialized.
565 //
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000566 exprs.release();
567 return Owned(new (Context) CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc));
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000568}
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +0000569
570
Sebastian Redlbd150f42008-11-21 19:14:01 +0000571/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
572/// @code new (memory) int[size][4] @endcode
573/// or
574/// @code ::new Foo(23, "hello") @endcode
575/// For the interpretation of this heap of arguments, consult the base version.
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000576Action::OwningExprResult
Sebastian Redlbd150f42008-11-21 19:14:01 +0000577Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000578 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
Sebastian Redlbd150f42008-11-21 19:14:01 +0000579 SourceLocation PlacementRParen, bool ParenTypeId,
Sebastian Redl351bb782008-12-02 14:43:59 +0000580 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000581 MultiExprArg ConstructorArgs,
Mike Stump11289f42009-09-09 15:08:12 +0000582 SourceLocation ConstructorRParen) {
Sebastian Redl351bb782008-12-02 14:43:59 +0000583 Expr *ArraySize = 0;
Sebastian Redl351bb782008-12-02 14:43:59 +0000584 // If the specified type is an array, unwrap it and save the expression.
585 if (D.getNumTypeObjects() > 0 &&
586 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
587 DeclaratorChunk &Chunk = D.getTypeObject(0);
588 if (Chunk.Arr.hasStatic)
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000589 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
590 << D.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +0000591 if (!Chunk.Arr.NumElts)
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000592 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
593 << D.getSourceRange());
Sebastian Redld7b3d7d2009-10-25 21:45:37 +0000594
595 if (ParenTypeId) {
596 // Can't have dynamic array size when the type-id is in parentheses.
597 Expr *NumElts = (Expr *)Chunk.Arr.NumElts;
598 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
599 !NumElts->isIntegerConstantExpr(Context)) {
600 Diag(D.getTypeObject(0).Loc, diag::err_new_paren_array_nonconst)
601 << NumElts->getSourceRange();
602 return ExprError();
603 }
604 }
605
Sebastian Redl351bb782008-12-02 14:43:59 +0000606 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redld7b3d7d2009-10-25 21:45:37 +0000607 D.DropFirstTypeObject();
Sebastian Redl351bb782008-12-02 14:43:59 +0000608 }
609
Douglas Gregor73341c42009-09-11 00:18:58 +0000610 // Every dimension shall be of constant size.
Sebastian Redld7b3d7d2009-10-25 21:45:37 +0000611 if (ArraySize) {
612 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor73341c42009-09-11 00:18:58 +0000613 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
614 break;
615
616 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
617 if (Expr *NumElts = (Expr *)Array.NumElts) {
618 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
619 !NumElts->isIntegerConstantExpr(Context)) {
620 Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst)
621 << NumElts->getSourceRange();
622 return ExprError();
623 }
624 }
625 }
626 }
Sebastian Redld7b3d7d2009-10-25 21:45:37 +0000627
John McCallbcd03502009-12-07 02:54:59 +0000628 //FIXME: Store TypeSourceInfo in CXXNew expression.
629 TypeSourceInfo *TInfo = 0;
630 QualType AllocType = GetTypeForDeclarator(D, /*Scope=*/0, &TInfo);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +0000631 if (D.isInvalidType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000632 return ExprError();
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +0000633
Mike Stump11289f42009-09-09 15:08:12 +0000634 return BuildCXXNew(StartLoc, UseGlobal,
Douglas Gregord0fefba2009-05-21 00:00:09 +0000635 PlacementLParen,
Mike Stump11289f42009-09-09 15:08:12 +0000636 move(PlacementArgs),
Douglas Gregord0fefba2009-05-21 00:00:09 +0000637 PlacementRParen,
638 ParenTypeId,
Mike Stump11289f42009-09-09 15:08:12 +0000639 AllocType,
Douglas Gregord0fefba2009-05-21 00:00:09 +0000640 D.getSourceRange().getBegin(),
641 D.getSourceRange(),
642 Owned(ArraySize),
643 ConstructorLParen,
644 move(ConstructorArgs),
645 ConstructorRParen);
646}
647
Mike Stump11289f42009-09-09 15:08:12 +0000648Sema::OwningExprResult
Douglas Gregord0fefba2009-05-21 00:00:09 +0000649Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
650 SourceLocation PlacementLParen,
651 MultiExprArg PlacementArgs,
652 SourceLocation PlacementRParen,
Mike Stump11289f42009-09-09 15:08:12 +0000653 bool ParenTypeId,
Douglas Gregord0fefba2009-05-21 00:00:09 +0000654 QualType AllocType,
655 SourceLocation TypeLoc,
656 SourceRange TypeRange,
657 ExprArg ArraySizeE,
658 SourceLocation ConstructorLParen,
659 MultiExprArg ConstructorArgs,
660 SourceLocation ConstructorRParen) {
661 if (CheckAllocatedType(AllocType, TypeLoc, TypeRange))
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000662 return ExprError();
Sebastian Redl351bb782008-12-02 14:43:59 +0000663
Douglas Gregord0fefba2009-05-21 00:00:09 +0000664 QualType ResultType = Context.getPointerType(AllocType);
Sebastian Redlbd150f42008-11-21 19:14:01 +0000665
666 // That every array dimension except the first is constant was already
667 // checked by the type check above.
Sebastian Redl351bb782008-12-02 14:43:59 +0000668
Sebastian Redlbd150f42008-11-21 19:14:01 +0000669 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
670 // or enumeration type with a non-negative value."
Douglas Gregord0fefba2009-05-21 00:00:09 +0000671 Expr *ArraySize = (Expr *)ArraySizeE.get();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +0000672 if (ArraySize && !ArraySize->isTypeDependent()) {
Sebastian Redl351bb782008-12-02 14:43:59 +0000673 QualType SizeType = ArraySize->getType();
674 if (!SizeType->isIntegralType() && !SizeType->isEnumeralType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000675 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
676 diag::err_array_size_not_integral)
677 << SizeType << ArraySize->getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +0000678 // Let's see if this is a constant < 0. If so, we reject it out of hand.
679 // We don't care about special rules, so we tell the machinery it's not
680 // evaluated - it gives us a result in more cases.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +0000681 if (!ArraySize->isValueDependent()) {
682 llvm::APSInt Value;
683 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
684 if (Value < llvm::APSInt(
Anders Carlsson8ab20bb2009-09-23 00:37:25 +0000685 llvm::APInt::getNullValue(Value.getBitWidth()),
686 Value.isUnsigned()))
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000687 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
688 diag::err_typecheck_negative_array_size)
689 << ArraySize->getSourceRange());
Sebastian Redl8d2ccae2009-02-26 14:39:58 +0000690 }
Sebastian Redl351bb782008-12-02 14:43:59 +0000691 }
Anders Carlsson8ab20bb2009-09-23 00:37:25 +0000692
Eli Friedman06ed2a52009-10-20 08:27:19 +0000693 ImpCastExprToType(ArraySize, Context.getSizeType(),
694 CastExpr::CK_IntegralCast);
Sebastian Redl351bb782008-12-02 14:43:59 +0000695 }
Sebastian Redlbd150f42008-11-21 19:14:01 +0000696
Sebastian Redlbd150f42008-11-21 19:14:01 +0000697 FunctionDecl *OperatorNew = 0;
698 FunctionDecl *OperatorDelete = 0;
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000699 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
700 unsigned NumPlaceArgs = PlacementArgs.size();
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +0000701
Sebastian Redl8d2ccae2009-02-26 14:39:58 +0000702 if (!AllocType->isDependentType() &&
703 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
704 FindAllocationFunctions(StartLoc,
Sebastian Redl1df2bbe2009-02-09 18:24:27 +0000705 SourceRange(PlacementLParen, PlacementRParen),
706 UseGlobal, AllocType, ArraySize, PlaceArgs,
707 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000708 return ExprError();
Fariborz Jahanian835026e2009-11-24 18:29:37 +0000709 llvm::SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +0000710 if (OperatorNew) {
711 // Add default arguments, if any.
712 const FunctionProtoType *Proto =
713 OperatorNew->getType()->getAs<FunctionProtoType>();
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +0000714 VariadicCallType CallType =
715 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
Fariborz Jahanian835026e2009-11-24 18:29:37 +0000716 bool Invalid = GatherArgumentsForCall(PlacementLParen, OperatorNew,
717 Proto, 1, PlaceArgs, NumPlaceArgs,
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +0000718 AllPlaceArgs, CallType);
Fariborz Jahanian835026e2009-11-24 18:29:37 +0000719 if (Invalid)
720 return ExprError();
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +0000721
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +0000722 NumPlaceArgs = AllPlaceArgs.size();
723 if (NumPlaceArgs > 0)
724 PlaceArgs = &AllPlaceArgs[0];
725 }
726
Sebastian Redlbd150f42008-11-21 19:14:01 +0000727 bool Init = ConstructorLParen.isValid();
728 // --- Choosing a constructor ---
Sebastian Redlbd150f42008-11-21 19:14:01 +0000729 CXXConstructorDecl *Constructor = 0;
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000730 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
731 unsigned NumConsArgs = ConstructorArgs.size();
Eli Friedmanfd8d4e12009-11-08 22:15:39 +0000732 ASTOwningVector<&ActionBase::DeleteExpr> ConvertedConstructorArgs(*this);
733
Douglas Gregor85dabae2009-12-16 01:38:02 +0000734 if (!AllocType->isDependentType() &&
735 !Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) {
736 // C++0x [expr.new]p15:
737 // A new-expression that creates an object of type T initializes that
738 // object as follows:
739 InitializationKind Kind
740 // - If the new-initializer is omitted, the object is default-
741 // initialized (8.5); if no initialization is performed,
742 // the object has indeterminate value
743 = !Init? InitializationKind::CreateDefault(TypeLoc)
744 // - Otherwise, the new-initializer is interpreted according to the
745 // initialization rules of 8.5 for direct-initialization.
746 : InitializationKind::CreateDirect(TypeLoc,
747 ConstructorLParen,
748 ConstructorRParen);
749
Douglas Gregor85dabae2009-12-16 01:38:02 +0000750 InitializedEntity Entity
Douglas Gregor1b303932009-12-22 15:35:07 +0000751 = InitializedEntity::InitializeNew(StartLoc, AllocType);
Douglas Gregor85dabae2009-12-16 01:38:02 +0000752 InitializationSequence InitSeq(*this, Entity, Kind, ConsArgs, NumConsArgs);
Douglas Gregor85dabae2009-12-16 01:38:02 +0000753 OwningExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
754 move(ConstructorArgs));
755 if (FullInit.isInvalid())
756 return ExprError();
757
758 // FullInit is our initializer; walk through it to determine if it's a
759 // constructor call, which CXXNewExpr handles directly.
760 if (Expr *FullInitExpr = (Expr *)FullInit.get()) {
761 if (CXXBindTemporaryExpr *Binder
762 = dyn_cast<CXXBindTemporaryExpr>(FullInitExpr))
763 FullInitExpr = Binder->getSubExpr();
764 if (CXXConstructExpr *Construct
765 = dyn_cast<CXXConstructExpr>(FullInitExpr)) {
766 Constructor = Construct->getConstructor();
767 for (CXXConstructExpr::arg_iterator A = Construct->arg_begin(),
768 AEnd = Construct->arg_end();
769 A != AEnd; ++A)
770 ConvertedConstructorArgs.push_back(A->Retain());
771 } else {
772 // Take the converted initializer.
773 ConvertedConstructorArgs.push_back(FullInit.release());
774 }
775 } else {
776 // No initialization required.
777 }
778
779 // Take the converted arguments and use them for the new expression.
Douglas Gregor5d3507d2009-09-09 23:08:42 +0000780 NumConsArgs = ConvertedConstructorArgs.size();
781 ConsArgs = (Expr **)ConvertedConstructorArgs.take();
Sebastian Redlbd150f42008-11-21 19:14:01 +0000782 }
Douglas Gregor85dabae2009-12-16 01:38:02 +0000783
Douglas Gregor6642ca22010-02-26 05:06:18 +0000784 // Mark the new and delete operators as referenced.
785 if (OperatorNew)
786 MarkDeclarationReferenced(StartLoc, OperatorNew);
787 if (OperatorDelete)
788 MarkDeclarationReferenced(StartLoc, OperatorDelete);
789
Sebastian Redlbd150f42008-11-21 19:14:01 +0000790 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
Douglas Gregor4bbd1ac2009-10-17 21:40:42 +0000791
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000792 PlacementArgs.release();
793 ConstructorArgs.release();
Douglas Gregord0fefba2009-05-21 00:00:09 +0000794 ArraySizeE.release();
Ted Kremenek9d6eb402010-02-11 22:51:03 +0000795 return Owned(new (Context) CXXNewExpr(Context, UseGlobal, OperatorNew,
796 PlaceArgs, NumPlaceArgs, ParenTypeId,
797 ArraySize, Constructor, Init,
798 ConsArgs, NumConsArgs, OperatorDelete,
799 ResultType, StartLoc,
800 Init ? ConstructorRParen :
801 SourceLocation()));
Sebastian Redlbd150f42008-11-21 19:14:01 +0000802}
803
804/// CheckAllocatedType - Checks that a type is suitable as the allocated type
805/// in a new-expression.
806/// dimension off and stores the size expression in ArraySize.
Douglas Gregord0fefba2009-05-21 00:00:09 +0000807bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +0000808 SourceRange R) {
Sebastian Redlbd150f42008-11-21 19:14:01 +0000809 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
810 // abstract class type or array thereof.
Douglas Gregorac1fb652009-03-24 19:52:54 +0000811 if (AllocType->isFunctionType())
Douglas Gregord0fefba2009-05-21 00:00:09 +0000812 return Diag(Loc, diag::err_bad_new_type)
813 << AllocType << 0 << R;
Douglas Gregorac1fb652009-03-24 19:52:54 +0000814 else if (AllocType->isReferenceType())
Douglas Gregord0fefba2009-05-21 00:00:09 +0000815 return Diag(Loc, diag::err_bad_new_type)
816 << AllocType << 1 << R;
Douglas Gregorac1fb652009-03-24 19:52:54 +0000817 else if (!AllocType->isDependentType() &&
Douglas Gregord0fefba2009-05-21 00:00:09 +0000818 RequireCompleteType(Loc, AllocType,
Anders Carlssond624e162009-08-26 23:45:07 +0000819 PDiag(diag::err_new_incomplete_type)
820 << R))
Sebastian Redlbd150f42008-11-21 19:14:01 +0000821 return true;
Douglas Gregord0fefba2009-05-21 00:00:09 +0000822 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregorac1fb652009-03-24 19:52:54 +0000823 diag::err_allocation_of_abstract_type))
824 return true;
Sebastian Redlbd150f42008-11-21 19:14:01 +0000825
Sebastian Redlbd150f42008-11-21 19:14:01 +0000826 return false;
827}
828
Douglas Gregor6642ca22010-02-26 05:06:18 +0000829/// \brief Determine whether the given function is a non-placement
830/// deallocation function.
831static bool isNonPlacementDeallocationFunction(FunctionDecl *FD) {
832 if (FD->isInvalidDecl())
833 return false;
834
835 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
836 return Method->isUsualDeallocationFunction();
837
838 return ((FD->getOverloadedOperator() == OO_Delete ||
839 FD->getOverloadedOperator() == OO_Array_Delete) &&
840 FD->getNumParams() == 1);
841}
842
Sebastian Redlfaf68082008-12-03 20:26:15 +0000843/// FindAllocationFunctions - Finds the overloads of operator new and delete
844/// that are appropriate for the allocation.
Sebastian Redl1df2bbe2009-02-09 18:24:27 +0000845bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
846 bool UseGlobal, QualType AllocType,
847 bool IsArray, Expr **PlaceArgs,
848 unsigned NumPlaceArgs,
Sebastian Redlfaf68082008-12-03 20:26:15 +0000849 FunctionDecl *&OperatorNew,
Mike Stump11289f42009-09-09 15:08:12 +0000850 FunctionDecl *&OperatorDelete) {
Sebastian Redlfaf68082008-12-03 20:26:15 +0000851 // --- Choosing an allocation function ---
852 // C++ 5.3.4p8 - 14 & 18
853 // 1) If UseGlobal is true, only look in the global scope. Else, also look
854 // in the scope of the allocated class.
855 // 2) If an array size is given, look for operator new[], else look for
856 // operator new.
857 // 3) The first argument is always size_t. Append the arguments from the
858 // placement form.
Sebastian Redlfaf68082008-12-03 20:26:15 +0000859
860 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
861 // We don't care about the actual value of this argument.
862 // FIXME: Should the Sema create the expression and embed it in the syntax
863 // tree? Or should the consumer just recalculate the value?
Anders Carlssona471db02009-08-16 20:29:29 +0000864 IntegerLiteral Size(llvm::APInt::getNullValue(
865 Context.Target.getPointerWidth(0)),
866 Context.getSizeType(),
867 SourceLocation());
868 AllocArgs[0] = &Size;
Sebastian Redlfaf68082008-12-03 20:26:15 +0000869 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
870
Douglas Gregor6642ca22010-02-26 05:06:18 +0000871 // C++ [expr.new]p8:
872 // If the allocated type is a non-array type, the allocation
873 // function’s name is operator new and the deallocation function’s
874 // name is operator delete. If the allocated type is an array
875 // type, the allocation function’s name is operator new[] and the
876 // deallocation function’s name is operator delete[].
Sebastian Redlfaf68082008-12-03 20:26:15 +0000877 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
878 IsArray ? OO_Array_New : OO_New);
Douglas Gregor6642ca22010-02-26 05:06:18 +0000879 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
880 IsArray ? OO_Array_Delete : OO_Delete);
881
Sebastian Redlfaf68082008-12-03 20:26:15 +0000882 if (AllocType->isRecordType() && !UseGlobal) {
Mike Stump11289f42009-09-09 15:08:12 +0000883 CXXRecordDecl *Record
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000884 = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl());
Sebastian Redl1df2bbe2009-02-09 18:24:27 +0000885 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl33a31012008-12-04 22:20:51 +0000886 AllocArgs.size(), Record, /*AllowMissing=*/true,
887 OperatorNew))
Sebastian Redlfaf68082008-12-03 20:26:15 +0000888 return true;
Sebastian Redlfaf68082008-12-03 20:26:15 +0000889 }
890 if (!OperatorNew) {
891 // Didn't find a member overload. Look for a global one.
892 DeclareGlobalNewDelete();
Sebastian Redl33a31012008-12-04 22:20:51 +0000893 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl1df2bbe2009-02-09 18:24:27 +0000894 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl33a31012008-12-04 22:20:51 +0000895 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
896 OperatorNew))
Sebastian Redlfaf68082008-12-03 20:26:15 +0000897 return true;
Sebastian Redlfaf68082008-12-03 20:26:15 +0000898 }
899
Anders Carlsson6f9dabf2009-05-31 20:26:12 +0000900 // FindAllocationOverload can change the passed in arguments, so we need to
901 // copy them back.
902 if (NumPlaceArgs > 0)
903 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
Mike Stump11289f42009-09-09 15:08:12 +0000904
Douglas Gregor6642ca22010-02-26 05:06:18 +0000905 // C++ [expr.new]p19:
906 //
907 // If the new-expression begins with a unary :: operator, the
908 // deallocation function’s name is looked up in the global
909 // scope. Otherwise, if the allocated type is a class type T or an
910 // array thereof, the deallocation function’s name is looked up in
911 // the scope of T. If this lookup fails to find the name, or if
912 // the allocated type is not a class type or array thereof, the
913 // deallocation function’s name is looked up in the global scope.
914 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
915 if (AllocType->isRecordType() && !UseGlobal) {
916 CXXRecordDecl *RD
917 = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl());
918 LookupQualifiedName(FoundDelete, RD);
919 }
John McCallfb6f5262010-03-18 08:19:33 +0000920 if (FoundDelete.isAmbiguous())
921 return true; // FIXME: clean up expressions?
Douglas Gregor6642ca22010-02-26 05:06:18 +0000922
923 if (FoundDelete.empty()) {
924 DeclareGlobalNewDelete();
925 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
926 }
927
928 FoundDelete.suppressDiagnostics();
John McCalla0296f72010-03-19 07:35:19 +0000929
930 llvm::SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
931
John McCallfb6f5262010-03-18 08:19:33 +0000932 if (NumPlaceArgs > 0) {
Douglas Gregor6642ca22010-02-26 05:06:18 +0000933 // C++ [expr.new]p20:
934 // A declaration of a placement deallocation function matches the
935 // declaration of a placement allocation function if it has the
936 // same number of parameters and, after parameter transformations
937 // (8.3.5), all parameter types except the first are
938 // identical. [...]
939 //
940 // To perform this comparison, we compute the function type that
941 // the deallocation function should have, and use that type both
942 // for template argument deduction and for comparison purposes.
943 QualType ExpectedFunctionType;
944 {
945 const FunctionProtoType *Proto
946 = OperatorNew->getType()->getAs<FunctionProtoType>();
947 llvm::SmallVector<QualType, 4> ArgTypes;
948 ArgTypes.push_back(Context.VoidPtrTy);
949 for (unsigned I = 1, N = Proto->getNumArgs(); I < N; ++I)
950 ArgTypes.push_back(Proto->getArgType(I));
951
952 ExpectedFunctionType
953 = Context.getFunctionType(Context.VoidTy, ArgTypes.data(),
954 ArgTypes.size(),
955 Proto->isVariadic(),
Rafael Espindolac50c27c2010-03-30 20:24:48 +0000956 0, false, false, 0, 0,
957 FunctionType::ExtInfo());
Douglas Gregor6642ca22010-02-26 05:06:18 +0000958 }
959
960 for (LookupResult::iterator D = FoundDelete.begin(),
961 DEnd = FoundDelete.end();
962 D != DEnd; ++D) {
963 FunctionDecl *Fn = 0;
964 if (FunctionTemplateDecl *FnTmpl
965 = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
966 // Perform template argument deduction to try to match the
967 // expected function type.
968 TemplateDeductionInfo Info(Context, StartLoc);
969 if (DeduceTemplateArguments(FnTmpl, 0, ExpectedFunctionType, Fn, Info))
970 continue;
971 } else
972 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
973
974 if (Context.hasSameType(Fn->getType(), ExpectedFunctionType))
John McCalla0296f72010-03-19 07:35:19 +0000975 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6642ca22010-02-26 05:06:18 +0000976 }
977 } else {
978 // C++ [expr.new]p20:
979 // [...] Any non-placement deallocation function matches a
980 // non-placement allocation function. [...]
981 for (LookupResult::iterator D = FoundDelete.begin(),
982 DEnd = FoundDelete.end();
983 D != DEnd; ++D) {
984 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>((*D)->getUnderlyingDecl()))
985 if (isNonPlacementDeallocationFunction(Fn))
John McCalla0296f72010-03-19 07:35:19 +0000986 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6642ca22010-02-26 05:06:18 +0000987 }
988 }
989
990 // C++ [expr.new]p20:
991 // [...] If the lookup finds a single matching deallocation
992 // function, that function will be called; otherwise, no
993 // deallocation function will be called.
994 if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +0000995 OperatorDelete = Matches[0].second;
Douglas Gregor6642ca22010-02-26 05:06:18 +0000996
997 // C++0x [expr.new]p20:
998 // If the lookup finds the two-parameter form of a usual
999 // deallocation function (3.7.4.2) and that function, considered
1000 // as a placement deallocation function, would have been
1001 // selected as a match for the allocation function, the program
1002 // is ill-formed.
1003 if (NumPlaceArgs && getLangOptions().CPlusPlus0x &&
1004 isNonPlacementDeallocationFunction(OperatorDelete)) {
1005 Diag(StartLoc, diag::err_placement_new_non_placement_delete)
1006 << SourceRange(PlaceArgs[0]->getLocStart(),
1007 PlaceArgs[NumPlaceArgs - 1]->getLocEnd());
1008 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
1009 << DeleteName;
John McCallfb6f5262010-03-18 08:19:33 +00001010 } else {
1011 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
John McCalla0296f72010-03-19 07:35:19 +00001012 Matches[0].first);
Douglas Gregor6642ca22010-02-26 05:06:18 +00001013 }
1014 }
1015
Sebastian Redlfaf68082008-12-03 20:26:15 +00001016 return false;
1017}
1018
Sebastian Redl33a31012008-12-04 22:20:51 +00001019/// FindAllocationOverload - Find an fitting overload for the allocation
1020/// function in the specified scope.
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00001021bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
1022 DeclarationName Name, Expr** Args,
1023 unsigned NumArgs, DeclContext *Ctx,
Mike Stump11289f42009-09-09 15:08:12 +00001024 bool AllowMissing, FunctionDecl *&Operator) {
John McCall27b18f82009-11-17 02:14:36 +00001025 LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
1026 LookupQualifiedName(R, Ctx);
John McCall9f3059a2009-10-09 21:13:30 +00001027 if (R.empty()) {
Sebastian Redl33a31012008-12-04 22:20:51 +00001028 if (AllowMissing)
1029 return false;
Sebastian Redl33a31012008-12-04 22:20:51 +00001030 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner45d9d602009-02-17 07:29:20 +00001031 << Name << Range;
Sebastian Redl33a31012008-12-04 22:20:51 +00001032 }
1033
John McCallfb6f5262010-03-18 08:19:33 +00001034 if (R.isAmbiguous())
1035 return true;
1036
1037 R.suppressDiagnostics();
John McCall9f3059a2009-10-09 21:13:30 +00001038
John McCallbc077cf2010-02-08 23:07:23 +00001039 OverloadCandidateSet Candidates(StartLoc);
Douglas Gregor80a6cc52009-09-30 00:03:47 +00001040 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
1041 Alloc != AllocEnd; ++Alloc) {
Douglas Gregor55297ac2008-12-23 00:26:44 +00001042 // Even member operator new/delete are implicitly treated as
1043 // static, so don't use AddMemberCandidate.
John McCalla0296f72010-03-19 07:35:19 +00001044 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
Chandler Carruth93538422010-02-03 11:02:14 +00001045
John McCalla0296f72010-03-19 07:35:19 +00001046 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
1047 AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
Chandler Carruth93538422010-02-03 11:02:14 +00001048 /*ExplicitTemplateArgs=*/0, Args, NumArgs,
1049 Candidates,
1050 /*SuppressUserConversions=*/false);
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001051 continue;
Chandler Carruth93538422010-02-03 11:02:14 +00001052 }
1053
John McCalla0296f72010-03-19 07:35:19 +00001054 FunctionDecl *Fn = cast<FunctionDecl>(D);
1055 AddOverloadCandidate(Fn, Alloc.getPair(), Args, NumArgs, Candidates,
Chandler Carruth93538422010-02-03 11:02:14 +00001056 /*SuppressUserConversions=*/false);
Sebastian Redl33a31012008-12-04 22:20:51 +00001057 }
1058
1059 // Do the resolution.
1060 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00001061 switch(BestViableFunction(Candidates, StartLoc, Best)) {
Sebastian Redl33a31012008-12-04 22:20:51 +00001062 case OR_Success: {
1063 // Got one!
1064 FunctionDecl *FnDecl = Best->Function;
1065 // The first argument is size_t, and the first parameter must be size_t,
1066 // too. This is checked on declaration and can be assumed. (It can't be
1067 // asserted on, though, since invalid decls are left in there.)
John McCallfb6f5262010-03-18 08:19:33 +00001068 // Watch out for variadic allocator function.
Fariborz Jahanian835026e2009-11-24 18:29:37 +00001069 unsigned NumArgsInFnDecl = FnDecl->getNumParams();
1070 for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) {
Douglas Gregor34147272010-03-26 20:35:59 +00001071 OwningExprResult Result
1072 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
1073 FnDecl->getParamDecl(i)),
1074 SourceLocation(),
1075 Owned(Args[i]->Retain()));
1076 if (Result.isInvalid())
Sebastian Redl33a31012008-12-04 22:20:51 +00001077 return true;
Douglas Gregor34147272010-03-26 20:35:59 +00001078
1079 Args[i] = Result.takeAs<Expr>();
Sebastian Redl33a31012008-12-04 22:20:51 +00001080 }
1081 Operator = FnDecl;
John McCalla0296f72010-03-19 07:35:19 +00001082 CheckAllocationAccess(StartLoc, Range, R.getNamingClass(), Best->FoundDecl);
Sebastian Redl33a31012008-12-04 22:20:51 +00001083 return false;
1084 }
1085
1086 case OR_No_Viable_Function:
Sebastian Redl33a31012008-12-04 22:20:51 +00001087 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner45d9d602009-02-17 07:29:20 +00001088 << Name << Range;
John McCallad907772010-01-12 07:18:19 +00001089 PrintOverloadCandidates(Candidates, OCD_AllCandidates, Args, NumArgs);
Sebastian Redl33a31012008-12-04 22:20:51 +00001090 return true;
1091
1092 case OR_Ambiguous:
Sebastian Redl33a31012008-12-04 22:20:51 +00001093 Diag(StartLoc, diag::err_ovl_ambiguous_call)
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00001094 << Name << Range;
John McCallad907772010-01-12 07:18:19 +00001095 PrintOverloadCandidates(Candidates, OCD_ViableCandidates, Args, NumArgs);
Sebastian Redl33a31012008-12-04 22:20:51 +00001096 return true;
Douglas Gregor171c45a2009-02-18 21:56:37 +00001097
1098 case OR_Deleted:
1099 Diag(StartLoc, diag::err_ovl_deleted_call)
1100 << Best->Function->isDeleted()
1101 << Name << Range;
John McCallad907772010-01-12 07:18:19 +00001102 PrintOverloadCandidates(Candidates, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00001103 return true;
Sebastian Redl33a31012008-12-04 22:20:51 +00001104 }
1105 assert(false && "Unreachable, bad result from BestViableFunction");
1106 return true;
1107}
1108
1109
Sebastian Redlfaf68082008-12-03 20:26:15 +00001110/// DeclareGlobalNewDelete - Declare the global forms of operator new and
1111/// delete. These are:
1112/// @code
1113/// void* operator new(std::size_t) throw(std::bad_alloc);
1114/// void* operator new[](std::size_t) throw(std::bad_alloc);
1115/// void operator delete(void *) throw();
1116/// void operator delete[](void *) throw();
1117/// @endcode
1118/// Note that the placement and nothrow forms of new are *not* implicitly
1119/// declared. Their use requires including \<new\>.
Mike Stump11289f42009-09-09 15:08:12 +00001120void Sema::DeclareGlobalNewDelete() {
Sebastian Redlfaf68082008-12-03 20:26:15 +00001121 if (GlobalNewDeleteDeclared)
1122 return;
Douglas Gregor87f54062009-09-15 22:30:29 +00001123
1124 // C++ [basic.std.dynamic]p2:
1125 // [...] The following allocation and deallocation functions (18.4) are
1126 // implicitly declared in global scope in each translation unit of a
1127 // program
1128 //
1129 // void* operator new(std::size_t) throw(std::bad_alloc);
1130 // void* operator new[](std::size_t) throw(std::bad_alloc);
1131 // void operator delete(void*) throw();
1132 // void operator delete[](void*) throw();
1133 //
1134 // These implicit declarations introduce only the function names operator
1135 // new, operator new[], operator delete, operator delete[].
1136 //
1137 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
1138 // "std" or "bad_alloc" as necessary to form the exception specification.
1139 // However, we do not make these implicit declarations visible to name
1140 // lookup.
1141 if (!StdNamespace) {
1142 // The "std" namespace has not yet been defined, so build one implicitly.
1143 StdNamespace = NamespaceDecl::Create(Context,
1144 Context.getTranslationUnitDecl(),
1145 SourceLocation(),
1146 &PP.getIdentifierTable().get("std"));
1147 StdNamespace->setImplicit(true);
1148 }
1149
1150 if (!StdBadAlloc) {
1151 // The "std::bad_alloc" class has not yet been declared, so build it
1152 // implicitly.
1153 StdBadAlloc = CXXRecordDecl::Create(Context, TagDecl::TK_class,
1154 StdNamespace,
1155 SourceLocation(),
1156 &PP.getIdentifierTable().get("bad_alloc"),
1157 SourceLocation(), 0);
1158 StdBadAlloc->setImplicit(true);
1159 }
1160
Sebastian Redlfaf68082008-12-03 20:26:15 +00001161 GlobalNewDeleteDeclared = true;
1162
1163 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
1164 QualType SizeT = Context.getSizeType();
Nuno Lopes13c88c72009-12-16 16:59:22 +00001165 bool AssumeSaneOperatorNew = getLangOptions().AssumeSaneOperatorNew;
Sebastian Redlfaf68082008-12-03 20:26:15 +00001166
Sebastian Redlfaf68082008-12-03 20:26:15 +00001167 DeclareGlobalAllocationFunction(
1168 Context.DeclarationNames.getCXXOperatorName(OO_New),
Nuno Lopes13c88c72009-12-16 16:59:22 +00001169 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001170 DeclareGlobalAllocationFunction(
1171 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
Nuno Lopes13c88c72009-12-16 16:59:22 +00001172 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001173 DeclareGlobalAllocationFunction(
1174 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
1175 Context.VoidTy, VoidPtr);
1176 DeclareGlobalAllocationFunction(
1177 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
1178 Context.VoidTy, VoidPtr);
1179}
1180
1181/// DeclareGlobalAllocationFunction - Declares a single implicit global
1182/// allocation function if it doesn't already exist.
1183void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Nuno Lopes13c88c72009-12-16 16:59:22 +00001184 QualType Return, QualType Argument,
1185 bool AddMallocAttr) {
Sebastian Redlfaf68082008-12-03 20:26:15 +00001186 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
1187
1188 // Check if this function is already declared.
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001189 {
Douglas Gregor17eb26b2008-12-23 22:05:29 +00001190 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001191 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001192 Alloc != AllocEnd; ++Alloc) {
Chandler Carruth93538422010-02-03 11:02:14 +00001193 // Only look at non-template functions, as it is the predefined,
1194 // non-templated allocation function we are trying to declare here.
1195 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
1196 QualType InitialParamType =
Douglas Gregor684d7bd2009-12-22 23:42:49 +00001197 Context.getCanonicalType(
Chandler Carruth93538422010-02-03 11:02:14 +00001198 Func->getParamDecl(0)->getType().getUnqualifiedType());
1199 // FIXME: Do we need to check for default arguments here?
1200 if (Func->getNumParams() == 1 && InitialParamType == Argument)
1201 return;
1202 }
Sebastian Redlfaf68082008-12-03 20:26:15 +00001203 }
1204 }
1205
Douglas Gregor87f54062009-09-15 22:30:29 +00001206 QualType BadAllocType;
1207 bool HasBadAllocExceptionSpec
1208 = (Name.getCXXOverloadedOperator() == OO_New ||
1209 Name.getCXXOverloadedOperator() == OO_Array_New);
1210 if (HasBadAllocExceptionSpec) {
1211 assert(StdBadAlloc && "Must have std::bad_alloc declared");
1212 BadAllocType = Context.getTypeDeclType(StdBadAlloc);
1213 }
1214
1215 QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0,
1216 true, false,
1217 HasBadAllocExceptionSpec? 1 : 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001218 &BadAllocType,
1219 FunctionType::ExtInfo());
Sebastian Redlfaf68082008-12-03 20:26:15 +00001220 FunctionDecl *Alloc =
1221 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
John McCallbcd03502009-12-07 02:54:59 +00001222 FnType, /*TInfo=*/0, FunctionDecl::None, false, true);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001223 Alloc->setImplicit();
Nuno Lopes13c88c72009-12-16 16:59:22 +00001224
1225 if (AddMallocAttr)
1226 Alloc->addAttr(::new (Context) MallocAttr());
1227
Sebastian Redlfaf68082008-12-03 20:26:15 +00001228 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
John McCallbcd03502009-12-07 02:54:59 +00001229 0, Argument, /*TInfo=*/0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00001230 VarDecl::None, 0);
Douglas Gregord5058122010-02-11 01:19:42 +00001231 Alloc->setParams(&Param, 1);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001232
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001233 // FIXME: Also add this declaration to the IdentifierResolver, but
1234 // make sure it is at the end of the chain to coincide with the
1235 // global scope.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001236 ((DeclContext *)TUScope->getEntity())->addDecl(Alloc);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001237}
1238
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001239bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
1240 DeclarationName Name,
Anders Carlssonf98849e2009-12-02 17:15:43 +00001241 FunctionDecl* &Operator) {
John McCall27b18f82009-11-17 02:14:36 +00001242 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001243 // Try to find operator delete/operator delete[] in class scope.
John McCall27b18f82009-11-17 02:14:36 +00001244 LookupQualifiedName(Found, RD);
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001245
John McCall27b18f82009-11-17 02:14:36 +00001246 if (Found.isAmbiguous())
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001247 return true;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001248
1249 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1250 F != FEnd; ++F) {
1251 if (CXXMethodDecl *Delete = dyn_cast<CXXMethodDecl>(*F))
1252 if (Delete->isUsualDeallocationFunction()) {
1253 Operator = Delete;
1254 return false;
1255 }
1256 }
1257
1258 // We did find operator delete/operator delete[] declarations, but
1259 // none of them were suitable.
1260 if (!Found.empty()) {
1261 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
1262 << Name << RD;
1263
1264 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1265 F != FEnd; ++F) {
1266 Diag((*F)->getLocation(),
1267 diag::note_delete_member_function_declared_here)
1268 << Name;
1269 }
1270
1271 return true;
1272 }
1273
1274 // Look for a global declaration.
1275 DeclareGlobalNewDelete();
1276 DeclContext *TUDecl = Context.getTranslationUnitDecl();
1277
1278 CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation());
1279 Expr* DeallocArgs[1];
1280 DeallocArgs[0] = &Null;
1281 if (FindAllocationOverload(StartLoc, SourceRange(), Name,
1282 DeallocArgs, 1, TUDecl, /*AllowMissing=*/false,
1283 Operator))
1284 return true;
1285
1286 assert(Operator && "Did not find a deallocation function!");
1287 return false;
1288}
1289
Sebastian Redlbd150f42008-11-21 19:14:01 +00001290/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
1291/// @code ::delete ptr; @endcode
1292/// or
1293/// @code delete [] ptr; @endcode
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001294Action::OwningExprResult
Sebastian Redlbd150f42008-11-21 19:14:01 +00001295Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
Mike Stump11289f42009-09-09 15:08:12 +00001296 bool ArrayForm, ExprArg Operand) {
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001297 // C++ [expr.delete]p1:
1298 // The operand shall have a pointer type, or a class type having a single
1299 // conversion function to a pointer type. The result has type void.
1300 //
Sebastian Redlbd150f42008-11-21 19:14:01 +00001301 // DR599 amends "pointer type" to "pointer to object type" in both cases.
1302
Anders Carlssona471db02009-08-16 20:29:29 +00001303 FunctionDecl *OperatorDelete = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001304
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001305 Expr *Ex = (Expr *)Operand.get();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001306 if (!Ex->isTypeDependent()) {
1307 QualType Type = Ex->getType();
Sebastian Redlbd150f42008-11-21 19:14:01 +00001308
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001309 if (const RecordType *Record = Type->getAs<RecordType>()) {
John McCallda4458e2010-03-31 01:36:47 +00001310 llvm::SmallVector<CXXConversionDecl*, 4> ObjectPtrConversions;
1311
Fariborz Jahanianb54ccb22009-09-11 21:44:33 +00001312 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
John McCallda4458e2010-03-31 01:36:47 +00001313 const UnresolvedSetImpl *Conversions = RD->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00001314 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00001315 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00001316 NamedDecl *D = I.getDecl();
1317 if (isa<UsingShadowDecl>(D))
1318 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1319
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001320 // Skip over templated conversion functions; they aren't considered.
John McCallda4458e2010-03-31 01:36:47 +00001321 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001322 continue;
1323
John McCallda4458e2010-03-31 01:36:47 +00001324 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001325
1326 QualType ConvType = Conv->getConversionType().getNonReferenceType();
1327 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
1328 if (ConvPtrType->getPointeeType()->isObjectType())
Fariborz Jahanianadcea102009-09-15 22:15:23 +00001329 ObjectPtrConversions.push_back(Conv);
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001330 }
Fariborz Jahanianadcea102009-09-15 22:15:23 +00001331 if (ObjectPtrConversions.size() == 1) {
1332 // We have a single conversion to a pointer-to-object type. Perform
1333 // that conversion.
John McCallda4458e2010-03-31 01:36:47 +00001334 // TODO: don't redo the conversion calculation.
Fariborz Jahanianadcea102009-09-15 22:15:23 +00001335 Operand.release();
John McCallda4458e2010-03-31 01:36:47 +00001336 if (!PerformImplicitConversion(Ex,
1337 ObjectPtrConversions.front()->getConversionType(),
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001338 AA_Converting)) {
Fariborz Jahanianadcea102009-09-15 22:15:23 +00001339 Operand = Owned(Ex);
1340 Type = Ex->getType();
1341 }
1342 }
1343 else if (ObjectPtrConversions.size() > 1) {
1344 Diag(StartLoc, diag::err_ambiguous_delete_operand)
1345 << Type << Ex->getSourceRange();
John McCallda4458e2010-03-31 01:36:47 +00001346 for (unsigned i= 0; i < ObjectPtrConversions.size(); i++)
1347 NoteOverloadCandidate(ObjectPtrConversions[i]);
Fariborz Jahanianadcea102009-09-15 22:15:23 +00001348 return ExprError();
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001349 }
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001350 }
1351
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001352 if (!Type->isPointerType())
1353 return ExprError(Diag(StartLoc, diag::err_delete_operand)
1354 << Type << Ex->getSourceRange());
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001355
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001356 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Douglas Gregorc9a1a3b2009-03-24 20:13:58 +00001357 if (Pointee->isFunctionType() || Pointee->isVoidType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001358 return ExprError(Diag(StartLoc, diag::err_delete_operand)
1359 << Type << Ex->getSourceRange());
Douglas Gregorc9a1a3b2009-03-24 20:13:58 +00001360 else if (!Pointee->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00001361 RequireCompleteType(StartLoc, Pointee,
Anders Carlssond624e162009-08-26 23:45:07 +00001362 PDiag(diag::warn_delete_incomplete)
1363 << Ex->getSourceRange()))
Douglas Gregorc9a1a3b2009-03-24 20:13:58 +00001364 return ExprError();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001365
Douglas Gregor98496dc2009-09-29 21:38:53 +00001366 // C++ [expr.delete]p2:
1367 // [Note: a pointer to a const type can be the operand of a
1368 // delete-expression; it is not necessary to cast away the constness
1369 // (5.2.11) of the pointer expression before it is used as the operand
1370 // of the delete-expression. ]
1371 ImpCastExprToType(Ex, Context.getPointerType(Context.VoidTy),
1372 CastExpr::CK_NoOp);
1373
1374 // Update the operand.
1375 Operand.take();
1376 Operand = ExprArg(*this, Ex);
1377
Anders Carlssona471db02009-08-16 20:29:29 +00001378 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1379 ArrayForm ? OO_Array_Delete : OO_Delete);
1380
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001381 if (const RecordType *RT = Pointee->getAs<RecordType>()) {
1382 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1383
1384 if (!UseGlobal &&
1385 FindDeallocationFunction(StartLoc, RD, DeleteName, OperatorDelete))
Anders Carlsson654e5c72009-11-14 03:17:38 +00001386 return ExprError();
Anders Carlsson654e5c72009-11-14 03:17:38 +00001387
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001388 if (!RD->hasTrivialDestructor())
1389 if (const CXXDestructorDecl *Dtor = RD->getDestructor(Context))
Mike Stump11289f42009-09-09 15:08:12 +00001390 MarkDeclarationReferenced(StartLoc,
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001391 const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssona471db02009-08-16 20:29:29 +00001392 }
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001393
Anders Carlssona471db02009-08-16 20:29:29 +00001394 if (!OperatorDelete) {
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001395 // Look for a global declaration.
Anders Carlssona471db02009-08-16 20:29:29 +00001396 DeclareGlobalNewDelete();
1397 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001398 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001399 &Ex, 1, TUDecl, /*AllowMissing=*/false,
Anders Carlssona471db02009-08-16 20:29:29 +00001400 OperatorDelete))
1401 return ExprError();
1402 }
Mike Stump11289f42009-09-09 15:08:12 +00001403
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001404 // FIXME: Check access and ambiguity of operator delete and destructor.
Sebastian Redlbd150f42008-11-21 19:14:01 +00001405 }
1406
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001407 Operand.release();
1408 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
Anders Carlssona471db02009-08-16 20:29:29 +00001409 OperatorDelete, Ex, StartLoc));
Sebastian Redlbd150f42008-11-21 19:14:01 +00001410}
1411
Douglas Gregor633caca2009-11-23 23:44:04 +00001412/// \brief Check the use of the given variable as a C++ condition in an if,
1413/// while, do-while, or switch statement.
1414Action::OwningExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar) {
1415 QualType T = ConditionVar->getType();
1416
1417 // C++ [stmt.select]p2:
1418 // The declarator shall not specify a function or an array.
1419 if (T->isFunctionType())
1420 return ExprError(Diag(ConditionVar->getLocation(),
1421 diag::err_invalid_use_of_function_type)
1422 << ConditionVar->getSourceRange());
1423 else if (T->isArrayType())
1424 return ExprError(Diag(ConditionVar->getLocation(),
1425 diag::err_invalid_use_of_array_type)
1426 << ConditionVar->getSourceRange());
Douglas Gregor0156d1c2009-11-24 16:07:02 +00001427
Douglas Gregor633caca2009-11-23 23:44:04 +00001428 return Owned(DeclRefExpr::Create(Context, 0, SourceRange(), ConditionVar,
1429 ConditionVar->getLocation(),
1430 ConditionVar->getType().getNonReferenceType()));
1431}
1432
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001433/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
1434bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
1435 // C++ 6.4p4:
1436 // The value of a condition that is an initialized declaration in a statement
1437 // other than a switch statement is the value of the declared variable
1438 // implicitly converted to type bool. If that conversion is ill-formed, the
1439 // program is ill-formed.
1440 // The value of a condition that is an expression is the value of the
1441 // expression, implicitly converted to bool.
1442 //
Douglas Gregor5fb53972009-01-14 15:45:31 +00001443 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001444}
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001445
1446/// Helper function to determine whether this is the (deprecated) C++
1447/// conversion from a string literal to a pointer to non-const char or
1448/// non-const wchar_t (for narrow and wide string literals,
1449/// respectively).
Mike Stump11289f42009-09-09 15:08:12 +00001450bool
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001451Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
1452 // Look inside the implicit cast, if it exists.
1453 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
1454 From = Cast->getSubExpr();
1455
1456 // A string literal (2.13.4) that is not a wide string literal can
1457 // be converted to an rvalue of type "pointer to char"; a wide
1458 // string literal can be converted to an rvalue of type "pointer
1459 // to wchar_t" (C++ 4.2p2).
1460 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From))
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001461 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump11289f42009-09-09 15:08:12 +00001462 if (const BuiltinType *ToPointeeType
John McCall9dd450b2009-09-21 23:43:11 +00001463 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001464 // This conversion is considered only when there is an
1465 // explicit appropriate pointer target type (C++ 4.2p2).
John McCall8ccfcb52009-09-24 19:53:00 +00001466 if (!ToPtrType->getPointeeType().hasQualifiers() &&
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001467 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
1468 (!StrLit->isWide() &&
1469 (ToPointeeType->getKind() == BuiltinType::Char_U ||
1470 ToPointeeType->getKind() == BuiltinType::Char_S))))
1471 return true;
1472 }
1473
1474 return false;
1475}
Douglas Gregor39c16d42008-10-24 04:54:22 +00001476
1477/// PerformImplicitConversion - Perform an implicit conversion of the
1478/// expression From to the type ToType. Returns true if there was an
1479/// error, false otherwise. The expression From is replaced with the
Douglas Gregor47d3f272008-12-19 17:40:08 +00001480/// converted expression. Flavor is the kind of conversion we're
Douglas Gregor5fb53972009-01-14 15:45:31 +00001481/// performing, used in the error message. If @p AllowExplicit,
Sebastian Redl42e92c42009-04-12 17:16:29 +00001482/// explicit user-defined conversions are permitted. @p Elidable should be true
1483/// when called for copies which may be elided (C++ 12.8p15). C++0x overload
1484/// resolution works differently in that case.
1485bool
Douglas Gregor47d3f272008-12-19 17:40:08 +00001486Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001487 AssignmentAction Action, bool AllowExplicit,
Mike Stump11289f42009-09-09 15:08:12 +00001488 bool Elidable) {
Sebastian Redl42e92c42009-04-12 17:16:29 +00001489 ImplicitConversionSequence ICS;
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001490 return PerformImplicitConversion(From, ToType, Action, AllowExplicit,
Fariborz Jahanianaf0262d2009-09-23 20:55:32 +00001491 Elidable, ICS);
1492}
1493
1494bool
1495Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001496 AssignmentAction Action, bool AllowExplicit,
Fariborz Jahanianaf0262d2009-09-23 20:55:32 +00001497 bool Elidable,
1498 ImplicitConversionSequence& ICS) {
John McCall65eb8792010-02-25 01:37:24 +00001499 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Sebastian Redl42e92c42009-04-12 17:16:29 +00001500 if (Elidable && getLangOptions().CPlusPlus0x) {
Mike Stump11289f42009-09-09 15:08:12 +00001501 ICS = TryImplicitConversion(From, ToType,
Anders Carlssonef4c7212009-08-27 17:24:15 +00001502 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00001503 AllowExplicit,
Anders Carlsson228eea32009-08-28 15:33:32 +00001504 /*ForceRValue=*/true,
1505 /*InOverloadResolution=*/false);
Sebastian Redl42e92c42009-04-12 17:16:29 +00001506 }
John McCall0d1da222010-01-12 00:44:57 +00001507 if (ICS.isBad()) {
Mike Stump11289f42009-09-09 15:08:12 +00001508 ICS = TryImplicitConversion(From, ToType,
Anders Carlssonef4c7212009-08-27 17:24:15 +00001509 /*SuppressUserConversions=*/false,
1510 AllowExplicit,
Anders Carlsson228eea32009-08-28 15:33:32 +00001511 /*ForceRValue=*/false,
1512 /*InOverloadResolution=*/false);
Sebastian Redl42e92c42009-04-12 17:16:29 +00001513 }
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001514 return PerformImplicitConversion(From, ToType, ICS, Action);
Douglas Gregor5fb53972009-01-14 15:45:31 +00001515}
1516
1517/// PerformImplicitConversion - Perform an implicit conversion of the
1518/// expression From to the type ToType using the pre-computed implicit
1519/// conversion sequence ICS. Returns true if there was an error, false
1520/// otherwise. The expression From is replaced with the converted
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001521/// expression. Action is the kind of conversion we're performing,
Douglas Gregor5fb53972009-01-14 15:45:31 +00001522/// used in the error message.
1523bool
1524Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
1525 const ImplicitConversionSequence &ICS,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001526 AssignmentAction Action, bool IgnoreBaseAccess) {
John McCall0d1da222010-01-12 00:44:57 +00001527 switch (ICS.getKind()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001528 case ImplicitConversionSequence::StandardConversion:
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001529 if (PerformImplicitConversion(From, ToType, ICS.Standard, Action,
Sebastian Redl7c353682009-11-14 21:15:49 +00001530 IgnoreBaseAccess))
Douglas Gregor39c16d42008-10-24 04:54:22 +00001531 return true;
1532 break;
1533
Anders Carlsson110b07b2009-09-15 06:28:28 +00001534 case ImplicitConversionSequence::UserDefinedConversion: {
1535
Fariborz Jahanian2fee79a2009-08-28 22:04:50 +00001536 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
1537 CastExpr::CastKind CastKind = CastExpr::CK_Unknown;
Anders Carlsson110b07b2009-09-15 06:28:28 +00001538 QualType BeforeToType;
1539 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
Fariborz Jahanian2fee79a2009-08-28 22:04:50 +00001540 CastKind = CastExpr::CK_UserDefinedConversion;
Anders Carlsson110b07b2009-09-15 06:28:28 +00001541
1542 // If the user-defined conversion is specified by a conversion function,
1543 // the initial standard conversion sequence converts the source type to
1544 // the implicit object parameter of the conversion function.
1545 BeforeToType = Context.getTagDeclType(Conv->getParent());
1546 } else if (const CXXConstructorDecl *Ctor =
1547 dyn_cast<CXXConstructorDecl>(FD)) {
Anders Carlssone9766d52009-09-09 21:33:21 +00001548 CastKind = CastExpr::CK_ConstructorConversion;
Fariborz Jahanian55824512009-11-06 00:23:08 +00001549 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregor3153da72009-11-20 02:31:03 +00001550 if (!ICS.UserDefined.EllipsisConversion) {
Fariborz Jahanian55824512009-11-06 00:23:08 +00001551 // If the user-defined conversion is specified by a constructor, the
1552 // initial standard conversion sequence converts the source type to the
1553 // type required by the argument of the constructor
Douglas Gregor3153da72009-11-20 02:31:03 +00001554 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
1555 }
Anders Carlsson110b07b2009-09-15 06:28:28 +00001556 }
Anders Carlssone9766d52009-09-09 21:33:21 +00001557 else
1558 assert(0 && "Unknown conversion function kind!");
Fariborz Jahanian55824512009-11-06 00:23:08 +00001559 // Whatch out for elipsis conversion.
Fariborz Jahanianeec642f2009-11-06 00:55:14 +00001560 if (!ICS.UserDefined.EllipsisConversion) {
Fariborz Jahanian55824512009-11-06 00:23:08 +00001561 if (PerformImplicitConversion(From, BeforeToType,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001562 ICS.UserDefined.Before, AA_Converting,
Sebastian Redl7c353682009-11-14 21:15:49 +00001563 IgnoreBaseAccess))
Fariborz Jahanian55824512009-11-06 00:23:08 +00001564 return true;
1565 }
Anders Carlsson110b07b2009-09-15 06:28:28 +00001566
Anders Carlssone9766d52009-09-09 21:33:21 +00001567 OwningExprResult CastArg
1568 = BuildCXXCastArgument(From->getLocStart(),
1569 ToType.getNonReferenceType(),
1570 CastKind, cast<CXXMethodDecl>(FD),
1571 Owned(From));
1572
1573 if (CastArg.isInvalid())
1574 return true;
Eli Friedmane96f1d32009-11-27 04:41:50 +00001575
1576 From = CastArg.takeAs<Expr>();
1577
Eli Friedmane96f1d32009-11-27 04:41:50 +00001578 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001579 AA_Converting, IgnoreBaseAccess);
Fariborz Jahanianda21efb2009-10-16 19:20:59 +00001580 }
John McCall0d1da222010-01-12 00:44:57 +00001581
1582 case ImplicitConversionSequence::AmbiguousConversion:
1583 DiagnoseAmbiguousConversion(ICS, From->getExprLoc(),
1584 PDiag(diag::err_typecheck_ambiguous_condition)
1585 << From->getSourceRange());
1586 return true;
Fariborz Jahanianda21efb2009-10-16 19:20:59 +00001587
Douglas Gregor39c16d42008-10-24 04:54:22 +00001588 case ImplicitConversionSequence::EllipsisConversion:
1589 assert(false && "Cannot perform an ellipsis conversion");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001590 return false;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001591
1592 case ImplicitConversionSequence::BadConversion:
1593 return true;
1594 }
1595
1596 // Everything went well.
1597 return false;
1598}
1599
1600/// PerformImplicitConversion - Perform an implicit conversion of the
1601/// expression From to the type ToType by following the standard
1602/// conversion sequence SCS. Returns true if there was an error, false
1603/// otherwise. The expression From is replaced with the converted
Douglas Gregor47d3f272008-12-19 17:40:08 +00001604/// expression. Flavor is the context in which we're performing this
1605/// conversion, for use in error messages.
Mike Stump11289f42009-09-09 15:08:12 +00001606bool
Douglas Gregor39c16d42008-10-24 04:54:22 +00001607Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor47d3f272008-12-19 17:40:08 +00001608 const StandardConversionSequence& SCS,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001609 AssignmentAction Action, bool IgnoreBaseAccess) {
Mike Stump87c57ac2009-05-16 07:39:55 +00001610 // Overall FIXME: we are recomputing too many types here and doing far too
1611 // much extra work. What this means is that we need to keep track of more
1612 // information that is computed when we try the implicit conversion initially,
1613 // so that we don't need to recompute anything here.
Douglas Gregor39c16d42008-10-24 04:54:22 +00001614 QualType FromType = From->getType();
1615
Douglas Gregor2fe98832008-11-03 19:09:14 +00001616 if (SCS.CopyConstructor) {
Anders Carlsson549c5bd2009-05-19 04:45:15 +00001617 // FIXME: When can ToType be a reference type?
1618 assert(!ToType->isReferenceType());
Fariborz Jahanian49850df2009-09-25 18:59:21 +00001619 if (SCS.Second == ICK_Derived_To_Base) {
1620 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1621 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
1622 MultiExprArg(*this, (void **)&From, 1),
1623 /*FIXME:ConstructLoc*/SourceLocation(),
1624 ConstructorArgs))
1625 return true;
1626 OwningExprResult FromResult =
1627 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1628 ToType, SCS.CopyConstructor,
1629 move_arg(ConstructorArgs));
1630 if (FromResult.isInvalid())
1631 return true;
1632 From = FromResult.takeAs<Expr>();
1633 return false;
1634 }
Mike Stump11289f42009-09-09 15:08:12 +00001635 OwningExprResult FromResult =
1636 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1637 ToType, SCS.CopyConstructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00001638 MultiExprArg(*this, (void**)&From, 1));
Mike Stump11289f42009-09-09 15:08:12 +00001639
Anders Carlsson6eb55572009-08-25 05:12:04 +00001640 if (FromResult.isInvalid())
1641 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001642
Anders Carlsson6eb55572009-08-25 05:12:04 +00001643 From = FromResult.takeAs<Expr>();
Douglas Gregor2fe98832008-11-03 19:09:14 +00001644 return false;
1645 }
1646
Douglas Gregor39c16d42008-10-24 04:54:22 +00001647 // Perform the first implicit conversion.
1648 switch (SCS.First) {
1649 case ICK_Identity:
1650 case ICK_Lvalue_To_Rvalue:
1651 // Nothing to do.
1652 break;
1653
1654 case ICK_Array_To_Pointer:
Douglas Gregor171c45a2009-02-18 21:56:37 +00001655 FromType = Context.getArrayDecayedType(FromType);
Anders Carlsson2c101b32009-08-08 21:04:35 +00001656 ImpCastExprToType(From, FromType, CastExpr::CK_ArrayToPointerDecay);
Douglas Gregor171c45a2009-02-18 21:56:37 +00001657 break;
1658
1659 case ICK_Function_To_Pointer:
Douglas Gregor1baf54e2009-03-13 18:40:31 +00001660 if (Context.getCanonicalType(FromType) == Context.OverloadTy) {
John McCall16df1e52010-03-30 21:47:33 +00001661 DeclAccessPair Found;
1662 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
1663 true, Found);
Douglas Gregorcd695e52008-11-10 20:40:00 +00001664 if (!Fn)
1665 return true;
1666
Douglas Gregor171c45a2009-02-18 21:56:37 +00001667 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
1668 return true;
1669
John McCall16df1e52010-03-30 21:47:33 +00001670 From = FixOverloadedFunctionReference(From, Found, Fn);
Douglas Gregorcd695e52008-11-10 20:40:00 +00001671 FromType = From->getType();
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00001672
Sebastian Redlfef1c0d2009-10-17 20:50:27 +00001673 // If there's already an address-of operator in the expression, we have
1674 // the right type already, and the code below would just introduce an
1675 // invalid additional pointer level.
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00001676 if (FromType->isPointerType() || FromType->isMemberFunctionPointerType())
Sebastian Redlfef1c0d2009-10-17 20:50:27 +00001677 break;
Douglas Gregorcd695e52008-11-10 20:40:00 +00001678 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00001679 FromType = Context.getPointerType(FromType);
Anders Carlsson6904f642009-09-01 20:37:18 +00001680 ImpCastExprToType(From, FromType, CastExpr::CK_FunctionToPointerDecay);
Douglas Gregor39c16d42008-10-24 04:54:22 +00001681 break;
1682
1683 default:
1684 assert(false && "Improper first standard conversion");
1685 break;
1686 }
1687
1688 // Perform the second implicit conversion
1689 switch (SCS.Second) {
1690 case ICK_Identity:
Sebastian Redl5d431642009-10-10 12:04:10 +00001691 // If both sides are functions (or pointers/references to them), there could
1692 // be incompatible exception declarations.
1693 if (CheckExceptionSpecCompatibility(From, ToType))
1694 return true;
1695 // Nothing else to do.
Douglas Gregor39c16d42008-10-24 04:54:22 +00001696 break;
1697
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001698 case ICK_NoReturn_Adjustment:
1699 // If both sides are functions (or pointers/references to them), there could
1700 // be incompatible exception declarations.
1701 if (CheckExceptionSpecCompatibility(From, ToType))
1702 return true;
1703
1704 ImpCastExprToType(From, Context.getNoReturnType(From->getType(), false),
1705 CastExpr::CK_NoOp);
1706 break;
1707
Douglas Gregor39c16d42008-10-24 04:54:22 +00001708 case ICK_Integral_Promotion:
Douglas Gregor39c16d42008-10-24 04:54:22 +00001709 case ICK_Integral_Conversion:
Eli Friedman06ed2a52009-10-20 08:27:19 +00001710 ImpCastExprToType(From, ToType, CastExpr::CK_IntegralCast);
1711 break;
1712
1713 case ICK_Floating_Promotion:
Douglas Gregor39c16d42008-10-24 04:54:22 +00001714 case ICK_Floating_Conversion:
Eli Friedman06ed2a52009-10-20 08:27:19 +00001715 ImpCastExprToType(From, ToType, CastExpr::CK_FloatingCast);
1716 break;
1717
1718 case ICK_Complex_Promotion:
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001719 case ICK_Complex_Conversion:
Eli Friedman06ed2a52009-10-20 08:27:19 +00001720 ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1721 break;
1722
Douglas Gregor39c16d42008-10-24 04:54:22 +00001723 case ICK_Floating_Integral:
Eli Friedman06ed2a52009-10-20 08:27:19 +00001724 if (ToType->isFloatingType())
1725 ImpCastExprToType(From, ToType, CastExpr::CK_IntegralToFloating);
1726 else
1727 ImpCastExprToType(From, ToType, CastExpr::CK_FloatingToIntegral);
1728 break;
1729
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001730 case ICK_Complex_Real:
Eli Friedman06ed2a52009-10-20 08:27:19 +00001731 ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1732 break;
1733
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001734 case ICK_Compatible_Conversion:
Eli Friedman06ed2a52009-10-20 08:27:19 +00001735 ImpCastExprToType(From, ToType, CastExpr::CK_NoOp);
Douglas Gregor39c16d42008-10-24 04:54:22 +00001736 break;
1737
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001738 case ICK_Pointer_Conversion: {
Douglas Gregor47d3f272008-12-19 17:40:08 +00001739 if (SCS.IncompatibleObjC) {
1740 // Diagnose incompatible Objective-C conversions
Mike Stump11289f42009-09-09 15:08:12 +00001741 Diag(From->getSourceRange().getBegin(),
Douglas Gregor47d3f272008-12-19 17:40:08 +00001742 diag::ext_typecheck_convert_incompatible_pointer)
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001743 << From->getType() << ToType << Action
Douglas Gregor47d3f272008-12-19 17:40:08 +00001744 << From->getSourceRange();
1745 }
1746
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001747
1748 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Sebastian Redl7c353682009-11-14 21:15:49 +00001749 if (CheckPointerConversion(From, ToType, Kind, IgnoreBaseAccess))
Douglas Gregor39c16d42008-10-24 04:54:22 +00001750 return true;
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001751 ImpCastExprToType(From, ToType, Kind);
Douglas Gregor39c16d42008-10-24 04:54:22 +00001752 break;
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001753 }
1754
1755 case ICK_Pointer_Member: {
1756 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Sebastian Redl7c353682009-11-14 21:15:49 +00001757 if (CheckMemberPointerConversion(From, ToType, Kind, IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001758 return true;
Sebastian Redl5d431642009-10-10 12:04:10 +00001759 if (CheckExceptionSpecCompatibility(From, ToType))
1760 return true;
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001761 ImpCastExprToType(From, ToType, Kind);
1762 break;
1763 }
Anders Carlsson7fa434c2009-11-23 20:04:44 +00001764 case ICK_Boolean_Conversion: {
1765 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
1766 if (FromType->isMemberPointerType())
1767 Kind = CastExpr::CK_MemberPointerToBoolean;
1768
1769 ImpCastExprToType(From, Context.BoolTy, Kind);
Douglas Gregor39c16d42008-10-24 04:54:22 +00001770 break;
Anders Carlsson7fa434c2009-11-23 20:04:44 +00001771 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00001772
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00001773 case ICK_Derived_To_Base:
1774 if (CheckDerivedToBaseConversion(From->getType(),
1775 ToType.getNonReferenceType(),
1776 From->getLocStart(),
Sebastian Redl7c353682009-11-14 21:15:49 +00001777 From->getSourceRange(),
1778 IgnoreBaseAccess))
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00001779 return true;
1780 ImpCastExprToType(From, ToType.getNonReferenceType(),
1781 CastExpr::CK_DerivedToBase);
1782 break;
1783
Douglas Gregor39c16d42008-10-24 04:54:22 +00001784 default:
1785 assert(false && "Improper second standard conversion");
1786 break;
1787 }
1788
1789 switch (SCS.Third) {
1790 case ICK_Identity:
1791 // Nothing to do.
1792 break;
1793
1794 case ICK_Qualification:
Mike Stump87c57ac2009-05-16 07:39:55 +00001795 // FIXME: Not sure about lvalue vs rvalue here in the presence of rvalue
1796 // references.
Mike Stump11289f42009-09-09 15:08:12 +00001797 ImpCastExprToType(From, ToType.getNonReferenceType(),
Eli Friedman06ed2a52009-10-20 08:27:19 +00001798 CastExpr::CK_NoOp,
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001799 ToType->isLValueReferenceType());
Douglas Gregore489a7d2010-02-28 18:30:25 +00001800
1801 if (SCS.DeprecatedStringLiteralToCharPtr)
1802 Diag(From->getLocStart(), diag::warn_deprecated_string_literal_conversion)
1803 << ToType.getNonReferenceType();
1804
Douglas Gregor39c16d42008-10-24 04:54:22 +00001805 break;
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00001806
Douglas Gregor39c16d42008-10-24 04:54:22 +00001807 default:
1808 assert(false && "Improper second standard conversion");
1809 break;
1810 }
1811
1812 return false;
1813}
1814
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001815Sema::OwningExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
1816 SourceLocation KWLoc,
1817 SourceLocation LParen,
1818 TypeTy *Ty,
1819 SourceLocation RParen) {
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00001820 QualType T = GetTypeFromParser(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00001821
Anders Carlsson1f9648d2009-07-07 19:06:02 +00001822 // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
1823 // all traits except __is_class, __is_enum and __is_union require a the type
1824 // to be complete.
1825 if (OTT != UTT_IsClass && OTT != UTT_IsEnum && OTT != UTT_IsUnion) {
Mike Stump11289f42009-09-09 15:08:12 +00001826 if (RequireCompleteType(KWLoc, T,
Anders Carlsson029fc692009-08-26 22:59:12 +00001827 diag::err_incomplete_type_used_in_type_trait_expr))
Anders Carlsson1f9648d2009-07-07 19:06:02 +00001828 return ExprError();
1829 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001830
1831 // There is no point in eagerly computing the value. The traits are designed
1832 // to be used from type trait templates, so Ty will be a template parameter
1833 // 99% of the time.
Anders Carlsson1f9648d2009-07-07 19:06:02 +00001834 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT, T,
1835 RParen, Context.BoolTy));
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001836}
Sebastian Redl5822f082009-02-07 20:10:22 +00001837
1838QualType Sema::CheckPointerToMemberOperands(
Mike Stump11289f42009-09-09 15:08:12 +00001839 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect) {
Sebastian Redl5822f082009-02-07 20:10:22 +00001840 const char *OpSpelling = isIndirect ? "->*" : ".*";
1841 // C++ 5.5p2
1842 // The binary operator .* [p3: ->*] binds its second operand, which shall
1843 // be of type "pointer to member of T" (where T is a completely-defined
1844 // class type) [...]
1845 QualType RType = rex->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001846 const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
Douglas Gregorac1fb652009-03-24 19:52:54 +00001847 if (!MemPtr) {
Sebastian Redl5822f082009-02-07 20:10:22 +00001848 Diag(Loc, diag::err_bad_memptr_rhs)
1849 << OpSpelling << RType << rex->getSourceRange();
1850 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00001851 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00001852
Sebastian Redl5822f082009-02-07 20:10:22 +00001853 QualType Class(MemPtr->getClass(), 0);
1854
Sebastian Redlc72350e2010-04-10 10:14:54 +00001855 if (RequireCompleteType(Loc, Class, diag::err_memptr_rhs_to_incomplete))
1856 return QualType();
1857
Sebastian Redl5822f082009-02-07 20:10:22 +00001858 // C++ 5.5p2
1859 // [...] to its first operand, which shall be of class T or of a class of
1860 // which T is an unambiguous and accessible base class. [p3: a pointer to
1861 // such a class]
1862 QualType LType = lex->getType();
1863 if (isIndirect) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001864 if (const PointerType *Ptr = LType->getAs<PointerType>())
Sebastian Redl5822f082009-02-07 20:10:22 +00001865 LType = Ptr->getPointeeType().getNonReferenceType();
1866 else {
1867 Diag(Loc, diag::err_bad_memptr_lhs)
Fariborz Jahanian59f64202009-10-26 20:45:27 +00001868 << OpSpelling << 1 << LType
Douglas Gregora771f462010-03-31 17:46:05 +00001869 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl5822f082009-02-07 20:10:22 +00001870 return QualType();
1871 }
1872 }
1873
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001874 if (!Context.hasSameUnqualifiedType(Class, LType)) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001875 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1876 /*DetectVirtual=*/false);
Mike Stump87c57ac2009-05-16 07:39:55 +00001877 // FIXME: Would it be useful to print full ambiguity paths, or is that
1878 // overkill?
Sebastian Redl5822f082009-02-07 20:10:22 +00001879 if (!IsDerivedFrom(LType, Class, Paths) ||
1880 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
1881 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Eli Friedman1fcf66b2010-01-16 00:00:48 +00001882 << (int)isIndirect << lex->getType();
Sebastian Redl5822f082009-02-07 20:10:22 +00001883 return QualType();
1884 }
Eli Friedman1fcf66b2010-01-16 00:00:48 +00001885 // Cast LHS to type of use.
1886 QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
1887 bool isLValue = !isIndirect && lex->isLvalue(Context) == Expr::LV_Valid;
1888 ImpCastExprToType(lex, UseType, CastExpr::CK_DerivedToBase, isLValue);
Sebastian Redl5822f082009-02-07 20:10:22 +00001889 }
1890
Fariborz Jahanianfff3fb22009-11-18 22:16:17 +00001891 if (isa<CXXZeroInitValueExpr>(rex->IgnoreParens())) {
Fariborz Jahanian1bc0f9a2009-11-18 21:54:48 +00001892 // Diagnose use of pointer-to-member type which when used as
1893 // the functional cast in a pointer-to-member expression.
1894 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
1895 return QualType();
1896 }
Sebastian Redl5822f082009-02-07 20:10:22 +00001897 // C++ 5.5p2
1898 // The result is an object or a function of the type specified by the
1899 // second operand.
1900 // The cv qualifiers are the union of those in the pointer and the left side,
1901 // in accordance with 5.5p5 and 5.2.5.
1902 // FIXME: This returns a dereferenced member function pointer as a normal
1903 // function type. However, the only operation valid on such functions is
Mike Stump87c57ac2009-05-16 07:39:55 +00001904 // calling them. There's also a GCC extension to get a function pointer to the
1905 // thing, which is another complication, because this type - unlike the type
1906 // that is the result of this expression - takes the class as the first
Sebastian Redl5822f082009-02-07 20:10:22 +00001907 // argument.
1908 // We probably need a "MemberFunctionClosureType" or something like that.
1909 QualType Result = MemPtr->getPointeeType();
John McCall8ccfcb52009-09-24 19:53:00 +00001910 Result = Context.getCVRQualifiedType(Result, LType.getCVRQualifiers());
Sebastian Redl5822f082009-02-07 20:10:22 +00001911 return Result;
1912}
Sebastian Redl1a99f442009-04-16 17:51:27 +00001913
Sebastian Redl1a99f442009-04-16 17:51:27 +00001914/// \brief Try to convert a type to another according to C++0x 5.16p3.
1915///
1916/// This is part of the parameter validation for the ? operator. If either
1917/// value operand is a class type, the two operands are attempted to be
1918/// converted to each other. This function does the conversion in one direction.
Douglas Gregor838fcc32010-03-26 20:14:36 +00001919/// It returns true if the program is ill-formed and has already been diagnosed
1920/// as such.
Sebastian Redl1a99f442009-04-16 17:51:27 +00001921static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
1922 SourceLocation QuestionLoc,
Douglas Gregor838fcc32010-03-26 20:14:36 +00001923 bool &HaveConversion,
1924 QualType &ToType) {
1925 HaveConversion = false;
1926 ToType = To->getType();
1927
1928 InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
1929 SourceLocation());
Sebastian Redl1a99f442009-04-16 17:51:27 +00001930 // C++0x 5.16p3
1931 // The process for determining whether an operand expression E1 of type T1
1932 // can be converted to match an operand expression E2 of type T2 is defined
1933 // as follows:
1934 // -- If E2 is an lvalue:
Douglas Gregorf9edf802010-03-26 20:59:55 +00001935 bool ToIsLvalue = (To->isLvalue(Self.Context) == Expr::LV_Valid);
1936 if (ToIsLvalue) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00001937 // E1 can be converted to match E2 if E1 can be implicitly converted to
1938 // type "lvalue reference to T2", subject to the constraint that in the
1939 // conversion the reference must bind directly to E1.
Douglas Gregor838fcc32010-03-26 20:14:36 +00001940 QualType T = Self.Context.getLValueReferenceType(ToType);
1941 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
1942
1943 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
1944 if (InitSeq.isDirectReferenceBinding()) {
1945 ToType = T;
1946 HaveConversion = true;
1947 return false;
Sebastian Redl1a99f442009-04-16 17:51:27 +00001948 }
Douglas Gregor838fcc32010-03-26 20:14:36 +00001949
1950 if (InitSeq.isAmbiguous())
1951 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
Sebastian Redl1a99f442009-04-16 17:51:27 +00001952 }
John McCall65eb8792010-02-25 01:37:24 +00001953
Sebastian Redl1a99f442009-04-16 17:51:27 +00001954 // -- If E2 is an rvalue, or if the conversion above cannot be done:
1955 // -- if E1 and E2 have class type, and the underlying class types are
1956 // the same or one is a base class of the other:
1957 QualType FTy = From->getType();
1958 QualType TTy = To->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001959 const RecordType *FRec = FTy->getAs<RecordType>();
1960 const RecordType *TRec = TTy->getAs<RecordType>();
Douglas Gregor838fcc32010-03-26 20:14:36 +00001961 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
1962 Self.IsDerivedFrom(FTy, TTy);
1963 if (FRec && TRec &&
1964 (FRec == TRec || FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00001965 // E1 can be converted to match E2 if the class of T2 is the
1966 // same type as, or a base class of, the class of T1, and
1967 // [cv2 > cv1].
John McCall65eb8792010-02-25 01:37:24 +00001968 if (FRec == TRec || FDerivedFromT) {
1969 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00001970 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
1971 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
1972 if (InitSeq.getKind() != InitializationSequence::FailedSequence) {
1973 HaveConversion = true;
1974 return false;
1975 }
1976
1977 if (InitSeq.isAmbiguous())
1978 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
1979 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00001980 }
Douglas Gregor838fcc32010-03-26 20:14:36 +00001981
1982 return false;
Sebastian Redl1a99f442009-04-16 17:51:27 +00001983 }
Douglas Gregor838fcc32010-03-26 20:14:36 +00001984
1985 // -- Otherwise: E1 can be converted to match E2 if E1 can be
1986 // implicitly converted to the type that expression E2 would have
Douglas Gregorf9edf802010-03-26 20:59:55 +00001987 // if E2 were converted to an rvalue (or the type it has, if E2 is
1988 // an rvalue).
1989 //
1990 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
1991 // to the array-to-pointer or function-to-pointer conversions.
1992 if (!TTy->getAs<TagType>())
1993 TTy = TTy.getUnqualifiedType();
Douglas Gregor838fcc32010-03-26 20:14:36 +00001994
1995 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
1996 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
1997 HaveConversion = InitSeq.getKind() != InitializationSequence::FailedSequence;
1998 ToType = TTy;
1999 if (InitSeq.isAmbiguous())
2000 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
2001
Sebastian Redl1a99f442009-04-16 17:51:27 +00002002 return false;
2003}
2004
2005/// \brief Try to find a common type for two according to C++0x 5.16p5.
2006///
2007/// This is part of the parameter validation for the ? operator. If either
2008/// value operand is a class type, overload resolution is used to find a
2009/// conversion to a common type.
2010static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
2011 SourceLocation Loc) {
2012 Expr *Args[2] = { LHS, RHS };
John McCallbc077cf2010-02-08 23:07:23 +00002013 OverloadCandidateSet CandidateSet(Loc);
Douglas Gregorc02cfe22009-10-21 23:19:44 +00002014 Self.AddBuiltinOperatorCandidates(OO_Conditional, Loc, Args, 2, CandidateSet);
Sebastian Redl1a99f442009-04-16 17:51:27 +00002015
2016 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00002017 switch (Self.BestViableFunction(CandidateSet, Loc, Best)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002018 case OR_Success:
Sebastian Redl1a99f442009-04-16 17:51:27 +00002019 // We found a match. Perform the conversions on the arguments and move on.
2020 if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00002021 Best->Conversions[0], Sema::AA_Converting) ||
Sebastian Redl1a99f442009-04-16 17:51:27 +00002022 Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00002023 Best->Conversions[1], Sema::AA_Converting))
Sebastian Redl1a99f442009-04-16 17:51:27 +00002024 break;
2025 return false;
2026
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002027 case OR_No_Viable_Function:
Sebastian Redl1a99f442009-04-16 17:51:27 +00002028 Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
2029 << LHS->getType() << RHS->getType()
2030 << LHS->getSourceRange() << RHS->getSourceRange();
2031 return true;
2032
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002033 case OR_Ambiguous:
Sebastian Redl1a99f442009-04-16 17:51:27 +00002034 Self.Diag(Loc, diag::err_conditional_ambiguous_ovl)
2035 << LHS->getType() << RHS->getType()
2036 << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stump87c57ac2009-05-16 07:39:55 +00002037 // FIXME: Print the possible common types by printing the return types of
2038 // the viable candidates.
Sebastian Redl1a99f442009-04-16 17:51:27 +00002039 break;
2040
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002041 case OR_Deleted:
Sebastian Redl1a99f442009-04-16 17:51:27 +00002042 assert(false && "Conditional operator has only built-in overloads");
2043 break;
2044 }
2045 return true;
2046}
2047
Sebastian Redl5775af1a2009-04-17 16:30:52 +00002048/// \brief Perform an "extended" implicit conversion as returned by
2049/// TryClassUnification.
Douglas Gregor838fcc32010-03-26 20:14:36 +00002050static bool ConvertForConditional(Sema &Self, Expr *&E, QualType T) {
2051 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
2052 InitializationKind Kind = InitializationKind::CreateCopy(E->getLocStart(),
2053 SourceLocation());
2054 InitializationSequence InitSeq(Self, Entity, Kind, &E, 1);
2055 Sema::OwningExprResult Result = InitSeq.Perform(Self, Entity, Kind,
2056 Sema::MultiExprArg(Self, (void **)&E, 1));
2057 if (Result.isInvalid())
Sebastian Redl5775af1a2009-04-17 16:30:52 +00002058 return true;
Douglas Gregor838fcc32010-03-26 20:14:36 +00002059
2060 E = Result.takeAs<Expr>();
Sebastian Redl5775af1a2009-04-17 16:30:52 +00002061 return false;
2062}
2063
Sebastian Redl1a99f442009-04-16 17:51:27 +00002064/// \brief Check the operands of ?: under C++ semantics.
2065///
2066/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
2067/// extension. In this case, LHS == Cond. (But they're not aliases.)
2068QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
2069 SourceLocation QuestionLoc) {
Mike Stump87c57ac2009-05-16 07:39:55 +00002070 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
2071 // interface pointers.
Sebastian Redl1a99f442009-04-16 17:51:27 +00002072
2073 // C++0x 5.16p1
2074 // The first expression is contextually converted to bool.
2075 if (!Cond->isTypeDependent()) {
2076 if (CheckCXXBooleanCondition(Cond))
2077 return QualType();
2078 }
2079
2080 // Either of the arguments dependent?
2081 if (LHS->isTypeDependent() || RHS->isTypeDependent())
2082 return Context.DependentTy;
2083
John McCall71d8d9b2010-03-11 19:43:18 +00002084 CheckSignCompare(LHS, RHS, QuestionLoc);
John McCall1fa36b72009-11-05 09:23:39 +00002085
Sebastian Redl1a99f442009-04-16 17:51:27 +00002086 // C++0x 5.16p2
2087 // If either the second or the third operand has type (cv) void, ...
2088 QualType LTy = LHS->getType();
2089 QualType RTy = RHS->getType();
2090 bool LVoid = LTy->isVoidType();
2091 bool RVoid = RTy->isVoidType();
2092 if (LVoid || RVoid) {
2093 // ... then the [l2r] conversions are performed on the second and third
2094 // operands ...
Douglas Gregorb92a1562010-02-03 00:27:59 +00002095 DefaultFunctionArrayLvalueConversion(LHS);
2096 DefaultFunctionArrayLvalueConversion(RHS);
Sebastian Redl1a99f442009-04-16 17:51:27 +00002097 LTy = LHS->getType();
2098 RTy = RHS->getType();
2099
2100 // ... and one of the following shall hold:
2101 // -- The second or the third operand (but not both) is a throw-
2102 // expression; the result is of the type of the other and is an rvalue.
2103 bool LThrow = isa<CXXThrowExpr>(LHS);
2104 bool RThrow = isa<CXXThrowExpr>(RHS);
2105 if (LThrow && !RThrow)
2106 return RTy;
2107 if (RThrow && !LThrow)
2108 return LTy;
2109
2110 // -- Both the second and third operands have type void; the result is of
2111 // type void and is an rvalue.
2112 if (LVoid && RVoid)
2113 return Context.VoidTy;
2114
2115 // Neither holds, error.
2116 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
2117 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
2118 << LHS->getSourceRange() << RHS->getSourceRange();
2119 return QualType();
2120 }
2121
2122 // Neither is void.
2123
2124 // C++0x 5.16p3
2125 // Otherwise, if the second and third operand have different types, and
2126 // either has (cv) class type, and attempt is made to convert each of those
2127 // operands to the other.
Douglas Gregor838fcc32010-03-26 20:14:36 +00002128 if (!Context.hasSameType(LTy, RTy) &&
Sebastian Redl1a99f442009-04-16 17:51:27 +00002129 (LTy->isRecordType() || RTy->isRecordType())) {
2130 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
2131 // These return true if a single direction is already ambiguous.
Douglas Gregor838fcc32010-03-26 20:14:36 +00002132 QualType L2RType, R2LType;
2133 bool HaveL2R, HaveR2L;
2134 if (TryClassUnification(*this, LHS, RHS, QuestionLoc, HaveL2R, L2RType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00002135 return QualType();
Douglas Gregor838fcc32010-03-26 20:14:36 +00002136 if (TryClassUnification(*this, RHS, LHS, QuestionLoc, HaveR2L, R2LType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00002137 return QualType();
Douglas Gregor838fcc32010-03-26 20:14:36 +00002138
Sebastian Redl1a99f442009-04-16 17:51:27 +00002139 // If both can be converted, [...] the program is ill-formed.
2140 if (HaveL2R && HaveR2L) {
2141 Diag(QuestionLoc, diag::err_conditional_ambiguous)
2142 << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
2143 return QualType();
2144 }
2145
2146 // If exactly one conversion is possible, that conversion is applied to
2147 // the chosen operand and the converted operands are used in place of the
2148 // original operands for the remainder of this section.
2149 if (HaveL2R) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00002150 if (ConvertForConditional(*this, LHS, L2RType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00002151 return QualType();
2152 LTy = LHS->getType();
2153 } else if (HaveR2L) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00002154 if (ConvertForConditional(*this, RHS, R2LType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00002155 return QualType();
2156 RTy = RHS->getType();
2157 }
2158 }
2159
2160 // C++0x 5.16p4
2161 // If the second and third operands are lvalues and have the same type,
2162 // the result is of that type [...]
Douglas Gregor697a3912010-04-01 22:47:07 +00002163 bool Same = Context.hasSameType(LTy, RTy);
Sebastian Redl1a99f442009-04-16 17:51:27 +00002164 if (Same && LHS->isLvalue(Context) == Expr::LV_Valid &&
2165 RHS->isLvalue(Context) == Expr::LV_Valid)
2166 return LTy;
2167
2168 // C++0x 5.16p5
2169 // Otherwise, the result is an rvalue. If the second and third operands
2170 // do not have the same type, and either has (cv) class type, ...
2171 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
2172 // ... overload resolution is used to determine the conversions (if any)
2173 // to be applied to the operands. If the overload resolution fails, the
2174 // program is ill-formed.
2175 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
2176 return QualType();
2177 }
2178
2179 // C++0x 5.16p6
2180 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
2181 // conversions are performed on the second and third operands.
Douglas Gregorb92a1562010-02-03 00:27:59 +00002182 DefaultFunctionArrayLvalueConversion(LHS);
2183 DefaultFunctionArrayLvalueConversion(RHS);
Sebastian Redl1a99f442009-04-16 17:51:27 +00002184 LTy = LHS->getType();
2185 RTy = RHS->getType();
2186
2187 // After those conversions, one of the following shall hold:
2188 // -- The second and third operands have the same type; the result
2189 // is of that type.
2190 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy))
2191 return LTy;
2192
2193 // -- The second and third operands have arithmetic or enumeration type;
2194 // the usual arithmetic conversions are performed to bring them to a
2195 // common type, and the result is of that type.
2196 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
2197 UsualArithmeticConversions(LHS, RHS);
2198 return LHS->getType();
2199 }
2200
2201 // -- The second and third operands have pointer type, or one has pointer
2202 // type and the other is a null pointer constant; pointer conversions
2203 // and qualification conversions are performed to bring them to their
2204 // composite pointer type. The result is of the composite pointer type.
Eli Friedman81390df2010-01-02 22:56:07 +00002205 // -- The second and third operands have pointer to member type, or one has
2206 // pointer to member type and the other is a null pointer constant;
2207 // pointer to member conversions and qualification conversions are
2208 // performed to bring them to a common type, whose cv-qualification
2209 // shall match the cv-qualification of either the second or the third
2210 // operand. The result is of the common type.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00002211 bool NonStandardCompositeType = false;
2212 QualType Composite = FindCompositePointerType(LHS, RHS,
2213 isSFINAEContext()? 0 : &NonStandardCompositeType);
2214 if (!Composite.isNull()) {
2215 if (NonStandardCompositeType)
2216 Diag(QuestionLoc,
2217 diag::ext_typecheck_cond_incompatible_operands_nonstandard)
2218 << LTy << RTy << Composite
2219 << LHS->getSourceRange() << RHS->getSourceRange();
2220
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002221 return Composite;
Douglas Gregor6f5f6422010-02-25 22:29:57 +00002222 }
Fariborz Jahanian798d2bd2009-12-10 20:46:08 +00002223
Douglas Gregor697a3912010-04-01 22:47:07 +00002224 // Similarly, attempt to find composite type of two objective-c pointers.
Fariborz Jahanian798d2bd2009-12-10 20:46:08 +00002225 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
2226 if (!Composite.isNull())
2227 return Composite;
Sebastian Redl1a99f442009-04-16 17:51:27 +00002228
Sebastian Redl1a99f442009-04-16 17:51:27 +00002229 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
2230 << LHS->getType() << RHS->getType()
2231 << LHS->getSourceRange() << RHS->getSourceRange();
2232 return QualType();
2233}
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002234
2235/// \brief Find a merged pointer type and convert the two expressions to it.
2236///
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002237/// This finds the composite pointer type (or member pointer type) for @p E1
2238/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
2239/// type and returns it.
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002240/// It does not emit diagnostics.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00002241///
2242/// If \p NonStandardCompositeType is non-NULL, then we are permitted to find
2243/// a non-standard (but still sane) composite type to which both expressions
2244/// can be converted. When such a type is chosen, \c *NonStandardCompositeType
2245/// will be set true.
2246QualType Sema::FindCompositePointerType(Expr *&E1, Expr *&E2,
2247 bool *NonStandardCompositeType) {
2248 if (NonStandardCompositeType)
2249 *NonStandardCompositeType = false;
2250
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002251 assert(getLangOptions().CPlusPlus && "This function assumes C++");
2252 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002253
Fariborz Jahanian33e148f2009-12-08 20:04:24 +00002254 if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
2255 !T2->isAnyPointerType() && !T2->isMemberPointerType())
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002256 return QualType();
Sebastian Redl3b7ef5e2009-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 Gregor56751b52009-09-25 04:25:58 +00002263 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-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 Redl3b7ef5e2009-04-19 19:26:31 +00002268 return T2;
2269 }
Douglas Gregor56751b52009-09-25 04:25:58 +00002270 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-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 Redl3b7ef5e2009-04-19 19:26:31 +00002275 return T1;
2276 }
Mike Stump11289f42009-09-09 15:08:12 +00002277
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002278 // Now both have to be pointers or member pointers.
Sebastian Redl658262f2009-11-16 21:03:45 +00002279 if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
2280 (!T2->isPointerType() && !T2->isMemberPointerType()))
Sebastian Redl3b7ef5e2009-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 McCall8ccfcb52009-09-24 19:53:00 +00002293 // FIXME: extended qualifiers?
Sebastian Redl658262f2009-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 Gregor6f5f6422010-02-25 22:29:57 +00002301 unsigned NeedConstBefore = 0;
Douglas Gregorb00b10e2009-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 Gregor6f5f6422010-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 Gregorb00b10e2009-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 Stump11289f42009-09-09 15:08:12 +00002320
Douglas Gregorb00b10e2009-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 Gregor6f5f6422010-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 Gregorb00b10e2009-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 Stump11289f42009-09-09 15:08:12 +00002339
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002340 // FIXME: block pointer types?
Mike Stump11289f42009-09-09 15:08:12 +00002341
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002342 // Cannot unwrap any more types.
2343 break;
2344 } while (true);
Mike Stump11289f42009-09-09 15:08:12 +00002345
Douglas Gregor6f5f6422010-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 Gregorb00b10e2009-08-24 17:42:35 +00002358 // Rewrap the composites as pointers or member pointers with the union CVRs.
Sebastian Redl658262f2009-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 Gregorb00b10e2009-08-24 17:42:35 +00002364 I != E; (void)++I, ++MOC) {
John McCall8ccfcb52009-09-24 19:53:00 +00002365 Qualifiers Quals = Qualifiers::fromCVRMask(*I);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002366 if (MOC->first && MOC->second) {
2367 // Rebuild member pointer type
John McCall8ccfcb52009-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 Gregorb00b10e2009-08-24 17:42:35 +00002374 } else {
2375 // Rebuild pointer type
John McCall8ccfcb52009-09-24 19:53:00 +00002376 Composite1
2377 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
2378 Composite2
2379 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002380 }
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002381 }
2382
Mike Stump11289f42009-09-09 15:08:12 +00002383 ImplicitConversionSequence E1ToC1 =
Anders Carlssonef4c7212009-08-27 17:24:15 +00002384 TryImplicitConversion(E1, Composite1,
2385 /*SuppressUserConversions=*/false,
2386 /*AllowExplicit=*/false,
Anders Carlsson228eea32009-08-28 15:33:32 +00002387 /*ForceRValue=*/false,
2388 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00002389 ImplicitConversionSequence E2ToC1 =
Anders Carlssonef4c7212009-08-27 17:24:15 +00002390 TryImplicitConversion(E2, Composite1,
2391 /*SuppressUserConversions=*/false,
2392 /*AllowExplicit=*/false,
Anders Carlsson228eea32009-08-28 15:33:32 +00002393 /*ForceRValue=*/false,
2394 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00002395
John McCall65eb8792010-02-25 01:37:24 +00002396 bool ToC2Viable = false;
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002397 ImplicitConversionSequence E1ToC2, E2ToC2;
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002398 if (Context.getCanonicalType(Composite1) !=
2399 Context.getCanonicalType(Composite2)) {
Anders Carlssonef4c7212009-08-27 17:24:15 +00002400 E1ToC2 = TryImplicitConversion(E1, Composite2,
2401 /*SuppressUserConversions=*/false,
2402 /*AllowExplicit=*/false,
Anders Carlsson228eea32009-08-28 15:33:32 +00002403 /*ForceRValue=*/false,
2404 /*InOverloadResolution=*/false);
Anders Carlssonef4c7212009-08-27 17:24:15 +00002405 E2ToC2 = TryImplicitConversion(E2, Composite2,
2406 /*SuppressUserConversions=*/false,
2407 /*AllowExplicit=*/false,
Anders Carlsson228eea32009-08-28 15:33:32 +00002408 /*ForceRValue=*/false,
2409 /*InOverloadResolution=*/false);
John McCall65eb8792010-02-25 01:37:24 +00002410 ToC2Viable = !E1ToC2.isBad() && !E2ToC2.isBad();
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002411 }
2412
John McCall0d1da222010-01-12 00:44:57 +00002413 bool ToC1Viable = !E1ToC1.isBad() && !E2ToC1.isBad();
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002414 if (ToC1Viable && !ToC2Viable) {
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00002415 if (!PerformImplicitConversion(E1, Composite1, E1ToC1, Sema::AA_Converting) &&
2416 !PerformImplicitConversion(E2, Composite1, E2ToC1, Sema::AA_Converting))
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002417 return Composite1;
2418 }
2419 if (ToC2Viable && !ToC1Viable) {
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00002420 if (!PerformImplicitConversion(E1, Composite2, E1ToC2, Sema::AA_Converting) &&
2421 !PerformImplicitConversion(E2, Composite2, E2ToC2, Sema::AA_Converting))
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002422 return Composite2;
2423 }
2424 return QualType();
2425}
Anders Carlsson85a307d2009-05-17 18:41:29 +00002426
Anders Carlsson2d4cada2009-05-30 20:36:53 +00002427Sema::OwningExprResult Sema::MaybeBindToTemporary(Expr *E) {
Anders Carlssonf86a8d12009-08-15 23:41:35 +00002428 if (!Context.getLangOptions().CPlusPlus)
2429 return Owned(E);
Mike Stump11289f42009-09-09 15:08:12 +00002430
Douglas Gregor363b1512009-12-24 18:51:59 +00002431 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
2432
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002433 const RecordType *RT = E->getType()->getAs<RecordType>();
Anders Carlsson2d4cada2009-05-30 20:36:53 +00002434 if (!RT)
2435 return Owned(E);
Mike Stump11289f42009-09-09 15:08:12 +00002436
John McCall67da35c2010-02-04 22:26:26 +00002437 // If this is the result of a call expression, our source might
2438 // actually be a reference, in which case we shouldn't bind.
Anders Carlssonaedb46f2009-09-14 01:30:44 +00002439 if (CallExpr *CE = dyn_cast<CallExpr>(E)) {
2440 QualType Ty = CE->getCallee()->getType();
2441 if (const PointerType *PT = Ty->getAs<PointerType>())
2442 Ty = PT->getPointeeType();
Fariborz Jahanianffcfecd2010-02-18 20:31:02 +00002443 else if (const BlockPointerType *BPT = Ty->getAs<BlockPointerType>())
2444 Ty = BPT->getPointeeType();
2445
John McCall9dd450b2009-09-21 23:43:11 +00002446 const FunctionType *FTy = Ty->getAs<FunctionType>();
Anders Carlssonaedb46f2009-09-14 01:30:44 +00002447 if (FTy->getResultType()->isReferenceType())
2448 return Owned(E);
2449 }
John McCall67da35c2010-02-04 22:26:26 +00002450
2451 // That should be enough to guarantee that this type is complete.
2452 // If it has a trivial destructor, we can avoid the extra copy.
2453 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2454 if (RD->hasTrivialDestructor())
2455 return Owned(E);
2456
Mike Stump11289f42009-09-09 15:08:12 +00002457 CXXTemporary *Temp = CXXTemporary::Create(Context,
Anders Carlsson2d4cada2009-05-30 20:36:53 +00002458 RD->getDestructor(Context));
Anders Carlssonc78576e2009-05-30 21:21:49 +00002459 ExprTemporaries.push_back(Temp);
Fariborz Jahanian67828442009-08-03 19:13:25 +00002460 if (CXXDestructorDecl *Destructor =
John McCall8e36d532010-04-07 00:41:46 +00002461 const_cast<CXXDestructorDecl*>(RD->getDestructor(Context))) {
Fariborz Jahanian67828442009-08-03 19:13:25 +00002462 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
John McCall8e36d532010-04-07 00:41:46 +00002463 CheckDestructorAccess(E->getExprLoc(), Destructor,
2464 PDiag(diag::err_access_dtor_temp)
2465 << E->getType());
2466 }
Anders Carlsson2d4cada2009-05-30 20:36:53 +00002467 // FIXME: Add the temporary to the temporaries vector.
2468 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
2469}
2470
Anders Carlsson6e997b22009-12-15 20:51:39 +00002471Expr *Sema::MaybeCreateCXXExprWithTemporaries(Expr *SubExpr) {
Anders Carlssonb3d05d62009-06-05 15:38:08 +00002472 assert(SubExpr && "sub expression can't be null!");
Mike Stump11289f42009-09-09 15:08:12 +00002473
Douglas Gregor580cd4a2009-12-03 17:10:37 +00002474 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
2475 assert(ExprTemporaries.size() >= FirstTemporary);
2476 if (ExprTemporaries.size() == FirstTemporary)
Anders Carlssonb3d05d62009-06-05 15:38:08 +00002477 return SubExpr;
Mike Stump11289f42009-09-09 15:08:12 +00002478
Anders Carlssonb3d05d62009-06-05 15:38:08 +00002479 Expr *E = CXXExprWithTemporaries::Create(Context, SubExpr,
Douglas Gregor580cd4a2009-12-03 17:10:37 +00002480 &ExprTemporaries[FirstTemporary],
Anders Carlsson6e997b22009-12-15 20:51:39 +00002481 ExprTemporaries.size() - FirstTemporary);
Douglas Gregor580cd4a2009-12-03 17:10:37 +00002482 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
2483 ExprTemporaries.end());
Mike Stump11289f42009-09-09 15:08:12 +00002484
Anders Carlssonb3d05d62009-06-05 15:38:08 +00002485 return E;
2486}
2487
Douglas Gregorb6ea6082009-12-22 22:17:25 +00002488Sema::OwningExprResult
2489Sema::MaybeCreateCXXExprWithTemporaries(OwningExprResult SubExpr) {
2490 if (SubExpr.isInvalid())
2491 return ExprError();
2492
2493 return Owned(MaybeCreateCXXExprWithTemporaries(SubExpr.takeAs<Expr>()));
2494}
2495
Anders Carlssonafb2dad2009-12-16 02:09:40 +00002496FullExpr Sema::CreateFullExpr(Expr *SubExpr) {
2497 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
2498 assert(ExprTemporaries.size() >= FirstTemporary);
2499
2500 unsigned NumTemporaries = ExprTemporaries.size() - FirstTemporary;
2501 CXXTemporary **Temporaries =
2502 NumTemporaries == 0 ? 0 : &ExprTemporaries[FirstTemporary];
2503
2504 FullExpr E = FullExpr::Create(Context, SubExpr, Temporaries, NumTemporaries);
2505
2506 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
2507 ExprTemporaries.end());
2508
2509 return E;
2510}
2511
Mike Stump11289f42009-09-09 15:08:12 +00002512Sema::OwningExprResult
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002513Sema::ActOnStartCXXMemberReference(Scope *S, ExprArg Base, SourceLocation OpLoc,
Douglas Gregore610ada2010-02-24 18:44:31 +00002514 tok::TokenKind OpKind, TypeTy *&ObjectType,
2515 bool &MayBePseudoDestructor) {
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002516 // Since this might be a postfix expression, get rid of ParenListExprs.
2517 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
Mike Stump11289f42009-09-09 15:08:12 +00002518
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002519 Expr *BaseExpr = (Expr*)Base.get();
2520 assert(BaseExpr && "no record expansion");
Mike Stump11289f42009-09-09 15:08:12 +00002521
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002522 QualType BaseType = BaseExpr->getType();
Douglas Gregore610ada2010-02-24 18:44:31 +00002523 MayBePseudoDestructor = false;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002524 if (BaseType->isDependentType()) {
Douglas Gregor41127182009-11-04 22:49:18 +00002525 // If we have a pointer to a dependent type and are using the -> operator,
2526 // the object type is the type that the pointer points to. We might still
2527 // have enough information about that type to do something useful.
2528 if (OpKind == tok::arrow)
2529 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
2530 BaseType = Ptr->getPointeeType();
2531
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002532 ObjectType = BaseType.getAsOpaquePtr();
Douglas Gregore610ada2010-02-24 18:44:31 +00002533 MayBePseudoDestructor = true;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002534 return move(Base);
2535 }
Mike Stump11289f42009-09-09 15:08:12 +00002536
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002537 // C++ [over.match.oper]p8:
Mike Stump11289f42009-09-09 15:08:12 +00002538 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002539 // returned, with the original second operand.
2540 if (OpKind == tok::arrow) {
John McCallc1538c02009-09-30 01:01:30 +00002541 // The set of types we've considered so far.
John McCallbd0465b2009-09-30 01:30:54 +00002542 llvm::SmallPtrSet<CanQualType,8> CTypes;
Fariborz Jahanianac3005c2009-09-30 17:46:20 +00002543 llvm::SmallVector<SourceLocation, 8> Locations;
John McCallbd0465b2009-09-30 01:30:54 +00002544 CTypes.insert(Context.getCanonicalType(BaseType));
John McCallc1538c02009-09-30 01:01:30 +00002545
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002546 while (BaseType->isRecordType()) {
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00002547 Base = BuildOverloadedArrowExpr(S, move(Base), OpLoc);
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002548 BaseExpr = (Expr*)Base.get();
2549 if (BaseExpr == NULL)
2550 return ExprError();
Fariborz Jahanianac3005c2009-09-30 17:46:20 +00002551 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(BaseExpr))
Anders Carlssonfbd2d492009-10-13 22:55:59 +00002552 Locations.push_back(OpCall->getDirectCallee()->getLocation());
John McCallc1538c02009-09-30 01:01:30 +00002553 BaseType = BaseExpr->getType();
2554 CanQualType CBaseType = Context.getCanonicalType(BaseType);
John McCallbd0465b2009-09-30 01:30:54 +00002555 if (!CTypes.insert(CBaseType)) {
Fariborz Jahanian10ce9582009-09-30 00:19:41 +00002556 Diag(OpLoc, diag::err_operator_arrow_circular);
Fariborz Jahanianac3005c2009-09-30 17:46:20 +00002557 for (unsigned i = 0; i < Locations.size(); i++)
2558 Diag(Locations[i], diag::note_declared_at);
Fariborz Jahanian10ce9582009-09-30 00:19:41 +00002559 return ExprError();
2560 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002561 }
Mike Stump11289f42009-09-09 15:08:12 +00002562
Douglas Gregore4f764f2009-11-20 19:58:21 +00002563 if (BaseType->isPointerType())
2564 BaseType = BaseType->getPointeeType();
2565 }
Mike Stump11289f42009-09-09 15:08:12 +00002566
2567 // We could end up with various non-record types here, such as extended
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002568 // vector types or Objective-C interfaces. Just return early and let
2569 // ActOnMemberReferenceExpr do the work.
Douglas Gregor2b6ca462009-09-03 21:38:09 +00002570 if (!BaseType->isRecordType()) {
2571 // C++ [basic.lookup.classref]p2:
2572 // [...] If the type of the object expression is of pointer to scalar
2573 // type, the unqualified-id is looked up in the context of the complete
2574 // postfix-expression.
Douglas Gregore610ada2010-02-24 18:44:31 +00002575 //
2576 // This also indicates that we should be parsing a
2577 // pseudo-destructor-name.
Douglas Gregor2b6ca462009-09-03 21:38:09 +00002578 ObjectType = 0;
Douglas Gregore610ada2010-02-24 18:44:31 +00002579 MayBePseudoDestructor = true;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002580 return move(Base);
Douglas Gregor2b6ca462009-09-03 21:38:09 +00002581 }
Mike Stump11289f42009-09-09 15:08:12 +00002582
Douglas Gregor3fad6172009-11-17 05:17:33 +00002583 // The object type must be complete (or dependent).
2584 if (!BaseType->isDependentType() &&
2585 RequireCompleteType(OpLoc, BaseType,
2586 PDiag(diag::err_incomplete_member_access)))
2587 return ExprError();
2588
Douglas Gregor2b6ca462009-09-03 21:38:09 +00002589 // C++ [basic.lookup.classref]p2:
Mike Stump11289f42009-09-09 15:08:12 +00002590 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor3fad6172009-11-17 05:17:33 +00002591 // unqualified-id, and the type of the object expression is of a class
Douglas Gregor2b6ca462009-09-03 21:38:09 +00002592 // type C (or of pointer to a class type C), the unqualified-id is looked
2593 // up in the scope of class C. [...]
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002594 ObjectType = BaseType.getAsOpaquePtr();
Mike Stump11289f42009-09-09 15:08:12 +00002595 return move(Base);
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002596}
2597
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002598Sema::OwningExprResult Sema::DiagnoseDtorReference(SourceLocation NameLoc,
2599 ExprArg MemExpr) {
2600 Expr *E = (Expr *) MemExpr.get();
2601 SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(NameLoc);
2602 Diag(E->getLocStart(), diag::err_dtor_expr_without_call)
2603 << isa<CXXPseudoDestructorExpr>(E)
Douglas Gregora771f462010-03-31 17:46:05 +00002604 << FixItHint::CreateInsertion(ExpectedLParenLoc, "()");
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002605
2606 return ActOnCallExpr(/*Scope*/ 0,
2607 move(MemExpr),
2608 /*LPLoc*/ ExpectedLParenLoc,
2609 Sema::MultiExprArg(*this, 0, 0),
2610 /*CommaLocs*/ 0,
2611 /*RPLoc*/ ExpectedLParenLoc);
2612}
Douglas Gregore610ada2010-02-24 18:44:31 +00002613
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002614Sema::OwningExprResult Sema::BuildPseudoDestructorExpr(ExprArg Base,
2615 SourceLocation OpLoc,
2616 tok::TokenKind OpKind,
2617 const CXXScopeSpec &SS,
Douglas Gregor651fe5e2010-02-24 23:40:28 +00002618 TypeSourceInfo *ScopeTypeInfo,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002619 SourceLocation CCLoc,
Douglas Gregorcdbd5152010-02-24 23:50:37 +00002620 SourceLocation TildeLoc,
Douglas Gregor678f90d2010-02-25 01:56:36 +00002621 PseudoDestructorTypeStorage Destructed,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002622 bool HasTrailingLParen) {
Douglas Gregor678f90d2010-02-25 01:56:36 +00002623 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002624
2625 // C++ [expr.pseudo]p2:
2626 // The left-hand side of the dot operator shall be of scalar type. The
2627 // left-hand side of the arrow operator shall be of pointer to scalar type.
2628 // This scalar type is the object type.
2629 Expr *BaseE = (Expr *)Base.get();
2630 QualType ObjectType = BaseE->getType();
2631 if (OpKind == tok::arrow) {
2632 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
2633 ObjectType = Ptr->getPointeeType();
2634 } else if (!BaseE->isTypeDependent()) {
2635 // The user wrote "p->" when she probably meant "p."; fix it.
2636 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
2637 << ObjectType << true
Douglas Gregora771f462010-03-31 17:46:05 +00002638 << FixItHint::CreateReplacement(OpLoc, ".");
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002639 if (isSFINAEContext())
2640 return ExprError();
2641
2642 OpKind = tok::period;
2643 }
2644 }
2645
2646 if (!ObjectType->isDependentType() && !ObjectType->isScalarType()) {
2647 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
2648 << ObjectType << BaseE->getSourceRange();
2649 return ExprError();
2650 }
2651
2652 // C++ [expr.pseudo]p2:
2653 // [...] The cv-unqualified versions of the object type and of the type
2654 // designated by the pseudo-destructor-name shall be the same type.
Douglas Gregor678f90d2010-02-25 01:56:36 +00002655 if (DestructedTypeInfo) {
2656 QualType DestructedType = DestructedTypeInfo->getType();
2657 SourceLocation DestructedTypeStart
2658 = DestructedTypeInfo->getTypeLoc().getSourceRange().getBegin();
2659 if (!DestructedType->isDependentType() && !ObjectType->isDependentType() &&
2660 !Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
2661 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
2662 << ObjectType << DestructedType << BaseE->getSourceRange()
2663 << DestructedTypeInfo->getTypeLoc().getSourceRange();
2664
2665 // Recover by setting the destructed type to the object type.
2666 DestructedType = ObjectType;
2667 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
2668 DestructedTypeStart);
2669 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
2670 }
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002671 }
Douglas Gregor678f90d2010-02-25 01:56:36 +00002672
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002673 // C++ [expr.pseudo]p2:
2674 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
2675 // form
2676 //
2677 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
2678 //
2679 // shall designate the same scalar type.
2680 if (ScopeTypeInfo) {
2681 QualType ScopeType = ScopeTypeInfo->getType();
2682 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
2683 !Context.hasSameType(ScopeType, ObjectType)) {
2684
2685 Diag(ScopeTypeInfo->getTypeLoc().getSourceRange().getBegin(),
2686 diag::err_pseudo_dtor_type_mismatch)
2687 << ObjectType << ScopeType << BaseE->getSourceRange()
2688 << ScopeTypeInfo->getTypeLoc().getSourceRange();
2689
2690 ScopeType = QualType();
2691 ScopeTypeInfo = 0;
2692 }
2693 }
2694
2695 OwningExprResult Result
2696 = Owned(new (Context) CXXPseudoDestructorExpr(Context,
2697 Base.takeAs<Expr>(),
2698 OpKind == tok::arrow,
2699 OpLoc,
2700 (NestedNameSpecifier *) SS.getScopeRep(),
2701 SS.getRange(),
2702 ScopeTypeInfo,
2703 CCLoc,
Douglas Gregorcdbd5152010-02-24 23:50:37 +00002704 TildeLoc,
Douglas Gregor678f90d2010-02-25 01:56:36 +00002705 Destructed));
2706
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002707 if (HasTrailingLParen)
2708 return move(Result);
2709
Douglas Gregor678f90d2010-02-25 01:56:36 +00002710 return DiagnoseDtorReference(Destructed.getLocation(), move(Result));
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002711}
2712
2713Sema::OwningExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, ExprArg Base,
2714 SourceLocation OpLoc,
2715 tok::TokenKind OpKind,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00002716 CXXScopeSpec &SS,
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002717 UnqualifiedId &FirstTypeName,
2718 SourceLocation CCLoc,
2719 SourceLocation TildeLoc,
2720 UnqualifiedId &SecondTypeName,
2721 bool HasTrailingLParen) {
2722 assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
2723 FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
2724 "Invalid first type name in pseudo-destructor");
2725 assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
2726 SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
2727 "Invalid second type name in pseudo-destructor");
2728
2729 Expr *BaseE = (Expr *)Base.get();
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002730
2731 // C++ [expr.pseudo]p2:
2732 // The left-hand side of the dot operator shall be of scalar type. The
2733 // left-hand side of the arrow operator shall be of pointer to scalar type.
2734 // This scalar type is the object type.
2735 QualType ObjectType = BaseE->getType();
2736 if (OpKind == tok::arrow) {
2737 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
2738 ObjectType = Ptr->getPointeeType();
Douglas Gregor678f90d2010-02-25 01:56:36 +00002739 } else if (!ObjectType->isDependentType()) {
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002740 // The user wrote "p->" when she probably meant "p."; fix it.
2741 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
Douglas Gregor678f90d2010-02-25 01:56:36 +00002742 << ObjectType << true
Douglas Gregora771f462010-03-31 17:46:05 +00002743 << FixItHint::CreateReplacement(OpLoc, ".");
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002744 if (isSFINAEContext())
2745 return ExprError();
2746
2747 OpKind = tok::period;
2748 }
2749 }
Douglas Gregor678f90d2010-02-25 01:56:36 +00002750
2751 // Compute the object type that we should use for name lookup purposes. Only
2752 // record types and dependent types matter.
2753 void *ObjectTypePtrForLookup = 0;
2754 if (!SS.isSet()) {
2755 ObjectTypePtrForLookup = (void *)ObjectType->getAs<RecordType>();
2756 if (!ObjectTypePtrForLookup && ObjectType->isDependentType())
2757 ObjectTypePtrForLookup = Context.DependentTy.getAsOpaquePtr();
2758 }
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002759
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002760 // Convert the name of the type being destructed (following the ~) into a
2761 // type (with source-location information).
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002762 QualType DestructedType;
2763 TypeSourceInfo *DestructedTypeInfo = 0;
Douglas Gregor678f90d2010-02-25 01:56:36 +00002764 PseudoDestructorTypeStorage Destructed;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002765 if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
2766 TypeTy *T = getTypeName(*SecondTypeName.Identifier,
2767 SecondTypeName.StartLocation,
Douglas Gregor678f90d2010-02-25 01:56:36 +00002768 S, &SS, true, ObjectTypePtrForLookup);
2769 if (!T &&
2770 ((SS.isSet() && !computeDeclContext(SS, false)) ||
2771 (!SS.isSet() && ObjectType->isDependentType()))) {
2772 // The name of the type being destroyed is a dependent name, and we
2773 // couldn't find anything useful in scope. Just store the identifier and
2774 // it's location, and we'll perform (qualified) name lookup again at
2775 // template instantiation time.
2776 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
2777 SecondTypeName.StartLocation);
2778 } else if (!T) {
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002779 Diag(SecondTypeName.StartLocation,
2780 diag::err_pseudo_dtor_destructor_non_type)
2781 << SecondTypeName.Identifier << ObjectType;
2782 if (isSFINAEContext())
2783 return ExprError();
2784
2785 // Recover by assuming we had the right type all along.
2786 DestructedType = ObjectType;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002787 } else
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002788 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002789 } else {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002790 // Resolve the template-id to a type.
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002791 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002792 ASTTemplateArgsPtr TemplateArgsPtr(*this,
2793 TemplateId->getTemplateArgs(),
2794 TemplateId->NumArgs);
2795 TypeResult T = ActOnTemplateIdType(TemplateTy::make(TemplateId->Template),
2796 TemplateId->TemplateNameLoc,
2797 TemplateId->LAngleLoc,
2798 TemplateArgsPtr,
2799 TemplateId->RAngleLoc);
2800 if (T.isInvalid() || !T.get()) {
2801 // Recover by assuming we had the right type all along.
2802 DestructedType = ObjectType;
2803 } else
2804 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002805 }
2806
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002807 // If we've performed some kind of recovery, (re-)build the type source
2808 // information.
Douglas Gregor678f90d2010-02-25 01:56:36 +00002809 if (!DestructedType.isNull()) {
2810 if (!DestructedTypeInfo)
2811 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002812 SecondTypeName.StartLocation);
Douglas Gregor678f90d2010-02-25 01:56:36 +00002813 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
2814 }
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002815
2816 // Convert the name of the scope type (the type prior to '::') into a type.
2817 TypeSourceInfo *ScopeTypeInfo = 0;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002818 QualType ScopeType;
2819 if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
2820 FirstTypeName.Identifier) {
2821 if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
2822 TypeTy *T = getTypeName(*FirstTypeName.Identifier,
2823 FirstTypeName.StartLocation,
Douglas Gregor678f90d2010-02-25 01:56:36 +00002824 S, &SS, false, ObjectTypePtrForLookup);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002825 if (!T) {
2826 Diag(FirstTypeName.StartLocation,
2827 diag::err_pseudo_dtor_destructor_non_type)
2828 << FirstTypeName.Identifier << ObjectType;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002829
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002830 if (isSFINAEContext())
2831 return ExprError();
2832
2833 // Just drop this type. It's unnecessary anyway.
2834 ScopeType = QualType();
2835 } else
2836 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002837 } else {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002838 // Resolve the template-id to a type.
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002839 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002840 ASTTemplateArgsPtr TemplateArgsPtr(*this,
2841 TemplateId->getTemplateArgs(),
2842 TemplateId->NumArgs);
2843 TypeResult T = ActOnTemplateIdType(TemplateTy::make(TemplateId->Template),
2844 TemplateId->TemplateNameLoc,
2845 TemplateId->LAngleLoc,
2846 TemplateArgsPtr,
2847 TemplateId->RAngleLoc);
2848 if (T.isInvalid() || !T.get()) {
2849 // Recover by dropping this type.
2850 ScopeType = QualType();
2851 } else
2852 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002853 }
2854 }
Douglas Gregor90ad9222010-02-24 23:02:30 +00002855
2856 if (!ScopeType.isNull() && !ScopeTypeInfo)
2857 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
2858 FirstTypeName.StartLocation);
2859
2860
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002861 return BuildPseudoDestructorExpr(move(Base), OpLoc, OpKind, SS,
Douglas Gregorcdbd5152010-02-24 23:50:37 +00002862 ScopeTypeInfo, CCLoc, TildeLoc,
Douglas Gregor678f90d2010-02-25 01:56:36 +00002863 Destructed, HasTrailingLParen);
Douglas Gregore610ada2010-02-24 18:44:31 +00002864}
2865
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00002866CXXMemberCallExpr *Sema::BuildCXXMemberCallExpr(Expr *Exp,
John McCall16df1e52010-03-30 21:47:33 +00002867 NamedDecl *FoundDecl,
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00002868 CXXMethodDecl *Method) {
John McCall16df1e52010-03-30 21:47:33 +00002869 if (PerformObjectArgumentInitialization(Exp, /*Qualifier=*/0,
2870 FoundDecl, Method))
Eli Friedmanf7195532009-12-09 04:53:56 +00002871 assert(0 && "Calling BuildCXXMemberCallExpr with invalid call?");
2872
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00002873 MemberExpr *ME =
2874 new (Context) MemberExpr(Exp, /*IsArrow=*/false, Method,
2875 SourceLocation(), Method->getType());
Eli Friedmanf7195532009-12-09 04:53:56 +00002876 QualType ResultType = Method->getResultType().getNonReferenceType();
Douglas Gregor27381f32009-11-23 12:27:39 +00002877 MarkDeclarationReferenced(Exp->getLocStart(), Method);
2878 CXXMemberCallExpr *CE =
2879 new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType,
2880 Exp->getLocEnd());
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00002881 return CE;
2882}
2883
Anders Carlssone9766d52009-09-09 21:33:21 +00002884Sema::OwningExprResult Sema::BuildCXXCastArgument(SourceLocation CastLoc,
2885 QualType Ty,
2886 CastExpr::CastKind Kind,
2887 CXXMethodDecl *Method,
2888 ExprArg Arg) {
2889 Expr *From = Arg.takeAs<Expr>();
2890
2891 switch (Kind) {
2892 default: assert(0 && "Unhandled cast kind!");
2893 case CastExpr::CK_ConstructorConversion: {
Douglas Gregor5d3507d2009-09-09 23:08:42 +00002894 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
2895
2896 if (CompleteConstructorCall(cast<CXXConstructorDecl>(Method),
2897 MultiExprArg(*this, (void **)&From, 1),
2898 CastLoc, ConstructorArgs))
2899 return ExprError();
Anders Carlsson8f741bf2009-10-18 21:20:14 +00002900
2901 OwningExprResult Result =
2902 BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
2903 move_arg(ConstructorArgs));
2904 if (Result.isInvalid())
2905 return ExprError();
2906
2907 return MaybeBindToTemporary(Result.takeAs<Expr>());
Anders Carlssone9766d52009-09-09 21:33:21 +00002908 }
2909
2910 case CastExpr::CK_UserDefinedConversion: {
Anders Carlsson6b2737d2009-09-15 07:42:44 +00002911 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
Eli Friedmanf7195532009-12-09 04:53:56 +00002912
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00002913 // Create an implicit call expr that calls it.
John McCall16df1e52010-03-30 21:47:33 +00002914 // FIXME: pass the FoundDecl for the user-defined conversion here
2915 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(From, Method, Method);
Anders Carlsson8f741bf2009-10-18 21:20:14 +00002916 return MaybeBindToTemporary(CE);
Anders Carlssone9766d52009-09-09 21:33:21 +00002917 }
Anders Carlssone9766d52009-09-09 21:33:21 +00002918 }
2919}
2920
Anders Carlsson85a307d2009-05-17 18:41:29 +00002921Sema::OwningExprResult Sema::ActOnFinishFullExpr(ExprArg Arg) {
2922 Expr *FullExpr = Arg.takeAs<Expr>();
Anders Carlssonb3d05d62009-06-05 15:38:08 +00002923 if (FullExpr)
Anders Carlsson6e997b22009-12-15 20:51:39 +00002924 FullExpr = MaybeCreateCXXExprWithTemporaries(FullExpr);
Anders Carlsson7e3f0e42009-08-25 23:46:41 +00002925
Anders Carlsson85a307d2009-05-17 18:41:29 +00002926 return Owned(FullExpr);
2927}