blob: 9d41f9d0dbf940de2bf60768e084760c2e58fc7b [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"
20#include "clang/Basic/PartialDiagnostic.h"
Sebastian Redlb5a57a62008-12-03 20:26:15 +000021#include "clang/Basic/TargetInfo.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000022#include "clang/Lex/Preprocessor.h"
23#include "clang/Parse/DeclSpec.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000024#include "llvm/ADT/STLExtras.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000025using namespace clang;
26
Douglas Gregor124b8782010-02-16 19:09:40 +000027Action::TypeTy *Sema::getDestructorName(SourceLocation TildeLoc,
28 IdentifierInfo &II,
29 SourceLocation NameLoc,
30 Scope *S, const CXXScopeSpec &SS,
31 TypeTy *ObjectTypePtr,
32 bool EnteringContext) {
33 // Determine where to perform name lookup.
34
35 // FIXME: This area of the standard is very messy, and the current
36 // wording is rather unclear about which scopes we search for the
37 // destructor name; see core issues 399 and 555. Issue 399 in
38 // particular shows where the current description of destructor name
39 // lookup is completely out of line with existing practice, e.g.,
40 // this appears to be ill-formed:
41 //
42 // namespace N {
43 // template <typename T> struct S {
44 // ~S();
45 // };
46 // }
47 //
48 // void f(N::S<int>* s) {
49 // s->N::S<int>::~S();
50 // }
51 //
Douglas Gregor93649fd2010-02-23 00:15:22 +000052 // See also PR6358 and PR6359.
Douglas Gregor124b8782010-02-16 19:09:40 +000053 QualType SearchType;
54 DeclContext *LookupCtx = 0;
55 bool isDependent = false;
56 bool LookInScope = false;
57
58 // If we have an object type, it's because we are in a
59 // pseudo-destructor-expression or a member access expression, and
60 // we know what type we're looking for.
61 if (ObjectTypePtr)
62 SearchType = GetTypeFromParser(ObjectTypePtr);
63
64 if (SS.isSet()) {
Douglas Gregor93649fd2010-02-23 00:15:22 +000065 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
66
67 bool AlreadySearched = false;
68 bool LookAtPrefix = true;
69 if (!getLangOptions().CPlusPlus0x) {
70 // C++ [basic.lookup.qual]p6:
71 // If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier,
72 // the type-names are looked up as types in the scope designated by the
73 // nested-name-specifier. In a qualified-id of the form:
74 //
75 // ::[opt] nested-name-specifier ̃ class-name
76 //
77 // where the nested-name-specifier designates a namespace scope, and in
78 // a qualified-id of the form:
79 //
80 // ::opt nested-name-specifier class-name :: ̃ class-name
81 //
82 // the class-names are looked up as types in the scope designated by
83 // the nested-name-specifier.
84 //
85 // Here, we check the first case (completely) and determine whether the
86 // code below is permitted to look at the prefix of the
87 // nested-name-specifier (as we do in C++0x).
88 DeclContext *DC = computeDeclContext(SS, EnteringContext);
89 if (DC && DC->isFileContext()) {
90 AlreadySearched = true;
91 LookupCtx = DC;
92 isDependent = false;
93 } else if (DC && isa<CXXRecordDecl>(DC))
94 LookAtPrefix = false;
95 }
96
97 // C++0x [basic.lookup.qual]p6:
Douglas Gregor124b8782010-02-16 19:09:40 +000098 // If a pseudo-destructor-name (5.2.4) contains a
99 // nested-name-specifier, the type-names are looked up as types
100 // in the scope designated by the nested-name-specifier. Similarly, in
Chandler Carruth5e895a82010-02-21 10:19:54 +0000101 // a qualified-id of the form:
Douglas Gregor124b8782010-02-16 19:09:40 +0000102 //
103 // :: [opt] nested-name-specifier[opt] class-name :: ~class-name
104 //
105 // the second class-name is looked up in the same scope as the first.
106 //
Douglas Gregor93649fd2010-02-23 00:15:22 +0000107 // To implement this, we look at the prefix of the
108 // nested-name-specifier we were given, and determine the lookup
109 // context from that.
110 //
111 // We also fold in the second case from the C++03 rules quoted further
112 // above.
113 NestedNameSpecifier *Prefix = 0;
114 if (AlreadySearched) {
115 // Nothing left to do.
116 } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) {
117 CXXScopeSpec PrefixSS;
118 PrefixSS.setScopeRep(Prefix);
119 LookupCtx = computeDeclContext(PrefixSS, EnteringContext);
120 isDependent = isDependentScopeSpecifier(PrefixSS);
121 } else if (getLangOptions().CPlusPlus0x &&
122 (LookupCtx = computeDeclContext(SS, EnteringContext))) {
123 if (!LookupCtx->isTranslationUnit())
124 LookupCtx = LookupCtx->getParent();
125 isDependent = LookupCtx && LookupCtx->isDependentContext();
126 } else if (ObjectTypePtr) {
Douglas Gregor124b8782010-02-16 19:09:40 +0000127 LookupCtx = computeDeclContext(SearchType);
128 isDependent = SearchType->isDependentType();
129 } else {
130 LookupCtx = computeDeclContext(SS, EnteringContext);
Douglas Gregor93649fd2010-02-23 00:15:22 +0000131 isDependent = LookupCtx && LookupCtx->isDependentContext();
Douglas Gregor124b8782010-02-16 19:09:40 +0000132 }
Douglas Gregor93649fd2010-02-23 00:15:22 +0000133
Douglas Gregorb10cd042010-02-21 18:36:56 +0000134 LookInScope = (LookupCtx == 0) && !isDependent;
Douglas Gregor124b8782010-02-16 19:09:40 +0000135 } else if (ObjectTypePtr) {
136 // C++ [basic.lookup.classref]p3:
137 // If the unqualified-id is ~type-name, the type-name is looked up
138 // in the context of the entire postfix-expression. If the type T
139 // of the object expression is of a class type C, the type-name is
140 // also looked up in the scope of class C. At least one of the
141 // lookups shall find a name that refers to (possibly
142 // cv-qualified) T.
143 LookupCtx = computeDeclContext(SearchType);
144 isDependent = SearchType->isDependentType();
145 assert((isDependent || !SearchType->isIncompleteType()) &&
146 "Caller should have completed object type");
147
148 LookInScope = true;
149 } else {
150 // Perform lookup into the current scope (only).
151 LookInScope = true;
152 }
153
154 LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName);
155 for (unsigned Step = 0; Step != 2; ++Step) {
156 // Look for the name first in the computed lookup context (if we
157 // have one) and, if that fails to find a match, in the sope (if
158 // we're allowed to look there).
159 Found.clear();
160 if (Step == 0 && LookupCtx)
161 LookupQualifiedName(Found, LookupCtx);
162 else if (Step == 1 && LookInScope)
163 LookupName(Found, S);
164 else
165 continue;
166
167 // FIXME: Should we be suppressing ambiguities here?
168 if (Found.isAmbiguous())
169 return 0;
170
171 if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
172 QualType T = Context.getTypeDeclType(Type);
173 // If we found the injected-class-name of a class template, retrieve the
174 // type of that template.
175 // FIXME: We really shouldn't need to do this.
176 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Type))
177 if (Record->isInjectedClassName())
178 if (Record->getDescribedClassTemplate())
179 T = Record->getDescribedClassTemplate()
180 ->getInjectedClassNameType(Context);
181
182 if (SearchType.isNull() || SearchType->isDependentType() ||
183 Context.hasSameUnqualifiedType(T, SearchType)) {
184 // We found our type!
185
186 return T.getAsOpaquePtr();
187 }
188 }
189
190 // If the name that we found is a class template name, and it is
191 // the same name as the template name in the last part of the
192 // nested-name-specifier (if present) or the object type, then
193 // this is the destructor for that class.
194 // FIXME: This is a workaround until we get real drafting for core
195 // issue 399, for which there isn't even an obvious direction.
196 if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) {
197 QualType MemberOfType;
198 if (SS.isSet()) {
199 if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) {
200 // Figure out the type of the context, if it has one.
201 if (ClassTemplateSpecializationDecl *Spec
202 = dyn_cast<ClassTemplateSpecializationDecl>(Ctx))
203 MemberOfType = Context.getTypeDeclType(Spec);
204 else if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
205 if (Record->getDescribedClassTemplate())
206 MemberOfType = Record->getDescribedClassTemplate()
207 ->getInjectedClassNameType(Context);
208 else
209 MemberOfType = Context.getTypeDeclType(Record);
210 }
211 }
212 }
213 if (MemberOfType.isNull())
214 MemberOfType = SearchType;
215
216 if (MemberOfType.isNull())
217 continue;
218
219 // We're referring into a class template specialization. If the
220 // class template we found is the same as the template being
221 // specialized, we found what we are looking for.
222 if (const RecordType *Record = MemberOfType->getAs<RecordType>()) {
223 if (ClassTemplateSpecializationDecl *Spec
224 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
225 if (Spec->getSpecializedTemplate()->getCanonicalDecl() ==
226 Template->getCanonicalDecl())
227 return MemberOfType.getAsOpaquePtr();
228 }
229
230 continue;
231 }
232
233 // We're referring to an unresolved class template
234 // specialization. Determine whether we class template we found
235 // is the same as the template being specialized or, if we don't
236 // know which template is being specialized, that it at least
237 // has the same name.
238 if (const TemplateSpecializationType *SpecType
239 = MemberOfType->getAs<TemplateSpecializationType>()) {
240 TemplateName SpecName = SpecType->getTemplateName();
241
242 // The class template we found is the same template being
243 // specialized.
244 if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) {
245 if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl())
246 return MemberOfType.getAsOpaquePtr();
247
248 continue;
249 }
250
251 // The class template we found has the same name as the
252 // (dependent) template name being specialized.
253 if (DependentTemplateName *DepTemplate
254 = SpecName.getAsDependentTemplateName()) {
255 if (DepTemplate->isIdentifier() &&
256 DepTemplate->getIdentifier() == Template->getIdentifier())
257 return MemberOfType.getAsOpaquePtr();
258
259 continue;
260 }
261 }
262 }
263 }
264
265 if (isDependent) {
266 // We didn't find our type, but that's okay: it's dependent
267 // anyway.
268 NestedNameSpecifier *NNS = 0;
269 SourceRange Range;
270 if (SS.isSet()) {
271 NNS = (NestedNameSpecifier *)SS.getScopeRep();
272 Range = SourceRange(SS.getRange().getBegin(), NameLoc);
273 } else {
274 NNS = NestedNameSpecifier::Create(Context, &II);
275 Range = SourceRange(NameLoc);
276 }
277
278 return CheckTypenameType(NNS, II, Range).getAsOpaquePtr();
279 }
280
281 if (ObjectTypePtr)
282 Diag(NameLoc, diag::err_ident_in_pseudo_dtor_not_a_type)
283 << &II;
284 else
285 Diag(NameLoc, diag::err_destructor_class_name);
286
287 return 0;
288}
289
Sebastian Redlc42e1182008-11-11 11:37:55 +0000290/// ActOnCXXTypeidOfType - Parse typeid( type-id ).
Sebastian Redlf53597f2009-03-15 17:47:39 +0000291Action::OwningExprResult
Sebastian Redlc42e1182008-11-11 11:37:55 +0000292Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
293 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +0000294 if (!StdNamespace)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000295 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000296
Douglas Gregorf57f2072009-12-23 20:51:04 +0000297 if (isType) {
298 // C++ [expr.typeid]p4:
299 // The top-level cv-qualifiers of the lvalue expression or the type-id
300 // that is the operand of typeid are always ignored.
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000301 // FIXME: Preserve type source info.
Douglas Gregorf57f2072009-12-23 20:51:04 +0000302 // FIXME: Preserve the type before we stripped the cv-qualifiers?
Douglas Gregor765ccba2009-12-23 21:06:06 +0000303 QualType T = GetTypeFromParser(TyOrExpr);
304 if (T.isNull())
305 return ExprError();
306
307 // C++ [expr.typeid]p4:
308 // If the type of the type-id is a class type or a reference to a class
309 // type, the class shall be completely-defined.
310 QualType CheckT = T;
311 if (const ReferenceType *RefType = CheckT->getAs<ReferenceType>())
312 CheckT = RefType->getPointeeType();
313
314 if (CheckT->getAs<RecordType>() &&
315 RequireCompleteType(OpLoc, CheckT, diag::err_incomplete_typeid))
316 return ExprError();
317
318 TyOrExpr = T.getUnqualifiedType().getAsOpaquePtr();
Douglas Gregorf57f2072009-12-23 20:51:04 +0000319 }
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000320
Chris Lattner572af492008-11-20 05:51:55 +0000321 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
John McCalla24dc2e2009-11-17 02:14:36 +0000322 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
323 LookupQualifiedName(R, StdNamespace);
John McCall1bcee0a2009-12-02 08:25:40 +0000324 RecordDecl *TypeInfoRecordDecl = R.getAsSingle<RecordDecl>();
Chris Lattner572af492008-11-20 05:51:55 +0000325 if (!TypeInfoRecordDecl)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000326 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Sebastian Redlc42e1182008-11-11 11:37:55 +0000327
328 QualType TypeInfoType = Context.getTypeDeclType(TypeInfoRecordDecl);
329
Douglas Gregorac7610d2009-06-22 20:57:11 +0000330 if (!isType) {
Douglas Gregorac7610d2009-06-22 20:57:11 +0000331 bool isUnevaluatedOperand = true;
332 Expr *E = static_cast<Expr *>(TyOrExpr);
Douglas Gregorf57f2072009-12-23 20:51:04 +0000333 if (E && !E->isTypeDependent()) {
Douglas Gregorac7610d2009-06-22 20:57:11 +0000334 QualType T = E->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000335 if (const RecordType *RecordT = T->getAs<RecordType>()) {
Douglas Gregorac7610d2009-06-22 20:57:11 +0000336 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
Douglas Gregorf57f2072009-12-23 20:51:04 +0000337 // C++ [expr.typeid]p3:
John McCall86ff3082010-02-04 22:26:26 +0000338 // [...] If the type of the expression is a class type, the class
339 // shall be completely-defined.
340 if (RequireCompleteType(OpLoc, T, diag::err_incomplete_typeid))
341 return ExprError();
342
343 // C++ [expr.typeid]p3:
Douglas Gregorf57f2072009-12-23 20:51:04 +0000344 // When typeid is applied to an expression other than an lvalue of a
345 // polymorphic class type [...] [the] expression is an unevaluated
346 // operand. [...]
347 if (RecordD->isPolymorphic() && E->isLvalue(Context) == Expr::LV_Valid)
Douglas Gregorac7610d2009-06-22 20:57:11 +0000348 isUnevaluatedOperand = false;
Douglas Gregorf57f2072009-12-23 20:51:04 +0000349 }
350
351 // C++ [expr.typeid]p4:
352 // [...] If the type of the type-id is a reference to a possibly
353 // cv-qualified type, the result of the typeid expression refers to a
354 // std::type_info object representing the cv-unqualified referenced
355 // type.
356 if (T.hasQualifiers()) {
357 ImpCastExprToType(E, T.getUnqualifiedType(), CastExpr::CK_NoOp,
358 E->isLvalue(Context));
359 TyOrExpr = E;
Douglas Gregorac7610d2009-06-22 20:57:11 +0000360 }
361 }
Mike Stump1eb44332009-09-09 15:08:12 +0000362
Douglas Gregor2afce722009-11-26 00:44:06 +0000363 // If this is an unevaluated operand, clear out the set of
364 // declaration references we have been computing and eliminate any
365 // temporaries introduced in its computation.
Douglas Gregorac7610d2009-06-22 20:57:11 +0000366 if (isUnevaluatedOperand)
Douglas Gregor2afce722009-11-26 00:44:06 +0000367 ExprEvalContexts.back().Context = Unevaluated;
Douglas Gregorac7610d2009-06-22 20:57:11 +0000368 }
Mike Stump1eb44332009-09-09 15:08:12 +0000369
Sebastian Redlf53597f2009-03-15 17:47:39 +0000370 return Owned(new (Context) CXXTypeidExpr(isType, TyOrExpr,
371 TypeInfoType.withConst(),
372 SourceRange(OpLoc, RParenLoc)));
Sebastian Redlc42e1182008-11-11 11:37:55 +0000373}
374
Steve Naroff1b273c42007-09-16 14:56:35 +0000375/// ActOnCXXBoolLiteral - Parse {true,false} literals.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000376Action::OwningExprResult
Steve Naroff1b273c42007-09-16 14:56:35 +0000377Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor2f639b92008-10-24 15:36:09 +0000378 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000379 "Unknown C++ Boolean value!");
Sebastian Redlf53597f2009-03-15 17:47:39 +0000380 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
381 Context.BoolTy, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000382}
Chris Lattner50dd2892008-02-26 00:51:44 +0000383
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000384/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
385Action::OwningExprResult
386Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
387 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
388}
389
Chris Lattner50dd2892008-02-26 00:51:44 +0000390/// ActOnCXXThrow - Parse throw expressions.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000391Action::OwningExprResult
392Sema::ActOnCXXThrow(SourceLocation OpLoc, ExprArg E) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000393 Expr *Ex = E.takeAs<Expr>();
394 if (Ex && !Ex->isTypeDependent() && CheckCXXThrowOperand(OpLoc, Ex))
395 return ExprError();
396 return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc));
397}
398
399/// CheckCXXThrowOperand - Validate the operand of a throw.
400bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *&E) {
401 // C++ [except.throw]p3:
Douglas Gregor154fe982009-12-23 22:04:40 +0000402 // A throw-expression initializes a temporary object, called the exception
403 // object, the type of which is determined by removing any top-level
404 // cv-qualifiers from the static type of the operand of throw and adjusting
405 // the type from "array of T" or "function returning T" to "pointer to T"
406 // or "pointer to function returning T", [...]
407 if (E->getType().hasQualifiers())
408 ImpCastExprToType(E, E->getType().getUnqualifiedType(), CastExpr::CK_NoOp,
409 E->isLvalue(Context) == Expr::LV_Valid);
410
Sebastian Redl972041f2009-04-27 20:27:31 +0000411 DefaultFunctionArrayConversion(E);
412
413 // If the type of the exception would be an incomplete type or a pointer
414 // to an incomplete type other than (cv) void the program is ill-formed.
415 QualType Ty = E->getType();
416 int isPointer = 0;
Ted Kremenek6217b802009-07-29 21:53:49 +0000417 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000418 Ty = Ptr->getPointeeType();
419 isPointer = 1;
420 }
421 if (!isPointer || !Ty->isVoidType()) {
422 if (RequireCompleteType(ThrowLoc, Ty,
Anders Carlssond497ba72009-08-26 22:59:12 +0000423 PDiag(isPointer ? diag::err_throw_incomplete_ptr
424 : diag::err_throw_incomplete)
425 << E->getSourceRange()))
Sebastian Redl972041f2009-04-27 20:27:31 +0000426 return true;
427 }
428
429 // FIXME: Construct a temporary here.
430 return false;
Chris Lattner50dd2892008-02-26 00:51:44 +0000431}
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000432
Sebastian Redlf53597f2009-03-15 17:47:39 +0000433Action::OwningExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000434 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
435 /// is a non-lvalue expression whose value is the address of the object for
436 /// which the function is called.
437
Sebastian Redlf53597f2009-03-15 17:47:39 +0000438 if (!isa<FunctionDecl>(CurContext))
439 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000440
441 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext))
442 if (MD->isInstance())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000443 return Owned(new (Context) CXXThisExpr(ThisLoc,
Douglas Gregor828a1972010-01-07 23:12:05 +0000444 MD->getThisType(Context),
445 /*isImplicit=*/false));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000446
Sebastian Redlf53597f2009-03-15 17:47:39 +0000447 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000448}
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000449
450/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
451/// Can be interpreted either as function-style casting ("int(x)")
452/// or class type construction ("ClassType(x,y,z)")
453/// or creation of a value-initialized type ("int()").
Sebastian Redlf53597f2009-03-15 17:47:39 +0000454Action::OwningExprResult
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000455Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep,
456 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000457 MultiExprArg exprs,
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000458 SourceLocation *CommaLocs,
459 SourceLocation RParenLoc) {
Douglas Gregorae4c77d2010-02-05 19:11:37 +0000460 if (!TypeRep)
461 return ExprError();
462
John McCall9d125032010-01-15 18:39:57 +0000463 TypeSourceInfo *TInfo;
464 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
465 if (!TInfo)
466 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
Sebastian Redlf53597f2009-03-15 17:47:39 +0000467 unsigned NumExprs = exprs.size();
468 Expr **Exprs = (Expr**)exprs.get();
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000469 SourceLocation TyBeginLoc = TypeRange.getBegin();
470 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
471
Sebastian Redlf53597f2009-03-15 17:47:39 +0000472 if (Ty->isDependentType() ||
Douglas Gregorba498172009-03-13 21:01:28 +0000473 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
Sebastian Redlf53597f2009-03-15 17:47:39 +0000474 exprs.release();
Mike Stump1eb44332009-09-09 15:08:12 +0000475
476 return Owned(CXXUnresolvedConstructExpr::Create(Context,
477 TypeRange.getBegin(), Ty,
Douglas Gregord81e6ca2009-05-20 18:46:25 +0000478 LParenLoc,
479 Exprs, NumExprs,
480 RParenLoc));
Douglas Gregorba498172009-03-13 21:01:28 +0000481 }
482
Anders Carlssonbb60a502009-08-27 03:53:50 +0000483 if (Ty->isArrayType())
484 return ExprError(Diag(TyBeginLoc,
485 diag::err_value_init_for_array_type) << FullRange);
486 if (!Ty->isVoidType() &&
487 RequireCompleteType(TyBeginLoc, Ty,
488 PDiag(diag::err_invalid_incomplete_type_use)
489 << FullRange))
490 return ExprError();
Fariborz Jahanianf071e9b2009-10-23 21:01:39 +0000491
Anders Carlssonbb60a502009-08-27 03:53:50 +0000492 if (RequireNonAbstractType(TyBeginLoc, Ty,
493 diag::err_allocation_of_abstract_type))
494 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000495
496
Douglas Gregor506ae412009-01-16 18:33:17 +0000497 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000498 // If the expression list is a single expression, the type conversion
499 // expression is equivalent (in definedness, and if defined in meaning) to the
500 // corresponding cast expression.
501 //
502 if (NumExprs == 1) {
Anders Carlssoncdb61972009-08-07 22:21:05 +0000503 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Anders Carlsson0aebc812009-09-09 21:33:21 +0000504 CXXMethodDecl *Method = 0;
505 if (CheckCastTypes(TypeRange, Ty, Exprs[0], Kind, Method,
506 /*FunctionalStyle=*/true))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000507 return ExprError();
Anders Carlsson0aebc812009-09-09 21:33:21 +0000508
509 exprs.release();
510 if (Method) {
511 OwningExprResult CastArg
512 = BuildCXXCastArgument(TypeRange.getBegin(), Ty.getNonReferenceType(),
513 Kind, Method, Owned(Exprs[0]));
514 if (CastArg.isInvalid())
515 return ExprError();
516
517 Exprs[0] = CastArg.takeAs<Expr>();
Fariborz Jahanian4fc7ab32009-08-28 15:11:24 +0000518 }
Anders Carlsson0aebc812009-09-09 21:33:21 +0000519
520 return Owned(new (Context) CXXFunctionalCastExpr(Ty.getNonReferenceType(),
John McCall9d125032010-01-15 18:39:57 +0000521 TInfo, TyBeginLoc, Kind,
Anders Carlsson0aebc812009-09-09 21:33:21 +0000522 Exprs[0], RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000523 }
524
Ted Kremenek6217b802009-07-29 21:53:49 +0000525 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Douglas Gregor506ae412009-01-16 18:33:17 +0000526 CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
Sebastian Redlf53597f2009-03-15 17:47:39 +0000527
Mike Stump1eb44332009-09-09 15:08:12 +0000528 if (NumExprs > 1 || !Record->hasTrivialConstructor() ||
Anders Carlssone7624a72009-08-27 05:08:22 +0000529 !Record->hasTrivialDestructor()) {
Eli Friedman6997aae2010-01-31 20:58:15 +0000530 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty);
531 InitializationKind Kind
532 = NumExprs ? InitializationKind::CreateDirect(TypeRange.getBegin(),
533 LParenLoc, RParenLoc)
534 : InitializationKind::CreateValue(TypeRange.getBegin(),
535 LParenLoc, RParenLoc);
536 InitializationSequence InitSeq(*this, Entity, Kind, Exprs, NumExprs);
537 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
538 move(exprs));
Douglas Gregor506ae412009-01-16 18:33:17 +0000539
Eli Friedman6997aae2010-01-31 20:58:15 +0000540 // FIXME: Improve AST representation?
541 return move(Result);
Douglas Gregor506ae412009-01-16 18:33:17 +0000542 }
543
544 // Fall through to value-initialize an object of class type that
545 // doesn't have a user-declared default constructor.
546 }
547
548 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000549 // If the expression list specifies more than a single value, the type shall
550 // be a class with a suitably declared constructor.
551 //
552 if (NumExprs > 1)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000553 return ExprError(Diag(CommaLocs[0],
554 diag::err_builtin_func_cast_more_than_one_arg)
555 << FullRange);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000556
557 assert(NumExprs == 0 && "Expected 0 expressions");
Douglas Gregor506ae412009-01-16 18:33:17 +0000558 // C++ [expr.type.conv]p2:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000559 // The expression T(), where T is a simple-type-specifier for a non-array
560 // complete object type or the (possibly cv-qualified) void type, creates an
561 // rvalue of the specified type, which is value-initialized.
562 //
Sebastian Redlf53597f2009-03-15 17:47:39 +0000563 exprs.release();
564 return Owned(new (Context) CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000565}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000566
567
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000568/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
569/// @code new (memory) int[size][4] @endcode
570/// or
571/// @code ::new Foo(23, "hello") @endcode
572/// For the interpretation of this heap of arguments, consult the base version.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000573Action::OwningExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000574Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000575 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000576 SourceLocation PlacementRParen, bool ParenTypeId,
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000577 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000578 MultiExprArg ConstructorArgs,
Mike Stump1eb44332009-09-09 15:08:12 +0000579 SourceLocation ConstructorRParen) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000580 Expr *ArraySize = 0;
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000581 // If the specified type is an array, unwrap it and save the expression.
582 if (D.getNumTypeObjects() > 0 &&
583 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
584 DeclaratorChunk &Chunk = D.getTypeObject(0);
585 if (Chunk.Arr.hasStatic)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000586 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
587 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000588 if (!Chunk.Arr.NumElts)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000589 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
590 << D.getSourceRange());
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000591
592 if (ParenTypeId) {
593 // Can't have dynamic array size when the type-id is in parentheses.
594 Expr *NumElts = (Expr *)Chunk.Arr.NumElts;
595 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
596 !NumElts->isIntegerConstantExpr(Context)) {
597 Diag(D.getTypeObject(0).Loc, diag::err_new_paren_array_nonconst)
598 << NumElts->getSourceRange();
599 return ExprError();
600 }
601 }
602
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000603 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000604 D.DropFirstTypeObject();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000605 }
606
Douglas Gregor043cad22009-09-11 00:18:58 +0000607 // Every dimension shall be of constant size.
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000608 if (ArraySize) {
609 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor043cad22009-09-11 00:18:58 +0000610 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
611 break;
612
613 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
614 if (Expr *NumElts = (Expr *)Array.NumElts) {
615 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
616 !NumElts->isIntegerConstantExpr(Context)) {
617 Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst)
618 << NumElts->getSourceRange();
619 return ExprError();
620 }
621 }
622 }
623 }
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000624
John McCalla93c9342009-12-07 02:54:59 +0000625 //FIXME: Store TypeSourceInfo in CXXNew expression.
626 TypeSourceInfo *TInfo = 0;
627 QualType AllocType = GetTypeForDeclarator(D, /*Scope=*/0, &TInfo);
Chris Lattnereaaebc72009-04-25 08:06:05 +0000628 if (D.isInvalidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000629 return ExprError();
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000630
Mike Stump1eb44332009-09-09 15:08:12 +0000631 return BuildCXXNew(StartLoc, UseGlobal,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000632 PlacementLParen,
Mike Stump1eb44332009-09-09 15:08:12 +0000633 move(PlacementArgs),
Douglas Gregor3433cf72009-05-21 00:00:09 +0000634 PlacementRParen,
635 ParenTypeId,
Mike Stump1eb44332009-09-09 15:08:12 +0000636 AllocType,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000637 D.getSourceRange().getBegin(),
638 D.getSourceRange(),
639 Owned(ArraySize),
640 ConstructorLParen,
641 move(ConstructorArgs),
642 ConstructorRParen);
643}
644
Mike Stump1eb44332009-09-09 15:08:12 +0000645Sema::OwningExprResult
Douglas Gregor3433cf72009-05-21 00:00:09 +0000646Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
647 SourceLocation PlacementLParen,
648 MultiExprArg PlacementArgs,
649 SourceLocation PlacementRParen,
Mike Stump1eb44332009-09-09 15:08:12 +0000650 bool ParenTypeId,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000651 QualType AllocType,
652 SourceLocation TypeLoc,
653 SourceRange TypeRange,
654 ExprArg ArraySizeE,
655 SourceLocation ConstructorLParen,
656 MultiExprArg ConstructorArgs,
657 SourceLocation ConstructorRParen) {
658 if (CheckAllocatedType(AllocType, TypeLoc, TypeRange))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000659 return ExprError();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000660
Douglas Gregor3433cf72009-05-21 00:00:09 +0000661 QualType ResultType = Context.getPointerType(AllocType);
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000662
663 // That every array dimension except the first is constant was already
664 // checked by the type check above.
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000665
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000666 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
667 // or enumeration type with a non-negative value."
Douglas Gregor3433cf72009-05-21 00:00:09 +0000668 Expr *ArraySize = (Expr *)ArraySizeE.get();
Sebastian Redl28507842009-02-26 14:39:58 +0000669 if (ArraySize && !ArraySize->isTypeDependent()) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000670 QualType SizeType = ArraySize->getType();
671 if (!SizeType->isIntegralType() && !SizeType->isEnumeralType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000672 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
673 diag::err_array_size_not_integral)
674 << SizeType << ArraySize->getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000675 // Let's see if this is a constant < 0. If so, we reject it out of hand.
676 // We don't care about special rules, so we tell the machinery it's not
677 // evaluated - it gives us a result in more cases.
Sebastian Redl28507842009-02-26 14:39:58 +0000678 if (!ArraySize->isValueDependent()) {
679 llvm::APSInt Value;
680 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
681 if (Value < llvm::APSInt(
Anders Carlssonac18b2e2009-09-23 00:37:25 +0000682 llvm::APInt::getNullValue(Value.getBitWidth()),
683 Value.isUnsigned()))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000684 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
685 diag::err_typecheck_negative_array_size)
686 << ArraySize->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +0000687 }
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000688 }
Anders Carlssonac18b2e2009-09-23 00:37:25 +0000689
Eli Friedman73c39ab2009-10-20 08:27:19 +0000690 ImpCastExprToType(ArraySize, Context.getSizeType(),
691 CastExpr::CK_IntegralCast);
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000692 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000693
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000694 FunctionDecl *OperatorNew = 0;
695 FunctionDecl *OperatorDelete = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000696 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
697 unsigned NumPlaceArgs = PlacementArgs.size();
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000698
Sebastian Redl28507842009-02-26 14:39:58 +0000699 if (!AllocType->isDependentType() &&
700 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
701 FindAllocationFunctions(StartLoc,
Sebastian Redl00e68e22009-02-09 18:24:27 +0000702 SourceRange(PlacementLParen, PlacementRParen),
703 UseGlobal, AllocType, ArraySize, PlaceArgs,
704 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000705 return ExprError();
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000706 llvm::SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000707 if (OperatorNew) {
708 // Add default arguments, if any.
709 const FunctionProtoType *Proto =
710 OperatorNew->getType()->getAs<FunctionProtoType>();
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +0000711 VariadicCallType CallType =
712 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000713 bool Invalid = GatherArgumentsForCall(PlacementLParen, OperatorNew,
714 Proto, 1, PlaceArgs, NumPlaceArgs,
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +0000715 AllPlaceArgs, CallType);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000716 if (Invalid)
717 return ExprError();
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000718
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000719 NumPlaceArgs = AllPlaceArgs.size();
720 if (NumPlaceArgs > 0)
721 PlaceArgs = &AllPlaceArgs[0];
722 }
723
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000724 bool Init = ConstructorLParen.isValid();
725 // --- Choosing a constructor ---
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000726 CXXConstructorDecl *Constructor = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000727 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
728 unsigned NumConsArgs = ConstructorArgs.size();
Eli Friedmana8ce9ec2009-11-08 22:15:39 +0000729 ASTOwningVector<&ActionBase::DeleteExpr> ConvertedConstructorArgs(*this);
730
Douglas Gregor99a2e602009-12-16 01:38:02 +0000731 if (!AllocType->isDependentType() &&
732 !Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) {
733 // C++0x [expr.new]p15:
734 // A new-expression that creates an object of type T initializes that
735 // object as follows:
736 InitializationKind Kind
737 // - If the new-initializer is omitted, the object is default-
738 // initialized (8.5); if no initialization is performed,
739 // the object has indeterminate value
740 = !Init? InitializationKind::CreateDefault(TypeLoc)
741 // - Otherwise, the new-initializer is interpreted according to the
742 // initialization rules of 8.5 for direct-initialization.
743 : InitializationKind::CreateDirect(TypeLoc,
744 ConstructorLParen,
745 ConstructorRParen);
746
Douglas Gregor99a2e602009-12-16 01:38:02 +0000747 InitializedEntity Entity
Douglas Gregord6542d82009-12-22 15:35:07 +0000748 = InitializedEntity::InitializeNew(StartLoc, AllocType);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000749 InitializationSequence InitSeq(*this, Entity, Kind, ConsArgs, NumConsArgs);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000750 OwningExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
751 move(ConstructorArgs));
752 if (FullInit.isInvalid())
753 return ExprError();
754
755 // FullInit is our initializer; walk through it to determine if it's a
756 // constructor call, which CXXNewExpr handles directly.
757 if (Expr *FullInitExpr = (Expr *)FullInit.get()) {
758 if (CXXBindTemporaryExpr *Binder
759 = dyn_cast<CXXBindTemporaryExpr>(FullInitExpr))
760 FullInitExpr = Binder->getSubExpr();
761 if (CXXConstructExpr *Construct
762 = dyn_cast<CXXConstructExpr>(FullInitExpr)) {
763 Constructor = Construct->getConstructor();
764 for (CXXConstructExpr::arg_iterator A = Construct->arg_begin(),
765 AEnd = Construct->arg_end();
766 A != AEnd; ++A)
767 ConvertedConstructorArgs.push_back(A->Retain());
768 } else {
769 // Take the converted initializer.
770 ConvertedConstructorArgs.push_back(FullInit.release());
771 }
772 } else {
773 // No initialization required.
774 }
775
776 // Take the converted arguments and use them for the new expression.
Douglas Gregor39da0b82009-09-09 23:08:42 +0000777 NumConsArgs = ConvertedConstructorArgs.size();
778 ConsArgs = (Expr **)ConvertedConstructorArgs.take();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000779 }
Douglas Gregor99a2e602009-12-16 01:38:02 +0000780
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000781 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
Douglas Gregor089407b2009-10-17 21:40:42 +0000782
Sebastian Redlf53597f2009-03-15 17:47:39 +0000783 PlacementArgs.release();
784 ConstructorArgs.release();
Douglas Gregor3433cf72009-05-21 00:00:09 +0000785 ArraySizeE.release();
Ted Kremenekad7fe862010-02-11 22:51:03 +0000786 return Owned(new (Context) CXXNewExpr(Context, UseGlobal, OperatorNew,
787 PlaceArgs, NumPlaceArgs, ParenTypeId,
788 ArraySize, Constructor, Init,
789 ConsArgs, NumConsArgs, OperatorDelete,
790 ResultType, StartLoc,
791 Init ? ConstructorRParen :
792 SourceLocation()));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000793}
794
795/// CheckAllocatedType - Checks that a type is suitable as the allocated type
796/// in a new-expression.
797/// dimension off and stores the size expression in ArraySize.
Douglas Gregor3433cf72009-05-21 00:00:09 +0000798bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +0000799 SourceRange R) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000800 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
801 // abstract class type or array thereof.
Douglas Gregore7450f52009-03-24 19:52:54 +0000802 if (AllocType->isFunctionType())
Douglas Gregor3433cf72009-05-21 00:00:09 +0000803 return Diag(Loc, diag::err_bad_new_type)
804 << AllocType << 0 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +0000805 else if (AllocType->isReferenceType())
Douglas Gregor3433cf72009-05-21 00:00:09 +0000806 return Diag(Loc, diag::err_bad_new_type)
807 << AllocType << 1 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +0000808 else if (!AllocType->isDependentType() &&
Douglas Gregor3433cf72009-05-21 00:00:09 +0000809 RequireCompleteType(Loc, AllocType,
Anders Carlssonb7906612009-08-26 23:45:07 +0000810 PDiag(diag::err_new_incomplete_type)
811 << R))
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000812 return true;
Douglas Gregor3433cf72009-05-21 00:00:09 +0000813 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregore7450f52009-03-24 19:52:54 +0000814 diag::err_allocation_of_abstract_type))
815 return true;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000816
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000817 return false;
818}
819
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000820/// FindAllocationFunctions - Finds the overloads of operator new and delete
821/// that are appropriate for the allocation.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000822bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
823 bool UseGlobal, QualType AllocType,
824 bool IsArray, Expr **PlaceArgs,
825 unsigned NumPlaceArgs,
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000826 FunctionDecl *&OperatorNew,
Mike Stump1eb44332009-09-09 15:08:12 +0000827 FunctionDecl *&OperatorDelete) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000828 // --- Choosing an allocation function ---
829 // C++ 5.3.4p8 - 14 & 18
830 // 1) If UseGlobal is true, only look in the global scope. Else, also look
831 // in the scope of the allocated class.
832 // 2) If an array size is given, look for operator new[], else look for
833 // operator new.
834 // 3) The first argument is always size_t. Append the arguments from the
835 // placement form.
836 // FIXME: Also find the appropriate delete operator.
837
838 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
839 // We don't care about the actual value of this argument.
840 // FIXME: Should the Sema create the expression and embed it in the syntax
841 // tree? Or should the consumer just recalculate the value?
Anders Carlssond67c4c32009-08-16 20:29:29 +0000842 IntegerLiteral Size(llvm::APInt::getNullValue(
843 Context.Target.getPointerWidth(0)),
844 Context.getSizeType(),
845 SourceLocation());
846 AllocArgs[0] = &Size;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000847 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
848
849 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
850 IsArray ? OO_Array_New : OO_New);
851 if (AllocType->isRecordType() && !UseGlobal) {
Mike Stump1eb44332009-09-09 15:08:12 +0000852 CXXRecordDecl *Record
Ted Kremenek6217b802009-07-29 21:53:49 +0000853 = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl());
Sebastian Redl7f662392008-12-04 22:20:51 +0000854 // FIXME: We fail to find inherited overloads.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000855 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000856 AllocArgs.size(), Record, /*AllowMissing=*/true,
857 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000858 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000859 }
860 if (!OperatorNew) {
861 // Didn't find a member overload. Look for a global one.
862 DeclareGlobalNewDelete();
Sebastian Redl7f662392008-12-04 22:20:51 +0000863 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl00e68e22009-02-09 18:24:27 +0000864 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000865 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
866 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000867 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000868 }
869
Anders Carlssond9583892009-05-31 20:26:12 +0000870 // FindAllocationOverload can change the passed in arguments, so we need to
871 // copy them back.
872 if (NumPlaceArgs > 0)
873 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
Mike Stump1eb44332009-09-09 15:08:12 +0000874
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000875 return false;
876}
877
Sebastian Redl7f662392008-12-04 22:20:51 +0000878/// FindAllocationOverload - Find an fitting overload for the allocation
879/// function in the specified scope.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000880bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
881 DeclarationName Name, Expr** Args,
882 unsigned NumArgs, DeclContext *Ctx,
Mike Stump1eb44332009-09-09 15:08:12 +0000883 bool AllowMissing, FunctionDecl *&Operator) {
John McCalla24dc2e2009-11-17 02:14:36 +0000884 LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
885 LookupQualifiedName(R, Ctx);
John McCallf36e02d2009-10-09 21:13:30 +0000886 if (R.empty()) {
Sebastian Redl7f662392008-12-04 22:20:51 +0000887 if (AllowMissing)
888 return false;
Sebastian Redl7f662392008-12-04 22:20:51 +0000889 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +0000890 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +0000891 }
892
John McCallf36e02d2009-10-09 21:13:30 +0000893 // FIXME: handle ambiguity
894
John McCall5769d612010-02-08 23:07:23 +0000895 OverloadCandidateSet Candidates(StartLoc);
Douglas Gregor5d64e5b2009-09-30 00:03:47 +0000896 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
897 Alloc != AllocEnd; ++Alloc) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000898 // Even member operator new/delete are implicitly treated as
899 // static, so don't use AddMemberCandidate.
Chandler Carruth4a73ea92010-02-03 11:02:14 +0000900
901 if (FunctionTemplateDecl *FnTemplate =
902 dyn_cast<FunctionTemplateDecl>((*Alloc)->getUnderlyingDecl())) {
903 AddTemplateOverloadCandidate(FnTemplate, Alloc.getAccess(),
904 /*ExplicitTemplateArgs=*/0, Args, NumArgs,
905 Candidates,
906 /*SuppressUserConversions=*/false);
Douglas Gregor90916562009-09-29 18:16:17 +0000907 continue;
Chandler Carruth4a73ea92010-02-03 11:02:14 +0000908 }
909
910 FunctionDecl *Fn = cast<FunctionDecl>((*Alloc)->getUnderlyingDecl());
911 AddOverloadCandidate(Fn, Alloc.getAccess(), Args, NumArgs, Candidates,
912 /*SuppressUserConversions=*/false);
Sebastian Redl7f662392008-12-04 22:20:51 +0000913 }
914
915 // Do the resolution.
916 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +0000917 switch(BestViableFunction(Candidates, StartLoc, Best)) {
Sebastian Redl7f662392008-12-04 22:20:51 +0000918 case OR_Success: {
919 // Got one!
920 FunctionDecl *FnDecl = Best->Function;
921 // The first argument is size_t, and the first parameter must be size_t,
922 // too. This is checked on declaration and can be assumed. (It can't be
923 // asserted on, though, since invalid decls are left in there.)
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000924 // Whatch out for variadic allocator function.
925 unsigned NumArgsInFnDecl = FnDecl->getNumParams();
926 for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) {
Anders Carlssonfc27d262009-05-31 19:49:47 +0000927 if (PerformCopyInitialization(Args[i],
Sebastian Redl7f662392008-12-04 22:20:51 +0000928 FnDecl->getParamDecl(i)->getType(),
Douglas Gregor68647482009-12-16 03:45:30 +0000929 AA_Passing))
Sebastian Redl7f662392008-12-04 22:20:51 +0000930 return true;
931 }
932 Operator = FnDecl;
933 return false;
934 }
935
936 case OR_No_Viable_Function:
Sebastian Redl7f662392008-12-04 22:20:51 +0000937 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +0000938 << Name << Range;
John McCallcbce6062010-01-12 07:18:19 +0000939 PrintOverloadCandidates(Candidates, OCD_AllCandidates, Args, NumArgs);
Sebastian Redl7f662392008-12-04 22:20:51 +0000940 return true;
941
942 case OR_Ambiguous:
Sebastian Redl7f662392008-12-04 22:20:51 +0000943 Diag(StartLoc, diag::err_ovl_ambiguous_call)
Sebastian Redl00e68e22009-02-09 18:24:27 +0000944 << Name << Range;
John McCallcbce6062010-01-12 07:18:19 +0000945 PrintOverloadCandidates(Candidates, OCD_ViableCandidates, Args, NumArgs);
Sebastian Redl7f662392008-12-04 22:20:51 +0000946 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000947
948 case OR_Deleted:
949 Diag(StartLoc, diag::err_ovl_deleted_call)
950 << Best->Function->isDeleted()
951 << Name << Range;
John McCallcbce6062010-01-12 07:18:19 +0000952 PrintOverloadCandidates(Candidates, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000953 return true;
Sebastian Redl7f662392008-12-04 22:20:51 +0000954 }
955 assert(false && "Unreachable, bad result from BestViableFunction");
956 return true;
957}
958
959
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000960/// DeclareGlobalNewDelete - Declare the global forms of operator new and
961/// delete. These are:
962/// @code
963/// void* operator new(std::size_t) throw(std::bad_alloc);
964/// void* operator new[](std::size_t) throw(std::bad_alloc);
965/// void operator delete(void *) throw();
966/// void operator delete[](void *) throw();
967/// @endcode
968/// Note that the placement and nothrow forms of new are *not* implicitly
969/// declared. Their use requires including \<new\>.
Mike Stump1eb44332009-09-09 15:08:12 +0000970void Sema::DeclareGlobalNewDelete() {
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000971 if (GlobalNewDeleteDeclared)
972 return;
Douglas Gregor7adb10f2009-09-15 22:30:29 +0000973
974 // C++ [basic.std.dynamic]p2:
975 // [...] The following allocation and deallocation functions (18.4) are
976 // implicitly declared in global scope in each translation unit of a
977 // program
978 //
979 // void* operator new(std::size_t) throw(std::bad_alloc);
980 // void* operator new[](std::size_t) throw(std::bad_alloc);
981 // void operator delete(void*) throw();
982 // void operator delete[](void*) throw();
983 //
984 // These implicit declarations introduce only the function names operator
985 // new, operator new[], operator delete, operator delete[].
986 //
987 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
988 // "std" or "bad_alloc" as necessary to form the exception specification.
989 // However, we do not make these implicit declarations visible to name
990 // lookup.
991 if (!StdNamespace) {
992 // The "std" namespace has not yet been defined, so build one implicitly.
993 StdNamespace = NamespaceDecl::Create(Context,
994 Context.getTranslationUnitDecl(),
995 SourceLocation(),
996 &PP.getIdentifierTable().get("std"));
997 StdNamespace->setImplicit(true);
998 }
999
1000 if (!StdBadAlloc) {
1001 // The "std::bad_alloc" class has not yet been declared, so build it
1002 // implicitly.
1003 StdBadAlloc = CXXRecordDecl::Create(Context, TagDecl::TK_class,
1004 StdNamespace,
1005 SourceLocation(),
1006 &PP.getIdentifierTable().get("bad_alloc"),
1007 SourceLocation(), 0);
1008 StdBadAlloc->setImplicit(true);
1009 }
1010
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001011 GlobalNewDeleteDeclared = true;
1012
1013 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
1014 QualType SizeT = Context.getSizeType();
Nuno Lopesfc284482009-12-16 16:59:22 +00001015 bool AssumeSaneOperatorNew = getLangOptions().AssumeSaneOperatorNew;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001016
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001017 DeclareGlobalAllocationFunction(
1018 Context.DeclarationNames.getCXXOperatorName(OO_New),
Nuno Lopesfc284482009-12-16 16:59:22 +00001019 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001020 DeclareGlobalAllocationFunction(
1021 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
Nuno Lopesfc284482009-12-16 16:59:22 +00001022 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001023 DeclareGlobalAllocationFunction(
1024 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
1025 Context.VoidTy, VoidPtr);
1026 DeclareGlobalAllocationFunction(
1027 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
1028 Context.VoidTy, VoidPtr);
1029}
1030
1031/// DeclareGlobalAllocationFunction - Declares a single implicit global
1032/// allocation function if it doesn't already exist.
1033void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Nuno Lopesfc284482009-12-16 16:59:22 +00001034 QualType Return, QualType Argument,
1035 bool AddMallocAttr) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001036 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
1037
1038 // Check if this function is already declared.
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001039 {
Douglas Gregor5cc37092008-12-23 22:05:29 +00001040 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001041 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001042 Alloc != AllocEnd; ++Alloc) {
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001043 // Only look at non-template functions, as it is the predefined,
1044 // non-templated allocation function we are trying to declare here.
1045 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
1046 QualType InitialParamType =
Douglas Gregor6e790ab2009-12-22 23:42:49 +00001047 Context.getCanonicalType(
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001048 Func->getParamDecl(0)->getType().getUnqualifiedType());
1049 // FIXME: Do we need to check for default arguments here?
1050 if (Func->getNumParams() == 1 && InitialParamType == Argument)
1051 return;
1052 }
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001053 }
1054 }
1055
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001056 QualType BadAllocType;
1057 bool HasBadAllocExceptionSpec
1058 = (Name.getCXXOverloadedOperator() == OO_New ||
1059 Name.getCXXOverloadedOperator() == OO_Array_New);
1060 if (HasBadAllocExceptionSpec) {
1061 assert(StdBadAlloc && "Must have std::bad_alloc declared");
1062 BadAllocType = Context.getTypeDeclType(StdBadAlloc);
1063 }
1064
1065 QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0,
1066 true, false,
1067 HasBadAllocExceptionSpec? 1 : 0,
Douglas Gregorce056bc2010-02-21 22:15:06 +00001068 &BadAllocType, false, CC_Default);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001069 FunctionDecl *Alloc =
1070 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
John McCalla93c9342009-12-07 02:54:59 +00001071 FnType, /*TInfo=*/0, FunctionDecl::None, false, true);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001072 Alloc->setImplicit();
Nuno Lopesfc284482009-12-16 16:59:22 +00001073
1074 if (AddMallocAttr)
1075 Alloc->addAttr(::new (Context) MallocAttr());
1076
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001077 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
John McCalla93c9342009-12-07 02:54:59 +00001078 0, Argument, /*TInfo=*/0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001079 VarDecl::None, 0);
Douglas Gregor838db382010-02-11 01:19:42 +00001080 Alloc->setParams(&Param, 1);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001081
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001082 // FIXME: Also add this declaration to the IdentifierResolver, but
1083 // make sure it is at the end of the chain to coincide with the
1084 // global scope.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001085 ((DeclContext *)TUScope->getEntity())->addDecl(Alloc);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001086}
1087
Anders Carlsson78f74552009-11-15 18:45:20 +00001088bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
1089 DeclarationName Name,
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00001090 FunctionDecl* &Operator) {
John McCalla24dc2e2009-11-17 02:14:36 +00001091 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlsson78f74552009-11-15 18:45:20 +00001092 // Try to find operator delete/operator delete[] in class scope.
John McCalla24dc2e2009-11-17 02:14:36 +00001093 LookupQualifiedName(Found, RD);
Anders Carlsson78f74552009-11-15 18:45:20 +00001094
John McCalla24dc2e2009-11-17 02:14:36 +00001095 if (Found.isAmbiguous())
Anders Carlsson78f74552009-11-15 18:45:20 +00001096 return true;
Anders Carlsson78f74552009-11-15 18:45:20 +00001097
1098 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1099 F != FEnd; ++F) {
1100 if (CXXMethodDecl *Delete = dyn_cast<CXXMethodDecl>(*F))
1101 if (Delete->isUsualDeallocationFunction()) {
1102 Operator = Delete;
1103 return false;
1104 }
1105 }
1106
1107 // We did find operator delete/operator delete[] declarations, but
1108 // none of them were suitable.
1109 if (!Found.empty()) {
1110 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
1111 << Name << RD;
1112
1113 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1114 F != FEnd; ++F) {
1115 Diag((*F)->getLocation(),
1116 diag::note_delete_member_function_declared_here)
1117 << Name;
1118 }
1119
1120 return true;
1121 }
1122
1123 // Look for a global declaration.
1124 DeclareGlobalNewDelete();
1125 DeclContext *TUDecl = Context.getTranslationUnitDecl();
1126
1127 CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation());
1128 Expr* DeallocArgs[1];
1129 DeallocArgs[0] = &Null;
1130 if (FindAllocationOverload(StartLoc, SourceRange(), Name,
1131 DeallocArgs, 1, TUDecl, /*AllowMissing=*/false,
1132 Operator))
1133 return true;
1134
1135 assert(Operator && "Did not find a deallocation function!");
1136 return false;
1137}
1138
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001139/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
1140/// @code ::delete ptr; @endcode
1141/// or
1142/// @code delete [] ptr; @endcode
Sebastian Redlf53597f2009-03-15 17:47:39 +00001143Action::OwningExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001144Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
Mike Stump1eb44332009-09-09 15:08:12 +00001145 bool ArrayForm, ExprArg Operand) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001146 // C++ [expr.delete]p1:
1147 // The operand shall have a pointer type, or a class type having a single
1148 // conversion function to a pointer type. The result has type void.
1149 //
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001150 // DR599 amends "pointer type" to "pointer to object type" in both cases.
1151
Anders Carlssond67c4c32009-08-16 20:29:29 +00001152 FunctionDecl *OperatorDelete = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001153
Sebastian Redlf53597f2009-03-15 17:47:39 +00001154 Expr *Ex = (Expr *)Operand.get();
Sebastian Redl28507842009-02-26 14:39:58 +00001155 if (!Ex->isTypeDependent()) {
1156 QualType Type = Ex->getType();
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001157
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001158 if (const RecordType *Record = Type->getAs<RecordType>()) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001159 llvm::SmallVector<CXXConversionDecl *, 4> ObjectPtrConversions;
Fariborz Jahanian53462782009-09-11 21:44:33 +00001160 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
John McCalleec51cf2010-01-20 00:46:10 +00001161 const UnresolvedSetImpl *Conversions = RD->getVisibleConversionFunctions();
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001162
John McCalleec51cf2010-01-20 00:46:10 +00001163 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00001164 E = Conversions->end(); I != E; ++I) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001165 // Skip over templated conversion functions; they aren't considered.
John McCallba135432009-11-21 08:51:07 +00001166 if (isa<FunctionTemplateDecl>(*I))
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001167 continue;
1168
John McCallba135432009-11-21 08:51:07 +00001169 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*I);
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001170
1171 QualType ConvType = Conv->getConversionType().getNonReferenceType();
1172 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
1173 if (ConvPtrType->getPointeeType()->isObjectType())
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001174 ObjectPtrConversions.push_back(Conv);
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001175 }
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001176 if (ObjectPtrConversions.size() == 1) {
1177 // We have a single conversion to a pointer-to-object type. Perform
1178 // that conversion.
1179 Operand.release();
1180 if (!PerformImplicitConversion(Ex,
1181 ObjectPtrConversions.front()->getConversionType(),
Douglas Gregor68647482009-12-16 03:45:30 +00001182 AA_Converting)) {
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001183 Operand = Owned(Ex);
1184 Type = Ex->getType();
1185 }
1186 }
1187 else if (ObjectPtrConversions.size() > 1) {
1188 Diag(StartLoc, diag::err_ambiguous_delete_operand)
1189 << Type << Ex->getSourceRange();
1190 for (unsigned i= 0; i < ObjectPtrConversions.size(); i++) {
1191 CXXConversionDecl *Conv = ObjectPtrConversions[i];
John McCallb1622a12010-01-06 09:43:14 +00001192 NoteOverloadCandidate(Conv);
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001193 }
1194 return ExprError();
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001195 }
Sebastian Redl28507842009-02-26 14:39:58 +00001196 }
1197
Sebastian Redlf53597f2009-03-15 17:47:39 +00001198 if (!Type->isPointerType())
1199 return ExprError(Diag(StartLoc, diag::err_delete_operand)
1200 << Type << Ex->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +00001201
Ted Kremenek6217b802009-07-29 21:53:49 +00001202 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Douglas Gregor8dcb29d2009-03-24 20:13:58 +00001203 if (Pointee->isFunctionType() || Pointee->isVoidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +00001204 return ExprError(Diag(StartLoc, diag::err_delete_operand)
1205 << Type << Ex->getSourceRange());
Douglas Gregor8dcb29d2009-03-24 20:13:58 +00001206 else if (!Pointee->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00001207 RequireCompleteType(StartLoc, Pointee,
Anders Carlssonb7906612009-08-26 23:45:07 +00001208 PDiag(diag::warn_delete_incomplete)
1209 << Ex->getSourceRange()))
Douglas Gregor8dcb29d2009-03-24 20:13:58 +00001210 return ExprError();
Sebastian Redl28507842009-02-26 14:39:58 +00001211
Douglas Gregor1070c9f2009-09-29 21:38:53 +00001212 // C++ [expr.delete]p2:
1213 // [Note: a pointer to a const type can be the operand of a
1214 // delete-expression; it is not necessary to cast away the constness
1215 // (5.2.11) of the pointer expression before it is used as the operand
1216 // of the delete-expression. ]
1217 ImpCastExprToType(Ex, Context.getPointerType(Context.VoidTy),
1218 CastExpr::CK_NoOp);
1219
1220 // Update the operand.
1221 Operand.take();
1222 Operand = ExprArg(*this, Ex);
1223
Anders Carlssond67c4c32009-08-16 20:29:29 +00001224 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1225 ArrayForm ? OO_Array_Delete : OO_Delete);
1226
Anders Carlsson78f74552009-11-15 18:45:20 +00001227 if (const RecordType *RT = Pointee->getAs<RecordType>()) {
1228 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1229
1230 if (!UseGlobal &&
1231 FindDeallocationFunction(StartLoc, RD, DeleteName, OperatorDelete))
Anders Carlsson0ba63ea2009-11-14 03:17:38 +00001232 return ExprError();
Anders Carlsson0ba63ea2009-11-14 03:17:38 +00001233
Anders Carlsson78f74552009-11-15 18:45:20 +00001234 if (!RD->hasTrivialDestructor())
1235 if (const CXXDestructorDecl *Dtor = RD->getDestructor(Context))
Mike Stump1eb44332009-09-09 15:08:12 +00001236 MarkDeclarationReferenced(StartLoc,
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001237 const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssond67c4c32009-08-16 20:29:29 +00001238 }
Anders Carlsson78f74552009-11-15 18:45:20 +00001239
Anders Carlssond67c4c32009-08-16 20:29:29 +00001240 if (!OperatorDelete) {
Anders Carlsson78f74552009-11-15 18:45:20 +00001241 // Look for a global declaration.
Anders Carlssond67c4c32009-08-16 20:29:29 +00001242 DeclareGlobalNewDelete();
1243 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001244 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
Douglas Gregor90916562009-09-29 18:16:17 +00001245 &Ex, 1, TUDecl, /*AllowMissing=*/false,
Anders Carlssond67c4c32009-08-16 20:29:29 +00001246 OperatorDelete))
1247 return ExprError();
1248 }
Mike Stump1eb44332009-09-09 15:08:12 +00001249
Sebastian Redl28507842009-02-26 14:39:58 +00001250 // FIXME: Check access and ambiguity of operator delete and destructor.
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001251 }
1252
Sebastian Redlf53597f2009-03-15 17:47:39 +00001253 Operand.release();
1254 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
Anders Carlssond67c4c32009-08-16 20:29:29 +00001255 OperatorDelete, Ex, StartLoc));
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001256}
1257
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001258/// \brief Check the use of the given variable as a C++ condition in an if,
1259/// while, do-while, or switch statement.
1260Action::OwningExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar) {
1261 QualType T = ConditionVar->getType();
1262
1263 // C++ [stmt.select]p2:
1264 // The declarator shall not specify a function or an array.
1265 if (T->isFunctionType())
1266 return ExprError(Diag(ConditionVar->getLocation(),
1267 diag::err_invalid_use_of_function_type)
1268 << ConditionVar->getSourceRange());
1269 else if (T->isArrayType())
1270 return ExprError(Diag(ConditionVar->getLocation(),
1271 diag::err_invalid_use_of_array_type)
1272 << ConditionVar->getSourceRange());
Douglas Gregora7605db2009-11-24 16:07:02 +00001273
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001274 return Owned(DeclRefExpr::Create(Context, 0, SourceRange(), ConditionVar,
1275 ConditionVar->getLocation(),
1276 ConditionVar->getType().getNonReferenceType()));
1277}
1278
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001279/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
1280bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
1281 // C++ 6.4p4:
1282 // The value of a condition that is an initialized declaration in a statement
1283 // other than a switch statement is the value of the declared variable
1284 // implicitly converted to type bool. If that conversion is ill-formed, the
1285 // program is ill-formed.
1286 // The value of a condition that is an expression is the value of the
1287 // expression, implicitly converted to bool.
1288 //
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001289 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001290}
Douglas Gregor77a52232008-09-12 00:47:35 +00001291
1292/// Helper function to determine whether this is the (deprecated) C++
1293/// conversion from a string literal to a pointer to non-const char or
1294/// non-const wchar_t (for narrow and wide string literals,
1295/// respectively).
Mike Stump1eb44332009-09-09 15:08:12 +00001296bool
Douglas Gregor77a52232008-09-12 00:47:35 +00001297Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
1298 // Look inside the implicit cast, if it exists.
1299 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
1300 From = Cast->getSubExpr();
1301
1302 // A string literal (2.13.4) that is not a wide string literal can
1303 // be converted to an rvalue of type "pointer to char"; a wide
1304 // string literal can be converted to an rvalue of type "pointer
1305 // to wchar_t" (C++ 4.2p2).
1306 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From))
Ted Kremenek6217b802009-07-29 21:53:49 +00001307 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump1eb44332009-09-09 15:08:12 +00001308 if (const BuiltinType *ToPointeeType
John McCall183700f2009-09-21 23:43:11 +00001309 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregor77a52232008-09-12 00:47:35 +00001310 // This conversion is considered only when there is an
1311 // explicit appropriate pointer target type (C++ 4.2p2).
John McCall0953e762009-09-24 19:53:00 +00001312 if (!ToPtrType->getPointeeType().hasQualifiers() &&
Douglas Gregor77a52232008-09-12 00:47:35 +00001313 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
1314 (!StrLit->isWide() &&
1315 (ToPointeeType->getKind() == BuiltinType::Char_U ||
1316 ToPointeeType->getKind() == BuiltinType::Char_S))))
1317 return true;
1318 }
1319
1320 return false;
1321}
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001322
1323/// PerformImplicitConversion - Perform an implicit conversion of the
1324/// expression From to the type ToType. Returns true if there was an
1325/// error, false otherwise. The expression From is replaced with the
Douglas Gregor45920e82008-12-19 17:40:08 +00001326/// converted expression. Flavor is the kind of conversion we're
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001327/// performing, used in the error message. If @p AllowExplicit,
Sebastian Redle2b68332009-04-12 17:16:29 +00001328/// explicit user-defined conversions are permitted. @p Elidable should be true
1329/// when called for copies which may be elided (C++ 12.8p15). C++0x overload
1330/// resolution works differently in that case.
1331bool
Douglas Gregor45920e82008-12-19 17:40:08 +00001332Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor68647482009-12-16 03:45:30 +00001333 AssignmentAction Action, bool AllowExplicit,
Mike Stump1eb44332009-09-09 15:08:12 +00001334 bool Elidable) {
Sebastian Redle2b68332009-04-12 17:16:29 +00001335 ImplicitConversionSequence ICS;
Douglas Gregor68647482009-12-16 03:45:30 +00001336 return PerformImplicitConversion(From, ToType, Action, AllowExplicit,
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00001337 Elidable, ICS);
1338}
1339
1340bool
1341Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor68647482009-12-16 03:45:30 +00001342 AssignmentAction Action, bool AllowExplicit,
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00001343 bool Elidable,
1344 ImplicitConversionSequence& ICS) {
John McCall1d318332010-01-12 00:44:57 +00001345 ICS.setBad();
John McCalladbb8f82010-01-13 09:16:55 +00001346 ICS.Bad.init(BadConversionSequence::no_conversion, From, ToType);
Sebastian Redle2b68332009-04-12 17:16:29 +00001347 if (Elidable && getLangOptions().CPlusPlus0x) {
Mike Stump1eb44332009-09-09 15:08:12 +00001348 ICS = TryImplicitConversion(From, ToType,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001349 /*SuppressUserConversions=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +00001350 AllowExplicit,
Anders Carlsson08972922009-08-28 15:33:32 +00001351 /*ForceRValue=*/true,
1352 /*InOverloadResolution=*/false);
Sebastian Redle2b68332009-04-12 17:16:29 +00001353 }
John McCall1d318332010-01-12 00:44:57 +00001354 if (ICS.isBad()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001355 ICS = TryImplicitConversion(From, ToType,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001356 /*SuppressUserConversions=*/false,
1357 AllowExplicit,
Anders Carlsson08972922009-08-28 15:33:32 +00001358 /*ForceRValue=*/false,
1359 /*InOverloadResolution=*/false);
Sebastian Redle2b68332009-04-12 17:16:29 +00001360 }
Douglas Gregor68647482009-12-16 03:45:30 +00001361 return PerformImplicitConversion(From, ToType, ICS, Action);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001362}
1363
1364/// PerformImplicitConversion - Perform an implicit conversion of the
1365/// expression From to the type ToType using the pre-computed implicit
1366/// conversion sequence ICS. Returns true if there was an error, false
1367/// otherwise. The expression From is replaced with the converted
Douglas Gregor68647482009-12-16 03:45:30 +00001368/// expression. Action is the kind of conversion we're performing,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001369/// used in the error message.
1370bool
1371Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
1372 const ImplicitConversionSequence &ICS,
Douglas Gregor68647482009-12-16 03:45:30 +00001373 AssignmentAction Action, bool IgnoreBaseAccess) {
John McCall1d318332010-01-12 00:44:57 +00001374 switch (ICS.getKind()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001375 case ImplicitConversionSequence::StandardConversion:
Douglas Gregor68647482009-12-16 03:45:30 +00001376 if (PerformImplicitConversion(From, ToType, ICS.Standard, Action,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001377 IgnoreBaseAccess))
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001378 return true;
1379 break;
1380
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001381 case ImplicitConversionSequence::UserDefinedConversion: {
1382
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00001383 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
1384 CastExpr::CastKind CastKind = CastExpr::CK_Unknown;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001385 QualType BeforeToType;
1386 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00001387 CastKind = CastExpr::CK_UserDefinedConversion;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001388
1389 // If the user-defined conversion is specified by a conversion function,
1390 // the initial standard conversion sequence converts the source type to
1391 // the implicit object parameter of the conversion function.
1392 BeforeToType = Context.getTagDeclType(Conv->getParent());
1393 } else if (const CXXConstructorDecl *Ctor =
1394 dyn_cast<CXXConstructorDecl>(FD)) {
Anders Carlsson0aebc812009-09-09 21:33:21 +00001395 CastKind = CastExpr::CK_ConstructorConversion;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001396 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregore44201a2009-11-20 02:31:03 +00001397 if (!ICS.UserDefined.EllipsisConversion) {
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001398 // If the user-defined conversion is specified by a constructor, the
1399 // initial standard conversion sequence converts the source type to the
1400 // type required by the argument of the constructor
Douglas Gregore44201a2009-11-20 02:31:03 +00001401 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
1402 }
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001403 }
Anders Carlsson0aebc812009-09-09 21:33:21 +00001404 else
1405 assert(0 && "Unknown conversion function kind!");
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001406 // Whatch out for elipsis conversion.
Fariborz Jahanian4c0cea22009-11-06 00:55:14 +00001407 if (!ICS.UserDefined.EllipsisConversion) {
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001408 if (PerformImplicitConversion(From, BeforeToType,
Douglas Gregor68647482009-12-16 03:45:30 +00001409 ICS.UserDefined.Before, AA_Converting,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001410 IgnoreBaseAccess))
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001411 return true;
1412 }
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001413
Anders Carlsson0aebc812009-09-09 21:33:21 +00001414 OwningExprResult CastArg
1415 = BuildCXXCastArgument(From->getLocStart(),
1416 ToType.getNonReferenceType(),
1417 CastKind, cast<CXXMethodDecl>(FD),
1418 Owned(From));
1419
1420 if (CastArg.isInvalid())
1421 return true;
Eli Friedmand8889622009-11-27 04:41:50 +00001422
1423 From = CastArg.takeAs<Expr>();
1424
Eli Friedmand8889622009-11-27 04:41:50 +00001425 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
Douglas Gregor68647482009-12-16 03:45:30 +00001426 AA_Converting, IgnoreBaseAccess);
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001427 }
John McCall1d318332010-01-12 00:44:57 +00001428
1429 case ImplicitConversionSequence::AmbiguousConversion:
1430 DiagnoseAmbiguousConversion(ICS, From->getExprLoc(),
1431 PDiag(diag::err_typecheck_ambiguous_condition)
1432 << From->getSourceRange());
1433 return true;
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001434
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001435 case ImplicitConversionSequence::EllipsisConversion:
1436 assert(false && "Cannot perform an ellipsis conversion");
Douglas Gregor60d62c22008-10-31 16:23:19 +00001437 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001438
1439 case ImplicitConversionSequence::BadConversion:
1440 return true;
1441 }
1442
1443 // Everything went well.
1444 return false;
1445}
1446
1447/// PerformImplicitConversion - Perform an implicit conversion of the
1448/// expression From to the type ToType by following the standard
1449/// conversion sequence SCS. Returns true if there was an error, false
1450/// otherwise. The expression From is replaced with the converted
Douglas Gregor45920e82008-12-19 17:40:08 +00001451/// expression. Flavor is the context in which we're performing this
1452/// conversion, for use in error messages.
Mike Stump1eb44332009-09-09 15:08:12 +00001453bool
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001454Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor45920e82008-12-19 17:40:08 +00001455 const StandardConversionSequence& SCS,
Douglas Gregor68647482009-12-16 03:45:30 +00001456 AssignmentAction Action, bool IgnoreBaseAccess) {
Mike Stump390b4cc2009-05-16 07:39:55 +00001457 // Overall FIXME: we are recomputing too many types here and doing far too
1458 // much extra work. What this means is that we need to keep track of more
1459 // information that is computed when we try the implicit conversion initially,
1460 // so that we don't need to recompute anything here.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001461 QualType FromType = From->getType();
1462
Douglas Gregor225c41e2008-11-03 19:09:14 +00001463 if (SCS.CopyConstructor) {
Anders Carlsson7c3e8a12009-05-19 04:45:15 +00001464 // FIXME: When can ToType be a reference type?
1465 assert(!ToType->isReferenceType());
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00001466 if (SCS.Second == ICK_Derived_To_Base) {
1467 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1468 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
1469 MultiExprArg(*this, (void **)&From, 1),
1470 /*FIXME:ConstructLoc*/SourceLocation(),
1471 ConstructorArgs))
1472 return true;
1473 OwningExprResult FromResult =
1474 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1475 ToType, SCS.CopyConstructor,
1476 move_arg(ConstructorArgs));
1477 if (FromResult.isInvalid())
1478 return true;
1479 From = FromResult.takeAs<Expr>();
1480 return false;
1481 }
Mike Stump1eb44332009-09-09 15:08:12 +00001482 OwningExprResult FromResult =
1483 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1484 ToType, SCS.CopyConstructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00001485 MultiExprArg(*this, (void**)&From, 1));
Mike Stump1eb44332009-09-09 15:08:12 +00001486
Anders Carlssonda3f4e22009-08-25 05:12:04 +00001487 if (FromResult.isInvalid())
1488 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001489
Anders Carlssonda3f4e22009-08-25 05:12:04 +00001490 From = FromResult.takeAs<Expr>();
Douglas Gregor225c41e2008-11-03 19:09:14 +00001491 return false;
1492 }
1493
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001494 // Perform the first implicit conversion.
1495 switch (SCS.First) {
1496 case ICK_Identity:
1497 case ICK_Lvalue_To_Rvalue:
1498 // Nothing to do.
1499 break;
1500
1501 case ICK_Array_To_Pointer:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001502 FromType = Context.getArrayDecayedType(FromType);
Anders Carlsson82495762009-08-08 21:04:35 +00001503 ImpCastExprToType(From, FromType, CastExpr::CK_ArrayToPointerDecay);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001504 break;
1505
1506 case ICK_Function_To_Pointer:
Douglas Gregor063daf62009-03-13 18:40:31 +00001507 if (Context.getCanonicalType(FromType) == Context.OverloadTy) {
Douglas Gregor904eed32008-11-10 20:40:00 +00001508 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, true);
1509 if (!Fn)
1510 return true;
1511
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001512 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
1513 return true;
1514
Anders Carlsson96ad5332009-10-21 17:16:23 +00001515 From = FixOverloadedFunctionReference(From, Fn);
Douglas Gregor904eed32008-11-10 20:40:00 +00001516 FromType = From->getType();
Anders Carlsson96ad5332009-10-21 17:16:23 +00001517
Sebastian Redl759986e2009-10-17 20:50:27 +00001518 // If there's already an address-of operator in the expression, we have
1519 // the right type already, and the code below would just introduce an
1520 // invalid additional pointer level.
Anders Carlsson96ad5332009-10-21 17:16:23 +00001521 if (FromType->isPointerType() || FromType->isMemberFunctionPointerType())
Sebastian Redl759986e2009-10-17 20:50:27 +00001522 break;
Douglas Gregor904eed32008-11-10 20:40:00 +00001523 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001524 FromType = Context.getPointerType(FromType);
Anders Carlssonb633c4e2009-09-01 20:37:18 +00001525 ImpCastExprToType(From, FromType, CastExpr::CK_FunctionToPointerDecay);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001526 break;
1527
1528 default:
1529 assert(false && "Improper first standard conversion");
1530 break;
1531 }
1532
1533 // Perform the second implicit conversion
1534 switch (SCS.Second) {
1535 case ICK_Identity:
Sebastian Redl2c7588f2009-10-10 12:04:10 +00001536 // If both sides are functions (or pointers/references to them), there could
1537 // be incompatible exception declarations.
1538 if (CheckExceptionSpecCompatibility(From, ToType))
1539 return true;
1540 // Nothing else to do.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001541 break;
1542
Douglas Gregor43c79c22009-12-09 00:47:37 +00001543 case ICK_NoReturn_Adjustment:
1544 // If both sides are functions (or pointers/references to them), there could
1545 // be incompatible exception declarations.
1546 if (CheckExceptionSpecCompatibility(From, ToType))
1547 return true;
1548
1549 ImpCastExprToType(From, Context.getNoReturnType(From->getType(), false),
1550 CastExpr::CK_NoOp);
1551 break;
1552
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001553 case ICK_Integral_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001554 case ICK_Integral_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001555 ImpCastExprToType(From, ToType, CastExpr::CK_IntegralCast);
1556 break;
1557
1558 case ICK_Floating_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001559 case ICK_Floating_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001560 ImpCastExprToType(From, ToType, CastExpr::CK_FloatingCast);
1561 break;
1562
1563 case ICK_Complex_Promotion:
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001564 case ICK_Complex_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001565 ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1566 break;
1567
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001568 case ICK_Floating_Integral:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001569 if (ToType->isFloatingType())
1570 ImpCastExprToType(From, ToType, CastExpr::CK_IntegralToFloating);
1571 else
1572 ImpCastExprToType(From, ToType, CastExpr::CK_FloatingToIntegral);
1573 break;
1574
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001575 case ICK_Complex_Real:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001576 ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1577 break;
1578
Douglas Gregorf9201e02009-02-11 23:02:49 +00001579 case ICK_Compatible_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001580 ImpCastExprToType(From, ToType, CastExpr::CK_NoOp);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001581 break;
1582
Anders Carlsson61faec12009-09-12 04:46:44 +00001583 case ICK_Pointer_Conversion: {
Douglas Gregor45920e82008-12-19 17:40:08 +00001584 if (SCS.IncompatibleObjC) {
1585 // Diagnose incompatible Objective-C conversions
Mike Stump1eb44332009-09-09 15:08:12 +00001586 Diag(From->getSourceRange().getBegin(),
Douglas Gregor45920e82008-12-19 17:40:08 +00001587 diag::ext_typecheck_convert_incompatible_pointer)
Douglas Gregor68647482009-12-16 03:45:30 +00001588 << From->getType() << ToType << Action
Douglas Gregor45920e82008-12-19 17:40:08 +00001589 << From->getSourceRange();
1590 }
1591
Anders Carlsson61faec12009-09-12 04:46:44 +00001592
1593 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001594 if (CheckPointerConversion(From, ToType, Kind, IgnoreBaseAccess))
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001595 return true;
Anders Carlsson61faec12009-09-12 04:46:44 +00001596 ImpCastExprToType(From, ToType, Kind);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001597 break;
Anders Carlsson61faec12009-09-12 04:46:44 +00001598 }
1599
1600 case ICK_Pointer_Member: {
1601 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001602 if (CheckMemberPointerConversion(From, ToType, Kind, IgnoreBaseAccess))
Anders Carlsson61faec12009-09-12 04:46:44 +00001603 return true;
Sebastian Redl2c7588f2009-10-10 12:04:10 +00001604 if (CheckExceptionSpecCompatibility(From, ToType))
1605 return true;
Anders Carlsson61faec12009-09-12 04:46:44 +00001606 ImpCastExprToType(From, ToType, Kind);
1607 break;
1608 }
Anders Carlssonbc0e0782009-11-23 20:04:44 +00001609 case ICK_Boolean_Conversion: {
1610 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
1611 if (FromType->isMemberPointerType())
1612 Kind = CastExpr::CK_MemberPointerToBoolean;
1613
1614 ImpCastExprToType(From, Context.BoolTy, Kind);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001615 break;
Anders Carlssonbc0e0782009-11-23 20:04:44 +00001616 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001617
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001618 case ICK_Derived_To_Base:
1619 if (CheckDerivedToBaseConversion(From->getType(),
1620 ToType.getNonReferenceType(),
1621 From->getLocStart(),
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001622 From->getSourceRange(),
1623 IgnoreBaseAccess))
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001624 return true;
1625 ImpCastExprToType(From, ToType.getNonReferenceType(),
1626 CastExpr::CK_DerivedToBase);
1627 break;
1628
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001629 default:
1630 assert(false && "Improper second standard conversion");
1631 break;
1632 }
1633
1634 switch (SCS.Third) {
1635 case ICK_Identity:
1636 // Nothing to do.
1637 break;
1638
1639 case ICK_Qualification:
Mike Stump390b4cc2009-05-16 07:39:55 +00001640 // FIXME: Not sure about lvalue vs rvalue here in the presence of rvalue
1641 // references.
Mike Stump1eb44332009-09-09 15:08:12 +00001642 ImpCastExprToType(From, ToType.getNonReferenceType(),
Eli Friedman73c39ab2009-10-20 08:27:19 +00001643 CastExpr::CK_NoOp,
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001644 ToType->isLValueReferenceType());
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001645 break;
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001646
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001647 default:
1648 assert(false && "Improper second standard conversion");
1649 break;
1650 }
1651
1652 return false;
1653}
1654
Sebastian Redl64b45f72009-01-05 20:52:13 +00001655Sema::OwningExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
1656 SourceLocation KWLoc,
1657 SourceLocation LParen,
1658 TypeTy *Ty,
1659 SourceLocation RParen) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00001660 QualType T = GetTypeFromParser(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00001661
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001662 // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
1663 // all traits except __is_class, __is_enum and __is_union require a the type
1664 // to be complete.
1665 if (OTT != UTT_IsClass && OTT != UTT_IsEnum && OTT != UTT_IsUnion) {
Mike Stump1eb44332009-09-09 15:08:12 +00001666 if (RequireCompleteType(KWLoc, T,
Anders Carlssond497ba72009-08-26 22:59:12 +00001667 diag::err_incomplete_type_used_in_type_trait_expr))
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001668 return ExprError();
1669 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00001670
1671 // There is no point in eagerly computing the value. The traits are designed
1672 // to be used from type trait templates, so Ty will be a template parameter
1673 // 99% of the time.
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001674 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT, T,
1675 RParen, Context.BoolTy));
Sebastian Redl64b45f72009-01-05 20:52:13 +00001676}
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001677
1678QualType Sema::CheckPointerToMemberOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00001679 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001680 const char *OpSpelling = isIndirect ? "->*" : ".*";
1681 // C++ 5.5p2
1682 // The binary operator .* [p3: ->*] binds its second operand, which shall
1683 // be of type "pointer to member of T" (where T is a completely-defined
1684 // class type) [...]
1685 QualType RType = rex->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001686 const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
Douglas Gregore7450f52009-03-24 19:52:54 +00001687 if (!MemPtr) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001688 Diag(Loc, diag::err_bad_memptr_rhs)
1689 << OpSpelling << RType << rex->getSourceRange();
1690 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00001691 }
Douglas Gregore7450f52009-03-24 19:52:54 +00001692
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001693 QualType Class(MemPtr->getClass(), 0);
1694
1695 // C++ 5.5p2
1696 // [...] to its first operand, which shall be of class T or of a class of
1697 // which T is an unambiguous and accessible base class. [p3: a pointer to
1698 // such a class]
1699 QualType LType = lex->getType();
1700 if (isIndirect) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001701 if (const PointerType *Ptr = LType->getAs<PointerType>())
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001702 LType = Ptr->getPointeeType().getNonReferenceType();
1703 else {
1704 Diag(Loc, diag::err_bad_memptr_lhs)
Fariborz Jahanianef78ac62009-10-26 20:45:27 +00001705 << OpSpelling << 1 << LType
1706 << CodeModificationHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001707 return QualType();
1708 }
1709 }
1710
Douglas Gregora4923eb2009-11-16 21:35:15 +00001711 if (!Context.hasSameUnqualifiedType(Class, LType)) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001712 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1713 /*DetectVirtual=*/false);
Mike Stump390b4cc2009-05-16 07:39:55 +00001714 // FIXME: Would it be useful to print full ambiguity paths, or is that
1715 // overkill?
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001716 if (!IsDerivedFrom(LType, Class, Paths) ||
1717 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
1718 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Eli Friedman3005efe2010-01-16 00:00:48 +00001719 << (int)isIndirect << lex->getType();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001720 return QualType();
1721 }
Eli Friedman3005efe2010-01-16 00:00:48 +00001722 // Cast LHS to type of use.
1723 QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
1724 bool isLValue = !isIndirect && lex->isLvalue(Context) == Expr::LV_Valid;
1725 ImpCastExprToType(lex, UseType, CastExpr::CK_DerivedToBase, isLValue);
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001726 }
1727
Fariborz Jahanian19d70732009-11-18 22:16:17 +00001728 if (isa<CXXZeroInitValueExpr>(rex->IgnoreParens())) {
Fariborz Jahanian05ebda92009-11-18 21:54:48 +00001729 // Diagnose use of pointer-to-member type which when used as
1730 // the functional cast in a pointer-to-member expression.
1731 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
1732 return QualType();
1733 }
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001734 // C++ 5.5p2
1735 // The result is an object or a function of the type specified by the
1736 // second operand.
1737 // The cv qualifiers are the union of those in the pointer and the left side,
1738 // in accordance with 5.5p5 and 5.2.5.
1739 // FIXME: This returns a dereferenced member function pointer as a normal
1740 // function type. However, the only operation valid on such functions is
Mike Stump390b4cc2009-05-16 07:39:55 +00001741 // calling them. There's also a GCC extension to get a function pointer to the
1742 // thing, which is another complication, because this type - unlike the type
1743 // that is the result of this expression - takes the class as the first
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001744 // argument.
1745 // We probably need a "MemberFunctionClosureType" or something like that.
1746 QualType Result = MemPtr->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00001747 Result = Context.getCVRQualifiedType(Result, LType.getCVRQualifiers());
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001748 return Result;
1749}
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001750
1751/// \brief Get the target type of a standard or user-defined conversion.
1752static QualType TargetType(const ImplicitConversionSequence &ICS) {
John McCall1d318332010-01-12 00:44:57 +00001753 switch (ICS.getKind()) {
1754 case ImplicitConversionSequence::StandardConversion:
Douglas Gregorad323a82010-01-27 03:51:04 +00001755 return ICS.Standard.getToType(2);
John McCall1d318332010-01-12 00:44:57 +00001756 case ImplicitConversionSequence::UserDefinedConversion:
Douglas Gregorad323a82010-01-27 03:51:04 +00001757 return ICS.UserDefined.After.getToType(2);
John McCall1d318332010-01-12 00:44:57 +00001758 case ImplicitConversionSequence::AmbiguousConversion:
1759 return ICS.Ambiguous.getToType();
1760 case ImplicitConversionSequence::EllipsisConversion:
1761 case ImplicitConversionSequence::BadConversion:
1762 llvm_unreachable("function not valid for ellipsis or bad conversions");
1763 }
1764 return QualType(); // silence warnings
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001765}
1766
1767/// \brief Try to convert a type to another according to C++0x 5.16p3.
1768///
1769/// This is part of the parameter validation for the ? operator. If either
1770/// value operand is a class type, the two operands are attempted to be
1771/// converted to each other. This function does the conversion in one direction.
1772/// It emits a diagnostic and returns true only if it finds an ambiguous
1773/// conversion.
1774static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
1775 SourceLocation QuestionLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00001776 ImplicitConversionSequence &ICS) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001777 // C++0x 5.16p3
1778 // The process for determining whether an operand expression E1 of type T1
1779 // can be converted to match an operand expression E2 of type T2 is defined
1780 // as follows:
1781 // -- If E2 is an lvalue:
1782 if (To->isLvalue(Self.Context) == Expr::LV_Valid) {
1783 // E1 can be converted to match E2 if E1 can be implicitly converted to
1784 // type "lvalue reference to T2", subject to the constraint that in the
1785 // conversion the reference must bind directly to E1.
1786 if (!Self.CheckReferenceInit(From,
1787 Self.Context.getLValueReferenceType(To->getType()),
Douglas Gregor739d8282009-09-23 23:04:10 +00001788 To->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001789 /*SuppressUserConversions=*/false,
1790 /*AllowExplicit=*/false,
1791 /*ForceRValue=*/false,
1792 &ICS))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001793 {
John McCall1d318332010-01-12 00:44:57 +00001794 assert((ICS.isStandard() || ICS.isUserDefined()) &&
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001795 "expected a definite conversion");
1796 bool DirectBinding =
John McCall1d318332010-01-12 00:44:57 +00001797 ICS.isStandard() ? ICS.Standard.DirectBinding
1798 : ICS.UserDefined.After.DirectBinding;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001799 if (DirectBinding)
1800 return false;
1801 }
1802 }
John McCall1d318332010-01-12 00:44:57 +00001803 ICS.setBad();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001804 // -- If E2 is an rvalue, or if the conversion above cannot be done:
1805 // -- if E1 and E2 have class type, and the underlying class types are
1806 // the same or one is a base class of the other:
1807 QualType FTy = From->getType();
1808 QualType TTy = To->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001809 const RecordType *FRec = FTy->getAs<RecordType>();
1810 const RecordType *TRec = TTy->getAs<RecordType>();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001811 bool FDerivedFromT = FRec && TRec && Self.IsDerivedFrom(FTy, TTy);
1812 if (FRec && TRec && (FRec == TRec ||
1813 FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
1814 // E1 can be converted to match E2 if the class of T2 is the
1815 // same type as, or a base class of, the class of T1, and
1816 // [cv2 > cv1].
1817 if ((FRec == TRec || FDerivedFromT) && TTy.isAtLeastAsQualifiedAs(FTy)) {
1818 // Could still fail if there's no copy constructor.
1819 // FIXME: Is this a hard error then, or just a conversion failure? The
1820 // standard doesn't say.
Mike Stump1eb44332009-09-09 15:08:12 +00001821 ICS = Self.TryCopyInitialization(From, TTy,
Anders Carlssond28b4282009-08-27 17:18:13 +00001822 /*SuppressUserConversions=*/false,
Anders Carlsson7b361b52009-08-27 17:37:39 +00001823 /*ForceRValue=*/false,
1824 /*InOverloadResolution=*/false);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001825 }
1826 } else {
1827 // -- Otherwise: E1 can be converted to match E2 if E1 can be
1828 // implicitly converted to the type that expression E2 would have
1829 // if E2 were converted to an rvalue.
1830 // First find the decayed type.
1831 if (TTy->isFunctionType())
1832 TTy = Self.Context.getPointerType(TTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001833 else if (TTy->isArrayType())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001834 TTy = Self.Context.getArrayDecayedType(TTy);
1835
1836 // Now try the implicit conversion.
1837 // FIXME: This doesn't detect ambiguities.
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001838 ICS = Self.TryImplicitConversion(From, TTy,
1839 /*SuppressUserConversions=*/false,
1840 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00001841 /*ForceRValue=*/false,
1842 /*InOverloadResolution=*/false);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001843 }
1844 return false;
1845}
1846
1847/// \brief Try to find a common type for two according to C++0x 5.16p5.
1848///
1849/// This is part of the parameter validation for the ? operator. If either
1850/// value operand is a class type, overload resolution is used to find a
1851/// conversion to a common type.
1852static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
1853 SourceLocation Loc) {
1854 Expr *Args[2] = { LHS, RHS };
John McCall5769d612010-02-08 23:07:23 +00001855 OverloadCandidateSet CandidateSet(Loc);
Douglas Gregor573d9c32009-10-21 23:19:44 +00001856 Self.AddBuiltinOperatorCandidates(OO_Conditional, Loc, Args, 2, CandidateSet);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001857
1858 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00001859 switch (Self.BestViableFunction(CandidateSet, Loc, Best)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00001860 case OR_Success:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001861 // We found a match. Perform the conversions on the arguments and move on.
1862 if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00001863 Best->Conversions[0], Sema::AA_Converting) ||
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001864 Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor68647482009-12-16 03:45:30 +00001865 Best->Conversions[1], Sema::AA_Converting))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001866 break;
1867 return false;
1868
Douglas Gregor20093b42009-12-09 23:02:17 +00001869 case OR_No_Viable_Function:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001870 Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
1871 << LHS->getType() << RHS->getType()
1872 << LHS->getSourceRange() << RHS->getSourceRange();
1873 return true;
1874
Douglas Gregor20093b42009-12-09 23:02:17 +00001875 case OR_Ambiguous:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001876 Self.Diag(Loc, diag::err_conditional_ambiguous_ovl)
1877 << LHS->getType() << RHS->getType()
1878 << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stump390b4cc2009-05-16 07:39:55 +00001879 // FIXME: Print the possible common types by printing the return types of
1880 // the viable candidates.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001881 break;
1882
Douglas Gregor20093b42009-12-09 23:02:17 +00001883 case OR_Deleted:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001884 assert(false && "Conditional operator has only built-in overloads");
1885 break;
1886 }
1887 return true;
1888}
1889
Sebastian Redl76458502009-04-17 16:30:52 +00001890/// \brief Perform an "extended" implicit conversion as returned by
1891/// TryClassUnification.
1892///
1893/// TryClassUnification generates ICSs that include reference bindings.
1894/// PerformImplicitConversion is not suitable for this; it chokes if the
1895/// second part of a standard conversion is ICK_DerivedToBase. This function
1896/// handles the reference binding specially.
1897static bool ConvertForConditional(Sema &Self, Expr *&E,
Mike Stump1eb44332009-09-09 15:08:12 +00001898 const ImplicitConversionSequence &ICS) {
John McCall1d318332010-01-12 00:44:57 +00001899 if (ICS.isStandard() && ICS.Standard.ReferenceBinding) {
Sebastian Redl76458502009-04-17 16:30:52 +00001900 assert(ICS.Standard.DirectBinding &&
1901 "TryClassUnification should never generate indirect ref bindings");
Sebastian Redla5cd2cd2009-04-26 11:21:02 +00001902 // FIXME: CheckReferenceInit should be able to reuse the ICS instead of
1903 // redoing all the work.
1904 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001905 TargetType(ICS)),
Douglas Gregor739d8282009-09-23 23:04:10 +00001906 /*FIXME:*/E->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001907 /*SuppressUserConversions=*/false,
1908 /*AllowExplicit=*/false,
1909 /*ForceRValue=*/false);
Sebastian Redl76458502009-04-17 16:30:52 +00001910 }
John McCall1d318332010-01-12 00:44:57 +00001911 if (ICS.isUserDefined() && ICS.UserDefined.After.ReferenceBinding) {
Sebastian Redl76458502009-04-17 16:30:52 +00001912 assert(ICS.UserDefined.After.DirectBinding &&
1913 "TryClassUnification should never generate indirect ref bindings");
Sebastian Redla5cd2cd2009-04-26 11:21:02 +00001914 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001915 TargetType(ICS)),
Douglas Gregor739d8282009-09-23 23:04:10 +00001916 /*FIXME:*/E->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001917 /*SuppressUserConversions=*/false,
1918 /*AllowExplicit=*/false,
1919 /*ForceRValue=*/false);
Sebastian Redl76458502009-04-17 16:30:52 +00001920 }
Douglas Gregor68647482009-12-16 03:45:30 +00001921 if (Self.PerformImplicitConversion(E, TargetType(ICS), ICS, Sema::AA_Converting))
Sebastian Redl76458502009-04-17 16:30:52 +00001922 return true;
1923 return false;
1924}
1925
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001926/// \brief Check the operands of ?: under C++ semantics.
1927///
1928/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
1929/// extension. In this case, LHS == Cond. (But they're not aliases.)
1930QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
1931 SourceLocation QuestionLoc) {
Mike Stump390b4cc2009-05-16 07:39:55 +00001932 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
1933 // interface pointers.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001934
1935 // C++0x 5.16p1
1936 // The first expression is contextually converted to bool.
1937 if (!Cond->isTypeDependent()) {
1938 if (CheckCXXBooleanCondition(Cond))
1939 return QualType();
1940 }
1941
1942 // Either of the arguments dependent?
1943 if (LHS->isTypeDependent() || RHS->isTypeDependent())
1944 return Context.DependentTy;
1945
John McCallb13c87f2009-11-05 09:23:39 +00001946 CheckSignCompare(LHS, RHS, QuestionLoc, diag::warn_mixed_sign_conditional);
1947
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001948 // C++0x 5.16p2
1949 // If either the second or the third operand has type (cv) void, ...
1950 QualType LTy = LHS->getType();
1951 QualType RTy = RHS->getType();
1952 bool LVoid = LTy->isVoidType();
1953 bool RVoid = RTy->isVoidType();
1954 if (LVoid || RVoid) {
1955 // ... then the [l2r] conversions are performed on the second and third
1956 // operands ...
Douglas Gregora873dfc2010-02-03 00:27:59 +00001957 DefaultFunctionArrayLvalueConversion(LHS);
1958 DefaultFunctionArrayLvalueConversion(RHS);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001959 LTy = LHS->getType();
1960 RTy = RHS->getType();
1961
1962 // ... and one of the following shall hold:
1963 // -- The second or the third operand (but not both) is a throw-
1964 // expression; the result is of the type of the other and is an rvalue.
1965 bool LThrow = isa<CXXThrowExpr>(LHS);
1966 bool RThrow = isa<CXXThrowExpr>(RHS);
1967 if (LThrow && !RThrow)
1968 return RTy;
1969 if (RThrow && !LThrow)
1970 return LTy;
1971
1972 // -- Both the second and third operands have type void; the result is of
1973 // type void and is an rvalue.
1974 if (LVoid && RVoid)
1975 return Context.VoidTy;
1976
1977 // Neither holds, error.
1978 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
1979 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
1980 << LHS->getSourceRange() << RHS->getSourceRange();
1981 return QualType();
1982 }
1983
1984 // Neither is void.
1985
1986 // C++0x 5.16p3
1987 // Otherwise, if the second and third operand have different types, and
1988 // either has (cv) class type, and attempt is made to convert each of those
1989 // operands to the other.
1990 if (Context.getCanonicalType(LTy) != Context.getCanonicalType(RTy) &&
1991 (LTy->isRecordType() || RTy->isRecordType())) {
1992 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
1993 // These return true if a single direction is already ambiguous.
1994 if (TryClassUnification(*this, LHS, RHS, QuestionLoc, ICSLeftToRight))
1995 return QualType();
1996 if (TryClassUnification(*this, RHS, LHS, QuestionLoc, ICSRightToLeft))
1997 return QualType();
1998
John McCall1d318332010-01-12 00:44:57 +00001999 bool HaveL2R = !ICSLeftToRight.isBad();
2000 bool HaveR2L = !ICSRightToLeft.isBad();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002001 // If both can be converted, [...] the program is ill-formed.
2002 if (HaveL2R && HaveR2L) {
2003 Diag(QuestionLoc, diag::err_conditional_ambiguous)
2004 << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
2005 return QualType();
2006 }
2007
2008 // If exactly one conversion is possible, that conversion is applied to
2009 // the chosen operand and the converted operands are used in place of the
2010 // original operands for the remainder of this section.
2011 if (HaveL2R) {
Sebastian Redl76458502009-04-17 16:30:52 +00002012 if (ConvertForConditional(*this, LHS, ICSLeftToRight))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002013 return QualType();
2014 LTy = LHS->getType();
2015 } else if (HaveR2L) {
Sebastian Redl76458502009-04-17 16:30:52 +00002016 if (ConvertForConditional(*this, RHS, ICSRightToLeft))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002017 return QualType();
2018 RTy = RHS->getType();
2019 }
2020 }
2021
2022 // C++0x 5.16p4
2023 // If the second and third operands are lvalues and have the same type,
2024 // the result is of that type [...]
2025 bool Same = Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy);
2026 if (Same && LHS->isLvalue(Context) == Expr::LV_Valid &&
2027 RHS->isLvalue(Context) == Expr::LV_Valid)
2028 return LTy;
2029
2030 // C++0x 5.16p5
2031 // Otherwise, the result is an rvalue. If the second and third operands
2032 // do not have the same type, and either has (cv) class type, ...
2033 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
2034 // ... overload resolution is used to determine the conversions (if any)
2035 // to be applied to the operands. If the overload resolution fails, the
2036 // program is ill-formed.
2037 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
2038 return QualType();
2039 }
2040
2041 // C++0x 5.16p6
2042 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
2043 // conversions are performed on the second and third operands.
Douglas Gregora873dfc2010-02-03 00:27:59 +00002044 DefaultFunctionArrayLvalueConversion(LHS);
2045 DefaultFunctionArrayLvalueConversion(RHS);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002046 LTy = LHS->getType();
2047 RTy = RHS->getType();
2048
2049 // After those conversions, one of the following shall hold:
2050 // -- The second and third operands have the same type; the result
2051 // is of that type.
2052 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy))
2053 return LTy;
2054
2055 // -- The second and third operands have arithmetic or enumeration type;
2056 // the usual arithmetic conversions are performed to bring them to a
2057 // common type, and the result is of that type.
2058 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
2059 UsualArithmeticConversions(LHS, RHS);
2060 return LHS->getType();
2061 }
2062
2063 // -- The second and third operands have pointer type, or one has pointer
2064 // type and the other is a null pointer constant; pointer conversions
2065 // and qualification conversions are performed to bring them to their
2066 // composite pointer type. The result is of the composite pointer type.
Eli Friedmande8ac492010-01-02 22:56:07 +00002067 // -- The second and third operands have pointer to member type, or one has
2068 // pointer to member type and the other is a null pointer constant;
2069 // pointer to member conversions and qualification conversions are
2070 // performed to bring them to a common type, whose cv-qualification
2071 // shall match the cv-qualification of either the second or the third
2072 // operand. The result is of the common type.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002073 QualType Composite = FindCompositePointerType(LHS, RHS);
2074 if (!Composite.isNull())
2075 return Composite;
Fariborz Jahanian55016362009-12-10 20:46:08 +00002076
2077 // Similarly, attempt to find composite type of twp objective-c pointers.
2078 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
2079 if (!Composite.isNull())
2080 return Composite;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002081
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002082 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
2083 << LHS->getType() << RHS->getType()
2084 << LHS->getSourceRange() << RHS->getSourceRange();
2085 return QualType();
2086}
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002087
2088/// \brief Find a merged pointer type and convert the two expressions to it.
2089///
Douglas Gregor20b3e992009-08-24 17:42:35 +00002090/// This finds the composite pointer type (or member pointer type) for @p E1
2091/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
2092/// type and returns it.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002093/// It does not emit diagnostics.
2094QualType Sema::FindCompositePointerType(Expr *&E1, Expr *&E2) {
2095 assert(getLangOptions().CPlusPlus && "This function assumes C++");
2096 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002097
Fariborz Jahanian0cedfbd2009-12-08 20:04:24 +00002098 if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
2099 !T2->isAnyPointerType() && !T2->isMemberPointerType())
Douglas Gregor20b3e992009-08-24 17:42:35 +00002100 return QualType();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002101
2102 // C++0x 5.9p2
2103 // Pointer conversions and qualification conversions are performed on
2104 // pointer operands to bring them to their composite pointer type. If
2105 // one operand is a null pointer constant, the composite pointer type is
2106 // the type of the other operand.
Douglas Gregorce940492009-09-25 04:25:58 +00002107 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00002108 if (T2->isMemberPointerType())
2109 ImpCastExprToType(E1, T2, CastExpr::CK_NullToMemberPointer);
2110 else
2111 ImpCastExprToType(E1, T2, CastExpr::CK_IntegralToPointer);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002112 return T2;
2113 }
Douglas Gregorce940492009-09-25 04:25:58 +00002114 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00002115 if (T1->isMemberPointerType())
2116 ImpCastExprToType(E2, T1, CastExpr::CK_NullToMemberPointer);
2117 else
2118 ImpCastExprToType(E2, T1, CastExpr::CK_IntegralToPointer);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002119 return T1;
2120 }
Mike Stump1eb44332009-09-09 15:08:12 +00002121
Douglas Gregor20b3e992009-08-24 17:42:35 +00002122 // Now both have to be pointers or member pointers.
Sebastian Redla439e6f2009-11-16 21:03:45 +00002123 if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
2124 (!T2->isPointerType() && !T2->isMemberPointerType()))
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002125 return QualType();
2126
2127 // Otherwise, of one of the operands has type "pointer to cv1 void," then
2128 // the other has type "pointer to cv2 T" and the composite pointer type is
2129 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
2130 // Otherwise, the composite pointer type is a pointer type similar to the
2131 // type of one of the operands, with a cv-qualification signature that is
2132 // the union of the cv-qualification signatures of the operand types.
2133 // In practice, the first part here is redundant; it's subsumed by the second.
2134 // What we do here is, we build the two possible composite types, and try the
2135 // conversions in both directions. If only one works, or if the two composite
2136 // types are the same, we have succeeded.
John McCall0953e762009-09-24 19:53:00 +00002137 // FIXME: extended qualifiers?
Sebastian Redla439e6f2009-11-16 21:03:45 +00002138 typedef llvm::SmallVector<unsigned, 4> QualifierVector;
2139 QualifierVector QualifierUnion;
2140 typedef llvm::SmallVector<std::pair<const Type *, const Type *>, 4>
2141 ContainingClassVector;
2142 ContainingClassVector MemberOfClass;
2143 QualType Composite1 = Context.getCanonicalType(T1),
2144 Composite2 = Context.getCanonicalType(T2);
Douglas Gregor20b3e992009-08-24 17:42:35 +00002145 do {
2146 const PointerType *Ptr1, *Ptr2;
2147 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
2148 (Ptr2 = Composite2->getAs<PointerType>())) {
2149 Composite1 = Ptr1->getPointeeType();
2150 Composite2 = Ptr2->getPointeeType();
2151 QualifierUnion.push_back(
2152 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
2153 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
2154 continue;
2155 }
Mike Stump1eb44332009-09-09 15:08:12 +00002156
Douglas Gregor20b3e992009-08-24 17:42:35 +00002157 const MemberPointerType *MemPtr1, *MemPtr2;
2158 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
2159 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
2160 Composite1 = MemPtr1->getPointeeType();
2161 Composite2 = MemPtr2->getPointeeType();
2162 QualifierUnion.push_back(
2163 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
2164 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
2165 MemPtr2->getClass()));
2166 continue;
2167 }
Mike Stump1eb44332009-09-09 15:08:12 +00002168
Douglas Gregor20b3e992009-08-24 17:42:35 +00002169 // FIXME: block pointer types?
Mike Stump1eb44332009-09-09 15:08:12 +00002170
Douglas Gregor20b3e992009-08-24 17:42:35 +00002171 // Cannot unwrap any more types.
2172 break;
2173 } while (true);
Mike Stump1eb44332009-09-09 15:08:12 +00002174
Douglas Gregor20b3e992009-08-24 17:42:35 +00002175 // Rewrap the composites as pointers or member pointers with the union CVRs.
Sebastian Redla439e6f2009-11-16 21:03:45 +00002176 ContainingClassVector::reverse_iterator MOC
2177 = MemberOfClass.rbegin();
2178 for (QualifierVector::reverse_iterator
2179 I = QualifierUnion.rbegin(),
2180 E = QualifierUnion.rend();
Douglas Gregor20b3e992009-08-24 17:42:35 +00002181 I != E; (void)++I, ++MOC) {
John McCall0953e762009-09-24 19:53:00 +00002182 Qualifiers Quals = Qualifiers::fromCVRMask(*I);
Douglas Gregor20b3e992009-08-24 17:42:35 +00002183 if (MOC->first && MOC->second) {
2184 // Rebuild member pointer type
John McCall0953e762009-09-24 19:53:00 +00002185 Composite1 = Context.getMemberPointerType(
2186 Context.getQualifiedType(Composite1, Quals),
2187 MOC->first);
2188 Composite2 = Context.getMemberPointerType(
2189 Context.getQualifiedType(Composite2, Quals),
2190 MOC->second);
Douglas Gregor20b3e992009-08-24 17:42:35 +00002191 } else {
2192 // Rebuild pointer type
John McCall0953e762009-09-24 19:53:00 +00002193 Composite1
2194 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
2195 Composite2
2196 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregor20b3e992009-08-24 17:42:35 +00002197 }
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002198 }
2199
Mike Stump1eb44332009-09-09 15:08:12 +00002200 ImplicitConversionSequence E1ToC1 =
Anders Carlssonda7a18b2009-08-27 17:24:15 +00002201 TryImplicitConversion(E1, Composite1,
2202 /*SuppressUserConversions=*/false,
2203 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00002204 /*ForceRValue=*/false,
2205 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00002206 ImplicitConversionSequence E2ToC1 =
Anders Carlssonda7a18b2009-08-27 17:24:15 +00002207 TryImplicitConversion(E2, Composite1,
2208 /*SuppressUserConversions=*/false,
2209 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00002210 /*ForceRValue=*/false,
2211 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00002212
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002213 ImplicitConversionSequence E1ToC2, E2ToC2;
John McCall1d318332010-01-12 00:44:57 +00002214 E1ToC2.setBad();
John McCalladbb8f82010-01-13 09:16:55 +00002215 E2ToC2.setBad();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002216 if (Context.getCanonicalType(Composite1) !=
2217 Context.getCanonicalType(Composite2)) {
Anders Carlssonda7a18b2009-08-27 17:24:15 +00002218 E1ToC2 = TryImplicitConversion(E1, Composite2,
2219 /*SuppressUserConversions=*/false,
2220 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00002221 /*ForceRValue=*/false,
2222 /*InOverloadResolution=*/false);
Anders Carlssonda7a18b2009-08-27 17:24:15 +00002223 E2ToC2 = TryImplicitConversion(E2, Composite2,
2224 /*SuppressUserConversions=*/false,
2225 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00002226 /*ForceRValue=*/false,
2227 /*InOverloadResolution=*/false);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002228 }
2229
John McCall1d318332010-01-12 00:44:57 +00002230 bool ToC1Viable = !E1ToC1.isBad() && !E2ToC1.isBad();
2231 bool ToC2Viable = !E1ToC2.isBad() && !E2ToC2.isBad();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002232 if (ToC1Viable && !ToC2Viable) {
Douglas Gregor68647482009-12-16 03:45:30 +00002233 if (!PerformImplicitConversion(E1, Composite1, E1ToC1, Sema::AA_Converting) &&
2234 !PerformImplicitConversion(E2, Composite1, E2ToC1, Sema::AA_Converting))
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002235 return Composite1;
2236 }
2237 if (ToC2Viable && !ToC1Viable) {
Douglas Gregor68647482009-12-16 03:45:30 +00002238 if (!PerformImplicitConversion(E1, Composite2, E1ToC2, Sema::AA_Converting) &&
2239 !PerformImplicitConversion(E2, Composite2, E2ToC2, Sema::AA_Converting))
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002240 return Composite2;
2241 }
2242 return QualType();
2243}
Anders Carlsson165a0a02009-05-17 18:41:29 +00002244
Anders Carlssondef11992009-05-30 20:36:53 +00002245Sema::OwningExprResult Sema::MaybeBindToTemporary(Expr *E) {
Anders Carlsson089c2602009-08-15 23:41:35 +00002246 if (!Context.getLangOptions().CPlusPlus)
2247 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002248
Douglas Gregor51326552009-12-24 18:51:59 +00002249 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
2250
Ted Kremenek6217b802009-07-29 21:53:49 +00002251 const RecordType *RT = E->getType()->getAs<RecordType>();
Anders Carlssondef11992009-05-30 20:36:53 +00002252 if (!RT)
2253 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002254
John McCall86ff3082010-02-04 22:26:26 +00002255 // If this is the result of a call expression, our source might
2256 // actually be a reference, in which case we shouldn't bind.
Anders Carlsson283e4d52009-09-14 01:30:44 +00002257 if (CallExpr *CE = dyn_cast<CallExpr>(E)) {
2258 QualType Ty = CE->getCallee()->getType();
2259 if (const PointerType *PT = Ty->getAs<PointerType>())
2260 Ty = PT->getPointeeType();
Fariborz Jahanianb372b0f2010-02-18 20:31:02 +00002261 else if (const BlockPointerType *BPT = Ty->getAs<BlockPointerType>())
2262 Ty = BPT->getPointeeType();
2263
John McCall183700f2009-09-21 23:43:11 +00002264 const FunctionType *FTy = Ty->getAs<FunctionType>();
Anders Carlsson283e4d52009-09-14 01:30:44 +00002265 if (FTy->getResultType()->isReferenceType())
2266 return Owned(E);
2267 }
John McCall86ff3082010-02-04 22:26:26 +00002268
2269 // That should be enough to guarantee that this type is complete.
2270 // If it has a trivial destructor, we can avoid the extra copy.
2271 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2272 if (RD->hasTrivialDestructor())
2273 return Owned(E);
2274
Mike Stump1eb44332009-09-09 15:08:12 +00002275 CXXTemporary *Temp = CXXTemporary::Create(Context,
Anders Carlssondef11992009-05-30 20:36:53 +00002276 RD->getDestructor(Context));
Anders Carlsson860306e2009-05-30 21:21:49 +00002277 ExprTemporaries.push_back(Temp);
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00002278 if (CXXDestructorDecl *Destructor =
2279 const_cast<CXXDestructorDecl*>(RD->getDestructor(Context)))
2280 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
Anders Carlssondef11992009-05-30 20:36:53 +00002281 // FIXME: Add the temporary to the temporaries vector.
2282 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
2283}
2284
Anders Carlsson0ece4912009-12-15 20:51:39 +00002285Expr *Sema::MaybeCreateCXXExprWithTemporaries(Expr *SubExpr) {
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002286 assert(SubExpr && "sub expression can't be null!");
Mike Stump1eb44332009-09-09 15:08:12 +00002287
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00002288 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
2289 assert(ExprTemporaries.size() >= FirstTemporary);
2290 if (ExprTemporaries.size() == FirstTemporary)
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002291 return SubExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00002292
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002293 Expr *E = CXXExprWithTemporaries::Create(Context, SubExpr,
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00002294 &ExprTemporaries[FirstTemporary],
Anders Carlsson0ece4912009-12-15 20:51:39 +00002295 ExprTemporaries.size() - FirstTemporary);
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00002296 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
2297 ExprTemporaries.end());
Mike Stump1eb44332009-09-09 15:08:12 +00002298
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002299 return E;
2300}
2301
Douglas Gregor90f93822009-12-22 22:17:25 +00002302Sema::OwningExprResult
2303Sema::MaybeCreateCXXExprWithTemporaries(OwningExprResult SubExpr) {
2304 if (SubExpr.isInvalid())
2305 return ExprError();
2306
2307 return Owned(MaybeCreateCXXExprWithTemporaries(SubExpr.takeAs<Expr>()));
2308}
2309
Anders Carlsson5ee56e92009-12-16 02:09:40 +00002310FullExpr Sema::CreateFullExpr(Expr *SubExpr) {
2311 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
2312 assert(ExprTemporaries.size() >= FirstTemporary);
2313
2314 unsigned NumTemporaries = ExprTemporaries.size() - FirstTemporary;
2315 CXXTemporary **Temporaries =
2316 NumTemporaries == 0 ? 0 : &ExprTemporaries[FirstTemporary];
2317
2318 FullExpr E = FullExpr::Create(Context, SubExpr, Temporaries, NumTemporaries);
2319
2320 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
2321 ExprTemporaries.end());
2322
2323 return E;
2324}
2325
Mike Stump1eb44332009-09-09 15:08:12 +00002326Sema::OwningExprResult
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002327Sema::ActOnStartCXXMemberReference(Scope *S, ExprArg Base, SourceLocation OpLoc,
2328 tok::TokenKind OpKind, TypeTy *&ObjectType) {
2329 // Since this might be a postfix expression, get rid of ParenListExprs.
2330 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
Mike Stump1eb44332009-09-09 15:08:12 +00002331
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002332 Expr *BaseExpr = (Expr*)Base.get();
2333 assert(BaseExpr && "no record expansion");
Mike Stump1eb44332009-09-09 15:08:12 +00002334
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002335 QualType BaseType = BaseExpr->getType();
2336 if (BaseType->isDependentType()) {
Douglas Gregor43d88632009-11-04 22:49:18 +00002337 // If we have a pointer to a dependent type and are using the -> operator,
2338 // the object type is the type that the pointer points to. We might still
2339 // have enough information about that type to do something useful.
2340 if (OpKind == tok::arrow)
2341 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
2342 BaseType = Ptr->getPointeeType();
2343
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002344 ObjectType = BaseType.getAsOpaquePtr();
2345 return move(Base);
2346 }
Mike Stump1eb44332009-09-09 15:08:12 +00002347
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002348 // C++ [over.match.oper]p8:
Mike Stump1eb44332009-09-09 15:08:12 +00002349 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002350 // returned, with the original second operand.
2351 if (OpKind == tok::arrow) {
John McCallc4e83212009-09-30 01:01:30 +00002352 // The set of types we've considered so far.
John McCall432887f2009-09-30 01:30:54 +00002353 llvm::SmallPtrSet<CanQualType,8> CTypes;
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002354 llvm::SmallVector<SourceLocation, 8> Locations;
John McCall432887f2009-09-30 01:30:54 +00002355 CTypes.insert(Context.getCanonicalType(BaseType));
John McCallc4e83212009-09-30 01:01:30 +00002356
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002357 while (BaseType->isRecordType()) {
Anders Carlsson15ea3782009-10-13 22:43:21 +00002358 Base = BuildOverloadedArrowExpr(S, move(Base), OpLoc);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002359 BaseExpr = (Expr*)Base.get();
2360 if (BaseExpr == NULL)
2361 return ExprError();
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002362 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(BaseExpr))
Anders Carlssonde699e52009-10-13 22:55:59 +00002363 Locations.push_back(OpCall->getDirectCallee()->getLocation());
John McCallc4e83212009-09-30 01:01:30 +00002364 BaseType = BaseExpr->getType();
2365 CanQualType CBaseType = Context.getCanonicalType(BaseType);
John McCall432887f2009-09-30 01:30:54 +00002366 if (!CTypes.insert(CBaseType)) {
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00002367 Diag(OpLoc, diag::err_operator_arrow_circular);
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002368 for (unsigned i = 0; i < Locations.size(); i++)
2369 Diag(Locations[i], diag::note_declared_at);
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00002370 return ExprError();
2371 }
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002372 }
Mike Stump1eb44332009-09-09 15:08:12 +00002373
Douglas Gregor31658df2009-11-20 19:58:21 +00002374 if (BaseType->isPointerType())
2375 BaseType = BaseType->getPointeeType();
2376 }
Mike Stump1eb44332009-09-09 15:08:12 +00002377
2378 // We could end up with various non-record types here, such as extended
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002379 // vector types or Objective-C interfaces. Just return early and let
2380 // ActOnMemberReferenceExpr do the work.
Douglas Gregorc68afe22009-09-03 21:38:09 +00002381 if (!BaseType->isRecordType()) {
2382 // C++ [basic.lookup.classref]p2:
2383 // [...] If the type of the object expression is of pointer to scalar
2384 // type, the unqualified-id is looked up in the context of the complete
2385 // postfix-expression.
2386 ObjectType = 0;
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002387 return move(Base);
Douglas Gregorc68afe22009-09-03 21:38:09 +00002388 }
Mike Stump1eb44332009-09-09 15:08:12 +00002389
Douglas Gregor03c57052009-11-17 05:17:33 +00002390 // The object type must be complete (or dependent).
2391 if (!BaseType->isDependentType() &&
2392 RequireCompleteType(OpLoc, BaseType,
2393 PDiag(diag::err_incomplete_member_access)))
2394 return ExprError();
2395
Douglas Gregorc68afe22009-09-03 21:38:09 +00002396 // C++ [basic.lookup.classref]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00002397 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor03c57052009-11-17 05:17:33 +00002398 // unqualified-id, and the type of the object expression is of a class
Douglas Gregorc68afe22009-09-03 21:38:09 +00002399 // type C (or of pointer to a class type C), the unqualified-id is looked
2400 // up in the scope of class C. [...]
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002401 ObjectType = BaseType.getAsOpaquePtr();
Douglas Gregor03c57052009-11-17 05:17:33 +00002402
Mike Stump1eb44332009-09-09 15:08:12 +00002403 return move(Base);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002404}
2405
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002406CXXMemberCallExpr *Sema::BuildCXXMemberCallExpr(Expr *Exp,
2407 CXXMethodDecl *Method) {
Eli Friedman772fffa2009-12-09 04:53:56 +00002408 if (PerformObjectArgumentInitialization(Exp, Method))
2409 assert(0 && "Calling BuildCXXMemberCallExpr with invalid call?");
2410
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002411 MemberExpr *ME =
2412 new (Context) MemberExpr(Exp, /*IsArrow=*/false, Method,
2413 SourceLocation(), Method->getType());
Eli Friedman772fffa2009-12-09 04:53:56 +00002414 QualType ResultType = Method->getResultType().getNonReferenceType();
Douglas Gregor7edfb692009-11-23 12:27:39 +00002415 MarkDeclarationReferenced(Exp->getLocStart(), Method);
2416 CXXMemberCallExpr *CE =
2417 new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType,
2418 Exp->getLocEnd());
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002419 return CE;
2420}
2421
Anders Carlsson0aebc812009-09-09 21:33:21 +00002422Sema::OwningExprResult Sema::BuildCXXCastArgument(SourceLocation CastLoc,
2423 QualType Ty,
2424 CastExpr::CastKind Kind,
2425 CXXMethodDecl *Method,
2426 ExprArg Arg) {
2427 Expr *From = Arg.takeAs<Expr>();
2428
2429 switch (Kind) {
2430 default: assert(0 && "Unhandled cast kind!");
2431 case CastExpr::CK_ConstructorConversion: {
Douglas Gregor39da0b82009-09-09 23:08:42 +00002432 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
2433
2434 if (CompleteConstructorCall(cast<CXXConstructorDecl>(Method),
2435 MultiExprArg(*this, (void **)&From, 1),
2436 CastLoc, ConstructorArgs))
2437 return ExprError();
Anders Carlsson4fa26842009-10-18 21:20:14 +00002438
2439 OwningExprResult Result =
2440 BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
2441 move_arg(ConstructorArgs));
2442 if (Result.isInvalid())
2443 return ExprError();
2444
2445 return MaybeBindToTemporary(Result.takeAs<Expr>());
Anders Carlsson0aebc812009-09-09 21:33:21 +00002446 }
2447
2448 case CastExpr::CK_UserDefinedConversion: {
Anders Carlssonaac6e3a2009-09-15 07:42:44 +00002449 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
Eli Friedman772fffa2009-12-09 04:53:56 +00002450
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002451 // Create an implicit call expr that calls it.
2452 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(From, Method);
Anders Carlsson4fa26842009-10-18 21:20:14 +00002453 return MaybeBindToTemporary(CE);
Anders Carlsson0aebc812009-09-09 21:33:21 +00002454 }
Anders Carlsson0aebc812009-09-09 21:33:21 +00002455 }
2456}
2457
Anders Carlsson165a0a02009-05-17 18:41:29 +00002458Sema::OwningExprResult Sema::ActOnFinishFullExpr(ExprArg Arg) {
2459 Expr *FullExpr = Arg.takeAs<Expr>();
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002460 if (FullExpr)
Anders Carlsson0ece4912009-12-15 20:51:39 +00002461 FullExpr = MaybeCreateCXXExprWithTemporaries(FullExpr);
Anders Carlssonec773872009-08-25 23:46:41 +00002462
Anders Carlsson165a0a02009-05-17 18:41:29 +00002463 return Owned(FullExpr);
2464}