blob: 5f1eee1f0a581081163954952e3b171961ef460e [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Douglas Gregor20093b42009-12-09 23:02:17 +000015#include "SemaInit.h"
John McCall7d384dd2009-11-18 07:57:50 +000016#include "Lookup.h"
Steve Naroff210679c2007-08-25 14:02:58 +000017#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000018#include "clang/AST/CXXInheritance.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000019#include "clang/AST/ExprCXX.h"
Douglas Gregorb57fb492010-02-24 22:38:50 +000020#include "clang/AST/TypeLoc.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000021#include "clang/Basic/PartialDiagnostic.h"
Sebastian Redlb5a57a62008-12-03 20:26:15 +000022#include "clang/Basic/TargetInfo.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000023#include "clang/Lex/Preprocessor.h"
24#include "clang/Parse/DeclSpec.h"
Douglas Gregord4dca082010-02-24 18:44:31 +000025#include "clang/Parse/Template.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000026#include "llvm/ADT/STLExtras.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000027using namespace clang;
28
Douglas Gregor124b8782010-02-16 19:09:40 +000029Action::TypeTy *Sema::getDestructorName(SourceLocation TildeLoc,
30 IdentifierInfo &II,
31 SourceLocation NameLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +000032 Scope *S, CXXScopeSpec &SS,
Douglas Gregor124b8782010-02-16 19:09:40 +000033 TypeTy *ObjectTypePtr,
34 bool EnteringContext) {
35 // Determine where to perform name lookup.
36
37 // FIXME: This area of the standard is very messy, and the current
38 // wording is rather unclear about which scopes we search for the
39 // destructor name; see core issues 399 and 555. Issue 399 in
40 // particular shows where the current description of destructor name
41 // lookup is completely out of line with existing practice, e.g.,
42 // this appears to be ill-formed:
43 //
44 // namespace N {
45 // template <typename T> struct S {
46 // ~S();
47 // };
48 // }
49 //
50 // void f(N::S<int>* s) {
51 // s->N::S<int>::~S();
52 // }
53 //
Douglas Gregor93649fd2010-02-23 00:15:22 +000054 // See also PR6358 and PR6359.
Douglas Gregor124b8782010-02-16 19:09:40 +000055 QualType SearchType;
56 DeclContext *LookupCtx = 0;
57 bool isDependent = false;
58 bool LookInScope = false;
59
60 // If we have an object type, it's because we are in a
61 // pseudo-destructor-expression or a member access expression, and
62 // we know what type we're looking for.
63 if (ObjectTypePtr)
64 SearchType = GetTypeFromParser(ObjectTypePtr);
65
66 if (SS.isSet()) {
Douglas Gregor93649fd2010-02-23 00:15:22 +000067 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
68
69 bool AlreadySearched = false;
70 bool LookAtPrefix = true;
71 if (!getLangOptions().CPlusPlus0x) {
72 // C++ [basic.lookup.qual]p6:
73 // If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier,
74 // the type-names are looked up as types in the scope designated by the
75 // nested-name-specifier. In a qualified-id of the form:
76 //
77 // ::[opt] nested-name-specifier ̃ class-name
78 //
79 // where the nested-name-specifier designates a namespace scope, and in
80 // a qualified-id of the form:
81 //
82 // ::opt nested-name-specifier class-name :: ̃ class-name
83 //
84 // the class-names are looked up as types in the scope designated by
85 // the nested-name-specifier.
86 //
87 // Here, we check the first case (completely) and determine whether the
88 // code below is permitted to look at the prefix of the
89 // nested-name-specifier (as we do in C++0x).
90 DeclContext *DC = computeDeclContext(SS, EnteringContext);
91 if (DC && DC->isFileContext()) {
92 AlreadySearched = true;
93 LookupCtx = DC;
94 isDependent = false;
95 } else if (DC && isa<CXXRecordDecl>(DC))
96 LookAtPrefix = false;
97 }
98
99 // C++0x [basic.lookup.qual]p6:
Douglas Gregor124b8782010-02-16 19:09:40 +0000100 // If a pseudo-destructor-name (5.2.4) contains a
101 // nested-name-specifier, the type-names are looked up as types
102 // in the scope designated by the nested-name-specifier. Similarly, in
Chandler Carruth5e895a82010-02-21 10:19:54 +0000103 // a qualified-id of the form:
Douglas Gregor124b8782010-02-16 19:09:40 +0000104 //
105 // :: [opt] nested-name-specifier[opt] class-name :: ~class-name
106 //
107 // the second class-name is looked up in the same scope as the first.
108 //
Douglas Gregor93649fd2010-02-23 00:15:22 +0000109 // To implement this, we look at the prefix of the
110 // nested-name-specifier we were given, and determine the lookup
111 // context from that.
112 //
113 // We also fold in the second case from the C++03 rules quoted further
114 // above.
115 NestedNameSpecifier *Prefix = 0;
116 if (AlreadySearched) {
117 // Nothing left to do.
118 } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) {
119 CXXScopeSpec PrefixSS;
120 PrefixSS.setScopeRep(Prefix);
121 LookupCtx = computeDeclContext(PrefixSS, EnteringContext);
122 isDependent = isDependentScopeSpecifier(PrefixSS);
123 } else if (getLangOptions().CPlusPlus0x &&
124 (LookupCtx = computeDeclContext(SS, EnteringContext))) {
125 if (!LookupCtx->isTranslationUnit())
126 LookupCtx = LookupCtx->getParent();
127 isDependent = LookupCtx && LookupCtx->isDependentContext();
128 } else if (ObjectTypePtr) {
Douglas Gregor124b8782010-02-16 19:09:40 +0000129 LookupCtx = computeDeclContext(SearchType);
130 isDependent = SearchType->isDependentType();
131 } else {
132 LookupCtx = computeDeclContext(SS, EnteringContext);
Douglas Gregor93649fd2010-02-23 00:15:22 +0000133 isDependent = LookupCtx && LookupCtx->isDependentContext();
Douglas Gregor124b8782010-02-16 19:09:40 +0000134 }
Douglas Gregor93649fd2010-02-23 00:15:22 +0000135
Douglas Gregoredc90502010-02-25 04:46:04 +0000136 LookInScope = false;
Douglas Gregor124b8782010-02-16 19:09:40 +0000137 } else if (ObjectTypePtr) {
138 // C++ [basic.lookup.classref]p3:
139 // If the unqualified-id is ~type-name, the type-name is looked up
140 // in the context of the entire postfix-expression. If the type T
141 // of the object expression is of a class type C, the type-name is
142 // also looked up in the scope of class C. At least one of the
143 // lookups shall find a name that refers to (possibly
144 // cv-qualified) T.
145 LookupCtx = computeDeclContext(SearchType);
146 isDependent = SearchType->isDependentType();
147 assert((isDependent || !SearchType->isIncompleteType()) &&
148 "Caller should have completed object type");
149
150 LookInScope = true;
151 } else {
152 // Perform lookup into the current scope (only).
153 LookInScope = true;
154 }
155
156 LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName);
157 for (unsigned Step = 0; Step != 2; ++Step) {
158 // Look for the name first in the computed lookup context (if we
159 // have one) and, if that fails to find a match, in the sope (if
160 // we're allowed to look there).
161 Found.clear();
162 if (Step == 0 && LookupCtx)
163 LookupQualifiedName(Found, LookupCtx);
Douglas Gregora2e7dd22010-02-25 01:56:36 +0000164 else if (Step == 1 && LookInScope && S)
Douglas Gregor124b8782010-02-16 19:09:40 +0000165 LookupName(Found, S);
166 else
167 continue;
168
169 // FIXME: Should we be suppressing ambiguities here?
170 if (Found.isAmbiguous())
171 return 0;
172
173 if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
174 QualType T = Context.getTypeDeclType(Type);
Douglas Gregor124b8782010-02-16 19:09:40 +0000175
176 if (SearchType.isNull() || SearchType->isDependentType() ||
177 Context.hasSameUnqualifiedType(T, SearchType)) {
178 // We found our type!
179
180 return T.getAsOpaquePtr();
181 }
182 }
183
184 // If the name that we found is a class template name, and it is
185 // the same name as the template name in the last part of the
186 // nested-name-specifier (if present) or the object type, then
187 // this is the destructor for that class.
188 // FIXME: This is a workaround until we get real drafting for core
189 // issue 399, for which there isn't even an obvious direction.
190 if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) {
191 QualType MemberOfType;
192 if (SS.isSet()) {
193 if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) {
194 // Figure out the type of the context, if it has one.
John McCall3cb0ebd2010-03-10 03:28:59 +0000195 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx))
196 MemberOfType = Context.getTypeDeclType(Record);
Douglas Gregor124b8782010-02-16 19:09:40 +0000197 }
198 }
199 if (MemberOfType.isNull())
200 MemberOfType = SearchType;
201
202 if (MemberOfType.isNull())
203 continue;
204
205 // We're referring into a class template specialization. If the
206 // class template we found is the same as the template being
207 // specialized, we found what we are looking for.
208 if (const RecordType *Record = MemberOfType->getAs<RecordType>()) {
209 if (ClassTemplateSpecializationDecl *Spec
210 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
211 if (Spec->getSpecializedTemplate()->getCanonicalDecl() ==
212 Template->getCanonicalDecl())
213 return MemberOfType.getAsOpaquePtr();
214 }
215
216 continue;
217 }
218
219 // We're referring to an unresolved class template
220 // specialization. Determine whether we class template we found
221 // is the same as the template being specialized or, if we don't
222 // know which template is being specialized, that it at least
223 // has the same name.
224 if (const TemplateSpecializationType *SpecType
225 = MemberOfType->getAs<TemplateSpecializationType>()) {
226 TemplateName SpecName = SpecType->getTemplateName();
227
228 // The class template we found is the same template being
229 // specialized.
230 if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) {
231 if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl())
232 return MemberOfType.getAsOpaquePtr();
233
234 continue;
235 }
236
237 // The class template we found has the same name as the
238 // (dependent) template name being specialized.
239 if (DependentTemplateName *DepTemplate
240 = SpecName.getAsDependentTemplateName()) {
241 if (DepTemplate->isIdentifier() &&
242 DepTemplate->getIdentifier() == Template->getIdentifier())
243 return MemberOfType.getAsOpaquePtr();
244
245 continue;
246 }
247 }
248 }
249 }
250
251 if (isDependent) {
252 // We didn't find our type, but that's okay: it's dependent
253 // anyway.
254 NestedNameSpecifier *NNS = 0;
255 SourceRange Range;
256 if (SS.isSet()) {
257 NNS = (NestedNameSpecifier *)SS.getScopeRep();
258 Range = SourceRange(SS.getRange().getBegin(), NameLoc);
259 } else {
260 NNS = NestedNameSpecifier::Create(Context, &II);
261 Range = SourceRange(NameLoc);
262 }
263
264 return CheckTypenameType(NNS, II, Range).getAsOpaquePtr();
265 }
266
267 if (ObjectTypePtr)
268 Diag(NameLoc, diag::err_ident_in_pseudo_dtor_not_a_type)
269 << &II;
270 else
271 Diag(NameLoc, diag::err_destructor_class_name);
272
273 return 0;
274}
275
Sebastian Redlc42e1182008-11-11 11:37:55 +0000276/// ActOnCXXTypeidOfType - Parse typeid( type-id ).
Sebastian Redlf53597f2009-03-15 17:47:39 +0000277Action::OwningExprResult
Sebastian Redlc42e1182008-11-11 11:37:55 +0000278Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
279 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +0000280 if (!StdNamespace)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000281 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000282
Douglas Gregorf57f2072009-12-23 20:51:04 +0000283 if (isType) {
284 // C++ [expr.typeid]p4:
285 // The top-level cv-qualifiers of the lvalue expression or the type-id
286 // that is the operand of typeid are always ignored.
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000287 // FIXME: Preserve type source info.
Douglas Gregorf57f2072009-12-23 20:51:04 +0000288 // FIXME: Preserve the type before we stripped the cv-qualifiers?
Douglas Gregor765ccba2009-12-23 21:06:06 +0000289 QualType T = GetTypeFromParser(TyOrExpr);
290 if (T.isNull())
291 return ExprError();
292
293 // C++ [expr.typeid]p4:
294 // If the type of the type-id is a class type or a reference to a class
295 // type, the class shall be completely-defined.
296 QualType CheckT = T;
297 if (const ReferenceType *RefType = CheckT->getAs<ReferenceType>())
298 CheckT = RefType->getPointeeType();
299
300 if (CheckT->getAs<RecordType>() &&
301 RequireCompleteType(OpLoc, CheckT, diag::err_incomplete_typeid))
302 return ExprError();
303
304 TyOrExpr = T.getUnqualifiedType().getAsOpaquePtr();
Douglas Gregorf57f2072009-12-23 20:51:04 +0000305 }
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000306
Chris Lattner572af492008-11-20 05:51:55 +0000307 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
John McCalla24dc2e2009-11-17 02:14:36 +0000308 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
309 LookupQualifiedName(R, StdNamespace);
John McCall1bcee0a2009-12-02 08:25:40 +0000310 RecordDecl *TypeInfoRecordDecl = R.getAsSingle<RecordDecl>();
Chris Lattner572af492008-11-20 05:51:55 +0000311 if (!TypeInfoRecordDecl)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000312 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Sebastian Redlc42e1182008-11-11 11:37:55 +0000313
314 QualType TypeInfoType = Context.getTypeDeclType(TypeInfoRecordDecl);
315
Douglas Gregorac7610d2009-06-22 20:57:11 +0000316 if (!isType) {
Douglas Gregorac7610d2009-06-22 20:57:11 +0000317 bool isUnevaluatedOperand = true;
318 Expr *E = static_cast<Expr *>(TyOrExpr);
Douglas Gregorf57f2072009-12-23 20:51:04 +0000319 if (E && !E->isTypeDependent()) {
Douglas Gregorac7610d2009-06-22 20:57:11 +0000320 QualType T = E->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000321 if (const RecordType *RecordT = T->getAs<RecordType>()) {
Douglas Gregorac7610d2009-06-22 20:57:11 +0000322 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
Douglas Gregorf57f2072009-12-23 20:51:04 +0000323 // C++ [expr.typeid]p3:
John McCall86ff3082010-02-04 22:26:26 +0000324 // [...] If the type of the expression is a class type, the class
325 // shall be completely-defined.
326 if (RequireCompleteType(OpLoc, T, diag::err_incomplete_typeid))
327 return ExprError();
328
329 // C++ [expr.typeid]p3:
Douglas Gregorf57f2072009-12-23 20:51:04 +0000330 // When typeid is applied to an expression other than an lvalue of a
331 // polymorphic class type [...] [the] expression is an unevaluated
332 // operand. [...]
333 if (RecordD->isPolymorphic() && E->isLvalue(Context) == Expr::LV_Valid)
Douglas Gregorac7610d2009-06-22 20:57:11 +0000334 isUnevaluatedOperand = false;
Douglas Gregorf57f2072009-12-23 20:51:04 +0000335 }
336
337 // C++ [expr.typeid]p4:
338 // [...] If the type of the type-id is a reference to a possibly
339 // cv-qualified type, the result of the typeid expression refers to a
340 // std::type_info object representing the cv-unqualified referenced
341 // type.
342 if (T.hasQualifiers()) {
343 ImpCastExprToType(E, T.getUnqualifiedType(), CastExpr::CK_NoOp,
344 E->isLvalue(Context));
345 TyOrExpr = E;
Douglas Gregorac7610d2009-06-22 20:57:11 +0000346 }
347 }
Mike Stump1eb44332009-09-09 15:08:12 +0000348
Douglas Gregor2afce722009-11-26 00:44:06 +0000349 // If this is an unevaluated operand, clear out the set of
350 // declaration references we have been computing and eliminate any
351 // temporaries introduced in its computation.
Douglas Gregorac7610d2009-06-22 20:57:11 +0000352 if (isUnevaluatedOperand)
Douglas Gregor2afce722009-11-26 00:44:06 +0000353 ExprEvalContexts.back().Context = Unevaluated;
Douglas Gregorac7610d2009-06-22 20:57:11 +0000354 }
Mike Stump1eb44332009-09-09 15:08:12 +0000355
Sebastian Redlf53597f2009-03-15 17:47:39 +0000356 return Owned(new (Context) CXXTypeidExpr(isType, TyOrExpr,
357 TypeInfoType.withConst(),
358 SourceRange(OpLoc, RParenLoc)));
Sebastian Redlc42e1182008-11-11 11:37:55 +0000359}
360
Steve Naroff1b273c42007-09-16 14:56:35 +0000361/// ActOnCXXBoolLiteral - Parse {true,false} literals.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000362Action::OwningExprResult
Steve Naroff1b273c42007-09-16 14:56:35 +0000363Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor2f639b92008-10-24 15:36:09 +0000364 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000365 "Unknown C++ Boolean value!");
Sebastian Redlf53597f2009-03-15 17:47:39 +0000366 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
367 Context.BoolTy, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000368}
Chris Lattner50dd2892008-02-26 00:51:44 +0000369
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000370/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
371Action::OwningExprResult
372Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
373 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
374}
375
Chris Lattner50dd2892008-02-26 00:51:44 +0000376/// ActOnCXXThrow - Parse throw expressions.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000377Action::OwningExprResult
378Sema::ActOnCXXThrow(SourceLocation OpLoc, ExprArg E) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000379 Expr *Ex = E.takeAs<Expr>();
380 if (Ex && !Ex->isTypeDependent() && CheckCXXThrowOperand(OpLoc, Ex))
381 return ExprError();
382 return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc));
383}
384
385/// CheckCXXThrowOperand - Validate the operand of a throw.
386bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *&E) {
387 // C++ [except.throw]p3:
Douglas Gregor154fe982009-12-23 22:04:40 +0000388 // A throw-expression initializes a temporary object, called the exception
389 // object, the type of which is determined by removing any top-level
390 // cv-qualifiers from the static type of the operand of throw and adjusting
391 // the type from "array of T" or "function returning T" to "pointer to T"
392 // or "pointer to function returning T", [...]
393 if (E->getType().hasQualifiers())
394 ImpCastExprToType(E, E->getType().getUnqualifiedType(), CastExpr::CK_NoOp,
395 E->isLvalue(Context) == Expr::LV_Valid);
396
Sebastian Redl972041f2009-04-27 20:27:31 +0000397 DefaultFunctionArrayConversion(E);
398
399 // If the type of the exception would be an incomplete type or a pointer
400 // to an incomplete type other than (cv) void the program is ill-formed.
401 QualType Ty = E->getType();
402 int isPointer = 0;
Ted Kremenek6217b802009-07-29 21:53:49 +0000403 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000404 Ty = Ptr->getPointeeType();
405 isPointer = 1;
406 }
407 if (!isPointer || !Ty->isVoidType()) {
408 if (RequireCompleteType(ThrowLoc, Ty,
Anders Carlssond497ba72009-08-26 22:59:12 +0000409 PDiag(isPointer ? diag::err_throw_incomplete_ptr
410 : diag::err_throw_incomplete)
411 << E->getSourceRange()))
Sebastian Redl972041f2009-04-27 20:27:31 +0000412 return true;
Rafael Espindola7b9a5aa2010-03-02 21:28:26 +0000413
Douglas Gregorbf422f92010-04-15 18:05:39 +0000414 if (RequireNonAbstractType(ThrowLoc, E->getType(),
415 PDiag(diag::err_throw_abstract_type)
416 << E->getSourceRange()))
417 return true;
418
Rafael Espindola7b9a5aa2010-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 Redl972041f2009-04-27 20:27:31 +0000430 }
431
432 // FIXME: Construct a temporary here.
433 return false;
Chris Lattner50dd2892008-02-26 00:51:44 +0000434}
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000435
Sebastian Redlf53597f2009-03-15 17:47:39 +0000436Action::OwningExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
Argyrios Kyrtzidis07952322008-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 Redlf53597f2009-03-15 17:47:39 +0000441 if (!isa<FunctionDecl>(CurContext))
442 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000443
444 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext))
445 if (MD->isInstance())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000446 return Owned(new (Context) CXXThisExpr(ThisLoc,
Douglas Gregor828a1972010-01-07 23:12:05 +0000447 MD->getThisType(Context),
448 /*isImplicit=*/false));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000449
Sebastian Redlf53597f2009-03-15 17:47:39 +0000450 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000451}
Argyrios Kyrtzidis987a14b2008-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 Redlf53597f2009-03-15 17:47:39 +0000457Action::OwningExprResult
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000458Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep,
459 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000460 MultiExprArg exprs,
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000461 SourceLocation *CommaLocs,
462 SourceLocation RParenLoc) {
Douglas Gregorae4c77d2010-02-05 19:11:37 +0000463 if (!TypeRep)
464 return ExprError();
465
John McCall9d125032010-01-15 18:39:57 +0000466 TypeSourceInfo *TInfo;
467 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
468 if (!TInfo)
469 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
Sebastian Redlf53597f2009-03-15 17:47:39 +0000470 unsigned NumExprs = exprs.size();
471 Expr **Exprs = (Expr**)exprs.get();
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000472 SourceLocation TyBeginLoc = TypeRange.getBegin();
473 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
474
Sebastian Redlf53597f2009-03-15 17:47:39 +0000475 if (Ty->isDependentType() ||
Douglas Gregorba498172009-03-13 21:01:28 +0000476 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
Sebastian Redlf53597f2009-03-15 17:47:39 +0000477 exprs.release();
Mike Stump1eb44332009-09-09 15:08:12 +0000478
479 return Owned(CXXUnresolvedConstructExpr::Create(Context,
480 TypeRange.getBegin(), Ty,
Douglas Gregord81e6ca2009-05-20 18:46:25 +0000481 LParenLoc,
482 Exprs, NumExprs,
483 RParenLoc));
Douglas Gregorba498172009-03-13 21:01:28 +0000484 }
485
Anders Carlssonbb60a502009-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 Jahanianf071e9b2009-10-23 21:01:39 +0000494
Anders Carlssonbb60a502009-08-27 03:53:50 +0000495 if (RequireNonAbstractType(TyBeginLoc, Ty,
496 diag::err_allocation_of_abstract_type))
497 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000498
499
Douglas Gregor506ae412009-01-16 18:33:17 +0000500 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-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 Carlssoncdb61972009-08-07 22:21:05 +0000506 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Douglas Gregord6e44a32010-04-16 22:09:46 +0000507 if (CheckCastTypes(TypeRange, Ty, Exprs[0], Kind, /*FunctionalStyle=*/true))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000508 return ExprError();
Anders Carlsson0aebc812009-09-09 21:33:21 +0000509
510 exprs.release();
Anders Carlsson0aebc812009-09-09 21:33:21 +0000511
512 return Owned(new (Context) CXXFunctionalCastExpr(Ty.getNonReferenceType(),
John McCall9d125032010-01-15 18:39:57 +0000513 TInfo, TyBeginLoc, Kind,
Anders Carlsson0aebc812009-09-09 21:33:21 +0000514 Exprs[0], RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000515 }
516
Ted Kremenek6217b802009-07-29 21:53:49 +0000517 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Douglas Gregor506ae412009-01-16 18:33:17 +0000518 CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
Sebastian Redlf53597f2009-03-15 17:47:39 +0000519
Mike Stump1eb44332009-09-09 15:08:12 +0000520 if (NumExprs > 1 || !Record->hasTrivialConstructor() ||
Anders Carlssone7624a72009-08-27 05:08:22 +0000521 !Record->hasTrivialDestructor()) {
Eli Friedman6997aae2010-01-31 20:58:15 +0000522 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty);
523 InitializationKind Kind
524 = NumExprs ? InitializationKind::CreateDirect(TypeRange.getBegin(),
525 LParenLoc, RParenLoc)
526 : InitializationKind::CreateValue(TypeRange.getBegin(),
527 LParenLoc, RParenLoc);
528 InitializationSequence InitSeq(*this, Entity, Kind, Exprs, NumExprs);
529 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
530 move(exprs));
Douglas Gregor506ae412009-01-16 18:33:17 +0000531
Eli Friedman6997aae2010-01-31 20:58:15 +0000532 // FIXME: Improve AST representation?
533 return move(Result);
Douglas Gregor506ae412009-01-16 18:33:17 +0000534 }
535
536 // Fall through to value-initialize an object of class type that
537 // doesn't have a user-declared default constructor.
538 }
539
540 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000541 // If the expression list specifies more than a single value, the type shall
542 // be a class with a suitably declared constructor.
543 //
544 if (NumExprs > 1)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000545 return ExprError(Diag(CommaLocs[0],
546 diag::err_builtin_func_cast_more_than_one_arg)
547 << FullRange);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000548
549 assert(NumExprs == 0 && "Expected 0 expressions");
Douglas Gregor506ae412009-01-16 18:33:17 +0000550 // C++ [expr.type.conv]p2:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000551 // The expression T(), where T is a simple-type-specifier for a non-array
552 // complete object type or the (possibly cv-qualified) void type, creates an
553 // rvalue of the specified type, which is value-initialized.
554 //
Sebastian Redlf53597f2009-03-15 17:47:39 +0000555 exprs.release();
556 return Owned(new (Context) CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000557}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000558
559
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000560/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
561/// @code new (memory) int[size][4] @endcode
562/// or
563/// @code ::new Foo(23, "hello") @endcode
564/// For the interpretation of this heap of arguments, consult the base version.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000565Action::OwningExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000566Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000567 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000568 SourceLocation PlacementRParen, bool ParenTypeId,
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000569 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000570 MultiExprArg ConstructorArgs,
Mike Stump1eb44332009-09-09 15:08:12 +0000571 SourceLocation ConstructorRParen) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000572 Expr *ArraySize = 0;
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000573 // If the specified type is an array, unwrap it and save the expression.
574 if (D.getNumTypeObjects() > 0 &&
575 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
576 DeclaratorChunk &Chunk = D.getTypeObject(0);
577 if (Chunk.Arr.hasStatic)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000578 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
579 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000580 if (!Chunk.Arr.NumElts)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000581 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
582 << D.getSourceRange());
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000583
584 if (ParenTypeId) {
585 // Can't have dynamic array size when the type-id is in parentheses.
586 Expr *NumElts = (Expr *)Chunk.Arr.NumElts;
587 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
588 !NumElts->isIntegerConstantExpr(Context)) {
589 Diag(D.getTypeObject(0).Loc, diag::err_new_paren_array_nonconst)
590 << NumElts->getSourceRange();
591 return ExprError();
592 }
593 }
594
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000595 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000596 D.DropFirstTypeObject();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000597 }
598
Douglas Gregor043cad22009-09-11 00:18:58 +0000599 // Every dimension shall be of constant size.
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000600 if (ArraySize) {
601 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor043cad22009-09-11 00:18:58 +0000602 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
603 break;
604
605 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
606 if (Expr *NumElts = (Expr *)Array.NumElts) {
607 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
608 !NumElts->isIntegerConstantExpr(Context)) {
609 Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst)
610 << NumElts->getSourceRange();
611 return ExprError();
612 }
613 }
614 }
615 }
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000616
John McCalla93c9342009-12-07 02:54:59 +0000617 //FIXME: Store TypeSourceInfo in CXXNew expression.
618 TypeSourceInfo *TInfo = 0;
619 QualType AllocType = GetTypeForDeclarator(D, /*Scope=*/0, &TInfo);
Chris Lattnereaaebc72009-04-25 08:06:05 +0000620 if (D.isInvalidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000621 return ExprError();
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000622
Mike Stump1eb44332009-09-09 15:08:12 +0000623 return BuildCXXNew(StartLoc, UseGlobal,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000624 PlacementLParen,
Mike Stump1eb44332009-09-09 15:08:12 +0000625 move(PlacementArgs),
Douglas Gregor3433cf72009-05-21 00:00:09 +0000626 PlacementRParen,
627 ParenTypeId,
Mike Stump1eb44332009-09-09 15:08:12 +0000628 AllocType,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000629 D.getSourceRange().getBegin(),
630 D.getSourceRange(),
631 Owned(ArraySize),
632 ConstructorLParen,
633 move(ConstructorArgs),
634 ConstructorRParen);
635}
636
Mike Stump1eb44332009-09-09 15:08:12 +0000637Sema::OwningExprResult
Douglas Gregor3433cf72009-05-21 00:00:09 +0000638Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
639 SourceLocation PlacementLParen,
640 MultiExprArg PlacementArgs,
641 SourceLocation PlacementRParen,
Mike Stump1eb44332009-09-09 15:08:12 +0000642 bool ParenTypeId,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000643 QualType AllocType,
644 SourceLocation TypeLoc,
645 SourceRange TypeRange,
646 ExprArg ArraySizeE,
647 SourceLocation ConstructorLParen,
648 MultiExprArg ConstructorArgs,
649 SourceLocation ConstructorRParen) {
650 if (CheckAllocatedType(AllocType, TypeLoc, TypeRange))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000651 return ExprError();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000652
Douglas Gregor3433cf72009-05-21 00:00:09 +0000653 QualType ResultType = Context.getPointerType(AllocType);
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000654
655 // That every array dimension except the first is constant was already
656 // checked by the type check above.
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000657
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000658 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
659 // or enumeration type with a non-negative value."
Douglas Gregor3433cf72009-05-21 00:00:09 +0000660 Expr *ArraySize = (Expr *)ArraySizeE.get();
Sebastian Redl28507842009-02-26 14:39:58 +0000661 if (ArraySize && !ArraySize->isTypeDependent()) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000662 QualType SizeType = ArraySize->getType();
663 if (!SizeType->isIntegralType() && !SizeType->isEnumeralType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000664 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
665 diag::err_array_size_not_integral)
666 << SizeType << ArraySize->getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000667 // Let's see if this is a constant < 0. If so, we reject it out of hand.
668 // We don't care about special rules, so we tell the machinery it's not
669 // evaluated - it gives us a result in more cases.
Sebastian Redl28507842009-02-26 14:39:58 +0000670 if (!ArraySize->isValueDependent()) {
671 llvm::APSInt Value;
672 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
673 if (Value < llvm::APSInt(
Anders Carlssonac18b2e2009-09-23 00:37:25 +0000674 llvm::APInt::getNullValue(Value.getBitWidth()),
675 Value.isUnsigned()))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000676 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
677 diag::err_typecheck_negative_array_size)
678 << ArraySize->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +0000679 }
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000680 }
Anders Carlssonac18b2e2009-09-23 00:37:25 +0000681
Eli Friedman73c39ab2009-10-20 08:27:19 +0000682 ImpCastExprToType(ArraySize, Context.getSizeType(),
683 CastExpr::CK_IntegralCast);
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000684 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000685
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000686 FunctionDecl *OperatorNew = 0;
687 FunctionDecl *OperatorDelete = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000688 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
689 unsigned NumPlaceArgs = PlacementArgs.size();
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000690
Sebastian Redl28507842009-02-26 14:39:58 +0000691 if (!AllocType->isDependentType() &&
692 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
693 FindAllocationFunctions(StartLoc,
Sebastian Redl00e68e22009-02-09 18:24:27 +0000694 SourceRange(PlacementLParen, PlacementRParen),
695 UseGlobal, AllocType, ArraySize, PlaceArgs,
696 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000697 return ExprError();
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000698 llvm::SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000699 if (OperatorNew) {
700 // Add default arguments, if any.
701 const FunctionProtoType *Proto =
702 OperatorNew->getType()->getAs<FunctionProtoType>();
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +0000703 VariadicCallType CallType =
704 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000705 bool Invalid = GatherArgumentsForCall(PlacementLParen, OperatorNew,
706 Proto, 1, PlaceArgs, NumPlaceArgs,
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +0000707 AllPlaceArgs, CallType);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000708 if (Invalid)
709 return ExprError();
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000710
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000711 NumPlaceArgs = AllPlaceArgs.size();
712 if (NumPlaceArgs > 0)
713 PlaceArgs = &AllPlaceArgs[0];
714 }
715
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000716 bool Init = ConstructorLParen.isValid();
717 // --- Choosing a constructor ---
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000718 CXXConstructorDecl *Constructor = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000719 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
720 unsigned NumConsArgs = ConstructorArgs.size();
Eli Friedmana8ce9ec2009-11-08 22:15:39 +0000721 ASTOwningVector<&ActionBase::DeleteExpr> ConvertedConstructorArgs(*this);
722
Douglas Gregor99a2e602009-12-16 01:38:02 +0000723 if (!AllocType->isDependentType() &&
724 !Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) {
725 // C++0x [expr.new]p15:
726 // A new-expression that creates an object of type T initializes that
727 // object as follows:
728 InitializationKind Kind
729 // - If the new-initializer is omitted, the object is default-
730 // initialized (8.5); if no initialization is performed,
731 // the object has indeterminate value
732 = !Init? InitializationKind::CreateDefault(TypeLoc)
733 // - Otherwise, the new-initializer is interpreted according to the
734 // initialization rules of 8.5 for direct-initialization.
735 : InitializationKind::CreateDirect(TypeLoc,
736 ConstructorLParen,
737 ConstructorRParen);
738
Douglas Gregor99a2e602009-12-16 01:38:02 +0000739 InitializedEntity Entity
Douglas Gregord6542d82009-12-22 15:35:07 +0000740 = InitializedEntity::InitializeNew(StartLoc, AllocType);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000741 InitializationSequence InitSeq(*this, Entity, Kind, ConsArgs, NumConsArgs);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000742 OwningExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
743 move(ConstructorArgs));
744 if (FullInit.isInvalid())
745 return ExprError();
746
747 // FullInit is our initializer; walk through it to determine if it's a
748 // constructor call, which CXXNewExpr handles directly.
749 if (Expr *FullInitExpr = (Expr *)FullInit.get()) {
750 if (CXXBindTemporaryExpr *Binder
751 = dyn_cast<CXXBindTemporaryExpr>(FullInitExpr))
752 FullInitExpr = Binder->getSubExpr();
753 if (CXXConstructExpr *Construct
754 = dyn_cast<CXXConstructExpr>(FullInitExpr)) {
755 Constructor = Construct->getConstructor();
756 for (CXXConstructExpr::arg_iterator A = Construct->arg_begin(),
757 AEnd = Construct->arg_end();
758 A != AEnd; ++A)
759 ConvertedConstructorArgs.push_back(A->Retain());
760 } else {
761 // Take the converted initializer.
762 ConvertedConstructorArgs.push_back(FullInit.release());
763 }
764 } else {
765 // No initialization required.
766 }
767
768 // Take the converted arguments and use them for the new expression.
Douglas Gregor39da0b82009-09-09 23:08:42 +0000769 NumConsArgs = ConvertedConstructorArgs.size();
770 ConsArgs = (Expr **)ConvertedConstructorArgs.take();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000771 }
Douglas Gregor99a2e602009-12-16 01:38:02 +0000772
Douglas Gregor6d908702010-02-26 05:06:18 +0000773 // Mark the new and delete operators as referenced.
774 if (OperatorNew)
775 MarkDeclarationReferenced(StartLoc, OperatorNew);
776 if (OperatorDelete)
777 MarkDeclarationReferenced(StartLoc, OperatorDelete);
778
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000779 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
Douglas Gregor089407b2009-10-17 21:40:42 +0000780
Sebastian Redlf53597f2009-03-15 17:47:39 +0000781 PlacementArgs.release();
782 ConstructorArgs.release();
Douglas Gregor3433cf72009-05-21 00:00:09 +0000783 ArraySizeE.release();
Ted Kremenekad7fe862010-02-11 22:51:03 +0000784 return Owned(new (Context) CXXNewExpr(Context, UseGlobal, OperatorNew,
785 PlaceArgs, NumPlaceArgs, ParenTypeId,
786 ArraySize, Constructor, Init,
787 ConsArgs, NumConsArgs, OperatorDelete,
788 ResultType, StartLoc,
789 Init ? ConstructorRParen :
790 SourceLocation()));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000791}
792
793/// CheckAllocatedType - Checks that a type is suitable as the allocated type
794/// in a new-expression.
795/// dimension off and stores the size expression in ArraySize.
Douglas Gregor3433cf72009-05-21 00:00:09 +0000796bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +0000797 SourceRange R) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000798 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
799 // abstract class type or array thereof.
Douglas Gregore7450f52009-03-24 19:52:54 +0000800 if (AllocType->isFunctionType())
Douglas Gregor3433cf72009-05-21 00:00:09 +0000801 return Diag(Loc, diag::err_bad_new_type)
802 << AllocType << 0 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +0000803 else if (AllocType->isReferenceType())
Douglas Gregor3433cf72009-05-21 00:00:09 +0000804 return Diag(Loc, diag::err_bad_new_type)
805 << AllocType << 1 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +0000806 else if (!AllocType->isDependentType() &&
Douglas Gregor3433cf72009-05-21 00:00:09 +0000807 RequireCompleteType(Loc, AllocType,
Anders Carlssonb7906612009-08-26 23:45:07 +0000808 PDiag(diag::err_new_incomplete_type)
809 << R))
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000810 return true;
Douglas Gregor3433cf72009-05-21 00:00:09 +0000811 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregore7450f52009-03-24 19:52:54 +0000812 diag::err_allocation_of_abstract_type))
813 return true;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000814
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000815 return false;
816}
817
Douglas Gregor6d908702010-02-26 05:06:18 +0000818/// \brief Determine whether the given function is a non-placement
819/// deallocation function.
820static bool isNonPlacementDeallocationFunction(FunctionDecl *FD) {
821 if (FD->isInvalidDecl())
822 return false;
823
824 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
825 return Method->isUsualDeallocationFunction();
826
827 return ((FD->getOverloadedOperator() == OO_Delete ||
828 FD->getOverloadedOperator() == OO_Array_Delete) &&
829 FD->getNumParams() == 1);
830}
831
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000832/// FindAllocationFunctions - Finds the overloads of operator new and delete
833/// that are appropriate for the allocation.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000834bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
835 bool UseGlobal, QualType AllocType,
836 bool IsArray, Expr **PlaceArgs,
837 unsigned NumPlaceArgs,
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000838 FunctionDecl *&OperatorNew,
Mike Stump1eb44332009-09-09 15:08:12 +0000839 FunctionDecl *&OperatorDelete) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000840 // --- Choosing an allocation function ---
841 // C++ 5.3.4p8 - 14 & 18
842 // 1) If UseGlobal is true, only look in the global scope. Else, also look
843 // in the scope of the allocated class.
844 // 2) If an array size is given, look for operator new[], else look for
845 // operator new.
846 // 3) The first argument is always size_t. Append the arguments from the
847 // placement form.
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000848
849 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
850 // We don't care about the actual value of this argument.
851 // FIXME: Should the Sema create the expression and embed it in the syntax
852 // tree? Or should the consumer just recalculate the value?
Anders Carlssond67c4c32009-08-16 20:29:29 +0000853 IntegerLiteral Size(llvm::APInt::getNullValue(
854 Context.Target.getPointerWidth(0)),
855 Context.getSizeType(),
856 SourceLocation());
857 AllocArgs[0] = &Size;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000858 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
859
Douglas Gregor6d908702010-02-26 05:06:18 +0000860 // C++ [expr.new]p8:
861 // If the allocated type is a non-array type, the allocation
862 // function’s name is operator new and the deallocation function’s
863 // name is operator delete. If the allocated type is an array
864 // type, the allocation function’s name is operator new[] and the
865 // deallocation function’s name is operator delete[].
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000866 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
867 IsArray ? OO_Array_New : OO_New);
Douglas Gregor6d908702010-02-26 05:06:18 +0000868 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
869 IsArray ? OO_Array_Delete : OO_Delete);
870
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000871 if (AllocType->isRecordType() && !UseGlobal) {
Mike Stump1eb44332009-09-09 15:08:12 +0000872 CXXRecordDecl *Record
Ted Kremenek6217b802009-07-29 21:53:49 +0000873 = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl());
Sebastian Redl00e68e22009-02-09 18:24:27 +0000874 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000875 AllocArgs.size(), Record, /*AllowMissing=*/true,
876 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000877 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000878 }
879 if (!OperatorNew) {
880 // Didn't find a member overload. Look for a global one.
881 DeclareGlobalNewDelete();
Sebastian Redl7f662392008-12-04 22:20:51 +0000882 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl00e68e22009-02-09 18:24:27 +0000883 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000884 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
885 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000886 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000887 }
888
John McCall9c82afc2010-04-20 02:18:25 +0000889 // We don't need an operator delete if we're running under
890 // -fno-exceptions.
891 if (!getLangOptions().Exceptions) {
892 OperatorDelete = 0;
893 return false;
894 }
895
Anders Carlssond9583892009-05-31 20:26:12 +0000896 // FindAllocationOverload can change the passed in arguments, so we need to
897 // copy them back.
898 if (NumPlaceArgs > 0)
899 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
Mike Stump1eb44332009-09-09 15:08:12 +0000900
Douglas Gregor6d908702010-02-26 05:06:18 +0000901 // C++ [expr.new]p19:
902 //
903 // If the new-expression begins with a unary :: operator, the
904 // deallocation function’s name is looked up in the global
905 // scope. Otherwise, if the allocated type is a class type T or an
906 // array thereof, the deallocation function’s name is looked up in
907 // the scope of T. If this lookup fails to find the name, or if
908 // the allocated type is not a class type or array thereof, the
909 // deallocation function’s name is looked up in the global scope.
910 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
911 if (AllocType->isRecordType() && !UseGlobal) {
912 CXXRecordDecl *RD
913 = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl());
914 LookupQualifiedName(FoundDelete, RD);
915 }
John McCall90c8c572010-03-18 08:19:33 +0000916 if (FoundDelete.isAmbiguous())
917 return true; // FIXME: clean up expressions?
Douglas Gregor6d908702010-02-26 05:06:18 +0000918
919 if (FoundDelete.empty()) {
920 DeclareGlobalNewDelete();
921 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
922 }
923
924 FoundDelete.suppressDiagnostics();
John McCall9aa472c2010-03-19 07:35:19 +0000925
926 llvm::SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
927
John McCall90c8c572010-03-18 08:19:33 +0000928 if (NumPlaceArgs > 0) {
Douglas Gregor6d908702010-02-26 05:06:18 +0000929 // C++ [expr.new]p20:
930 // A declaration of a placement deallocation function matches the
931 // declaration of a placement allocation function if it has the
932 // same number of parameters and, after parameter transformations
933 // (8.3.5), all parameter types except the first are
934 // identical. [...]
935 //
936 // To perform this comparison, we compute the function type that
937 // the deallocation function should have, and use that type both
938 // for template argument deduction and for comparison purposes.
939 QualType ExpectedFunctionType;
940 {
941 const FunctionProtoType *Proto
942 = OperatorNew->getType()->getAs<FunctionProtoType>();
943 llvm::SmallVector<QualType, 4> ArgTypes;
944 ArgTypes.push_back(Context.VoidPtrTy);
945 for (unsigned I = 1, N = Proto->getNumArgs(); I < N; ++I)
946 ArgTypes.push_back(Proto->getArgType(I));
947
948 ExpectedFunctionType
949 = Context.getFunctionType(Context.VoidTy, ArgTypes.data(),
950 ArgTypes.size(),
951 Proto->isVariadic(),
Rafael Espindola264ba482010-03-30 20:24:48 +0000952 0, false, false, 0, 0,
953 FunctionType::ExtInfo());
Douglas Gregor6d908702010-02-26 05:06:18 +0000954 }
955
956 for (LookupResult::iterator D = FoundDelete.begin(),
957 DEnd = FoundDelete.end();
958 D != DEnd; ++D) {
959 FunctionDecl *Fn = 0;
960 if (FunctionTemplateDecl *FnTmpl
961 = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
962 // Perform template argument deduction to try to match the
963 // expected function type.
964 TemplateDeductionInfo Info(Context, StartLoc);
965 if (DeduceTemplateArguments(FnTmpl, 0, ExpectedFunctionType, Fn, Info))
966 continue;
967 } else
968 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
969
970 if (Context.hasSameType(Fn->getType(), ExpectedFunctionType))
John McCall9aa472c2010-03-19 07:35:19 +0000971 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6d908702010-02-26 05:06:18 +0000972 }
973 } else {
974 // C++ [expr.new]p20:
975 // [...] Any non-placement deallocation function matches a
976 // non-placement allocation function. [...]
977 for (LookupResult::iterator D = FoundDelete.begin(),
978 DEnd = FoundDelete.end();
979 D != DEnd; ++D) {
980 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>((*D)->getUnderlyingDecl()))
981 if (isNonPlacementDeallocationFunction(Fn))
John McCall9aa472c2010-03-19 07:35:19 +0000982 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6d908702010-02-26 05:06:18 +0000983 }
984 }
985
986 // C++ [expr.new]p20:
987 // [...] If the lookup finds a single matching deallocation
988 // function, that function will be called; otherwise, no
989 // deallocation function will be called.
990 if (Matches.size() == 1) {
John McCall9aa472c2010-03-19 07:35:19 +0000991 OperatorDelete = Matches[0].second;
Douglas Gregor6d908702010-02-26 05:06:18 +0000992
993 // C++0x [expr.new]p20:
994 // If the lookup finds the two-parameter form of a usual
995 // deallocation function (3.7.4.2) and that function, considered
996 // as a placement deallocation function, would have been
997 // selected as a match for the allocation function, the program
998 // is ill-formed.
999 if (NumPlaceArgs && getLangOptions().CPlusPlus0x &&
1000 isNonPlacementDeallocationFunction(OperatorDelete)) {
1001 Diag(StartLoc, diag::err_placement_new_non_placement_delete)
1002 << SourceRange(PlaceArgs[0]->getLocStart(),
1003 PlaceArgs[NumPlaceArgs - 1]->getLocEnd());
1004 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
1005 << DeleteName;
John McCall90c8c572010-03-18 08:19:33 +00001006 } else {
1007 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
John McCall9aa472c2010-03-19 07:35:19 +00001008 Matches[0].first);
Douglas Gregor6d908702010-02-26 05:06:18 +00001009 }
1010 }
1011
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001012 return false;
1013}
1014
Sebastian Redl7f662392008-12-04 22:20:51 +00001015/// FindAllocationOverload - Find an fitting overload for the allocation
1016/// function in the specified scope.
Sebastian Redl00e68e22009-02-09 18:24:27 +00001017bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
1018 DeclarationName Name, Expr** Args,
1019 unsigned NumArgs, DeclContext *Ctx,
Mike Stump1eb44332009-09-09 15:08:12 +00001020 bool AllowMissing, FunctionDecl *&Operator) {
John McCalla24dc2e2009-11-17 02:14:36 +00001021 LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
1022 LookupQualifiedName(R, Ctx);
John McCallf36e02d2009-10-09 21:13:30 +00001023 if (R.empty()) {
Sebastian Redl7f662392008-12-04 22:20:51 +00001024 if (AllowMissing)
1025 return false;
Sebastian Redl7f662392008-12-04 22:20:51 +00001026 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +00001027 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +00001028 }
1029
John McCall90c8c572010-03-18 08:19:33 +00001030 if (R.isAmbiguous())
1031 return true;
1032
1033 R.suppressDiagnostics();
John McCallf36e02d2009-10-09 21:13:30 +00001034
John McCall5769d612010-02-08 23:07:23 +00001035 OverloadCandidateSet Candidates(StartLoc);
Douglas Gregor5d64e5b2009-09-30 00:03:47 +00001036 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
1037 Alloc != AllocEnd; ++Alloc) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001038 // Even member operator new/delete are implicitly treated as
1039 // static, so don't use AddMemberCandidate.
John McCall9aa472c2010-03-19 07:35:19 +00001040 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001041
John McCall9aa472c2010-03-19 07:35:19 +00001042 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
1043 AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001044 /*ExplicitTemplateArgs=*/0, Args, NumArgs,
1045 Candidates,
1046 /*SuppressUserConversions=*/false);
Douglas Gregor90916562009-09-29 18:16:17 +00001047 continue;
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001048 }
1049
John McCall9aa472c2010-03-19 07:35:19 +00001050 FunctionDecl *Fn = cast<FunctionDecl>(D);
1051 AddOverloadCandidate(Fn, Alloc.getPair(), Args, NumArgs, Candidates,
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001052 /*SuppressUserConversions=*/false);
Sebastian Redl7f662392008-12-04 22:20:51 +00001053 }
1054
1055 // Do the resolution.
1056 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00001057 switch(BestViableFunction(Candidates, StartLoc, Best)) {
Sebastian Redl7f662392008-12-04 22:20:51 +00001058 case OR_Success: {
1059 // Got one!
1060 FunctionDecl *FnDecl = Best->Function;
1061 // The first argument is size_t, and the first parameter must be size_t,
1062 // too. This is checked on declaration and can be assumed. (It can't be
1063 // asserted on, though, since invalid decls are left in there.)
John McCall90c8c572010-03-18 08:19:33 +00001064 // Watch out for variadic allocator function.
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00001065 unsigned NumArgsInFnDecl = FnDecl->getNumParams();
1066 for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) {
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001067 OwningExprResult Result
1068 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
1069 FnDecl->getParamDecl(i)),
1070 SourceLocation(),
1071 Owned(Args[i]->Retain()));
1072 if (Result.isInvalid())
Sebastian Redl7f662392008-12-04 22:20:51 +00001073 return true;
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001074
1075 Args[i] = Result.takeAs<Expr>();
Sebastian Redl7f662392008-12-04 22:20:51 +00001076 }
1077 Operator = FnDecl;
John McCall9aa472c2010-03-19 07:35:19 +00001078 CheckAllocationAccess(StartLoc, Range, R.getNamingClass(), Best->FoundDecl);
Sebastian Redl7f662392008-12-04 22:20:51 +00001079 return false;
1080 }
1081
1082 case OR_No_Viable_Function:
Sebastian Redl7f662392008-12-04 22:20:51 +00001083 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +00001084 << Name << Range;
John McCallcbce6062010-01-12 07:18:19 +00001085 PrintOverloadCandidates(Candidates, OCD_AllCandidates, Args, NumArgs);
Sebastian Redl7f662392008-12-04 22:20:51 +00001086 return true;
1087
1088 case OR_Ambiguous:
Sebastian Redl7f662392008-12-04 22:20:51 +00001089 Diag(StartLoc, diag::err_ovl_ambiguous_call)
Sebastian Redl00e68e22009-02-09 18:24:27 +00001090 << Name << Range;
John McCallcbce6062010-01-12 07:18:19 +00001091 PrintOverloadCandidates(Candidates, OCD_ViableCandidates, Args, NumArgs);
Sebastian Redl7f662392008-12-04 22:20:51 +00001092 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001093
1094 case OR_Deleted:
1095 Diag(StartLoc, diag::err_ovl_deleted_call)
1096 << Best->Function->isDeleted()
1097 << Name << Range;
John McCallcbce6062010-01-12 07:18:19 +00001098 PrintOverloadCandidates(Candidates, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001099 return true;
Sebastian Redl7f662392008-12-04 22:20:51 +00001100 }
1101 assert(false && "Unreachable, bad result from BestViableFunction");
1102 return true;
1103}
1104
1105
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001106/// DeclareGlobalNewDelete - Declare the global forms of operator new and
1107/// delete. These are:
1108/// @code
1109/// void* operator new(std::size_t) throw(std::bad_alloc);
1110/// void* operator new[](std::size_t) throw(std::bad_alloc);
1111/// void operator delete(void *) throw();
1112/// void operator delete[](void *) throw();
1113/// @endcode
1114/// Note that the placement and nothrow forms of new are *not* implicitly
1115/// declared. Their use requires including \<new\>.
Mike Stump1eb44332009-09-09 15:08:12 +00001116void Sema::DeclareGlobalNewDelete() {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001117 if (GlobalNewDeleteDeclared)
1118 return;
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001119
1120 // C++ [basic.std.dynamic]p2:
1121 // [...] The following allocation and deallocation functions (18.4) are
1122 // implicitly declared in global scope in each translation unit of a
1123 // program
1124 //
1125 // void* operator new(std::size_t) throw(std::bad_alloc);
1126 // void* operator new[](std::size_t) throw(std::bad_alloc);
1127 // void operator delete(void*) throw();
1128 // void operator delete[](void*) throw();
1129 //
1130 // These implicit declarations introduce only the function names operator
1131 // new, operator new[], operator delete, operator delete[].
1132 //
1133 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
1134 // "std" or "bad_alloc" as necessary to form the exception specification.
1135 // However, we do not make these implicit declarations visible to name
1136 // lookup.
1137 if (!StdNamespace) {
1138 // The "std" namespace has not yet been defined, so build one implicitly.
1139 StdNamespace = NamespaceDecl::Create(Context,
1140 Context.getTranslationUnitDecl(),
1141 SourceLocation(),
1142 &PP.getIdentifierTable().get("std"));
1143 StdNamespace->setImplicit(true);
1144 }
1145
1146 if (!StdBadAlloc) {
1147 // The "std::bad_alloc" class has not yet been declared, so build it
1148 // implicitly.
1149 StdBadAlloc = CXXRecordDecl::Create(Context, TagDecl::TK_class,
1150 StdNamespace,
1151 SourceLocation(),
1152 &PP.getIdentifierTable().get("bad_alloc"),
1153 SourceLocation(), 0);
1154 StdBadAlloc->setImplicit(true);
1155 }
1156
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001157 GlobalNewDeleteDeclared = true;
1158
1159 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
1160 QualType SizeT = Context.getSizeType();
Nuno Lopesfc284482009-12-16 16:59:22 +00001161 bool AssumeSaneOperatorNew = getLangOptions().AssumeSaneOperatorNew;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001162
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001163 DeclareGlobalAllocationFunction(
1164 Context.DeclarationNames.getCXXOperatorName(OO_New),
Nuno Lopesfc284482009-12-16 16:59:22 +00001165 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001166 DeclareGlobalAllocationFunction(
1167 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
Nuno Lopesfc284482009-12-16 16:59:22 +00001168 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001169 DeclareGlobalAllocationFunction(
1170 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
1171 Context.VoidTy, VoidPtr);
1172 DeclareGlobalAllocationFunction(
1173 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
1174 Context.VoidTy, VoidPtr);
1175}
1176
1177/// DeclareGlobalAllocationFunction - Declares a single implicit global
1178/// allocation function if it doesn't already exist.
1179void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Nuno Lopesfc284482009-12-16 16:59:22 +00001180 QualType Return, QualType Argument,
1181 bool AddMallocAttr) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001182 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
1183
1184 // Check if this function is already declared.
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001185 {
Douglas Gregor5cc37092008-12-23 22:05:29 +00001186 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001187 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001188 Alloc != AllocEnd; ++Alloc) {
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001189 // Only look at non-template functions, as it is the predefined,
1190 // non-templated allocation function we are trying to declare here.
1191 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
1192 QualType InitialParamType =
Douglas Gregor6e790ab2009-12-22 23:42:49 +00001193 Context.getCanonicalType(
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001194 Func->getParamDecl(0)->getType().getUnqualifiedType());
1195 // FIXME: Do we need to check for default arguments here?
1196 if (Func->getNumParams() == 1 && InitialParamType == Argument)
1197 return;
1198 }
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001199 }
1200 }
1201
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001202 QualType BadAllocType;
1203 bool HasBadAllocExceptionSpec
1204 = (Name.getCXXOverloadedOperator() == OO_New ||
1205 Name.getCXXOverloadedOperator() == OO_Array_New);
1206 if (HasBadAllocExceptionSpec) {
1207 assert(StdBadAlloc && "Must have std::bad_alloc declared");
1208 BadAllocType = Context.getTypeDeclType(StdBadAlloc);
1209 }
1210
1211 QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0,
1212 true, false,
1213 HasBadAllocExceptionSpec? 1 : 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00001214 &BadAllocType,
1215 FunctionType::ExtInfo());
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001216 FunctionDecl *Alloc =
1217 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001218 FnType, /*TInfo=*/0, FunctionDecl::None,
1219 FunctionDecl::None, false, true);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001220 Alloc->setImplicit();
Nuno Lopesfc284482009-12-16 16:59:22 +00001221
1222 if (AddMallocAttr)
1223 Alloc->addAttr(::new (Context) MallocAttr());
1224
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001225 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
John McCalla93c9342009-12-07 02:54:59 +00001226 0, Argument, /*TInfo=*/0,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001227 VarDecl::None,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001228 VarDecl::None, 0);
Douglas Gregor838db382010-02-11 01:19:42 +00001229 Alloc->setParams(&Param, 1);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001230
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001231 // FIXME: Also add this declaration to the IdentifierResolver, but
1232 // make sure it is at the end of the chain to coincide with the
1233 // global scope.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001234 ((DeclContext *)TUScope->getEntity())->addDecl(Alloc);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001235}
1236
Anders Carlsson78f74552009-11-15 18:45:20 +00001237bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
1238 DeclarationName Name,
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00001239 FunctionDecl* &Operator) {
John McCalla24dc2e2009-11-17 02:14:36 +00001240 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlsson78f74552009-11-15 18:45:20 +00001241 // Try to find operator delete/operator delete[] in class scope.
John McCalla24dc2e2009-11-17 02:14:36 +00001242 LookupQualifiedName(Found, RD);
Anders Carlsson78f74552009-11-15 18:45:20 +00001243
John McCalla24dc2e2009-11-17 02:14:36 +00001244 if (Found.isAmbiguous())
Anders Carlsson78f74552009-11-15 18:45:20 +00001245 return true;
Anders Carlsson78f74552009-11-15 18:45:20 +00001246
1247 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1248 F != FEnd; ++F) {
1249 if (CXXMethodDecl *Delete = dyn_cast<CXXMethodDecl>(*F))
1250 if (Delete->isUsualDeallocationFunction()) {
1251 Operator = Delete;
1252 return false;
1253 }
1254 }
1255
1256 // We did find operator delete/operator delete[] declarations, but
1257 // none of them were suitable.
1258 if (!Found.empty()) {
1259 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
1260 << Name << RD;
1261
1262 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1263 F != FEnd; ++F) {
1264 Diag((*F)->getLocation(),
1265 diag::note_delete_member_function_declared_here)
1266 << Name;
1267 }
1268
1269 return true;
1270 }
1271
1272 // Look for a global declaration.
1273 DeclareGlobalNewDelete();
1274 DeclContext *TUDecl = Context.getTranslationUnitDecl();
1275
1276 CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation());
1277 Expr* DeallocArgs[1];
1278 DeallocArgs[0] = &Null;
1279 if (FindAllocationOverload(StartLoc, SourceRange(), Name,
1280 DeallocArgs, 1, TUDecl, /*AllowMissing=*/false,
1281 Operator))
1282 return true;
1283
1284 assert(Operator && "Did not find a deallocation function!");
1285 return false;
1286}
1287
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001288/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
1289/// @code ::delete ptr; @endcode
1290/// or
1291/// @code delete [] ptr; @endcode
Sebastian Redlf53597f2009-03-15 17:47:39 +00001292Action::OwningExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001293Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
Mike Stump1eb44332009-09-09 15:08:12 +00001294 bool ArrayForm, ExprArg Operand) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001295 // C++ [expr.delete]p1:
1296 // The operand shall have a pointer type, or a class type having a single
1297 // conversion function to a pointer type. The result has type void.
1298 //
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001299 // DR599 amends "pointer type" to "pointer to object type" in both cases.
1300
Anders Carlssond67c4c32009-08-16 20:29:29 +00001301 FunctionDecl *OperatorDelete = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001302
Sebastian Redlf53597f2009-03-15 17:47:39 +00001303 Expr *Ex = (Expr *)Operand.get();
Sebastian Redl28507842009-02-26 14:39:58 +00001304 if (!Ex->isTypeDependent()) {
1305 QualType Type = Ex->getType();
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001306
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001307 if (const RecordType *Record = Type->getAs<RecordType>()) {
John McCall32daa422010-03-31 01:36:47 +00001308 llvm::SmallVector<CXXConversionDecl*, 4> ObjectPtrConversions;
1309
Fariborz Jahanian53462782009-09-11 21:44:33 +00001310 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
John McCall32daa422010-03-31 01:36:47 +00001311 const UnresolvedSetImpl *Conversions = RD->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00001312 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00001313 E = Conversions->end(); I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00001314 NamedDecl *D = I.getDecl();
1315 if (isa<UsingShadowDecl>(D))
1316 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1317
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001318 // Skip over templated conversion functions; they aren't considered.
John McCall32daa422010-03-31 01:36:47 +00001319 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001320 continue;
1321
John McCall32daa422010-03-31 01:36:47 +00001322 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001323
1324 QualType ConvType = Conv->getConversionType().getNonReferenceType();
1325 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
1326 if (ConvPtrType->getPointeeType()->isObjectType())
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001327 ObjectPtrConversions.push_back(Conv);
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001328 }
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001329 if (ObjectPtrConversions.size() == 1) {
1330 // We have a single conversion to a pointer-to-object type. Perform
1331 // that conversion.
John McCall32daa422010-03-31 01:36:47 +00001332 // TODO: don't redo the conversion calculation.
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001333 Operand.release();
John McCall32daa422010-03-31 01:36:47 +00001334 if (!PerformImplicitConversion(Ex,
1335 ObjectPtrConversions.front()->getConversionType(),
Douglas Gregor68647482009-12-16 03:45:30 +00001336 AA_Converting)) {
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001337 Operand = Owned(Ex);
1338 Type = Ex->getType();
1339 }
1340 }
1341 else if (ObjectPtrConversions.size() > 1) {
1342 Diag(StartLoc, diag::err_ambiguous_delete_operand)
1343 << Type << Ex->getSourceRange();
John McCall32daa422010-03-31 01:36:47 +00001344 for (unsigned i= 0; i < ObjectPtrConversions.size(); i++)
1345 NoteOverloadCandidate(ObjectPtrConversions[i]);
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001346 return ExprError();
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001347 }
Sebastian Redl28507842009-02-26 14:39:58 +00001348 }
1349
Sebastian Redlf53597f2009-03-15 17:47:39 +00001350 if (!Type->isPointerType())
1351 return ExprError(Diag(StartLoc, diag::err_delete_operand)
1352 << Type << Ex->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +00001353
Ted Kremenek6217b802009-07-29 21:53:49 +00001354 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Douglas Gregor8dcb29d2009-03-24 20:13:58 +00001355 if (Pointee->isFunctionType() || Pointee->isVoidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +00001356 return ExprError(Diag(StartLoc, diag::err_delete_operand)
1357 << Type << Ex->getSourceRange());
Douglas Gregor8dcb29d2009-03-24 20:13:58 +00001358 else if (!Pointee->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00001359 RequireCompleteType(StartLoc, Pointee,
Anders Carlssonb7906612009-08-26 23:45:07 +00001360 PDiag(diag::warn_delete_incomplete)
1361 << Ex->getSourceRange()))
Douglas Gregor8dcb29d2009-03-24 20:13:58 +00001362 return ExprError();
Sebastian Redl28507842009-02-26 14:39:58 +00001363
Douglas Gregor1070c9f2009-09-29 21:38:53 +00001364 // C++ [expr.delete]p2:
1365 // [Note: a pointer to a const type can be the operand of a
1366 // delete-expression; it is not necessary to cast away the constness
1367 // (5.2.11) of the pointer expression before it is used as the operand
1368 // of the delete-expression. ]
1369 ImpCastExprToType(Ex, Context.getPointerType(Context.VoidTy),
1370 CastExpr::CK_NoOp);
1371
1372 // Update the operand.
1373 Operand.take();
1374 Operand = ExprArg(*this, Ex);
1375
Anders Carlssond67c4c32009-08-16 20:29:29 +00001376 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1377 ArrayForm ? OO_Array_Delete : OO_Delete);
1378
Anders Carlsson78f74552009-11-15 18:45:20 +00001379 if (const RecordType *RT = Pointee->getAs<RecordType>()) {
1380 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1381
1382 if (!UseGlobal &&
1383 FindDeallocationFunction(StartLoc, RD, DeleteName, OperatorDelete))
Anders Carlsson0ba63ea2009-11-14 03:17:38 +00001384 return ExprError();
Anders Carlsson0ba63ea2009-11-14 03:17:38 +00001385
Anders Carlsson78f74552009-11-15 18:45:20 +00001386 if (!RD->hasTrivialDestructor())
1387 if (const CXXDestructorDecl *Dtor = RD->getDestructor(Context))
Mike Stump1eb44332009-09-09 15:08:12 +00001388 MarkDeclarationReferenced(StartLoc,
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001389 const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssond67c4c32009-08-16 20:29:29 +00001390 }
Anders Carlsson78f74552009-11-15 18:45:20 +00001391
Anders Carlssond67c4c32009-08-16 20:29:29 +00001392 if (!OperatorDelete) {
Anders Carlsson78f74552009-11-15 18:45:20 +00001393 // Look for a global declaration.
Anders Carlssond67c4c32009-08-16 20:29:29 +00001394 DeclareGlobalNewDelete();
1395 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001396 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
Douglas Gregor90916562009-09-29 18:16:17 +00001397 &Ex, 1, TUDecl, /*AllowMissing=*/false,
Anders Carlssond67c4c32009-08-16 20:29:29 +00001398 OperatorDelete))
1399 return ExprError();
1400 }
Mike Stump1eb44332009-09-09 15:08:12 +00001401
John McCall9c82afc2010-04-20 02:18:25 +00001402 MarkDeclarationReferenced(StartLoc, OperatorDelete);
1403
Sebastian Redl28507842009-02-26 14:39:58 +00001404 // FIXME: Check access and ambiguity of operator delete and destructor.
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001405 }
1406
Sebastian Redlf53597f2009-03-15 17:47:39 +00001407 Operand.release();
1408 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
Anders Carlssond67c4c32009-08-16 20:29:29 +00001409 OperatorDelete, Ex, StartLoc));
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001410}
1411
Douglas Gregor8cfe5a72009-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 Gregora7605db2009-11-24 16:07:02 +00001427
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001428 return Owned(DeclRefExpr::Create(Context, 0, SourceRange(), ConditionVar,
1429 ConditionVar->getLocation(),
1430 ConditionVar->getType().getNonReferenceType()));
1431}
1432
Argyrios Kyrtzidis59210932008-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 Gregor09f41cf2009-01-14 15:45:31 +00001443 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001444}
Douglas Gregor77a52232008-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 Stump1eb44332009-09-09 15:08:12 +00001450bool
Douglas Gregor77a52232008-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 Kremenek6217b802009-07-29 21:53:49 +00001461 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump1eb44332009-09-09 15:08:12 +00001462 if (const BuiltinType *ToPointeeType
John McCall183700f2009-09-21 23:43:11 +00001463 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregor77a52232008-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 McCall0953e762009-09-24 19:53:00 +00001466 if (!ToPtrType->getPointeeType().hasQualifiers() &&
Douglas Gregor77a52232008-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 Gregor94b1dd22008-10-24 04:54:22 +00001476
Douglas Gregorba70ab62010-04-16 22:17:36 +00001477static Sema::OwningExprResult BuildCXXCastArgument(Sema &S,
1478 SourceLocation CastLoc,
1479 QualType Ty,
1480 CastExpr::CastKind Kind,
1481 CXXMethodDecl *Method,
1482 Sema::ExprArg Arg) {
1483 Expr *From = Arg.takeAs<Expr>();
1484
1485 switch (Kind) {
1486 default: assert(0 && "Unhandled cast kind!");
1487 case CastExpr::CK_ConstructorConversion: {
1488 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(S);
1489
1490 if (S.CompleteConstructorCall(cast<CXXConstructorDecl>(Method),
1491 Sema::MultiExprArg(S, (void **)&From, 1),
1492 CastLoc, ConstructorArgs))
1493 return S.ExprError();
1494
1495 Sema::OwningExprResult Result =
1496 S.BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
1497 move_arg(ConstructorArgs));
1498 if (Result.isInvalid())
1499 return S.ExprError();
1500
1501 return S.MaybeBindToTemporary(Result.takeAs<Expr>());
1502 }
1503
1504 case CastExpr::CK_UserDefinedConversion: {
1505 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
1506
1507 // Create an implicit call expr that calls it.
1508 // FIXME: pass the FoundDecl for the user-defined conversion here
1509 CXXMemberCallExpr *CE = S.BuildCXXMemberCallExpr(From, Method, Method);
1510 return S.MaybeBindToTemporary(CE);
1511 }
1512 }
1513}
1514
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001515/// PerformImplicitConversion - Perform an implicit conversion of the
1516/// expression From to the type ToType using the pre-computed implicit
1517/// conversion sequence ICS. Returns true if there was an error, false
1518/// otherwise. The expression From is replaced with the converted
Douglas Gregor68647482009-12-16 03:45:30 +00001519/// expression. Action is the kind of conversion we're performing,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001520/// used in the error message.
1521bool
1522Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
1523 const ImplicitConversionSequence &ICS,
Douglas Gregor68647482009-12-16 03:45:30 +00001524 AssignmentAction Action, bool IgnoreBaseAccess) {
John McCall1d318332010-01-12 00:44:57 +00001525 switch (ICS.getKind()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001526 case ImplicitConversionSequence::StandardConversion:
Douglas Gregor68647482009-12-16 03:45:30 +00001527 if (PerformImplicitConversion(From, ToType, ICS.Standard, Action,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001528 IgnoreBaseAccess))
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001529 return true;
1530 break;
1531
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001532 case ImplicitConversionSequence::UserDefinedConversion: {
1533
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00001534 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
1535 CastExpr::CastKind CastKind = CastExpr::CK_Unknown;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001536 QualType BeforeToType;
1537 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00001538 CastKind = CastExpr::CK_UserDefinedConversion;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001539
1540 // If the user-defined conversion is specified by a conversion function,
1541 // the initial standard conversion sequence converts the source type to
1542 // the implicit object parameter of the conversion function.
1543 BeforeToType = Context.getTagDeclType(Conv->getParent());
1544 } else if (const CXXConstructorDecl *Ctor =
1545 dyn_cast<CXXConstructorDecl>(FD)) {
Anders Carlsson0aebc812009-09-09 21:33:21 +00001546 CastKind = CastExpr::CK_ConstructorConversion;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001547 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregore44201a2009-11-20 02:31:03 +00001548 if (!ICS.UserDefined.EllipsisConversion) {
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001549 // If the user-defined conversion is specified by a constructor, the
1550 // initial standard conversion sequence converts the source type to the
1551 // type required by the argument of the constructor
Douglas Gregore44201a2009-11-20 02:31:03 +00001552 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
1553 }
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001554 }
Anders Carlsson0aebc812009-09-09 21:33:21 +00001555 else
1556 assert(0 && "Unknown conversion function kind!");
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001557 // Whatch out for elipsis conversion.
Fariborz Jahanian4c0cea22009-11-06 00:55:14 +00001558 if (!ICS.UserDefined.EllipsisConversion) {
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001559 if (PerformImplicitConversion(From, BeforeToType,
Douglas Gregor68647482009-12-16 03:45:30 +00001560 ICS.UserDefined.Before, AA_Converting,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001561 IgnoreBaseAccess))
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001562 return true;
1563 }
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001564
Anders Carlsson0aebc812009-09-09 21:33:21 +00001565 OwningExprResult CastArg
Douglas Gregorba70ab62010-04-16 22:17:36 +00001566 = BuildCXXCastArgument(*this,
1567 From->getLocStart(),
Anders Carlsson0aebc812009-09-09 21:33:21 +00001568 ToType.getNonReferenceType(),
1569 CastKind, cast<CXXMethodDecl>(FD),
1570 Owned(From));
1571
1572 if (CastArg.isInvalid())
1573 return true;
Eli Friedmand8889622009-11-27 04:41:50 +00001574
1575 From = CastArg.takeAs<Expr>();
1576
Eli Friedmand8889622009-11-27 04:41:50 +00001577 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
Douglas Gregor68647482009-12-16 03:45:30 +00001578 AA_Converting, IgnoreBaseAccess);
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001579 }
John McCall1d318332010-01-12 00:44:57 +00001580
1581 case ImplicitConversionSequence::AmbiguousConversion:
1582 DiagnoseAmbiguousConversion(ICS, From->getExprLoc(),
1583 PDiag(diag::err_typecheck_ambiguous_condition)
1584 << From->getSourceRange());
1585 return true;
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001586
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001587 case ImplicitConversionSequence::EllipsisConversion:
1588 assert(false && "Cannot perform an ellipsis conversion");
Douglas Gregor60d62c22008-10-31 16:23:19 +00001589 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001590
1591 case ImplicitConversionSequence::BadConversion:
1592 return true;
1593 }
1594
1595 // Everything went well.
1596 return false;
1597}
1598
1599/// PerformImplicitConversion - Perform an implicit conversion of the
1600/// expression From to the type ToType by following the standard
1601/// conversion sequence SCS. Returns true if there was an error, false
1602/// otherwise. The expression From is replaced with the converted
Douglas Gregor45920e82008-12-19 17:40:08 +00001603/// expression. Flavor is the context in which we're performing this
1604/// conversion, for use in error messages.
Mike Stump1eb44332009-09-09 15:08:12 +00001605bool
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001606Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor45920e82008-12-19 17:40:08 +00001607 const StandardConversionSequence& SCS,
Douglas Gregor68647482009-12-16 03:45:30 +00001608 AssignmentAction Action, bool IgnoreBaseAccess) {
Mike Stump390b4cc2009-05-16 07:39:55 +00001609 // Overall FIXME: we are recomputing too many types here and doing far too
1610 // much extra work. What this means is that we need to keep track of more
1611 // information that is computed when we try the implicit conversion initially,
1612 // so that we don't need to recompute anything here.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001613 QualType FromType = From->getType();
1614
Douglas Gregor225c41e2008-11-03 19:09:14 +00001615 if (SCS.CopyConstructor) {
Anders Carlsson7c3e8a12009-05-19 04:45:15 +00001616 // FIXME: When can ToType be a reference type?
1617 assert(!ToType->isReferenceType());
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00001618 if (SCS.Second == ICK_Derived_To_Base) {
1619 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1620 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
1621 MultiExprArg(*this, (void **)&From, 1),
1622 /*FIXME:ConstructLoc*/SourceLocation(),
1623 ConstructorArgs))
1624 return true;
1625 OwningExprResult FromResult =
1626 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1627 ToType, SCS.CopyConstructor,
1628 move_arg(ConstructorArgs));
1629 if (FromResult.isInvalid())
1630 return true;
1631 From = FromResult.takeAs<Expr>();
1632 return false;
1633 }
Mike Stump1eb44332009-09-09 15:08:12 +00001634 OwningExprResult FromResult =
1635 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1636 ToType, SCS.CopyConstructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00001637 MultiExprArg(*this, (void**)&From, 1));
Mike Stump1eb44332009-09-09 15:08:12 +00001638
Anders Carlssonda3f4e22009-08-25 05:12:04 +00001639 if (FromResult.isInvalid())
1640 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001641
Anders Carlssonda3f4e22009-08-25 05:12:04 +00001642 From = FromResult.takeAs<Expr>();
Douglas Gregor225c41e2008-11-03 19:09:14 +00001643 return false;
1644 }
1645
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001646 // Perform the first implicit conversion.
1647 switch (SCS.First) {
1648 case ICK_Identity:
1649 case ICK_Lvalue_To_Rvalue:
1650 // Nothing to do.
1651 break;
1652
1653 case ICK_Array_To_Pointer:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001654 FromType = Context.getArrayDecayedType(FromType);
Anders Carlsson82495762009-08-08 21:04:35 +00001655 ImpCastExprToType(From, FromType, CastExpr::CK_ArrayToPointerDecay);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001656 break;
1657
1658 case ICK_Function_To_Pointer:
Douglas Gregor063daf62009-03-13 18:40:31 +00001659 if (Context.getCanonicalType(FromType) == Context.OverloadTy) {
John McCall6bb80172010-03-30 21:47:33 +00001660 DeclAccessPair Found;
1661 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
1662 true, Found);
Douglas Gregor904eed32008-11-10 20:40:00 +00001663 if (!Fn)
1664 return true;
1665
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001666 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
1667 return true;
1668
John McCall6bb80172010-03-30 21:47:33 +00001669 From = FixOverloadedFunctionReference(From, Found, Fn);
Douglas Gregor904eed32008-11-10 20:40:00 +00001670 FromType = From->getType();
Anders Carlsson96ad5332009-10-21 17:16:23 +00001671
Sebastian Redl759986e2009-10-17 20:50:27 +00001672 // If there's already an address-of operator in the expression, we have
1673 // the right type already, and the code below would just introduce an
1674 // invalid additional pointer level.
Anders Carlsson96ad5332009-10-21 17:16:23 +00001675 if (FromType->isPointerType() || FromType->isMemberFunctionPointerType())
Sebastian Redl759986e2009-10-17 20:50:27 +00001676 break;
Douglas Gregor904eed32008-11-10 20:40:00 +00001677 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001678 FromType = Context.getPointerType(FromType);
Anders Carlssonb633c4e2009-09-01 20:37:18 +00001679 ImpCastExprToType(From, FromType, CastExpr::CK_FunctionToPointerDecay);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001680 break;
1681
1682 default:
1683 assert(false && "Improper first standard conversion");
1684 break;
1685 }
1686
1687 // Perform the second implicit conversion
1688 switch (SCS.Second) {
1689 case ICK_Identity:
Sebastian Redl2c7588f2009-10-10 12:04:10 +00001690 // If both sides are functions (or pointers/references to them), there could
1691 // be incompatible exception declarations.
1692 if (CheckExceptionSpecCompatibility(From, ToType))
1693 return true;
1694 // Nothing else to do.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001695 break;
1696
Douglas Gregor43c79c22009-12-09 00:47:37 +00001697 case ICK_NoReturn_Adjustment:
1698 // If both sides are functions (or pointers/references to them), there could
1699 // be incompatible exception declarations.
1700 if (CheckExceptionSpecCompatibility(From, ToType))
1701 return true;
1702
1703 ImpCastExprToType(From, Context.getNoReturnType(From->getType(), false),
1704 CastExpr::CK_NoOp);
1705 break;
1706
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001707 case ICK_Integral_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001708 case ICK_Integral_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001709 ImpCastExprToType(From, ToType, CastExpr::CK_IntegralCast);
1710 break;
1711
1712 case ICK_Floating_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001713 case ICK_Floating_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001714 ImpCastExprToType(From, ToType, CastExpr::CK_FloatingCast);
1715 break;
1716
1717 case ICK_Complex_Promotion:
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001718 case ICK_Complex_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001719 ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1720 break;
1721
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001722 case ICK_Floating_Integral:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001723 if (ToType->isFloatingType())
1724 ImpCastExprToType(From, ToType, CastExpr::CK_IntegralToFloating);
1725 else
1726 ImpCastExprToType(From, ToType, CastExpr::CK_FloatingToIntegral);
1727 break;
1728
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001729 case ICK_Complex_Real:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001730 ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1731 break;
1732
Douglas Gregorf9201e02009-02-11 23:02:49 +00001733 case ICK_Compatible_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001734 ImpCastExprToType(From, ToType, CastExpr::CK_NoOp);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001735 break;
1736
Anders Carlsson61faec12009-09-12 04:46:44 +00001737 case ICK_Pointer_Conversion: {
Douglas Gregor45920e82008-12-19 17:40:08 +00001738 if (SCS.IncompatibleObjC) {
1739 // Diagnose incompatible Objective-C conversions
Mike Stump1eb44332009-09-09 15:08:12 +00001740 Diag(From->getSourceRange().getBegin(),
Douglas Gregor45920e82008-12-19 17:40:08 +00001741 diag::ext_typecheck_convert_incompatible_pointer)
Douglas Gregor68647482009-12-16 03:45:30 +00001742 << From->getType() << ToType << Action
Douglas Gregor45920e82008-12-19 17:40:08 +00001743 << From->getSourceRange();
1744 }
1745
Anders Carlsson61faec12009-09-12 04:46:44 +00001746
1747 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001748 if (CheckPointerConversion(From, ToType, Kind, IgnoreBaseAccess))
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001749 return true;
Anders Carlsson61faec12009-09-12 04:46:44 +00001750 ImpCastExprToType(From, ToType, Kind);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001751 break;
Anders Carlsson61faec12009-09-12 04:46:44 +00001752 }
1753
1754 case ICK_Pointer_Member: {
1755 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001756 if (CheckMemberPointerConversion(From, ToType, Kind, IgnoreBaseAccess))
Anders Carlsson61faec12009-09-12 04:46:44 +00001757 return true;
Sebastian Redl2c7588f2009-10-10 12:04:10 +00001758 if (CheckExceptionSpecCompatibility(From, ToType))
1759 return true;
Anders Carlsson61faec12009-09-12 04:46:44 +00001760 ImpCastExprToType(From, ToType, Kind);
1761 break;
1762 }
Anders Carlssonbc0e0782009-11-23 20:04:44 +00001763 case ICK_Boolean_Conversion: {
1764 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
1765 if (FromType->isMemberPointerType())
1766 Kind = CastExpr::CK_MemberPointerToBoolean;
1767
1768 ImpCastExprToType(From, Context.BoolTy, Kind);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001769 break;
Anders Carlssonbc0e0782009-11-23 20:04:44 +00001770 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001771
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001772 case ICK_Derived_To_Base:
1773 if (CheckDerivedToBaseConversion(From->getType(),
1774 ToType.getNonReferenceType(),
1775 From->getLocStart(),
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001776 From->getSourceRange(),
1777 IgnoreBaseAccess))
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001778 return true;
1779 ImpCastExprToType(From, ToType.getNonReferenceType(),
1780 CastExpr::CK_DerivedToBase);
1781 break;
1782
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001783 default:
1784 assert(false && "Improper second standard conversion");
1785 break;
1786 }
1787
1788 switch (SCS.Third) {
1789 case ICK_Identity:
1790 // Nothing to do.
1791 break;
1792
1793 case ICK_Qualification:
Mike Stump390b4cc2009-05-16 07:39:55 +00001794 // FIXME: Not sure about lvalue vs rvalue here in the presence of rvalue
1795 // references.
Mike Stump1eb44332009-09-09 15:08:12 +00001796 ImpCastExprToType(From, ToType.getNonReferenceType(),
Eli Friedman73c39ab2009-10-20 08:27:19 +00001797 CastExpr::CK_NoOp,
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001798 ToType->isLValueReferenceType());
Douglas Gregora9bff302010-02-28 18:30:25 +00001799
1800 if (SCS.DeprecatedStringLiteralToCharPtr)
1801 Diag(From->getLocStart(), diag::warn_deprecated_string_literal_conversion)
1802 << ToType.getNonReferenceType();
1803
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001804 break;
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001805
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001806 default:
1807 assert(false && "Improper second standard conversion");
1808 break;
1809 }
1810
1811 return false;
1812}
1813
Sebastian Redl64b45f72009-01-05 20:52:13 +00001814Sema::OwningExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
1815 SourceLocation KWLoc,
1816 SourceLocation LParen,
1817 TypeTy *Ty,
1818 SourceLocation RParen) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00001819 QualType T = GetTypeFromParser(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00001820
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001821 // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
1822 // all traits except __is_class, __is_enum and __is_union require a the type
1823 // to be complete.
1824 if (OTT != UTT_IsClass && OTT != UTT_IsEnum && OTT != UTT_IsUnion) {
Mike Stump1eb44332009-09-09 15:08:12 +00001825 if (RequireCompleteType(KWLoc, T,
Anders Carlssond497ba72009-08-26 22:59:12 +00001826 diag::err_incomplete_type_used_in_type_trait_expr))
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001827 return ExprError();
1828 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00001829
1830 // There is no point in eagerly computing the value. The traits are designed
1831 // to be used from type trait templates, so Ty will be a template parameter
1832 // 99% of the time.
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001833 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT, T,
1834 RParen, Context.BoolTy));
Sebastian Redl64b45f72009-01-05 20:52:13 +00001835}
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001836
1837QualType Sema::CheckPointerToMemberOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00001838 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001839 const char *OpSpelling = isIndirect ? "->*" : ".*";
1840 // C++ 5.5p2
1841 // The binary operator .* [p3: ->*] binds its second operand, which shall
1842 // be of type "pointer to member of T" (where T is a completely-defined
1843 // class type) [...]
1844 QualType RType = rex->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001845 const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
Douglas Gregore7450f52009-03-24 19:52:54 +00001846 if (!MemPtr) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001847 Diag(Loc, diag::err_bad_memptr_rhs)
1848 << OpSpelling << RType << rex->getSourceRange();
1849 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00001850 }
Douglas Gregore7450f52009-03-24 19:52:54 +00001851
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001852 QualType Class(MemPtr->getClass(), 0);
1853
Sebastian Redl59fc2692010-04-10 10:14:54 +00001854 if (RequireCompleteType(Loc, Class, diag::err_memptr_rhs_to_incomplete))
1855 return QualType();
1856
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001857 // C++ 5.5p2
1858 // [...] to its first operand, which shall be of class T or of a class of
1859 // which T is an unambiguous and accessible base class. [p3: a pointer to
1860 // such a class]
1861 QualType LType = lex->getType();
1862 if (isIndirect) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001863 if (const PointerType *Ptr = LType->getAs<PointerType>())
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001864 LType = Ptr->getPointeeType().getNonReferenceType();
1865 else {
1866 Diag(Loc, diag::err_bad_memptr_lhs)
Fariborz Jahanianef78ac62009-10-26 20:45:27 +00001867 << OpSpelling << 1 << LType
Douglas Gregor849b2432010-03-31 17:46:05 +00001868 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001869 return QualType();
1870 }
1871 }
1872
Douglas Gregora4923eb2009-11-16 21:35:15 +00001873 if (!Context.hasSameUnqualifiedType(Class, LType)) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001874 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1875 /*DetectVirtual=*/false);
Mike Stump390b4cc2009-05-16 07:39:55 +00001876 // FIXME: Would it be useful to print full ambiguity paths, or is that
1877 // overkill?
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001878 if (!IsDerivedFrom(LType, Class, Paths) ||
1879 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
1880 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Eli Friedman3005efe2010-01-16 00:00:48 +00001881 << (int)isIndirect << lex->getType();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001882 return QualType();
1883 }
Eli Friedman3005efe2010-01-16 00:00:48 +00001884 // Cast LHS to type of use.
1885 QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
1886 bool isLValue = !isIndirect && lex->isLvalue(Context) == Expr::LV_Valid;
1887 ImpCastExprToType(lex, UseType, CastExpr::CK_DerivedToBase, isLValue);
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001888 }
1889
Fariborz Jahanian19d70732009-11-18 22:16:17 +00001890 if (isa<CXXZeroInitValueExpr>(rex->IgnoreParens())) {
Fariborz Jahanian05ebda92009-11-18 21:54:48 +00001891 // Diagnose use of pointer-to-member type which when used as
1892 // the functional cast in a pointer-to-member expression.
1893 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
1894 return QualType();
1895 }
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001896 // C++ 5.5p2
1897 // The result is an object or a function of the type specified by the
1898 // second operand.
1899 // The cv qualifiers are the union of those in the pointer and the left side,
1900 // in accordance with 5.5p5 and 5.2.5.
1901 // FIXME: This returns a dereferenced member function pointer as a normal
1902 // function type. However, the only operation valid on such functions is
Mike Stump390b4cc2009-05-16 07:39:55 +00001903 // calling them. There's also a GCC extension to get a function pointer to the
1904 // thing, which is another complication, because this type - unlike the type
1905 // that is the result of this expression - takes the class as the first
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001906 // argument.
1907 // We probably need a "MemberFunctionClosureType" or something like that.
1908 QualType Result = MemPtr->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00001909 Result = Context.getCVRQualifiedType(Result, LType.getCVRQualifiers());
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001910 return Result;
1911}
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001912
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001913/// \brief Try to convert a type to another according to C++0x 5.16p3.
1914///
1915/// This is part of the parameter validation for the ? operator. If either
1916/// value operand is a class type, the two operands are attempted to be
1917/// converted to each other. This function does the conversion in one direction.
Douglas Gregorb70cf442010-03-26 20:14:36 +00001918/// It returns true if the program is ill-formed and has already been diagnosed
1919/// as such.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001920static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
1921 SourceLocation QuestionLoc,
Douglas Gregorb70cf442010-03-26 20:14:36 +00001922 bool &HaveConversion,
1923 QualType &ToType) {
1924 HaveConversion = false;
1925 ToType = To->getType();
1926
1927 InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
1928 SourceLocation());
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001929 // C++0x 5.16p3
1930 // The process for determining whether an operand expression E1 of type T1
1931 // can be converted to match an operand expression E2 of type T2 is defined
1932 // as follows:
1933 // -- If E2 is an lvalue:
Douglas Gregor0fd8ff72010-03-26 20:59:55 +00001934 bool ToIsLvalue = (To->isLvalue(Self.Context) == Expr::LV_Valid);
1935 if (ToIsLvalue) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001936 // E1 can be converted to match E2 if E1 can be implicitly converted to
1937 // type "lvalue reference to T2", subject to the constraint that in the
1938 // conversion the reference must bind directly to E1.
Douglas Gregorb70cf442010-03-26 20:14:36 +00001939 QualType T = Self.Context.getLValueReferenceType(ToType);
1940 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
1941
1942 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
1943 if (InitSeq.isDirectReferenceBinding()) {
1944 ToType = T;
1945 HaveConversion = true;
1946 return false;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001947 }
Douglas Gregorb70cf442010-03-26 20:14:36 +00001948
1949 if (InitSeq.isAmbiguous())
1950 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001951 }
John McCallb1bdc622010-02-25 01:37:24 +00001952
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001953 // -- If E2 is an rvalue, or if the conversion above cannot be done:
1954 // -- if E1 and E2 have class type, and the underlying class types are
1955 // the same or one is a base class of the other:
1956 QualType FTy = From->getType();
1957 QualType TTy = To->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001958 const RecordType *FRec = FTy->getAs<RecordType>();
1959 const RecordType *TRec = TTy->getAs<RecordType>();
Douglas Gregorb70cf442010-03-26 20:14:36 +00001960 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
1961 Self.IsDerivedFrom(FTy, TTy);
1962 if (FRec && TRec &&
1963 (FRec == TRec || FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001964 // E1 can be converted to match E2 if the class of T2 is the
1965 // same type as, or a base class of, the class of T1, and
1966 // [cv2 > cv1].
John McCallb1bdc622010-02-25 01:37:24 +00001967 if (FRec == TRec || FDerivedFromT) {
1968 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00001969 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
1970 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
1971 if (InitSeq.getKind() != InitializationSequence::FailedSequence) {
1972 HaveConversion = true;
1973 return false;
1974 }
1975
1976 if (InitSeq.isAmbiguous())
1977 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
1978 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001979 }
Douglas Gregorb70cf442010-03-26 20:14:36 +00001980
1981 return false;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001982 }
Douglas Gregorb70cf442010-03-26 20:14:36 +00001983
1984 // -- Otherwise: E1 can be converted to match E2 if E1 can be
1985 // implicitly converted to the type that expression E2 would have
Douglas Gregor0fd8ff72010-03-26 20:59:55 +00001986 // if E2 were converted to an rvalue (or the type it has, if E2 is
1987 // an rvalue).
1988 //
1989 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
1990 // to the array-to-pointer or function-to-pointer conversions.
1991 if (!TTy->getAs<TagType>())
1992 TTy = TTy.getUnqualifiedType();
Douglas Gregorb70cf442010-03-26 20:14:36 +00001993
1994 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
1995 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
1996 HaveConversion = InitSeq.getKind() != InitializationSequence::FailedSequence;
1997 ToType = TTy;
1998 if (InitSeq.isAmbiguous())
1999 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
2000
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002001 return false;
2002}
2003
2004/// \brief Try to find a common type for two according to C++0x 5.16p5.
2005///
2006/// This is part of the parameter validation for the ? operator. If either
2007/// value operand is a class type, overload resolution is used to find a
2008/// conversion to a common type.
2009static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
2010 SourceLocation Loc) {
2011 Expr *Args[2] = { LHS, RHS };
John McCall5769d612010-02-08 23:07:23 +00002012 OverloadCandidateSet CandidateSet(Loc);
Douglas Gregor573d9c32009-10-21 23:19:44 +00002013 Self.AddBuiltinOperatorCandidates(OO_Conditional, Loc, Args, 2, CandidateSet);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002014
2015 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00002016 switch (Self.BestViableFunction(CandidateSet, Loc, Best)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002017 case OR_Success:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002018 // We found a match. Perform the conversions on the arguments and move on.
2019 if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00002020 Best->Conversions[0], Sema::AA_Converting) ||
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002021 Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor68647482009-12-16 03:45:30 +00002022 Best->Conversions[1], Sema::AA_Converting))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002023 break;
2024 return false;
2025
Douglas Gregor20093b42009-12-09 23:02:17 +00002026 case OR_No_Viable_Function:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002027 Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
2028 << LHS->getType() << RHS->getType()
2029 << LHS->getSourceRange() << RHS->getSourceRange();
2030 return true;
2031
Douglas Gregor20093b42009-12-09 23:02:17 +00002032 case OR_Ambiguous:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002033 Self.Diag(Loc, diag::err_conditional_ambiguous_ovl)
2034 << LHS->getType() << RHS->getType()
2035 << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stump390b4cc2009-05-16 07:39:55 +00002036 // FIXME: Print the possible common types by printing the return types of
2037 // the viable candidates.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002038 break;
2039
Douglas Gregor20093b42009-12-09 23:02:17 +00002040 case OR_Deleted:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002041 assert(false && "Conditional operator has only built-in overloads");
2042 break;
2043 }
2044 return true;
2045}
2046
Sebastian Redl76458502009-04-17 16:30:52 +00002047/// \brief Perform an "extended" implicit conversion as returned by
2048/// TryClassUnification.
Douglas Gregorb70cf442010-03-26 20:14:36 +00002049static bool ConvertForConditional(Sema &Self, Expr *&E, QualType T) {
2050 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
2051 InitializationKind Kind = InitializationKind::CreateCopy(E->getLocStart(),
2052 SourceLocation());
2053 InitializationSequence InitSeq(Self, Entity, Kind, &E, 1);
2054 Sema::OwningExprResult Result = InitSeq.Perform(Self, Entity, Kind,
2055 Sema::MultiExprArg(Self, (void **)&E, 1));
2056 if (Result.isInvalid())
Sebastian Redl76458502009-04-17 16:30:52 +00002057 return true;
Douglas Gregorb70cf442010-03-26 20:14:36 +00002058
2059 E = Result.takeAs<Expr>();
Sebastian Redl76458502009-04-17 16:30:52 +00002060 return false;
2061}
2062
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002063/// \brief Check the operands of ?: under C++ semantics.
2064///
2065/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
2066/// extension. In this case, LHS == Cond. (But they're not aliases.)
2067QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
2068 SourceLocation QuestionLoc) {
Mike Stump390b4cc2009-05-16 07:39:55 +00002069 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
2070 // interface pointers.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002071
2072 // C++0x 5.16p1
2073 // The first expression is contextually converted to bool.
2074 if (!Cond->isTypeDependent()) {
2075 if (CheckCXXBooleanCondition(Cond))
2076 return QualType();
2077 }
2078
2079 // Either of the arguments dependent?
2080 if (LHS->isTypeDependent() || RHS->isTypeDependent())
2081 return Context.DependentTy;
2082
John McCalld1b47bf2010-03-11 19:43:18 +00002083 CheckSignCompare(LHS, RHS, QuestionLoc);
John McCallb13c87f2009-11-05 09:23:39 +00002084
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002085 // C++0x 5.16p2
2086 // If either the second or the third operand has type (cv) void, ...
2087 QualType LTy = LHS->getType();
2088 QualType RTy = RHS->getType();
2089 bool LVoid = LTy->isVoidType();
2090 bool RVoid = RTy->isVoidType();
2091 if (LVoid || RVoid) {
2092 // ... then the [l2r] conversions are performed on the second and third
2093 // operands ...
Douglas Gregora873dfc2010-02-03 00:27:59 +00002094 DefaultFunctionArrayLvalueConversion(LHS);
2095 DefaultFunctionArrayLvalueConversion(RHS);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002096 LTy = LHS->getType();
2097 RTy = RHS->getType();
2098
2099 // ... and one of the following shall hold:
2100 // -- The second or the third operand (but not both) is a throw-
2101 // expression; the result is of the type of the other and is an rvalue.
2102 bool LThrow = isa<CXXThrowExpr>(LHS);
2103 bool RThrow = isa<CXXThrowExpr>(RHS);
2104 if (LThrow && !RThrow)
2105 return RTy;
2106 if (RThrow && !LThrow)
2107 return LTy;
2108
2109 // -- Both the second and third operands have type void; the result is of
2110 // type void and is an rvalue.
2111 if (LVoid && RVoid)
2112 return Context.VoidTy;
2113
2114 // Neither holds, error.
2115 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
2116 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
2117 << LHS->getSourceRange() << RHS->getSourceRange();
2118 return QualType();
2119 }
2120
2121 // Neither is void.
2122
2123 // C++0x 5.16p3
2124 // Otherwise, if the second and third operand have different types, and
2125 // either has (cv) class type, and attempt is made to convert each of those
2126 // operands to the other.
Douglas Gregorb70cf442010-03-26 20:14:36 +00002127 if (!Context.hasSameType(LTy, RTy) &&
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002128 (LTy->isRecordType() || RTy->isRecordType())) {
2129 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
2130 // These return true if a single direction is already ambiguous.
Douglas Gregorb70cf442010-03-26 20:14:36 +00002131 QualType L2RType, R2LType;
2132 bool HaveL2R, HaveR2L;
2133 if (TryClassUnification(*this, LHS, RHS, QuestionLoc, HaveL2R, L2RType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002134 return QualType();
Douglas Gregorb70cf442010-03-26 20:14:36 +00002135 if (TryClassUnification(*this, RHS, LHS, QuestionLoc, HaveR2L, R2LType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002136 return QualType();
Douglas Gregorb70cf442010-03-26 20:14:36 +00002137
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002138 // If both can be converted, [...] the program is ill-formed.
2139 if (HaveL2R && HaveR2L) {
2140 Diag(QuestionLoc, diag::err_conditional_ambiguous)
2141 << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
2142 return QualType();
2143 }
2144
2145 // If exactly one conversion is possible, that conversion is applied to
2146 // the chosen operand and the converted operands are used in place of the
2147 // original operands for the remainder of this section.
2148 if (HaveL2R) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00002149 if (ConvertForConditional(*this, LHS, L2RType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002150 return QualType();
2151 LTy = LHS->getType();
2152 } else if (HaveR2L) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00002153 if (ConvertForConditional(*this, RHS, R2LType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002154 return QualType();
2155 RTy = RHS->getType();
2156 }
2157 }
2158
2159 // C++0x 5.16p4
2160 // If the second and third operands are lvalues and have the same type,
2161 // the result is of that type [...]
Douglas Gregor1927b1f2010-04-01 22:47:07 +00002162 bool Same = Context.hasSameType(LTy, RTy);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002163 if (Same && LHS->isLvalue(Context) == Expr::LV_Valid &&
2164 RHS->isLvalue(Context) == Expr::LV_Valid)
2165 return LTy;
2166
2167 // C++0x 5.16p5
2168 // Otherwise, the result is an rvalue. If the second and third operands
2169 // do not have the same type, and either has (cv) class type, ...
2170 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
2171 // ... overload resolution is used to determine the conversions (if any)
2172 // to be applied to the operands. If the overload resolution fails, the
2173 // program is ill-formed.
2174 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
2175 return QualType();
2176 }
2177
2178 // C++0x 5.16p6
2179 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
2180 // conversions are performed on the second and third operands.
Douglas Gregora873dfc2010-02-03 00:27:59 +00002181 DefaultFunctionArrayLvalueConversion(LHS);
2182 DefaultFunctionArrayLvalueConversion(RHS);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002183 LTy = LHS->getType();
2184 RTy = RHS->getType();
2185
2186 // After those conversions, one of the following shall hold:
2187 // -- The second and third operands have the same type; the result
2188 // is of that type.
2189 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy))
2190 return LTy;
2191
2192 // -- The second and third operands have arithmetic or enumeration type;
2193 // the usual arithmetic conversions are performed to bring them to a
2194 // common type, and the result is of that type.
2195 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
2196 UsualArithmeticConversions(LHS, RHS);
2197 return LHS->getType();
2198 }
2199
2200 // -- The second and third operands have pointer type, or one has pointer
2201 // type and the other is a null pointer constant; pointer conversions
2202 // and qualification conversions are performed to bring them to their
2203 // composite pointer type. The result is of the composite pointer type.
Eli Friedmande8ac492010-01-02 22:56:07 +00002204 // -- The second and third operands have pointer to member type, or one has
2205 // pointer to member type and the other is a null pointer constant;
2206 // pointer to member conversions and qualification conversions are
2207 // performed to bring them to a common type, whose cv-qualification
2208 // shall match the cv-qualification of either the second or the third
2209 // operand. The result is of the common type.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002210 bool NonStandardCompositeType = false;
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002211 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002212 isSFINAEContext()? 0 : &NonStandardCompositeType);
2213 if (!Composite.isNull()) {
2214 if (NonStandardCompositeType)
2215 Diag(QuestionLoc,
2216 diag::ext_typecheck_cond_incompatible_operands_nonstandard)
2217 << LTy << RTy << Composite
2218 << LHS->getSourceRange() << RHS->getSourceRange();
2219
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002220 return Composite;
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002221 }
Fariborz Jahanian55016362009-12-10 20:46:08 +00002222
Douglas Gregor1927b1f2010-04-01 22:47:07 +00002223 // Similarly, attempt to find composite type of two objective-c pointers.
Fariborz Jahanian55016362009-12-10 20:46:08 +00002224 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
2225 if (!Composite.isNull())
2226 return Composite;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002227
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002228 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
2229 << LHS->getType() << RHS->getType()
2230 << LHS->getSourceRange() << RHS->getSourceRange();
2231 return QualType();
2232}
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002233
2234/// \brief Find a merged pointer type and convert the two expressions to it.
2235///
Douglas Gregor20b3e992009-08-24 17:42:35 +00002236/// This finds the composite pointer type (or member pointer type) for @p E1
2237/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
2238/// type and returns it.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002239/// It does not emit diagnostics.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002240///
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002241/// \param Loc The location of the operator requiring these two expressions to
2242/// be converted to the composite pointer type.
2243///
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002244/// If \p NonStandardCompositeType is non-NULL, then we are permitted to find
2245/// a non-standard (but still sane) composite type to which both expressions
2246/// can be converted. When such a type is chosen, \c *NonStandardCompositeType
2247/// will be set true.
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002248QualType Sema::FindCompositePointerType(SourceLocation Loc,
2249 Expr *&E1, Expr *&E2,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002250 bool *NonStandardCompositeType) {
2251 if (NonStandardCompositeType)
2252 *NonStandardCompositeType = false;
2253
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002254 assert(getLangOptions().CPlusPlus && "This function assumes C++");
2255 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002256
Fariborz Jahanian0cedfbd2009-12-08 20:04:24 +00002257 if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
2258 !T2->isAnyPointerType() && !T2->isMemberPointerType())
Douglas Gregor20b3e992009-08-24 17:42:35 +00002259 return QualType();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002260
2261 // C++0x 5.9p2
2262 // Pointer conversions and qualification conversions are performed on
2263 // pointer operands to bring them to their composite pointer type. If
2264 // one operand is a null pointer constant, the composite pointer type is
2265 // the type of the other operand.
Douglas Gregorce940492009-09-25 04:25:58 +00002266 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00002267 if (T2->isMemberPointerType())
2268 ImpCastExprToType(E1, T2, CastExpr::CK_NullToMemberPointer);
2269 else
2270 ImpCastExprToType(E1, T2, CastExpr::CK_IntegralToPointer);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002271 return T2;
2272 }
Douglas Gregorce940492009-09-25 04:25:58 +00002273 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00002274 if (T1->isMemberPointerType())
2275 ImpCastExprToType(E2, T1, CastExpr::CK_NullToMemberPointer);
2276 else
2277 ImpCastExprToType(E2, T1, CastExpr::CK_IntegralToPointer);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002278 return T1;
2279 }
Mike Stump1eb44332009-09-09 15:08:12 +00002280
Douglas Gregor20b3e992009-08-24 17:42:35 +00002281 // Now both have to be pointers or member pointers.
Sebastian Redla439e6f2009-11-16 21:03:45 +00002282 if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
2283 (!T2->isPointerType() && !T2->isMemberPointerType()))
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002284 return QualType();
2285
2286 // Otherwise, of one of the operands has type "pointer to cv1 void," then
2287 // the other has type "pointer to cv2 T" and the composite pointer type is
2288 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
2289 // Otherwise, the composite pointer type is a pointer type similar to the
2290 // type of one of the operands, with a cv-qualification signature that is
2291 // the union of the cv-qualification signatures of the operand types.
2292 // In practice, the first part here is redundant; it's subsumed by the second.
2293 // What we do here is, we build the two possible composite types, and try the
2294 // conversions in both directions. If only one works, or if the two composite
2295 // types are the same, we have succeeded.
John McCall0953e762009-09-24 19:53:00 +00002296 // FIXME: extended qualifiers?
Sebastian Redla439e6f2009-11-16 21:03:45 +00002297 typedef llvm::SmallVector<unsigned, 4> QualifierVector;
2298 QualifierVector QualifierUnion;
2299 typedef llvm::SmallVector<std::pair<const Type *, const Type *>, 4>
2300 ContainingClassVector;
2301 ContainingClassVector MemberOfClass;
2302 QualType Composite1 = Context.getCanonicalType(T1),
2303 Composite2 = Context.getCanonicalType(T2);
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002304 unsigned NeedConstBefore = 0;
Douglas Gregor20b3e992009-08-24 17:42:35 +00002305 do {
2306 const PointerType *Ptr1, *Ptr2;
2307 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
2308 (Ptr2 = Composite2->getAs<PointerType>())) {
2309 Composite1 = Ptr1->getPointeeType();
2310 Composite2 = Ptr2->getPointeeType();
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002311
2312 // If we're allowed to create a non-standard composite type, keep track
2313 // of where we need to fill in additional 'const' qualifiers.
2314 if (NonStandardCompositeType &&
2315 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
2316 NeedConstBefore = QualifierUnion.size();
2317
Douglas Gregor20b3e992009-08-24 17:42:35 +00002318 QualifierUnion.push_back(
2319 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
2320 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
2321 continue;
2322 }
Mike Stump1eb44332009-09-09 15:08:12 +00002323
Douglas Gregor20b3e992009-08-24 17:42:35 +00002324 const MemberPointerType *MemPtr1, *MemPtr2;
2325 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
2326 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
2327 Composite1 = MemPtr1->getPointeeType();
2328 Composite2 = MemPtr2->getPointeeType();
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002329
2330 // If we're allowed to create a non-standard composite type, keep track
2331 // of where we need to fill in additional 'const' qualifiers.
2332 if (NonStandardCompositeType &&
2333 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
2334 NeedConstBefore = QualifierUnion.size();
2335
Douglas Gregor20b3e992009-08-24 17:42:35 +00002336 QualifierUnion.push_back(
2337 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
2338 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
2339 MemPtr2->getClass()));
2340 continue;
2341 }
Mike Stump1eb44332009-09-09 15:08:12 +00002342
Douglas Gregor20b3e992009-08-24 17:42:35 +00002343 // FIXME: block pointer types?
Mike Stump1eb44332009-09-09 15:08:12 +00002344
Douglas Gregor20b3e992009-08-24 17:42:35 +00002345 // Cannot unwrap any more types.
2346 break;
2347 } while (true);
Mike Stump1eb44332009-09-09 15:08:12 +00002348
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002349 if (NeedConstBefore && NonStandardCompositeType) {
2350 // Extension: Add 'const' to qualifiers that come before the first qualifier
2351 // mismatch, so that our (non-standard!) composite type meets the
2352 // requirements of C++ [conv.qual]p4 bullet 3.
2353 for (unsigned I = 0; I != NeedConstBefore; ++I) {
2354 if ((QualifierUnion[I] & Qualifiers::Const) == 0) {
2355 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
2356 *NonStandardCompositeType = true;
2357 }
2358 }
2359 }
2360
Douglas Gregor20b3e992009-08-24 17:42:35 +00002361 // Rewrap the composites as pointers or member pointers with the union CVRs.
Sebastian Redla439e6f2009-11-16 21:03:45 +00002362 ContainingClassVector::reverse_iterator MOC
2363 = MemberOfClass.rbegin();
2364 for (QualifierVector::reverse_iterator
2365 I = QualifierUnion.rbegin(),
2366 E = QualifierUnion.rend();
Douglas Gregor20b3e992009-08-24 17:42:35 +00002367 I != E; (void)++I, ++MOC) {
John McCall0953e762009-09-24 19:53:00 +00002368 Qualifiers Quals = Qualifiers::fromCVRMask(*I);
Douglas Gregor20b3e992009-08-24 17:42:35 +00002369 if (MOC->first && MOC->second) {
2370 // Rebuild member pointer type
John McCall0953e762009-09-24 19:53:00 +00002371 Composite1 = Context.getMemberPointerType(
2372 Context.getQualifiedType(Composite1, Quals),
2373 MOC->first);
2374 Composite2 = Context.getMemberPointerType(
2375 Context.getQualifiedType(Composite2, Quals),
2376 MOC->second);
Douglas Gregor20b3e992009-08-24 17:42:35 +00002377 } else {
2378 // Rebuild pointer type
John McCall0953e762009-09-24 19:53:00 +00002379 Composite1
2380 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
2381 Composite2
2382 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregor20b3e992009-08-24 17:42:35 +00002383 }
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002384 }
2385
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002386 // Try to convert to the first composite pointer type.
2387 InitializedEntity Entity1
2388 = InitializedEntity::InitializeTemporary(Composite1);
2389 InitializationKind Kind
2390 = InitializationKind::CreateCopy(Loc, SourceLocation());
2391 InitializationSequence E1ToC1(*this, Entity1, Kind, &E1, 1);
2392 InitializationSequence E2ToC1(*this, Entity1, Kind, &E2, 1);
Mike Stump1eb44332009-09-09 15:08:12 +00002393
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002394 if (E1ToC1 && E2ToC1) {
2395 // Conversion to Composite1 is viable.
2396 if (!Context.hasSameType(Composite1, Composite2)) {
2397 // Composite2 is a different type from Composite1. Check whether
2398 // Composite2 is also viable.
2399 InitializedEntity Entity2
2400 = InitializedEntity::InitializeTemporary(Composite2);
2401 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
2402 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
2403 if (E1ToC2 && E2ToC2) {
2404 // Both Composite1 and Composite2 are viable and are different;
2405 // this is an ambiguity.
2406 return QualType();
2407 }
2408 }
2409
2410 // Convert E1 to Composite1
2411 OwningExprResult E1Result
2412 = E1ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,(void**)&E1,1));
2413 if (E1Result.isInvalid())
2414 return QualType();
2415 E1 = E1Result.takeAs<Expr>();
2416
2417 // Convert E2 to Composite1
2418 OwningExprResult E2Result
2419 = E2ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,(void**)&E2,1));
2420 if (E2Result.isInvalid())
2421 return QualType();
2422 E2 = E2Result.takeAs<Expr>();
2423
2424 return Composite1;
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002425 }
2426
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002427 // Check whether Composite2 is viable.
2428 InitializedEntity Entity2
2429 = InitializedEntity::InitializeTemporary(Composite2);
2430 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
2431 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
2432 if (!E1ToC2 || !E2ToC2)
2433 return QualType();
2434
2435 // Convert E1 to Composite2
2436 OwningExprResult E1Result
2437 = E1ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, (void**)&E1, 1));
2438 if (E1Result.isInvalid())
2439 return QualType();
2440 E1 = E1Result.takeAs<Expr>();
2441
2442 // Convert E2 to Composite2
2443 OwningExprResult E2Result
2444 = E2ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, (void**)&E2, 1));
2445 if (E2Result.isInvalid())
2446 return QualType();
2447 E2 = E2Result.takeAs<Expr>();
2448
2449 return Composite2;
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002450}
Anders Carlsson165a0a02009-05-17 18:41:29 +00002451
Anders Carlssondef11992009-05-30 20:36:53 +00002452Sema::OwningExprResult Sema::MaybeBindToTemporary(Expr *E) {
Anders Carlsson089c2602009-08-15 23:41:35 +00002453 if (!Context.getLangOptions().CPlusPlus)
2454 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002455
Douglas Gregor51326552009-12-24 18:51:59 +00002456 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
2457
Ted Kremenek6217b802009-07-29 21:53:49 +00002458 const RecordType *RT = E->getType()->getAs<RecordType>();
Anders Carlssondef11992009-05-30 20:36:53 +00002459 if (!RT)
2460 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002461
John McCall86ff3082010-02-04 22:26:26 +00002462 // If this is the result of a call expression, our source might
2463 // actually be a reference, in which case we shouldn't bind.
Anders Carlsson283e4d52009-09-14 01:30:44 +00002464 if (CallExpr *CE = dyn_cast<CallExpr>(E)) {
2465 QualType Ty = CE->getCallee()->getType();
2466 if (const PointerType *PT = Ty->getAs<PointerType>())
2467 Ty = PT->getPointeeType();
Fariborz Jahanianb372b0f2010-02-18 20:31:02 +00002468 else if (const BlockPointerType *BPT = Ty->getAs<BlockPointerType>())
2469 Ty = BPT->getPointeeType();
2470
John McCall183700f2009-09-21 23:43:11 +00002471 const FunctionType *FTy = Ty->getAs<FunctionType>();
Anders Carlsson283e4d52009-09-14 01:30:44 +00002472 if (FTy->getResultType()->isReferenceType())
2473 return Owned(E);
2474 }
John McCall86ff3082010-02-04 22:26:26 +00002475
2476 // That should be enough to guarantee that this type is complete.
2477 // If it has a trivial destructor, we can avoid the extra copy.
2478 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2479 if (RD->hasTrivialDestructor())
2480 return Owned(E);
2481
Mike Stump1eb44332009-09-09 15:08:12 +00002482 CXXTemporary *Temp = CXXTemporary::Create(Context,
Anders Carlssondef11992009-05-30 20:36:53 +00002483 RD->getDestructor(Context));
Anders Carlsson860306e2009-05-30 21:21:49 +00002484 ExprTemporaries.push_back(Temp);
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00002485 if (CXXDestructorDecl *Destructor =
John McCallc91cc662010-04-07 00:41:46 +00002486 const_cast<CXXDestructorDecl*>(RD->getDestructor(Context))) {
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00002487 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
John McCallc91cc662010-04-07 00:41:46 +00002488 CheckDestructorAccess(E->getExprLoc(), Destructor,
2489 PDiag(diag::err_access_dtor_temp)
2490 << E->getType());
2491 }
Anders Carlssondef11992009-05-30 20:36:53 +00002492 // FIXME: Add the temporary to the temporaries vector.
2493 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
2494}
2495
Anders Carlsson0ece4912009-12-15 20:51:39 +00002496Expr *Sema::MaybeCreateCXXExprWithTemporaries(Expr *SubExpr) {
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002497 assert(SubExpr && "sub expression can't be null!");
Mike Stump1eb44332009-09-09 15:08:12 +00002498
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00002499 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
2500 assert(ExprTemporaries.size() >= FirstTemporary);
2501 if (ExprTemporaries.size() == FirstTemporary)
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002502 return SubExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00002503
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002504 Expr *E = CXXExprWithTemporaries::Create(Context, SubExpr,
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00002505 &ExprTemporaries[FirstTemporary],
Anders Carlsson0ece4912009-12-15 20:51:39 +00002506 ExprTemporaries.size() - FirstTemporary);
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00002507 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
2508 ExprTemporaries.end());
Mike Stump1eb44332009-09-09 15:08:12 +00002509
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002510 return E;
2511}
2512
Douglas Gregor90f93822009-12-22 22:17:25 +00002513Sema::OwningExprResult
2514Sema::MaybeCreateCXXExprWithTemporaries(OwningExprResult SubExpr) {
2515 if (SubExpr.isInvalid())
2516 return ExprError();
2517
2518 return Owned(MaybeCreateCXXExprWithTemporaries(SubExpr.takeAs<Expr>()));
2519}
2520
Anders Carlsson5ee56e92009-12-16 02:09:40 +00002521FullExpr Sema::CreateFullExpr(Expr *SubExpr) {
2522 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
2523 assert(ExprTemporaries.size() >= FirstTemporary);
2524
2525 unsigned NumTemporaries = ExprTemporaries.size() - FirstTemporary;
2526 CXXTemporary **Temporaries =
2527 NumTemporaries == 0 ? 0 : &ExprTemporaries[FirstTemporary];
2528
2529 FullExpr E = FullExpr::Create(Context, SubExpr, Temporaries, NumTemporaries);
2530
2531 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
2532 ExprTemporaries.end());
2533
2534 return E;
2535}
2536
Mike Stump1eb44332009-09-09 15:08:12 +00002537Sema::OwningExprResult
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002538Sema::ActOnStartCXXMemberReference(Scope *S, ExprArg Base, SourceLocation OpLoc,
Douglas Gregord4dca082010-02-24 18:44:31 +00002539 tok::TokenKind OpKind, TypeTy *&ObjectType,
2540 bool &MayBePseudoDestructor) {
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002541 // Since this might be a postfix expression, get rid of ParenListExprs.
2542 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
Mike Stump1eb44332009-09-09 15:08:12 +00002543
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002544 Expr *BaseExpr = (Expr*)Base.get();
2545 assert(BaseExpr && "no record expansion");
Mike Stump1eb44332009-09-09 15:08:12 +00002546
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002547 QualType BaseType = BaseExpr->getType();
Douglas Gregord4dca082010-02-24 18:44:31 +00002548 MayBePseudoDestructor = false;
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002549 if (BaseType->isDependentType()) {
Douglas Gregor43d88632009-11-04 22:49:18 +00002550 // If we have a pointer to a dependent type and are using the -> operator,
2551 // the object type is the type that the pointer points to. We might still
2552 // have enough information about that type to do something useful.
2553 if (OpKind == tok::arrow)
2554 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
2555 BaseType = Ptr->getPointeeType();
2556
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002557 ObjectType = BaseType.getAsOpaquePtr();
Douglas Gregord4dca082010-02-24 18:44:31 +00002558 MayBePseudoDestructor = true;
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002559 return move(Base);
2560 }
Mike Stump1eb44332009-09-09 15:08:12 +00002561
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002562 // C++ [over.match.oper]p8:
Mike Stump1eb44332009-09-09 15:08:12 +00002563 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002564 // returned, with the original second operand.
2565 if (OpKind == tok::arrow) {
John McCallc4e83212009-09-30 01:01:30 +00002566 // The set of types we've considered so far.
John McCall432887f2009-09-30 01:30:54 +00002567 llvm::SmallPtrSet<CanQualType,8> CTypes;
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002568 llvm::SmallVector<SourceLocation, 8> Locations;
John McCall432887f2009-09-30 01:30:54 +00002569 CTypes.insert(Context.getCanonicalType(BaseType));
John McCallc4e83212009-09-30 01:01:30 +00002570
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002571 while (BaseType->isRecordType()) {
Anders Carlsson15ea3782009-10-13 22:43:21 +00002572 Base = BuildOverloadedArrowExpr(S, move(Base), OpLoc);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002573 BaseExpr = (Expr*)Base.get();
2574 if (BaseExpr == NULL)
2575 return ExprError();
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002576 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(BaseExpr))
Anders Carlssonde699e52009-10-13 22:55:59 +00002577 Locations.push_back(OpCall->getDirectCallee()->getLocation());
John McCallc4e83212009-09-30 01:01:30 +00002578 BaseType = BaseExpr->getType();
2579 CanQualType CBaseType = Context.getCanonicalType(BaseType);
John McCall432887f2009-09-30 01:30:54 +00002580 if (!CTypes.insert(CBaseType)) {
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00002581 Diag(OpLoc, diag::err_operator_arrow_circular);
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002582 for (unsigned i = 0; i < Locations.size(); i++)
2583 Diag(Locations[i], diag::note_declared_at);
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00002584 return ExprError();
2585 }
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002586 }
Mike Stump1eb44332009-09-09 15:08:12 +00002587
Douglas Gregor31658df2009-11-20 19:58:21 +00002588 if (BaseType->isPointerType())
2589 BaseType = BaseType->getPointeeType();
2590 }
Mike Stump1eb44332009-09-09 15:08:12 +00002591
2592 // We could end up with various non-record types here, such as extended
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002593 // vector types or Objective-C interfaces. Just return early and let
2594 // ActOnMemberReferenceExpr do the work.
Douglas Gregorc68afe22009-09-03 21:38:09 +00002595 if (!BaseType->isRecordType()) {
2596 // C++ [basic.lookup.classref]p2:
2597 // [...] If the type of the object expression is of pointer to scalar
2598 // type, the unqualified-id is looked up in the context of the complete
2599 // postfix-expression.
Douglas Gregord4dca082010-02-24 18:44:31 +00002600 //
2601 // This also indicates that we should be parsing a
2602 // pseudo-destructor-name.
Douglas Gregorc68afe22009-09-03 21:38:09 +00002603 ObjectType = 0;
Douglas Gregord4dca082010-02-24 18:44:31 +00002604 MayBePseudoDestructor = true;
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002605 return move(Base);
Douglas Gregorc68afe22009-09-03 21:38:09 +00002606 }
Mike Stump1eb44332009-09-09 15:08:12 +00002607
Douglas Gregor03c57052009-11-17 05:17:33 +00002608 // The object type must be complete (or dependent).
2609 if (!BaseType->isDependentType() &&
2610 RequireCompleteType(OpLoc, BaseType,
2611 PDiag(diag::err_incomplete_member_access)))
2612 return ExprError();
2613
Douglas Gregorc68afe22009-09-03 21:38:09 +00002614 // C++ [basic.lookup.classref]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00002615 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor03c57052009-11-17 05:17:33 +00002616 // unqualified-id, and the type of the object expression is of a class
Douglas Gregorc68afe22009-09-03 21:38:09 +00002617 // type C (or of pointer to a class type C), the unqualified-id is looked
2618 // up in the scope of class C. [...]
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002619 ObjectType = BaseType.getAsOpaquePtr();
Mike Stump1eb44332009-09-09 15:08:12 +00002620 return move(Base);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002621}
2622
Douglas Gregor77549082010-02-24 21:29:12 +00002623Sema::OwningExprResult Sema::DiagnoseDtorReference(SourceLocation NameLoc,
2624 ExprArg MemExpr) {
2625 Expr *E = (Expr *) MemExpr.get();
2626 SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(NameLoc);
2627 Diag(E->getLocStart(), diag::err_dtor_expr_without_call)
2628 << isa<CXXPseudoDestructorExpr>(E)
Douglas Gregor849b2432010-03-31 17:46:05 +00002629 << FixItHint::CreateInsertion(ExpectedLParenLoc, "()");
Douglas Gregor77549082010-02-24 21:29:12 +00002630
2631 return ActOnCallExpr(/*Scope*/ 0,
2632 move(MemExpr),
2633 /*LPLoc*/ ExpectedLParenLoc,
2634 Sema::MultiExprArg(*this, 0, 0),
2635 /*CommaLocs*/ 0,
2636 /*RPLoc*/ ExpectedLParenLoc);
2637}
Douglas Gregord4dca082010-02-24 18:44:31 +00002638
Douglas Gregorb57fb492010-02-24 22:38:50 +00002639Sema::OwningExprResult Sema::BuildPseudoDestructorExpr(ExprArg Base,
2640 SourceLocation OpLoc,
2641 tok::TokenKind OpKind,
2642 const CXXScopeSpec &SS,
Douglas Gregor26d4ac92010-02-24 23:40:28 +00002643 TypeSourceInfo *ScopeTypeInfo,
Douglas Gregorb57fb492010-02-24 22:38:50 +00002644 SourceLocation CCLoc,
Douglas Gregorfce46ee2010-02-24 23:50:37 +00002645 SourceLocation TildeLoc,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002646 PseudoDestructorTypeStorage Destructed,
Douglas Gregorb57fb492010-02-24 22:38:50 +00002647 bool HasTrailingLParen) {
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002648 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
Douglas Gregorb57fb492010-02-24 22:38:50 +00002649
2650 // C++ [expr.pseudo]p2:
2651 // The left-hand side of the dot operator shall be of scalar type. The
2652 // left-hand side of the arrow operator shall be of pointer to scalar type.
2653 // This scalar type is the object type.
2654 Expr *BaseE = (Expr *)Base.get();
2655 QualType ObjectType = BaseE->getType();
2656 if (OpKind == tok::arrow) {
2657 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
2658 ObjectType = Ptr->getPointeeType();
2659 } else if (!BaseE->isTypeDependent()) {
2660 // The user wrote "p->" when she probably meant "p."; fix it.
2661 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
2662 << ObjectType << true
Douglas Gregor849b2432010-03-31 17:46:05 +00002663 << FixItHint::CreateReplacement(OpLoc, ".");
Douglas Gregorb57fb492010-02-24 22:38:50 +00002664 if (isSFINAEContext())
2665 return ExprError();
2666
2667 OpKind = tok::period;
2668 }
2669 }
2670
2671 if (!ObjectType->isDependentType() && !ObjectType->isScalarType()) {
2672 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
2673 << ObjectType << BaseE->getSourceRange();
2674 return ExprError();
2675 }
2676
2677 // C++ [expr.pseudo]p2:
2678 // [...] The cv-unqualified versions of the object type and of the type
2679 // designated by the pseudo-destructor-name shall be the same type.
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002680 if (DestructedTypeInfo) {
2681 QualType DestructedType = DestructedTypeInfo->getType();
2682 SourceLocation DestructedTypeStart
2683 = DestructedTypeInfo->getTypeLoc().getSourceRange().getBegin();
2684 if (!DestructedType->isDependentType() && !ObjectType->isDependentType() &&
2685 !Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
2686 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
2687 << ObjectType << DestructedType << BaseE->getSourceRange()
2688 << DestructedTypeInfo->getTypeLoc().getSourceRange();
2689
2690 // Recover by setting the destructed type to the object type.
2691 DestructedType = ObjectType;
2692 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
2693 DestructedTypeStart);
2694 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
2695 }
Douglas Gregorb57fb492010-02-24 22:38:50 +00002696 }
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002697
Douglas Gregorb57fb492010-02-24 22:38:50 +00002698 // C++ [expr.pseudo]p2:
2699 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
2700 // form
2701 //
2702 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
2703 //
2704 // shall designate the same scalar type.
2705 if (ScopeTypeInfo) {
2706 QualType ScopeType = ScopeTypeInfo->getType();
2707 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
2708 !Context.hasSameType(ScopeType, ObjectType)) {
2709
2710 Diag(ScopeTypeInfo->getTypeLoc().getSourceRange().getBegin(),
2711 diag::err_pseudo_dtor_type_mismatch)
2712 << ObjectType << ScopeType << BaseE->getSourceRange()
2713 << ScopeTypeInfo->getTypeLoc().getSourceRange();
2714
2715 ScopeType = QualType();
2716 ScopeTypeInfo = 0;
2717 }
2718 }
2719
2720 OwningExprResult Result
2721 = Owned(new (Context) CXXPseudoDestructorExpr(Context,
2722 Base.takeAs<Expr>(),
2723 OpKind == tok::arrow,
2724 OpLoc,
2725 (NestedNameSpecifier *) SS.getScopeRep(),
2726 SS.getRange(),
2727 ScopeTypeInfo,
2728 CCLoc,
Douglas Gregorfce46ee2010-02-24 23:50:37 +00002729 TildeLoc,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002730 Destructed));
2731
Douglas Gregorb57fb492010-02-24 22:38:50 +00002732 if (HasTrailingLParen)
2733 return move(Result);
2734
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002735 return DiagnoseDtorReference(Destructed.getLocation(), move(Result));
Douglas Gregor77549082010-02-24 21:29:12 +00002736}
2737
2738Sema::OwningExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, ExprArg Base,
2739 SourceLocation OpLoc,
2740 tok::TokenKind OpKind,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00002741 CXXScopeSpec &SS,
Douglas Gregor77549082010-02-24 21:29:12 +00002742 UnqualifiedId &FirstTypeName,
2743 SourceLocation CCLoc,
2744 SourceLocation TildeLoc,
2745 UnqualifiedId &SecondTypeName,
2746 bool HasTrailingLParen) {
2747 assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
2748 FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
2749 "Invalid first type name in pseudo-destructor");
2750 assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
2751 SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
2752 "Invalid second type name in pseudo-destructor");
2753
2754 Expr *BaseE = (Expr *)Base.get();
Douglas Gregor77549082010-02-24 21:29:12 +00002755
2756 // C++ [expr.pseudo]p2:
2757 // The left-hand side of the dot operator shall be of scalar type. The
2758 // left-hand side of the arrow operator shall be of pointer to scalar type.
2759 // This scalar type is the object type.
2760 QualType ObjectType = BaseE->getType();
2761 if (OpKind == tok::arrow) {
2762 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
2763 ObjectType = Ptr->getPointeeType();
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002764 } else if (!ObjectType->isDependentType()) {
Douglas Gregor77549082010-02-24 21:29:12 +00002765 // The user wrote "p->" when she probably meant "p."; fix it.
2766 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002767 << ObjectType << true
Douglas Gregor849b2432010-03-31 17:46:05 +00002768 << FixItHint::CreateReplacement(OpLoc, ".");
Douglas Gregor77549082010-02-24 21:29:12 +00002769 if (isSFINAEContext())
2770 return ExprError();
2771
2772 OpKind = tok::period;
2773 }
2774 }
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002775
2776 // Compute the object type that we should use for name lookup purposes. Only
2777 // record types and dependent types matter.
2778 void *ObjectTypePtrForLookup = 0;
2779 if (!SS.isSet()) {
2780 ObjectTypePtrForLookup = (void *)ObjectType->getAs<RecordType>();
2781 if (!ObjectTypePtrForLookup && ObjectType->isDependentType())
2782 ObjectTypePtrForLookup = Context.DependentTy.getAsOpaquePtr();
2783 }
Douglas Gregor77549082010-02-24 21:29:12 +00002784
Douglas Gregorb57fb492010-02-24 22:38:50 +00002785 // Convert the name of the type being destructed (following the ~) into a
2786 // type (with source-location information).
Douglas Gregor77549082010-02-24 21:29:12 +00002787 QualType DestructedType;
2788 TypeSourceInfo *DestructedTypeInfo = 0;
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002789 PseudoDestructorTypeStorage Destructed;
Douglas Gregor77549082010-02-24 21:29:12 +00002790 if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
2791 TypeTy *T = getTypeName(*SecondTypeName.Identifier,
2792 SecondTypeName.StartLocation,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002793 S, &SS, true, ObjectTypePtrForLookup);
2794 if (!T &&
2795 ((SS.isSet() && !computeDeclContext(SS, false)) ||
2796 (!SS.isSet() && ObjectType->isDependentType()))) {
2797 // The name of the type being destroyed is a dependent name, and we
2798 // couldn't find anything useful in scope. Just store the identifier and
2799 // it's location, and we'll perform (qualified) name lookup again at
2800 // template instantiation time.
2801 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
2802 SecondTypeName.StartLocation);
2803 } else if (!T) {
Douglas Gregor77549082010-02-24 21:29:12 +00002804 Diag(SecondTypeName.StartLocation,
2805 diag::err_pseudo_dtor_destructor_non_type)
2806 << SecondTypeName.Identifier << ObjectType;
2807 if (isSFINAEContext())
2808 return ExprError();
2809
2810 // Recover by assuming we had the right type all along.
2811 DestructedType = ObjectType;
Douglas Gregorb57fb492010-02-24 22:38:50 +00002812 } else
Douglas Gregor77549082010-02-24 21:29:12 +00002813 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00002814 } else {
Douglas Gregorb57fb492010-02-24 22:38:50 +00002815 // Resolve the template-id to a type.
Douglas Gregor77549082010-02-24 21:29:12 +00002816 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
Douglas Gregorb57fb492010-02-24 22:38:50 +00002817 ASTTemplateArgsPtr TemplateArgsPtr(*this,
2818 TemplateId->getTemplateArgs(),
2819 TemplateId->NumArgs);
2820 TypeResult T = ActOnTemplateIdType(TemplateTy::make(TemplateId->Template),
2821 TemplateId->TemplateNameLoc,
2822 TemplateId->LAngleLoc,
2823 TemplateArgsPtr,
2824 TemplateId->RAngleLoc);
2825 if (T.isInvalid() || !T.get()) {
2826 // Recover by assuming we had the right type all along.
2827 DestructedType = ObjectType;
2828 } else
2829 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00002830 }
2831
Douglas Gregorb57fb492010-02-24 22:38:50 +00002832 // If we've performed some kind of recovery, (re-)build the type source
2833 // information.
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002834 if (!DestructedType.isNull()) {
2835 if (!DestructedTypeInfo)
2836 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
Douglas Gregorb57fb492010-02-24 22:38:50 +00002837 SecondTypeName.StartLocation);
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002838 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
2839 }
Douglas Gregorb57fb492010-02-24 22:38:50 +00002840
2841 // Convert the name of the scope type (the type prior to '::') into a type.
2842 TypeSourceInfo *ScopeTypeInfo = 0;
Douglas Gregor77549082010-02-24 21:29:12 +00002843 QualType ScopeType;
2844 if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
2845 FirstTypeName.Identifier) {
2846 if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
2847 TypeTy *T = getTypeName(*FirstTypeName.Identifier,
2848 FirstTypeName.StartLocation,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002849 S, &SS, false, ObjectTypePtrForLookup);
Douglas Gregor77549082010-02-24 21:29:12 +00002850 if (!T) {
2851 Diag(FirstTypeName.StartLocation,
2852 diag::err_pseudo_dtor_destructor_non_type)
2853 << FirstTypeName.Identifier << ObjectType;
Douglas Gregor77549082010-02-24 21:29:12 +00002854
Douglas Gregorb57fb492010-02-24 22:38:50 +00002855 if (isSFINAEContext())
2856 return ExprError();
2857
2858 // Just drop this type. It's unnecessary anyway.
2859 ScopeType = QualType();
2860 } else
2861 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00002862 } else {
Douglas Gregorb57fb492010-02-24 22:38:50 +00002863 // Resolve the template-id to a type.
Douglas Gregor77549082010-02-24 21:29:12 +00002864 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
Douglas Gregorb57fb492010-02-24 22:38:50 +00002865 ASTTemplateArgsPtr TemplateArgsPtr(*this,
2866 TemplateId->getTemplateArgs(),
2867 TemplateId->NumArgs);
2868 TypeResult T = ActOnTemplateIdType(TemplateTy::make(TemplateId->Template),
2869 TemplateId->TemplateNameLoc,
2870 TemplateId->LAngleLoc,
2871 TemplateArgsPtr,
2872 TemplateId->RAngleLoc);
2873 if (T.isInvalid() || !T.get()) {
2874 // Recover by dropping this type.
2875 ScopeType = QualType();
2876 } else
2877 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00002878 }
2879 }
Douglas Gregorb4a418f2010-02-24 23:02:30 +00002880
2881 if (!ScopeType.isNull() && !ScopeTypeInfo)
2882 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
2883 FirstTypeName.StartLocation);
2884
2885
Douglas Gregorb57fb492010-02-24 22:38:50 +00002886 return BuildPseudoDestructorExpr(move(Base), OpLoc, OpKind, SS,
Douglas Gregorfce46ee2010-02-24 23:50:37 +00002887 ScopeTypeInfo, CCLoc, TildeLoc,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002888 Destructed, HasTrailingLParen);
Douglas Gregord4dca082010-02-24 18:44:31 +00002889}
2890
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002891CXXMemberCallExpr *Sema::BuildCXXMemberCallExpr(Expr *Exp,
John McCall6bb80172010-03-30 21:47:33 +00002892 NamedDecl *FoundDecl,
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002893 CXXMethodDecl *Method) {
John McCall6bb80172010-03-30 21:47:33 +00002894 if (PerformObjectArgumentInitialization(Exp, /*Qualifier=*/0,
2895 FoundDecl, Method))
Eli Friedman772fffa2009-12-09 04:53:56 +00002896 assert(0 && "Calling BuildCXXMemberCallExpr with invalid call?");
2897
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002898 MemberExpr *ME =
2899 new (Context) MemberExpr(Exp, /*IsArrow=*/false, Method,
2900 SourceLocation(), Method->getType());
Eli Friedman772fffa2009-12-09 04:53:56 +00002901 QualType ResultType = Method->getResultType().getNonReferenceType();
Douglas Gregor7edfb692009-11-23 12:27:39 +00002902 MarkDeclarationReferenced(Exp->getLocStart(), Method);
2903 CXXMemberCallExpr *CE =
2904 new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType,
2905 Exp->getLocEnd());
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002906 return CE;
2907}
2908
Anders Carlsson165a0a02009-05-17 18:41:29 +00002909Sema::OwningExprResult Sema::ActOnFinishFullExpr(ExprArg Arg) {
2910 Expr *FullExpr = Arg.takeAs<Expr>();
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002911 if (FullExpr)
Anders Carlsson0ece4912009-12-15 20:51:39 +00002912 FullExpr = MaybeCreateCXXExprWithTemporaries(FullExpr);
Anders Carlssonec773872009-08-25 23:46:41 +00002913
Anders Carlsson165a0a02009-05-17 18:41:29 +00002914 return Owned(FullExpr);
2915}