blob: e944f328ed98632ca4524fbf36766561949c11c5 [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
Sebastian Redlc42e1182008-11-11 11:37:55 +000027/// ActOnCXXTypeidOfType - Parse typeid( type-id ).
Sebastian Redlf53597f2009-03-15 17:47:39 +000028Action::OwningExprResult
Sebastian Redlc42e1182008-11-11 11:37:55 +000029Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
30 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +000031 if (!StdNamespace)
Sebastian Redlf53597f2009-03-15 17:47:39 +000032 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +000033
Douglas Gregorf57f2072009-12-23 20:51:04 +000034 if (isType) {
35 // C++ [expr.typeid]p4:
36 // The top-level cv-qualifiers of the lvalue expression or the type-id
37 // that is the operand of typeid are always ignored.
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +000038 // FIXME: Preserve type source info.
Douglas Gregorf57f2072009-12-23 20:51:04 +000039 // FIXME: Preserve the type before we stripped the cv-qualifiers?
Douglas Gregor765ccba2009-12-23 21:06:06 +000040 QualType T = GetTypeFromParser(TyOrExpr);
41 if (T.isNull())
42 return ExprError();
43
44 // C++ [expr.typeid]p4:
45 // If the type of the type-id is a class type or a reference to a class
46 // type, the class shall be completely-defined.
47 QualType CheckT = T;
48 if (const ReferenceType *RefType = CheckT->getAs<ReferenceType>())
49 CheckT = RefType->getPointeeType();
50
51 if (CheckT->getAs<RecordType>() &&
52 RequireCompleteType(OpLoc, CheckT, diag::err_incomplete_typeid))
53 return ExprError();
54
55 TyOrExpr = T.getUnqualifiedType().getAsOpaquePtr();
Douglas Gregorf57f2072009-12-23 20:51:04 +000056 }
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +000057
Chris Lattner572af492008-11-20 05:51:55 +000058 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
John McCalla24dc2e2009-11-17 02:14:36 +000059 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
60 LookupQualifiedName(R, StdNamespace);
John McCall1bcee0a2009-12-02 08:25:40 +000061 RecordDecl *TypeInfoRecordDecl = R.getAsSingle<RecordDecl>();
Chris Lattner572af492008-11-20 05:51:55 +000062 if (!TypeInfoRecordDecl)
Sebastian Redlf53597f2009-03-15 17:47:39 +000063 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Sebastian Redlc42e1182008-11-11 11:37:55 +000064
65 QualType TypeInfoType = Context.getTypeDeclType(TypeInfoRecordDecl);
66
Douglas Gregorac7610d2009-06-22 20:57:11 +000067 if (!isType) {
Douglas Gregorac7610d2009-06-22 20:57:11 +000068 bool isUnevaluatedOperand = true;
69 Expr *E = static_cast<Expr *>(TyOrExpr);
Douglas Gregorf57f2072009-12-23 20:51:04 +000070 if (E && !E->isTypeDependent()) {
Douglas Gregorac7610d2009-06-22 20:57:11 +000071 QualType T = E->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +000072 if (const RecordType *RecordT = T->getAs<RecordType>()) {
Douglas Gregorac7610d2009-06-22 20:57:11 +000073 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
Douglas Gregorf57f2072009-12-23 20:51:04 +000074 // C++ [expr.typeid]p3:
75 // When typeid is applied to an expression other than an lvalue of a
76 // polymorphic class type [...] [the] expression is an unevaluated
77 // operand. [...]
78 if (RecordD->isPolymorphic() && E->isLvalue(Context) == Expr::LV_Valid)
Douglas Gregorac7610d2009-06-22 20:57:11 +000079 isUnevaluatedOperand = false;
Douglas Gregorf57f2072009-12-23 20:51:04 +000080 else {
81 // C++ [expr.typeid]p3:
82 // [...] If the type of the expression is a class type, the class
83 // shall be completely-defined.
Douglas Gregor765ccba2009-12-23 21:06:06 +000084 if (RequireCompleteType(OpLoc, T, diag::err_incomplete_typeid))
85 return ExprError();
Douglas Gregorf57f2072009-12-23 20:51:04 +000086 }
87 }
88
89 // C++ [expr.typeid]p4:
90 // [...] If the type of the type-id is a reference to a possibly
91 // cv-qualified type, the result of the typeid expression refers to a
92 // std::type_info object representing the cv-unqualified referenced
93 // type.
94 if (T.hasQualifiers()) {
95 ImpCastExprToType(E, T.getUnqualifiedType(), CastExpr::CK_NoOp,
96 E->isLvalue(Context));
97 TyOrExpr = E;
Douglas Gregorac7610d2009-06-22 20:57:11 +000098 }
99 }
Mike Stump1eb44332009-09-09 15:08:12 +0000100
Douglas Gregor2afce722009-11-26 00:44:06 +0000101 // If this is an unevaluated operand, clear out the set of
102 // declaration references we have been computing and eliminate any
103 // temporaries introduced in its computation.
Douglas Gregorac7610d2009-06-22 20:57:11 +0000104 if (isUnevaluatedOperand)
Douglas Gregor2afce722009-11-26 00:44:06 +0000105 ExprEvalContexts.back().Context = Unevaluated;
Douglas Gregorac7610d2009-06-22 20:57:11 +0000106 }
Mike Stump1eb44332009-09-09 15:08:12 +0000107
Sebastian Redlf53597f2009-03-15 17:47:39 +0000108 return Owned(new (Context) CXXTypeidExpr(isType, TyOrExpr,
109 TypeInfoType.withConst(),
110 SourceRange(OpLoc, RParenLoc)));
Sebastian Redlc42e1182008-11-11 11:37:55 +0000111}
112
Steve Naroff1b273c42007-09-16 14:56:35 +0000113/// ActOnCXXBoolLiteral - Parse {true,false} literals.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000114Action::OwningExprResult
Steve Naroff1b273c42007-09-16 14:56:35 +0000115Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor2f639b92008-10-24 15:36:09 +0000116 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000117 "Unknown C++ Boolean value!");
Sebastian Redlf53597f2009-03-15 17:47:39 +0000118 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
119 Context.BoolTy, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000120}
Chris Lattner50dd2892008-02-26 00:51:44 +0000121
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000122/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
123Action::OwningExprResult
124Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
125 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
126}
127
Chris Lattner50dd2892008-02-26 00:51:44 +0000128/// ActOnCXXThrow - Parse throw expressions.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000129Action::OwningExprResult
130Sema::ActOnCXXThrow(SourceLocation OpLoc, ExprArg E) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000131 Expr *Ex = E.takeAs<Expr>();
132 if (Ex && !Ex->isTypeDependent() && CheckCXXThrowOperand(OpLoc, Ex))
133 return ExprError();
134 return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc));
135}
136
137/// CheckCXXThrowOperand - Validate the operand of a throw.
138bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *&E) {
139 // C++ [except.throw]p3:
Douglas Gregor154fe982009-12-23 22:04:40 +0000140 // A throw-expression initializes a temporary object, called the exception
141 // object, the type of which is determined by removing any top-level
142 // cv-qualifiers from the static type of the operand of throw and adjusting
143 // the type from "array of T" or "function returning T" to "pointer to T"
144 // or "pointer to function returning T", [...]
145 if (E->getType().hasQualifiers())
146 ImpCastExprToType(E, E->getType().getUnqualifiedType(), CastExpr::CK_NoOp,
147 E->isLvalue(Context) == Expr::LV_Valid);
148
Sebastian Redl972041f2009-04-27 20:27:31 +0000149 DefaultFunctionArrayConversion(E);
150
151 // If the type of the exception would be an incomplete type or a pointer
152 // to an incomplete type other than (cv) void the program is ill-formed.
153 QualType Ty = E->getType();
154 int isPointer = 0;
Ted Kremenek6217b802009-07-29 21:53:49 +0000155 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000156 Ty = Ptr->getPointeeType();
157 isPointer = 1;
158 }
159 if (!isPointer || !Ty->isVoidType()) {
160 if (RequireCompleteType(ThrowLoc, Ty,
Anders Carlssond497ba72009-08-26 22:59:12 +0000161 PDiag(isPointer ? diag::err_throw_incomplete_ptr
162 : diag::err_throw_incomplete)
163 << E->getSourceRange()))
Sebastian Redl972041f2009-04-27 20:27:31 +0000164 return true;
165 }
166
167 // FIXME: Construct a temporary here.
168 return false;
Chris Lattner50dd2892008-02-26 00:51:44 +0000169}
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000170
Sebastian Redlf53597f2009-03-15 17:47:39 +0000171Action::OwningExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000172 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
173 /// is a non-lvalue expression whose value is the address of the object for
174 /// which the function is called.
175
Sebastian Redlf53597f2009-03-15 17:47:39 +0000176 if (!isa<FunctionDecl>(CurContext))
177 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000178
179 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext))
180 if (MD->isInstance())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000181 return Owned(new (Context) CXXThisExpr(ThisLoc,
Douglas Gregor828a1972010-01-07 23:12:05 +0000182 MD->getThisType(Context),
183 /*isImplicit=*/false));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000184
Sebastian Redlf53597f2009-03-15 17:47:39 +0000185 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000186}
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000187
188/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
189/// Can be interpreted either as function-style casting ("int(x)")
190/// or class type construction ("ClassType(x,y,z)")
191/// or creation of a value-initialized type ("int()").
Sebastian Redlf53597f2009-03-15 17:47:39 +0000192Action::OwningExprResult
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000193Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep,
194 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000195 MultiExprArg exprs,
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000196 SourceLocation *CommaLocs,
197 SourceLocation RParenLoc) {
198 assert(TypeRep && "Missing type!");
John McCall9d125032010-01-15 18:39:57 +0000199 TypeSourceInfo *TInfo;
200 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
201 if (!TInfo)
202 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
Sebastian Redlf53597f2009-03-15 17:47:39 +0000203 unsigned NumExprs = exprs.size();
204 Expr **Exprs = (Expr**)exprs.get();
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000205 SourceLocation TyBeginLoc = TypeRange.getBegin();
206 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
207
Sebastian Redlf53597f2009-03-15 17:47:39 +0000208 if (Ty->isDependentType() ||
Douglas Gregorba498172009-03-13 21:01:28 +0000209 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
Sebastian Redlf53597f2009-03-15 17:47:39 +0000210 exprs.release();
Mike Stump1eb44332009-09-09 15:08:12 +0000211
212 return Owned(CXXUnresolvedConstructExpr::Create(Context,
213 TypeRange.getBegin(), Ty,
Douglas Gregord81e6ca2009-05-20 18:46:25 +0000214 LParenLoc,
215 Exprs, NumExprs,
216 RParenLoc));
Douglas Gregorba498172009-03-13 21:01:28 +0000217 }
218
Anders Carlssonbb60a502009-08-27 03:53:50 +0000219 if (Ty->isArrayType())
220 return ExprError(Diag(TyBeginLoc,
221 diag::err_value_init_for_array_type) << FullRange);
222 if (!Ty->isVoidType() &&
223 RequireCompleteType(TyBeginLoc, Ty,
224 PDiag(diag::err_invalid_incomplete_type_use)
225 << FullRange))
226 return ExprError();
Fariborz Jahanianf071e9b2009-10-23 21:01:39 +0000227
Anders Carlssonbb60a502009-08-27 03:53:50 +0000228 if (RequireNonAbstractType(TyBeginLoc, Ty,
229 diag::err_allocation_of_abstract_type))
230 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000231
232
Douglas Gregor506ae412009-01-16 18:33:17 +0000233 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000234 // If the expression list is a single expression, the type conversion
235 // expression is equivalent (in definedness, and if defined in meaning) to the
236 // corresponding cast expression.
237 //
238 if (NumExprs == 1) {
Anders Carlssoncdb61972009-08-07 22:21:05 +0000239 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Anders Carlsson0aebc812009-09-09 21:33:21 +0000240 CXXMethodDecl *Method = 0;
241 if (CheckCastTypes(TypeRange, Ty, Exprs[0], Kind, Method,
242 /*FunctionalStyle=*/true))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000243 return ExprError();
Anders Carlsson0aebc812009-09-09 21:33:21 +0000244
245 exprs.release();
246 if (Method) {
247 OwningExprResult CastArg
248 = BuildCXXCastArgument(TypeRange.getBegin(), Ty.getNonReferenceType(),
249 Kind, Method, Owned(Exprs[0]));
250 if (CastArg.isInvalid())
251 return ExprError();
252
253 Exprs[0] = CastArg.takeAs<Expr>();
Fariborz Jahanian4fc7ab32009-08-28 15:11:24 +0000254 }
Anders Carlsson0aebc812009-09-09 21:33:21 +0000255
256 return Owned(new (Context) CXXFunctionalCastExpr(Ty.getNonReferenceType(),
John McCall9d125032010-01-15 18:39:57 +0000257 TInfo, TyBeginLoc, Kind,
Anders Carlsson0aebc812009-09-09 21:33:21 +0000258 Exprs[0], RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000259 }
260
Ted Kremenek6217b802009-07-29 21:53:49 +0000261 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Douglas Gregor506ae412009-01-16 18:33:17 +0000262 CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
Sebastian Redlf53597f2009-03-15 17:47:39 +0000263
Mike Stump1eb44332009-09-09 15:08:12 +0000264 if (NumExprs > 1 || !Record->hasTrivialConstructor() ||
Anders Carlssone7624a72009-08-27 05:08:22 +0000265 !Record->hasTrivialDestructor()) {
Eli Friedman6997aae2010-01-31 20:58:15 +0000266 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty);
267 InitializationKind Kind
268 = NumExprs ? InitializationKind::CreateDirect(TypeRange.getBegin(),
269 LParenLoc, RParenLoc)
270 : InitializationKind::CreateValue(TypeRange.getBegin(),
271 LParenLoc, RParenLoc);
272 InitializationSequence InitSeq(*this, Entity, Kind, Exprs, NumExprs);
273 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
274 move(exprs));
Douglas Gregor506ae412009-01-16 18:33:17 +0000275
Eli Friedman6997aae2010-01-31 20:58:15 +0000276 // FIXME: Improve AST representation?
277 return move(Result);
Douglas Gregor506ae412009-01-16 18:33:17 +0000278 }
279
280 // Fall through to value-initialize an object of class type that
281 // doesn't have a user-declared default constructor.
282 }
283
284 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000285 // If the expression list specifies more than a single value, the type shall
286 // be a class with a suitably declared constructor.
287 //
288 if (NumExprs > 1)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000289 return ExprError(Diag(CommaLocs[0],
290 diag::err_builtin_func_cast_more_than_one_arg)
291 << FullRange);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000292
293 assert(NumExprs == 0 && "Expected 0 expressions");
Douglas Gregor506ae412009-01-16 18:33:17 +0000294 // C++ [expr.type.conv]p2:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000295 // The expression T(), where T is a simple-type-specifier for a non-array
296 // complete object type or the (possibly cv-qualified) void type, creates an
297 // rvalue of the specified type, which is value-initialized.
298 //
Sebastian Redlf53597f2009-03-15 17:47:39 +0000299 exprs.release();
300 return Owned(new (Context) CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000301}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000302
303
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000304/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
305/// @code new (memory) int[size][4] @endcode
306/// or
307/// @code ::new Foo(23, "hello") @endcode
308/// For the interpretation of this heap of arguments, consult the base version.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000309Action::OwningExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000310Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000311 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000312 SourceLocation PlacementRParen, bool ParenTypeId,
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000313 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000314 MultiExprArg ConstructorArgs,
Mike Stump1eb44332009-09-09 15:08:12 +0000315 SourceLocation ConstructorRParen) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000316 Expr *ArraySize = 0;
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000317 // If the specified type is an array, unwrap it and save the expression.
318 if (D.getNumTypeObjects() > 0 &&
319 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
320 DeclaratorChunk &Chunk = D.getTypeObject(0);
321 if (Chunk.Arr.hasStatic)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000322 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
323 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000324 if (!Chunk.Arr.NumElts)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000325 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
326 << D.getSourceRange());
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000327
328 if (ParenTypeId) {
329 // Can't have dynamic array size when the type-id is in parentheses.
330 Expr *NumElts = (Expr *)Chunk.Arr.NumElts;
331 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
332 !NumElts->isIntegerConstantExpr(Context)) {
333 Diag(D.getTypeObject(0).Loc, diag::err_new_paren_array_nonconst)
334 << NumElts->getSourceRange();
335 return ExprError();
336 }
337 }
338
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000339 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000340 D.DropFirstTypeObject();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000341 }
342
Douglas Gregor043cad22009-09-11 00:18:58 +0000343 // Every dimension shall be of constant size.
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000344 if (ArraySize) {
345 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor043cad22009-09-11 00:18:58 +0000346 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
347 break;
348
349 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
350 if (Expr *NumElts = (Expr *)Array.NumElts) {
351 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
352 !NumElts->isIntegerConstantExpr(Context)) {
353 Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst)
354 << NumElts->getSourceRange();
355 return ExprError();
356 }
357 }
358 }
359 }
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000360
John McCalla93c9342009-12-07 02:54:59 +0000361 //FIXME: Store TypeSourceInfo in CXXNew expression.
362 TypeSourceInfo *TInfo = 0;
363 QualType AllocType = GetTypeForDeclarator(D, /*Scope=*/0, &TInfo);
Chris Lattnereaaebc72009-04-25 08:06:05 +0000364 if (D.isInvalidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000365 return ExprError();
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000366
Mike Stump1eb44332009-09-09 15:08:12 +0000367 return BuildCXXNew(StartLoc, UseGlobal,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000368 PlacementLParen,
Mike Stump1eb44332009-09-09 15:08:12 +0000369 move(PlacementArgs),
Douglas Gregor3433cf72009-05-21 00:00:09 +0000370 PlacementRParen,
371 ParenTypeId,
Mike Stump1eb44332009-09-09 15:08:12 +0000372 AllocType,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000373 D.getSourceRange().getBegin(),
374 D.getSourceRange(),
375 Owned(ArraySize),
376 ConstructorLParen,
377 move(ConstructorArgs),
378 ConstructorRParen);
379}
380
Mike Stump1eb44332009-09-09 15:08:12 +0000381Sema::OwningExprResult
Douglas Gregor3433cf72009-05-21 00:00:09 +0000382Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
383 SourceLocation PlacementLParen,
384 MultiExprArg PlacementArgs,
385 SourceLocation PlacementRParen,
Mike Stump1eb44332009-09-09 15:08:12 +0000386 bool ParenTypeId,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000387 QualType AllocType,
388 SourceLocation TypeLoc,
389 SourceRange TypeRange,
390 ExprArg ArraySizeE,
391 SourceLocation ConstructorLParen,
392 MultiExprArg ConstructorArgs,
393 SourceLocation ConstructorRParen) {
394 if (CheckAllocatedType(AllocType, TypeLoc, TypeRange))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000395 return ExprError();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000396
Douglas Gregor3433cf72009-05-21 00:00:09 +0000397 QualType ResultType = Context.getPointerType(AllocType);
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000398
399 // That every array dimension except the first is constant was already
400 // checked by the type check above.
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000401
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000402 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
403 // or enumeration type with a non-negative value."
Douglas Gregor3433cf72009-05-21 00:00:09 +0000404 Expr *ArraySize = (Expr *)ArraySizeE.get();
Sebastian Redl28507842009-02-26 14:39:58 +0000405 if (ArraySize && !ArraySize->isTypeDependent()) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000406 QualType SizeType = ArraySize->getType();
407 if (!SizeType->isIntegralType() && !SizeType->isEnumeralType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000408 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
409 diag::err_array_size_not_integral)
410 << SizeType << ArraySize->getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000411 // Let's see if this is a constant < 0. If so, we reject it out of hand.
412 // We don't care about special rules, so we tell the machinery it's not
413 // evaluated - it gives us a result in more cases.
Sebastian Redl28507842009-02-26 14:39:58 +0000414 if (!ArraySize->isValueDependent()) {
415 llvm::APSInt Value;
416 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
417 if (Value < llvm::APSInt(
Anders Carlssonac18b2e2009-09-23 00:37:25 +0000418 llvm::APInt::getNullValue(Value.getBitWidth()),
419 Value.isUnsigned()))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000420 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
421 diag::err_typecheck_negative_array_size)
422 << ArraySize->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +0000423 }
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000424 }
Anders Carlssonac18b2e2009-09-23 00:37:25 +0000425
Eli Friedman73c39ab2009-10-20 08:27:19 +0000426 ImpCastExprToType(ArraySize, Context.getSizeType(),
427 CastExpr::CK_IntegralCast);
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000428 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000429
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000430 FunctionDecl *OperatorNew = 0;
431 FunctionDecl *OperatorDelete = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000432 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
433 unsigned NumPlaceArgs = PlacementArgs.size();
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000434
Sebastian Redl28507842009-02-26 14:39:58 +0000435 if (!AllocType->isDependentType() &&
436 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
437 FindAllocationFunctions(StartLoc,
Sebastian Redl00e68e22009-02-09 18:24:27 +0000438 SourceRange(PlacementLParen, PlacementRParen),
439 UseGlobal, AllocType, ArraySize, PlaceArgs,
440 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000441 return ExprError();
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000442 llvm::SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000443 if (OperatorNew) {
444 // Add default arguments, if any.
445 const FunctionProtoType *Proto =
446 OperatorNew->getType()->getAs<FunctionProtoType>();
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +0000447 VariadicCallType CallType =
448 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000449 bool Invalid = GatherArgumentsForCall(PlacementLParen, OperatorNew,
450 Proto, 1, PlaceArgs, NumPlaceArgs,
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +0000451 AllPlaceArgs, CallType);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000452 if (Invalid)
453 return ExprError();
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000454
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000455 NumPlaceArgs = AllPlaceArgs.size();
456 if (NumPlaceArgs > 0)
457 PlaceArgs = &AllPlaceArgs[0];
458 }
459
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000460 bool Init = ConstructorLParen.isValid();
461 // --- Choosing a constructor ---
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000462 CXXConstructorDecl *Constructor = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000463 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
464 unsigned NumConsArgs = ConstructorArgs.size();
Eli Friedmana8ce9ec2009-11-08 22:15:39 +0000465 ASTOwningVector<&ActionBase::DeleteExpr> ConvertedConstructorArgs(*this);
466
Douglas Gregor99a2e602009-12-16 01:38:02 +0000467 if (!AllocType->isDependentType() &&
468 !Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) {
469 // C++0x [expr.new]p15:
470 // A new-expression that creates an object of type T initializes that
471 // object as follows:
472 InitializationKind Kind
473 // - If the new-initializer is omitted, the object is default-
474 // initialized (8.5); if no initialization is performed,
475 // the object has indeterminate value
476 = !Init? InitializationKind::CreateDefault(TypeLoc)
477 // - Otherwise, the new-initializer is interpreted according to the
478 // initialization rules of 8.5 for direct-initialization.
479 : InitializationKind::CreateDirect(TypeLoc,
480 ConstructorLParen,
481 ConstructorRParen);
482
Douglas Gregor99a2e602009-12-16 01:38:02 +0000483 InitializedEntity Entity
Douglas Gregord6542d82009-12-22 15:35:07 +0000484 = InitializedEntity::InitializeNew(StartLoc, AllocType);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000485 InitializationSequence InitSeq(*this, Entity, Kind, ConsArgs, NumConsArgs);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000486 OwningExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
487 move(ConstructorArgs));
488 if (FullInit.isInvalid())
489 return ExprError();
490
491 // FullInit is our initializer; walk through it to determine if it's a
492 // constructor call, which CXXNewExpr handles directly.
493 if (Expr *FullInitExpr = (Expr *)FullInit.get()) {
494 if (CXXBindTemporaryExpr *Binder
495 = dyn_cast<CXXBindTemporaryExpr>(FullInitExpr))
496 FullInitExpr = Binder->getSubExpr();
497 if (CXXConstructExpr *Construct
498 = dyn_cast<CXXConstructExpr>(FullInitExpr)) {
499 Constructor = Construct->getConstructor();
500 for (CXXConstructExpr::arg_iterator A = Construct->arg_begin(),
501 AEnd = Construct->arg_end();
502 A != AEnd; ++A)
503 ConvertedConstructorArgs.push_back(A->Retain());
504 } else {
505 // Take the converted initializer.
506 ConvertedConstructorArgs.push_back(FullInit.release());
507 }
508 } else {
509 // No initialization required.
510 }
511
512 // Take the converted arguments and use them for the new expression.
Douglas Gregor39da0b82009-09-09 23:08:42 +0000513 NumConsArgs = ConvertedConstructorArgs.size();
514 ConsArgs = (Expr **)ConvertedConstructorArgs.take();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000515 }
Douglas Gregor99a2e602009-12-16 01:38:02 +0000516
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000517 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
Douglas Gregor089407b2009-10-17 21:40:42 +0000518
Sebastian Redlf53597f2009-03-15 17:47:39 +0000519 PlacementArgs.release();
520 ConstructorArgs.release();
Douglas Gregor3433cf72009-05-21 00:00:09 +0000521 ArraySizeE.release();
Sebastian Redlf53597f2009-03-15 17:47:39 +0000522 return Owned(new (Context) CXXNewExpr(UseGlobal, OperatorNew, PlaceArgs,
Ted Kremenek8189cde2009-02-07 01:47:29 +0000523 NumPlaceArgs, ParenTypeId, ArraySize, Constructor, Init,
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000524 ConsArgs, NumConsArgs, OperatorDelete, ResultType,
Mike Stump1eb44332009-09-09 15:08:12 +0000525 StartLoc, Init ? ConstructorRParen : SourceLocation()));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000526}
527
528/// CheckAllocatedType - Checks that a type is suitable as the allocated type
529/// in a new-expression.
530/// dimension off and stores the size expression in ArraySize.
Douglas Gregor3433cf72009-05-21 00:00:09 +0000531bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +0000532 SourceRange R) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000533 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
534 // abstract class type or array thereof.
Douglas Gregore7450f52009-03-24 19:52:54 +0000535 if (AllocType->isFunctionType())
Douglas Gregor3433cf72009-05-21 00:00:09 +0000536 return Diag(Loc, diag::err_bad_new_type)
537 << AllocType << 0 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +0000538 else if (AllocType->isReferenceType())
Douglas Gregor3433cf72009-05-21 00:00:09 +0000539 return Diag(Loc, diag::err_bad_new_type)
540 << AllocType << 1 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +0000541 else if (!AllocType->isDependentType() &&
Douglas Gregor3433cf72009-05-21 00:00:09 +0000542 RequireCompleteType(Loc, AllocType,
Anders Carlssonb7906612009-08-26 23:45:07 +0000543 PDiag(diag::err_new_incomplete_type)
544 << R))
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000545 return true;
Douglas Gregor3433cf72009-05-21 00:00:09 +0000546 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregore7450f52009-03-24 19:52:54 +0000547 diag::err_allocation_of_abstract_type))
548 return true;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000549
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000550 return false;
551}
552
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000553/// FindAllocationFunctions - Finds the overloads of operator new and delete
554/// that are appropriate for the allocation.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000555bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
556 bool UseGlobal, QualType AllocType,
557 bool IsArray, Expr **PlaceArgs,
558 unsigned NumPlaceArgs,
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000559 FunctionDecl *&OperatorNew,
Mike Stump1eb44332009-09-09 15:08:12 +0000560 FunctionDecl *&OperatorDelete) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000561 // --- Choosing an allocation function ---
562 // C++ 5.3.4p8 - 14 & 18
563 // 1) If UseGlobal is true, only look in the global scope. Else, also look
564 // in the scope of the allocated class.
565 // 2) If an array size is given, look for operator new[], else look for
566 // operator new.
567 // 3) The first argument is always size_t. Append the arguments from the
568 // placement form.
569 // FIXME: Also find the appropriate delete operator.
570
571 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
572 // We don't care about the actual value of this argument.
573 // FIXME: Should the Sema create the expression and embed it in the syntax
574 // tree? Or should the consumer just recalculate the value?
Anders Carlssond67c4c32009-08-16 20:29:29 +0000575 IntegerLiteral Size(llvm::APInt::getNullValue(
576 Context.Target.getPointerWidth(0)),
577 Context.getSizeType(),
578 SourceLocation());
579 AllocArgs[0] = &Size;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000580 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
581
582 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
583 IsArray ? OO_Array_New : OO_New);
584 if (AllocType->isRecordType() && !UseGlobal) {
Mike Stump1eb44332009-09-09 15:08:12 +0000585 CXXRecordDecl *Record
Ted Kremenek6217b802009-07-29 21:53:49 +0000586 = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl());
Sebastian Redl7f662392008-12-04 22:20:51 +0000587 // FIXME: We fail to find inherited overloads.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000588 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000589 AllocArgs.size(), Record, /*AllowMissing=*/true,
590 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000591 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000592 }
593 if (!OperatorNew) {
594 // Didn't find a member overload. Look for a global one.
595 DeclareGlobalNewDelete();
Sebastian Redl7f662392008-12-04 22:20:51 +0000596 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl00e68e22009-02-09 18:24:27 +0000597 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000598 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
599 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000600 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000601 }
602
Anders Carlssond9583892009-05-31 20:26:12 +0000603 // FindAllocationOverload can change the passed in arguments, so we need to
604 // copy them back.
605 if (NumPlaceArgs > 0)
606 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
Mike Stump1eb44332009-09-09 15:08:12 +0000607
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000608 return false;
609}
610
Sebastian Redl7f662392008-12-04 22:20:51 +0000611/// FindAllocationOverload - Find an fitting overload for the allocation
612/// function in the specified scope.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000613bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
614 DeclarationName Name, Expr** Args,
615 unsigned NumArgs, DeclContext *Ctx,
Mike Stump1eb44332009-09-09 15:08:12 +0000616 bool AllowMissing, FunctionDecl *&Operator) {
John McCalla24dc2e2009-11-17 02:14:36 +0000617 LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
618 LookupQualifiedName(R, Ctx);
John McCallf36e02d2009-10-09 21:13:30 +0000619 if (R.empty()) {
Sebastian Redl7f662392008-12-04 22:20:51 +0000620 if (AllowMissing)
621 return false;
Sebastian Redl7f662392008-12-04 22:20:51 +0000622 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +0000623 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +0000624 }
625
John McCallf36e02d2009-10-09 21:13:30 +0000626 // FIXME: handle ambiguity
627
Sebastian Redl7f662392008-12-04 22:20:51 +0000628 OverloadCandidateSet Candidates;
Douglas Gregor5d64e5b2009-09-30 00:03:47 +0000629 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
630 Alloc != AllocEnd; ++Alloc) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000631 // Even member operator new/delete are implicitly treated as
632 // static, so don't use AddMemberCandidate.
Anders Carlssoneac81392009-12-09 07:39:44 +0000633 if (FunctionDecl *Fn =
634 dyn_cast<FunctionDecl>((*Alloc)->getUnderlyingDecl())) {
John McCall86820f52010-01-26 01:37:31 +0000635 AddOverloadCandidate(Fn, Alloc.getAccess(), Args, NumArgs, Candidates,
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000636 /*SuppressUserConversions=*/false);
Douglas Gregor90916562009-09-29 18:16:17 +0000637 continue;
638 }
639
640 // FIXME: Handle function templates
Sebastian Redl7f662392008-12-04 22:20:51 +0000641 }
642
643 // Do the resolution.
644 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +0000645 switch(BestViableFunction(Candidates, StartLoc, Best)) {
Sebastian Redl7f662392008-12-04 22:20:51 +0000646 case OR_Success: {
647 // Got one!
648 FunctionDecl *FnDecl = Best->Function;
649 // The first argument is size_t, and the first parameter must be size_t,
650 // too. This is checked on declaration and can be assumed. (It can't be
651 // asserted on, though, since invalid decls are left in there.)
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000652 // Whatch out for variadic allocator function.
653 unsigned NumArgsInFnDecl = FnDecl->getNumParams();
654 for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) {
Anders Carlssonfc27d262009-05-31 19:49:47 +0000655 if (PerformCopyInitialization(Args[i],
Sebastian Redl7f662392008-12-04 22:20:51 +0000656 FnDecl->getParamDecl(i)->getType(),
Douglas Gregor68647482009-12-16 03:45:30 +0000657 AA_Passing))
Sebastian Redl7f662392008-12-04 22:20:51 +0000658 return true;
659 }
660 Operator = FnDecl;
661 return false;
662 }
663
664 case OR_No_Viable_Function:
Sebastian Redl7f662392008-12-04 22:20:51 +0000665 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +0000666 << Name << Range;
John McCallcbce6062010-01-12 07:18:19 +0000667 PrintOverloadCandidates(Candidates, OCD_AllCandidates, Args, NumArgs);
Sebastian Redl7f662392008-12-04 22:20:51 +0000668 return true;
669
670 case OR_Ambiguous:
Sebastian Redl7f662392008-12-04 22:20:51 +0000671 Diag(StartLoc, diag::err_ovl_ambiguous_call)
Sebastian Redl00e68e22009-02-09 18:24:27 +0000672 << Name << Range;
John McCallcbce6062010-01-12 07:18:19 +0000673 PrintOverloadCandidates(Candidates, OCD_ViableCandidates, Args, NumArgs);
Sebastian Redl7f662392008-12-04 22:20:51 +0000674 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000675
676 case OR_Deleted:
677 Diag(StartLoc, diag::err_ovl_deleted_call)
678 << Best->Function->isDeleted()
679 << Name << Range;
John McCallcbce6062010-01-12 07:18:19 +0000680 PrintOverloadCandidates(Candidates, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000681 return true;
Sebastian Redl7f662392008-12-04 22:20:51 +0000682 }
683 assert(false && "Unreachable, bad result from BestViableFunction");
684 return true;
685}
686
687
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000688/// DeclareGlobalNewDelete - Declare the global forms of operator new and
689/// delete. These are:
690/// @code
691/// void* operator new(std::size_t) throw(std::bad_alloc);
692/// void* operator new[](std::size_t) throw(std::bad_alloc);
693/// void operator delete(void *) throw();
694/// void operator delete[](void *) throw();
695/// @endcode
696/// Note that the placement and nothrow forms of new are *not* implicitly
697/// declared. Their use requires including \<new\>.
Mike Stump1eb44332009-09-09 15:08:12 +0000698void Sema::DeclareGlobalNewDelete() {
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000699 if (GlobalNewDeleteDeclared)
700 return;
Douglas Gregor7adb10f2009-09-15 22:30:29 +0000701
702 // C++ [basic.std.dynamic]p2:
703 // [...] The following allocation and deallocation functions (18.4) are
704 // implicitly declared in global scope in each translation unit of a
705 // program
706 //
707 // void* operator new(std::size_t) throw(std::bad_alloc);
708 // void* operator new[](std::size_t) throw(std::bad_alloc);
709 // void operator delete(void*) throw();
710 // void operator delete[](void*) throw();
711 //
712 // These implicit declarations introduce only the function names operator
713 // new, operator new[], operator delete, operator delete[].
714 //
715 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
716 // "std" or "bad_alloc" as necessary to form the exception specification.
717 // However, we do not make these implicit declarations visible to name
718 // lookup.
719 if (!StdNamespace) {
720 // The "std" namespace has not yet been defined, so build one implicitly.
721 StdNamespace = NamespaceDecl::Create(Context,
722 Context.getTranslationUnitDecl(),
723 SourceLocation(),
724 &PP.getIdentifierTable().get("std"));
725 StdNamespace->setImplicit(true);
726 }
727
728 if (!StdBadAlloc) {
729 // The "std::bad_alloc" class has not yet been declared, so build it
730 // implicitly.
731 StdBadAlloc = CXXRecordDecl::Create(Context, TagDecl::TK_class,
732 StdNamespace,
733 SourceLocation(),
734 &PP.getIdentifierTable().get("bad_alloc"),
735 SourceLocation(), 0);
736 StdBadAlloc->setImplicit(true);
737 }
738
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000739 GlobalNewDeleteDeclared = true;
740
741 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
742 QualType SizeT = Context.getSizeType();
Nuno Lopesfc284482009-12-16 16:59:22 +0000743 bool AssumeSaneOperatorNew = getLangOptions().AssumeSaneOperatorNew;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000744
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000745 DeclareGlobalAllocationFunction(
746 Context.DeclarationNames.getCXXOperatorName(OO_New),
Nuno Lopesfc284482009-12-16 16:59:22 +0000747 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000748 DeclareGlobalAllocationFunction(
749 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
Nuno Lopesfc284482009-12-16 16:59:22 +0000750 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000751 DeclareGlobalAllocationFunction(
752 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
753 Context.VoidTy, VoidPtr);
754 DeclareGlobalAllocationFunction(
755 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
756 Context.VoidTy, VoidPtr);
757}
758
759/// DeclareGlobalAllocationFunction - Declares a single implicit global
760/// allocation function if it doesn't already exist.
761void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Nuno Lopesfc284482009-12-16 16:59:22 +0000762 QualType Return, QualType Argument,
763 bool AddMallocAttr) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000764 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
765
766 // Check if this function is already declared.
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000767 {
Douglas Gregor5cc37092008-12-23 22:05:29 +0000768 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000769 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000770 Alloc != AllocEnd; ++Alloc) {
771 // FIXME: Do we need to check for default arguments here?
772 FunctionDecl *Func = cast<FunctionDecl>(*Alloc);
773 if (Func->getNumParams() == 1 &&
Douglas Gregor6e790ab2009-12-22 23:42:49 +0000774 Context.getCanonicalType(
775 Func->getParamDecl(0)->getType().getUnqualifiedType()) == Argument)
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000776 return;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000777 }
778 }
779
Douglas Gregor7adb10f2009-09-15 22:30:29 +0000780 QualType BadAllocType;
781 bool HasBadAllocExceptionSpec
782 = (Name.getCXXOverloadedOperator() == OO_New ||
783 Name.getCXXOverloadedOperator() == OO_Array_New);
784 if (HasBadAllocExceptionSpec) {
785 assert(StdBadAlloc && "Must have std::bad_alloc declared");
786 BadAllocType = Context.getTypeDeclType(StdBadAlloc);
787 }
788
789 QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0,
790 true, false,
791 HasBadAllocExceptionSpec? 1 : 0,
792 &BadAllocType);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000793 FunctionDecl *Alloc =
794 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
John McCalla93c9342009-12-07 02:54:59 +0000795 FnType, /*TInfo=*/0, FunctionDecl::None, false, true);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000796 Alloc->setImplicit();
Nuno Lopesfc284482009-12-16 16:59:22 +0000797
798 if (AddMallocAttr)
799 Alloc->addAttr(::new (Context) MallocAttr());
800
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000801 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
John McCalla93c9342009-12-07 02:54:59 +0000802 0, Argument, /*TInfo=*/0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000803 VarDecl::None, 0);
Ted Kremenekfc767612009-01-14 00:42:25 +0000804 Alloc->setParams(Context, &Param, 1);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000805
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000806 // FIXME: Also add this declaration to the IdentifierResolver, but
807 // make sure it is at the end of the chain to coincide with the
808 // global scope.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000809 ((DeclContext *)TUScope->getEntity())->addDecl(Alloc);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000810}
811
Anders Carlsson78f74552009-11-15 18:45:20 +0000812bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
813 DeclarationName Name,
Anders Carlsson5ec02ae2009-12-02 17:15:43 +0000814 FunctionDecl* &Operator) {
John McCalla24dc2e2009-11-17 02:14:36 +0000815 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlsson78f74552009-11-15 18:45:20 +0000816 // Try to find operator delete/operator delete[] in class scope.
John McCalla24dc2e2009-11-17 02:14:36 +0000817 LookupQualifiedName(Found, RD);
Anders Carlsson78f74552009-11-15 18:45:20 +0000818
John McCalla24dc2e2009-11-17 02:14:36 +0000819 if (Found.isAmbiguous())
Anders Carlsson78f74552009-11-15 18:45:20 +0000820 return true;
Anders Carlsson78f74552009-11-15 18:45:20 +0000821
822 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
823 F != FEnd; ++F) {
824 if (CXXMethodDecl *Delete = dyn_cast<CXXMethodDecl>(*F))
825 if (Delete->isUsualDeallocationFunction()) {
826 Operator = Delete;
827 return false;
828 }
829 }
830
831 // We did find operator delete/operator delete[] declarations, but
832 // none of them were suitable.
833 if (!Found.empty()) {
834 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
835 << Name << RD;
836
837 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
838 F != FEnd; ++F) {
839 Diag((*F)->getLocation(),
840 diag::note_delete_member_function_declared_here)
841 << Name;
842 }
843
844 return true;
845 }
846
847 // Look for a global declaration.
848 DeclareGlobalNewDelete();
849 DeclContext *TUDecl = Context.getTranslationUnitDecl();
850
851 CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation());
852 Expr* DeallocArgs[1];
853 DeallocArgs[0] = &Null;
854 if (FindAllocationOverload(StartLoc, SourceRange(), Name,
855 DeallocArgs, 1, TUDecl, /*AllowMissing=*/false,
856 Operator))
857 return true;
858
859 assert(Operator && "Did not find a deallocation function!");
860 return false;
861}
862
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000863/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
864/// @code ::delete ptr; @endcode
865/// or
866/// @code delete [] ptr; @endcode
Sebastian Redlf53597f2009-03-15 17:47:39 +0000867Action::OwningExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000868Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
Mike Stump1eb44332009-09-09 15:08:12 +0000869 bool ArrayForm, ExprArg Operand) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000870 // C++ [expr.delete]p1:
871 // The operand shall have a pointer type, or a class type having a single
872 // conversion function to a pointer type. The result has type void.
873 //
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000874 // DR599 amends "pointer type" to "pointer to object type" in both cases.
875
Anders Carlssond67c4c32009-08-16 20:29:29 +0000876 FunctionDecl *OperatorDelete = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000877
Sebastian Redlf53597f2009-03-15 17:47:39 +0000878 Expr *Ex = (Expr *)Operand.get();
Sebastian Redl28507842009-02-26 14:39:58 +0000879 if (!Ex->isTypeDependent()) {
880 QualType Type = Ex->getType();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000881
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000882 if (const RecordType *Record = Type->getAs<RecordType>()) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000883 llvm::SmallVector<CXXConversionDecl *, 4> ObjectPtrConversions;
Fariborz Jahanian53462782009-09-11 21:44:33 +0000884 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
John McCalleec51cf2010-01-20 00:46:10 +0000885 const UnresolvedSetImpl *Conversions = RD->getVisibleConversionFunctions();
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000886
John McCalleec51cf2010-01-20 00:46:10 +0000887 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +0000888 E = Conversions->end(); I != E; ++I) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000889 // Skip over templated conversion functions; they aren't considered.
John McCallba135432009-11-21 08:51:07 +0000890 if (isa<FunctionTemplateDecl>(*I))
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000891 continue;
892
John McCallba135432009-11-21 08:51:07 +0000893 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*I);
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000894
895 QualType ConvType = Conv->getConversionType().getNonReferenceType();
896 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
897 if (ConvPtrType->getPointeeType()->isObjectType())
Fariborz Jahanian8b915e72009-09-15 22:15:23 +0000898 ObjectPtrConversions.push_back(Conv);
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000899 }
Fariborz Jahanian8b915e72009-09-15 22:15:23 +0000900 if (ObjectPtrConversions.size() == 1) {
901 // We have a single conversion to a pointer-to-object type. Perform
902 // that conversion.
903 Operand.release();
904 if (!PerformImplicitConversion(Ex,
905 ObjectPtrConversions.front()->getConversionType(),
Douglas Gregor68647482009-12-16 03:45:30 +0000906 AA_Converting)) {
Fariborz Jahanian8b915e72009-09-15 22:15:23 +0000907 Operand = Owned(Ex);
908 Type = Ex->getType();
909 }
910 }
911 else if (ObjectPtrConversions.size() > 1) {
912 Diag(StartLoc, diag::err_ambiguous_delete_operand)
913 << Type << Ex->getSourceRange();
914 for (unsigned i= 0; i < ObjectPtrConversions.size(); i++) {
915 CXXConversionDecl *Conv = ObjectPtrConversions[i];
John McCallb1622a12010-01-06 09:43:14 +0000916 NoteOverloadCandidate(Conv);
Fariborz Jahanian8b915e72009-09-15 22:15:23 +0000917 }
918 return ExprError();
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000919 }
Sebastian Redl28507842009-02-26 14:39:58 +0000920 }
921
Sebastian Redlf53597f2009-03-15 17:47:39 +0000922 if (!Type->isPointerType())
923 return ExprError(Diag(StartLoc, diag::err_delete_operand)
924 << Type << Ex->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +0000925
Ted Kremenek6217b802009-07-29 21:53:49 +0000926 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Douglas Gregor8dcb29d2009-03-24 20:13:58 +0000927 if (Pointee->isFunctionType() || Pointee->isVoidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000928 return ExprError(Diag(StartLoc, diag::err_delete_operand)
929 << Type << Ex->getSourceRange());
Douglas Gregor8dcb29d2009-03-24 20:13:58 +0000930 else if (!Pointee->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +0000931 RequireCompleteType(StartLoc, Pointee,
Anders Carlssonb7906612009-08-26 23:45:07 +0000932 PDiag(diag::warn_delete_incomplete)
933 << Ex->getSourceRange()))
Douglas Gregor8dcb29d2009-03-24 20:13:58 +0000934 return ExprError();
Sebastian Redl28507842009-02-26 14:39:58 +0000935
Douglas Gregor1070c9f2009-09-29 21:38:53 +0000936 // C++ [expr.delete]p2:
937 // [Note: a pointer to a const type can be the operand of a
938 // delete-expression; it is not necessary to cast away the constness
939 // (5.2.11) of the pointer expression before it is used as the operand
940 // of the delete-expression. ]
941 ImpCastExprToType(Ex, Context.getPointerType(Context.VoidTy),
942 CastExpr::CK_NoOp);
943
944 // Update the operand.
945 Operand.take();
946 Operand = ExprArg(*this, Ex);
947
Anders Carlssond67c4c32009-08-16 20:29:29 +0000948 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
949 ArrayForm ? OO_Array_Delete : OO_Delete);
950
Anders Carlsson78f74552009-11-15 18:45:20 +0000951 if (const RecordType *RT = Pointee->getAs<RecordType>()) {
952 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
953
954 if (!UseGlobal &&
955 FindDeallocationFunction(StartLoc, RD, DeleteName, OperatorDelete))
Anders Carlsson0ba63ea2009-11-14 03:17:38 +0000956 return ExprError();
Anders Carlsson0ba63ea2009-11-14 03:17:38 +0000957
Anders Carlsson78f74552009-11-15 18:45:20 +0000958 if (!RD->hasTrivialDestructor())
959 if (const CXXDestructorDecl *Dtor = RD->getDestructor(Context))
Mike Stump1eb44332009-09-09 15:08:12 +0000960 MarkDeclarationReferenced(StartLoc,
Fariborz Jahanian34374e62009-09-03 23:18:17 +0000961 const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssond67c4c32009-08-16 20:29:29 +0000962 }
Anders Carlsson78f74552009-11-15 18:45:20 +0000963
Anders Carlssond67c4c32009-08-16 20:29:29 +0000964 if (!OperatorDelete) {
Anders Carlsson78f74552009-11-15 18:45:20 +0000965 // Look for a global declaration.
Anders Carlssond67c4c32009-08-16 20:29:29 +0000966 DeclareGlobalNewDelete();
967 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000968 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
Douglas Gregor90916562009-09-29 18:16:17 +0000969 &Ex, 1, TUDecl, /*AllowMissing=*/false,
Anders Carlssond67c4c32009-08-16 20:29:29 +0000970 OperatorDelete))
971 return ExprError();
972 }
Mike Stump1eb44332009-09-09 15:08:12 +0000973
Sebastian Redl28507842009-02-26 14:39:58 +0000974 // FIXME: Check access and ambiguity of operator delete and destructor.
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000975 }
976
Sebastian Redlf53597f2009-03-15 17:47:39 +0000977 Operand.release();
978 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
Anders Carlssond67c4c32009-08-16 20:29:29 +0000979 OperatorDelete, Ex, StartLoc));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000980}
981
Douglas Gregor8cfe5a72009-11-23 23:44:04 +0000982/// \brief Check the use of the given variable as a C++ condition in an if,
983/// while, do-while, or switch statement.
984Action::OwningExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar) {
985 QualType T = ConditionVar->getType();
986
987 // C++ [stmt.select]p2:
988 // The declarator shall not specify a function or an array.
989 if (T->isFunctionType())
990 return ExprError(Diag(ConditionVar->getLocation(),
991 diag::err_invalid_use_of_function_type)
992 << ConditionVar->getSourceRange());
993 else if (T->isArrayType())
994 return ExprError(Diag(ConditionVar->getLocation(),
995 diag::err_invalid_use_of_array_type)
996 << ConditionVar->getSourceRange());
Douglas Gregora7605db2009-11-24 16:07:02 +0000997
Douglas Gregor8cfe5a72009-11-23 23:44:04 +0000998 return Owned(DeclRefExpr::Create(Context, 0, SourceRange(), ConditionVar,
999 ConditionVar->getLocation(),
1000 ConditionVar->getType().getNonReferenceType()));
1001}
1002
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001003/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
1004bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
1005 // C++ 6.4p4:
1006 // The value of a condition that is an initialized declaration in a statement
1007 // other than a switch statement is the value of the declared variable
1008 // implicitly converted to type bool. If that conversion is ill-formed, the
1009 // program is ill-formed.
1010 // The value of a condition that is an expression is the value of the
1011 // expression, implicitly converted to bool.
1012 //
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001013 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001014}
Douglas Gregor77a52232008-09-12 00:47:35 +00001015
1016/// Helper function to determine whether this is the (deprecated) C++
1017/// conversion from a string literal to a pointer to non-const char or
1018/// non-const wchar_t (for narrow and wide string literals,
1019/// respectively).
Mike Stump1eb44332009-09-09 15:08:12 +00001020bool
Douglas Gregor77a52232008-09-12 00:47:35 +00001021Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
1022 // Look inside the implicit cast, if it exists.
1023 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
1024 From = Cast->getSubExpr();
1025
1026 // A string literal (2.13.4) that is not a wide string literal can
1027 // be converted to an rvalue of type "pointer to char"; a wide
1028 // string literal can be converted to an rvalue of type "pointer
1029 // to wchar_t" (C++ 4.2p2).
1030 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From))
Ted Kremenek6217b802009-07-29 21:53:49 +00001031 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump1eb44332009-09-09 15:08:12 +00001032 if (const BuiltinType *ToPointeeType
John McCall183700f2009-09-21 23:43:11 +00001033 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregor77a52232008-09-12 00:47:35 +00001034 // This conversion is considered only when there is an
1035 // explicit appropriate pointer target type (C++ 4.2p2).
John McCall0953e762009-09-24 19:53:00 +00001036 if (!ToPtrType->getPointeeType().hasQualifiers() &&
Douglas Gregor77a52232008-09-12 00:47:35 +00001037 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
1038 (!StrLit->isWide() &&
1039 (ToPointeeType->getKind() == BuiltinType::Char_U ||
1040 ToPointeeType->getKind() == BuiltinType::Char_S))))
1041 return true;
1042 }
1043
1044 return false;
1045}
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001046
1047/// PerformImplicitConversion - Perform an implicit conversion of the
1048/// expression From to the type ToType. Returns true if there was an
1049/// error, false otherwise. The expression From is replaced with the
Douglas Gregor45920e82008-12-19 17:40:08 +00001050/// converted expression. Flavor is the kind of conversion we're
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001051/// performing, used in the error message. If @p AllowExplicit,
Sebastian Redle2b68332009-04-12 17:16:29 +00001052/// explicit user-defined conversions are permitted. @p Elidable should be true
1053/// when called for copies which may be elided (C++ 12.8p15). C++0x overload
1054/// resolution works differently in that case.
1055bool
Douglas Gregor45920e82008-12-19 17:40:08 +00001056Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor68647482009-12-16 03:45:30 +00001057 AssignmentAction Action, bool AllowExplicit,
Mike Stump1eb44332009-09-09 15:08:12 +00001058 bool Elidable) {
Sebastian Redle2b68332009-04-12 17:16:29 +00001059 ImplicitConversionSequence ICS;
Douglas Gregor68647482009-12-16 03:45:30 +00001060 return PerformImplicitConversion(From, ToType, Action, AllowExplicit,
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00001061 Elidable, ICS);
1062}
1063
1064bool
1065Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor68647482009-12-16 03:45:30 +00001066 AssignmentAction Action, bool AllowExplicit,
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00001067 bool Elidable,
1068 ImplicitConversionSequence& ICS) {
John McCall1d318332010-01-12 00:44:57 +00001069 ICS.setBad();
John McCalladbb8f82010-01-13 09:16:55 +00001070 ICS.Bad.init(BadConversionSequence::no_conversion, From, ToType);
Sebastian Redle2b68332009-04-12 17:16:29 +00001071 if (Elidable && getLangOptions().CPlusPlus0x) {
Mike Stump1eb44332009-09-09 15:08:12 +00001072 ICS = TryImplicitConversion(From, ToType,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001073 /*SuppressUserConversions=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +00001074 AllowExplicit,
Anders Carlsson08972922009-08-28 15:33:32 +00001075 /*ForceRValue=*/true,
1076 /*InOverloadResolution=*/false);
Sebastian Redle2b68332009-04-12 17:16:29 +00001077 }
John McCall1d318332010-01-12 00:44:57 +00001078 if (ICS.isBad()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001079 ICS = TryImplicitConversion(From, ToType,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001080 /*SuppressUserConversions=*/false,
1081 AllowExplicit,
Anders Carlsson08972922009-08-28 15:33:32 +00001082 /*ForceRValue=*/false,
1083 /*InOverloadResolution=*/false);
Sebastian Redle2b68332009-04-12 17:16:29 +00001084 }
Douglas Gregor68647482009-12-16 03:45:30 +00001085 return PerformImplicitConversion(From, ToType, ICS, Action);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001086}
1087
1088/// PerformImplicitConversion - Perform an implicit conversion of the
1089/// expression From to the type ToType using the pre-computed implicit
1090/// conversion sequence ICS. Returns true if there was an error, false
1091/// otherwise. The expression From is replaced with the converted
Douglas Gregor68647482009-12-16 03:45:30 +00001092/// expression. Action is the kind of conversion we're performing,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001093/// used in the error message.
1094bool
1095Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
1096 const ImplicitConversionSequence &ICS,
Douglas Gregor68647482009-12-16 03:45:30 +00001097 AssignmentAction Action, bool IgnoreBaseAccess) {
John McCall1d318332010-01-12 00:44:57 +00001098 switch (ICS.getKind()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001099 case ImplicitConversionSequence::StandardConversion:
Douglas Gregor68647482009-12-16 03:45:30 +00001100 if (PerformImplicitConversion(From, ToType, ICS.Standard, Action,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001101 IgnoreBaseAccess))
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001102 return true;
1103 break;
1104
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001105 case ImplicitConversionSequence::UserDefinedConversion: {
1106
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00001107 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
1108 CastExpr::CastKind CastKind = CastExpr::CK_Unknown;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001109 QualType BeforeToType;
1110 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00001111 CastKind = CastExpr::CK_UserDefinedConversion;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001112
1113 // If the user-defined conversion is specified by a conversion function,
1114 // the initial standard conversion sequence converts the source type to
1115 // the implicit object parameter of the conversion function.
1116 BeforeToType = Context.getTagDeclType(Conv->getParent());
1117 } else if (const CXXConstructorDecl *Ctor =
1118 dyn_cast<CXXConstructorDecl>(FD)) {
Anders Carlsson0aebc812009-09-09 21:33:21 +00001119 CastKind = CastExpr::CK_ConstructorConversion;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001120 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregore44201a2009-11-20 02:31:03 +00001121 if (!ICS.UserDefined.EllipsisConversion) {
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001122 // If the user-defined conversion is specified by a constructor, the
1123 // initial standard conversion sequence converts the source type to the
1124 // type required by the argument of the constructor
Douglas Gregore44201a2009-11-20 02:31:03 +00001125 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
1126 }
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001127 }
Anders Carlsson0aebc812009-09-09 21:33:21 +00001128 else
1129 assert(0 && "Unknown conversion function kind!");
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001130 // Whatch out for elipsis conversion.
Fariborz Jahanian4c0cea22009-11-06 00:55:14 +00001131 if (!ICS.UserDefined.EllipsisConversion) {
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001132 if (PerformImplicitConversion(From, BeforeToType,
Douglas Gregor68647482009-12-16 03:45:30 +00001133 ICS.UserDefined.Before, AA_Converting,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001134 IgnoreBaseAccess))
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001135 return true;
1136 }
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001137
Anders Carlsson0aebc812009-09-09 21:33:21 +00001138 OwningExprResult CastArg
1139 = BuildCXXCastArgument(From->getLocStart(),
1140 ToType.getNonReferenceType(),
1141 CastKind, cast<CXXMethodDecl>(FD),
1142 Owned(From));
1143
1144 if (CastArg.isInvalid())
1145 return true;
Eli Friedmand8889622009-11-27 04:41:50 +00001146
1147 From = CastArg.takeAs<Expr>();
1148
Eli Friedmand8889622009-11-27 04:41:50 +00001149 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
Douglas Gregor68647482009-12-16 03:45:30 +00001150 AA_Converting, IgnoreBaseAccess);
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001151 }
John McCall1d318332010-01-12 00:44:57 +00001152
1153 case ImplicitConversionSequence::AmbiguousConversion:
1154 DiagnoseAmbiguousConversion(ICS, From->getExprLoc(),
1155 PDiag(diag::err_typecheck_ambiguous_condition)
1156 << From->getSourceRange());
1157 return true;
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001158
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001159 case ImplicitConversionSequence::EllipsisConversion:
1160 assert(false && "Cannot perform an ellipsis conversion");
Douglas Gregor60d62c22008-10-31 16:23:19 +00001161 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001162
1163 case ImplicitConversionSequence::BadConversion:
1164 return true;
1165 }
1166
1167 // Everything went well.
1168 return false;
1169}
1170
1171/// PerformImplicitConversion - Perform an implicit conversion of the
1172/// expression From to the type ToType by following the standard
1173/// conversion sequence SCS. Returns true if there was an error, false
1174/// otherwise. The expression From is replaced with the converted
Douglas Gregor45920e82008-12-19 17:40:08 +00001175/// expression. Flavor is the context in which we're performing this
1176/// conversion, for use in error messages.
Mike Stump1eb44332009-09-09 15:08:12 +00001177bool
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001178Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor45920e82008-12-19 17:40:08 +00001179 const StandardConversionSequence& SCS,
Douglas Gregor68647482009-12-16 03:45:30 +00001180 AssignmentAction Action, bool IgnoreBaseAccess) {
Mike Stump390b4cc2009-05-16 07:39:55 +00001181 // Overall FIXME: we are recomputing too many types here and doing far too
1182 // much extra work. What this means is that we need to keep track of more
1183 // information that is computed when we try the implicit conversion initially,
1184 // so that we don't need to recompute anything here.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001185 QualType FromType = From->getType();
1186
Douglas Gregor225c41e2008-11-03 19:09:14 +00001187 if (SCS.CopyConstructor) {
Anders Carlsson7c3e8a12009-05-19 04:45:15 +00001188 // FIXME: When can ToType be a reference type?
1189 assert(!ToType->isReferenceType());
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00001190 if (SCS.Second == ICK_Derived_To_Base) {
1191 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1192 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
1193 MultiExprArg(*this, (void **)&From, 1),
1194 /*FIXME:ConstructLoc*/SourceLocation(),
1195 ConstructorArgs))
1196 return true;
1197 OwningExprResult FromResult =
1198 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1199 ToType, SCS.CopyConstructor,
1200 move_arg(ConstructorArgs));
1201 if (FromResult.isInvalid())
1202 return true;
1203 From = FromResult.takeAs<Expr>();
1204 return false;
1205 }
Mike Stump1eb44332009-09-09 15:08:12 +00001206 OwningExprResult FromResult =
1207 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1208 ToType, SCS.CopyConstructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00001209 MultiExprArg(*this, (void**)&From, 1));
Mike Stump1eb44332009-09-09 15:08:12 +00001210
Anders Carlssonda3f4e22009-08-25 05:12:04 +00001211 if (FromResult.isInvalid())
1212 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001213
Anders Carlssonda3f4e22009-08-25 05:12:04 +00001214 From = FromResult.takeAs<Expr>();
Douglas Gregor225c41e2008-11-03 19:09:14 +00001215 return false;
1216 }
1217
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001218 // Perform the first implicit conversion.
1219 switch (SCS.First) {
1220 case ICK_Identity:
1221 case ICK_Lvalue_To_Rvalue:
1222 // Nothing to do.
1223 break;
1224
1225 case ICK_Array_To_Pointer:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001226 FromType = Context.getArrayDecayedType(FromType);
Anders Carlsson82495762009-08-08 21:04:35 +00001227 ImpCastExprToType(From, FromType, CastExpr::CK_ArrayToPointerDecay);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001228 break;
1229
1230 case ICK_Function_To_Pointer:
Douglas Gregor063daf62009-03-13 18:40:31 +00001231 if (Context.getCanonicalType(FromType) == Context.OverloadTy) {
Douglas Gregor904eed32008-11-10 20:40:00 +00001232 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, true);
1233 if (!Fn)
1234 return true;
1235
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001236 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
1237 return true;
1238
Anders Carlsson96ad5332009-10-21 17:16:23 +00001239 From = FixOverloadedFunctionReference(From, Fn);
Douglas Gregor904eed32008-11-10 20:40:00 +00001240 FromType = From->getType();
Anders Carlsson96ad5332009-10-21 17:16:23 +00001241
Sebastian Redl759986e2009-10-17 20:50:27 +00001242 // If there's already an address-of operator in the expression, we have
1243 // the right type already, and the code below would just introduce an
1244 // invalid additional pointer level.
Anders Carlsson96ad5332009-10-21 17:16:23 +00001245 if (FromType->isPointerType() || FromType->isMemberFunctionPointerType())
Sebastian Redl759986e2009-10-17 20:50:27 +00001246 break;
Douglas Gregor904eed32008-11-10 20:40:00 +00001247 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001248 FromType = Context.getPointerType(FromType);
Anders Carlssonb633c4e2009-09-01 20:37:18 +00001249 ImpCastExprToType(From, FromType, CastExpr::CK_FunctionToPointerDecay);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001250 break;
1251
1252 default:
1253 assert(false && "Improper first standard conversion");
1254 break;
1255 }
1256
1257 // Perform the second implicit conversion
1258 switch (SCS.Second) {
1259 case ICK_Identity:
Sebastian Redl2c7588f2009-10-10 12:04:10 +00001260 // If both sides are functions (or pointers/references to them), there could
1261 // be incompatible exception declarations.
1262 if (CheckExceptionSpecCompatibility(From, ToType))
1263 return true;
1264 // Nothing else to do.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001265 break;
1266
Douglas Gregor43c79c22009-12-09 00:47:37 +00001267 case ICK_NoReturn_Adjustment:
1268 // If both sides are functions (or pointers/references to them), there could
1269 // be incompatible exception declarations.
1270 if (CheckExceptionSpecCompatibility(From, ToType))
1271 return true;
1272
1273 ImpCastExprToType(From, Context.getNoReturnType(From->getType(), false),
1274 CastExpr::CK_NoOp);
1275 break;
1276
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001277 case ICK_Integral_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001278 case ICK_Integral_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001279 ImpCastExprToType(From, ToType, CastExpr::CK_IntegralCast);
1280 break;
1281
1282 case ICK_Floating_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001283 case ICK_Floating_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001284 ImpCastExprToType(From, ToType, CastExpr::CK_FloatingCast);
1285 break;
1286
1287 case ICK_Complex_Promotion:
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001288 case ICK_Complex_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001289 ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1290 break;
1291
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001292 case ICK_Floating_Integral:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001293 if (ToType->isFloatingType())
1294 ImpCastExprToType(From, ToType, CastExpr::CK_IntegralToFloating);
1295 else
1296 ImpCastExprToType(From, ToType, CastExpr::CK_FloatingToIntegral);
1297 break;
1298
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001299 case ICK_Complex_Real:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001300 ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1301 break;
1302
Douglas Gregorf9201e02009-02-11 23:02:49 +00001303 case ICK_Compatible_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001304 ImpCastExprToType(From, ToType, CastExpr::CK_NoOp);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001305 break;
1306
Anders Carlsson61faec12009-09-12 04:46:44 +00001307 case ICK_Pointer_Conversion: {
Douglas Gregor45920e82008-12-19 17:40:08 +00001308 if (SCS.IncompatibleObjC) {
1309 // Diagnose incompatible Objective-C conversions
Mike Stump1eb44332009-09-09 15:08:12 +00001310 Diag(From->getSourceRange().getBegin(),
Douglas Gregor45920e82008-12-19 17:40:08 +00001311 diag::ext_typecheck_convert_incompatible_pointer)
Douglas Gregor68647482009-12-16 03:45:30 +00001312 << From->getType() << ToType << Action
Douglas Gregor45920e82008-12-19 17:40:08 +00001313 << From->getSourceRange();
1314 }
1315
Anders Carlsson61faec12009-09-12 04:46:44 +00001316
1317 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001318 if (CheckPointerConversion(From, ToType, Kind, IgnoreBaseAccess))
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001319 return true;
Anders Carlsson61faec12009-09-12 04:46:44 +00001320 ImpCastExprToType(From, ToType, Kind);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001321 break;
Anders Carlsson61faec12009-09-12 04:46:44 +00001322 }
1323
1324 case ICK_Pointer_Member: {
1325 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001326 if (CheckMemberPointerConversion(From, ToType, Kind, IgnoreBaseAccess))
Anders Carlsson61faec12009-09-12 04:46:44 +00001327 return true;
Sebastian Redl2c7588f2009-10-10 12:04:10 +00001328 if (CheckExceptionSpecCompatibility(From, ToType))
1329 return true;
Anders Carlsson61faec12009-09-12 04:46:44 +00001330 ImpCastExprToType(From, ToType, Kind);
1331 break;
1332 }
Anders Carlssonbc0e0782009-11-23 20:04:44 +00001333 case ICK_Boolean_Conversion: {
1334 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
1335 if (FromType->isMemberPointerType())
1336 Kind = CastExpr::CK_MemberPointerToBoolean;
1337
1338 ImpCastExprToType(From, Context.BoolTy, Kind);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001339 break;
Anders Carlssonbc0e0782009-11-23 20:04:44 +00001340 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001341
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001342 case ICK_Derived_To_Base:
1343 if (CheckDerivedToBaseConversion(From->getType(),
1344 ToType.getNonReferenceType(),
1345 From->getLocStart(),
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001346 From->getSourceRange(),
1347 IgnoreBaseAccess))
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001348 return true;
1349 ImpCastExprToType(From, ToType.getNonReferenceType(),
1350 CastExpr::CK_DerivedToBase);
1351 break;
1352
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001353 default:
1354 assert(false && "Improper second standard conversion");
1355 break;
1356 }
1357
1358 switch (SCS.Third) {
1359 case ICK_Identity:
1360 // Nothing to do.
1361 break;
1362
1363 case ICK_Qualification:
Mike Stump390b4cc2009-05-16 07:39:55 +00001364 // FIXME: Not sure about lvalue vs rvalue here in the presence of rvalue
1365 // references.
Mike Stump1eb44332009-09-09 15:08:12 +00001366 ImpCastExprToType(From, ToType.getNonReferenceType(),
Eli Friedman73c39ab2009-10-20 08:27:19 +00001367 CastExpr::CK_NoOp,
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001368 ToType->isLValueReferenceType());
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001369 break;
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001370
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001371 default:
1372 assert(false && "Improper second standard conversion");
1373 break;
1374 }
1375
1376 return false;
1377}
1378
Sebastian Redl64b45f72009-01-05 20:52:13 +00001379Sema::OwningExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
1380 SourceLocation KWLoc,
1381 SourceLocation LParen,
1382 TypeTy *Ty,
1383 SourceLocation RParen) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00001384 QualType T = GetTypeFromParser(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00001385
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001386 // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
1387 // all traits except __is_class, __is_enum and __is_union require a the type
1388 // to be complete.
1389 if (OTT != UTT_IsClass && OTT != UTT_IsEnum && OTT != UTT_IsUnion) {
Mike Stump1eb44332009-09-09 15:08:12 +00001390 if (RequireCompleteType(KWLoc, T,
Anders Carlssond497ba72009-08-26 22:59:12 +00001391 diag::err_incomplete_type_used_in_type_trait_expr))
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001392 return ExprError();
1393 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00001394
1395 // There is no point in eagerly computing the value. The traits are designed
1396 // to be used from type trait templates, so Ty will be a template parameter
1397 // 99% of the time.
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001398 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT, T,
1399 RParen, Context.BoolTy));
Sebastian Redl64b45f72009-01-05 20:52:13 +00001400}
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001401
1402QualType Sema::CheckPointerToMemberOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00001403 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001404 const char *OpSpelling = isIndirect ? "->*" : ".*";
1405 // C++ 5.5p2
1406 // The binary operator .* [p3: ->*] binds its second operand, which shall
1407 // be of type "pointer to member of T" (where T is a completely-defined
1408 // class type) [...]
1409 QualType RType = rex->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001410 const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
Douglas Gregore7450f52009-03-24 19:52:54 +00001411 if (!MemPtr) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001412 Diag(Loc, diag::err_bad_memptr_rhs)
1413 << OpSpelling << RType << rex->getSourceRange();
1414 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00001415 }
Douglas Gregore7450f52009-03-24 19:52:54 +00001416
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001417 QualType Class(MemPtr->getClass(), 0);
1418
1419 // C++ 5.5p2
1420 // [...] to its first operand, which shall be of class T or of a class of
1421 // which T is an unambiguous and accessible base class. [p3: a pointer to
1422 // such a class]
1423 QualType LType = lex->getType();
1424 if (isIndirect) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001425 if (const PointerType *Ptr = LType->getAs<PointerType>())
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001426 LType = Ptr->getPointeeType().getNonReferenceType();
1427 else {
1428 Diag(Loc, diag::err_bad_memptr_lhs)
Fariborz Jahanianef78ac62009-10-26 20:45:27 +00001429 << OpSpelling << 1 << LType
1430 << CodeModificationHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001431 return QualType();
1432 }
1433 }
1434
Douglas Gregora4923eb2009-11-16 21:35:15 +00001435 if (!Context.hasSameUnqualifiedType(Class, LType)) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001436 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1437 /*DetectVirtual=*/false);
Mike Stump390b4cc2009-05-16 07:39:55 +00001438 // FIXME: Would it be useful to print full ambiguity paths, or is that
1439 // overkill?
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001440 if (!IsDerivedFrom(LType, Class, Paths) ||
1441 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
1442 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Eli Friedman3005efe2010-01-16 00:00:48 +00001443 << (int)isIndirect << lex->getType();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001444 return QualType();
1445 }
Eli Friedman3005efe2010-01-16 00:00:48 +00001446 // Cast LHS to type of use.
1447 QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
1448 bool isLValue = !isIndirect && lex->isLvalue(Context) == Expr::LV_Valid;
1449 ImpCastExprToType(lex, UseType, CastExpr::CK_DerivedToBase, isLValue);
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001450 }
1451
Fariborz Jahanian19d70732009-11-18 22:16:17 +00001452 if (isa<CXXZeroInitValueExpr>(rex->IgnoreParens())) {
Fariborz Jahanian05ebda92009-11-18 21:54:48 +00001453 // Diagnose use of pointer-to-member type which when used as
1454 // the functional cast in a pointer-to-member expression.
1455 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
1456 return QualType();
1457 }
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001458 // C++ 5.5p2
1459 // The result is an object or a function of the type specified by the
1460 // second operand.
1461 // The cv qualifiers are the union of those in the pointer and the left side,
1462 // in accordance with 5.5p5 and 5.2.5.
1463 // FIXME: This returns a dereferenced member function pointer as a normal
1464 // function type. However, the only operation valid on such functions is
Mike Stump390b4cc2009-05-16 07:39:55 +00001465 // calling them. There's also a GCC extension to get a function pointer to the
1466 // thing, which is another complication, because this type - unlike the type
1467 // that is the result of this expression - takes the class as the first
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001468 // argument.
1469 // We probably need a "MemberFunctionClosureType" or something like that.
1470 QualType Result = MemPtr->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00001471 Result = Context.getCVRQualifiedType(Result, LType.getCVRQualifiers());
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001472 return Result;
1473}
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001474
1475/// \brief Get the target type of a standard or user-defined conversion.
1476static QualType TargetType(const ImplicitConversionSequence &ICS) {
John McCall1d318332010-01-12 00:44:57 +00001477 switch (ICS.getKind()) {
1478 case ImplicitConversionSequence::StandardConversion:
Douglas Gregorad323a82010-01-27 03:51:04 +00001479 return ICS.Standard.getToType(2);
John McCall1d318332010-01-12 00:44:57 +00001480 case ImplicitConversionSequence::UserDefinedConversion:
Douglas Gregorad323a82010-01-27 03:51:04 +00001481 return ICS.UserDefined.After.getToType(2);
John McCall1d318332010-01-12 00:44:57 +00001482 case ImplicitConversionSequence::AmbiguousConversion:
1483 return ICS.Ambiguous.getToType();
1484 case ImplicitConversionSequence::EllipsisConversion:
1485 case ImplicitConversionSequence::BadConversion:
1486 llvm_unreachable("function not valid for ellipsis or bad conversions");
1487 }
1488 return QualType(); // silence warnings
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001489}
1490
1491/// \brief Try to convert a type to another according to C++0x 5.16p3.
1492///
1493/// This is part of the parameter validation for the ? operator. If either
1494/// value operand is a class type, the two operands are attempted to be
1495/// converted to each other. This function does the conversion in one direction.
1496/// It emits a diagnostic and returns true only if it finds an ambiguous
1497/// conversion.
1498static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
1499 SourceLocation QuestionLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00001500 ImplicitConversionSequence &ICS) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001501 // C++0x 5.16p3
1502 // The process for determining whether an operand expression E1 of type T1
1503 // can be converted to match an operand expression E2 of type T2 is defined
1504 // as follows:
1505 // -- If E2 is an lvalue:
1506 if (To->isLvalue(Self.Context) == Expr::LV_Valid) {
1507 // E1 can be converted to match E2 if E1 can be implicitly converted to
1508 // type "lvalue reference to T2", subject to the constraint that in the
1509 // conversion the reference must bind directly to E1.
1510 if (!Self.CheckReferenceInit(From,
1511 Self.Context.getLValueReferenceType(To->getType()),
Douglas Gregor739d8282009-09-23 23:04:10 +00001512 To->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001513 /*SuppressUserConversions=*/false,
1514 /*AllowExplicit=*/false,
1515 /*ForceRValue=*/false,
1516 &ICS))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001517 {
John McCall1d318332010-01-12 00:44:57 +00001518 assert((ICS.isStandard() || ICS.isUserDefined()) &&
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001519 "expected a definite conversion");
1520 bool DirectBinding =
John McCall1d318332010-01-12 00:44:57 +00001521 ICS.isStandard() ? ICS.Standard.DirectBinding
1522 : ICS.UserDefined.After.DirectBinding;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001523 if (DirectBinding)
1524 return false;
1525 }
1526 }
John McCall1d318332010-01-12 00:44:57 +00001527 ICS.setBad();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001528 // -- If E2 is an rvalue, or if the conversion above cannot be done:
1529 // -- if E1 and E2 have class type, and the underlying class types are
1530 // the same or one is a base class of the other:
1531 QualType FTy = From->getType();
1532 QualType TTy = To->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001533 const RecordType *FRec = FTy->getAs<RecordType>();
1534 const RecordType *TRec = TTy->getAs<RecordType>();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001535 bool FDerivedFromT = FRec && TRec && Self.IsDerivedFrom(FTy, TTy);
1536 if (FRec && TRec && (FRec == TRec ||
1537 FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
1538 // E1 can be converted to match E2 if the class of T2 is the
1539 // same type as, or a base class of, the class of T1, and
1540 // [cv2 > cv1].
1541 if ((FRec == TRec || FDerivedFromT) && TTy.isAtLeastAsQualifiedAs(FTy)) {
1542 // Could still fail if there's no copy constructor.
1543 // FIXME: Is this a hard error then, or just a conversion failure? The
1544 // standard doesn't say.
Mike Stump1eb44332009-09-09 15:08:12 +00001545 ICS = Self.TryCopyInitialization(From, TTy,
Anders Carlssond28b4282009-08-27 17:18:13 +00001546 /*SuppressUserConversions=*/false,
Anders Carlsson7b361b52009-08-27 17:37:39 +00001547 /*ForceRValue=*/false,
1548 /*InOverloadResolution=*/false);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001549 }
1550 } else {
1551 // -- Otherwise: E1 can be converted to match E2 if E1 can be
1552 // implicitly converted to the type that expression E2 would have
1553 // if E2 were converted to an rvalue.
1554 // First find the decayed type.
1555 if (TTy->isFunctionType())
1556 TTy = Self.Context.getPointerType(TTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001557 else if (TTy->isArrayType())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001558 TTy = Self.Context.getArrayDecayedType(TTy);
1559
1560 // Now try the implicit conversion.
1561 // FIXME: This doesn't detect ambiguities.
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001562 ICS = Self.TryImplicitConversion(From, TTy,
1563 /*SuppressUserConversions=*/false,
1564 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00001565 /*ForceRValue=*/false,
1566 /*InOverloadResolution=*/false);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001567 }
1568 return false;
1569}
1570
1571/// \brief Try to find a common type for two according to C++0x 5.16p5.
1572///
1573/// This is part of the parameter validation for the ? operator. If either
1574/// value operand is a class type, overload resolution is used to find a
1575/// conversion to a common type.
1576static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
1577 SourceLocation Loc) {
1578 Expr *Args[2] = { LHS, RHS };
1579 OverloadCandidateSet CandidateSet;
Douglas Gregor573d9c32009-10-21 23:19:44 +00001580 Self.AddBuiltinOperatorCandidates(OO_Conditional, Loc, Args, 2, CandidateSet);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001581
1582 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00001583 switch (Self.BestViableFunction(CandidateSet, Loc, Best)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00001584 case OR_Success:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001585 // We found a match. Perform the conversions on the arguments and move on.
1586 if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00001587 Best->Conversions[0], Sema::AA_Converting) ||
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001588 Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor68647482009-12-16 03:45:30 +00001589 Best->Conversions[1], Sema::AA_Converting))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001590 break;
1591 return false;
1592
Douglas Gregor20093b42009-12-09 23:02:17 +00001593 case OR_No_Viable_Function:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001594 Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
1595 << LHS->getType() << RHS->getType()
1596 << LHS->getSourceRange() << RHS->getSourceRange();
1597 return true;
1598
Douglas Gregor20093b42009-12-09 23:02:17 +00001599 case OR_Ambiguous:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001600 Self.Diag(Loc, diag::err_conditional_ambiguous_ovl)
1601 << LHS->getType() << RHS->getType()
1602 << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stump390b4cc2009-05-16 07:39:55 +00001603 // FIXME: Print the possible common types by printing the return types of
1604 // the viable candidates.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001605 break;
1606
Douglas Gregor20093b42009-12-09 23:02:17 +00001607 case OR_Deleted:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001608 assert(false && "Conditional operator has only built-in overloads");
1609 break;
1610 }
1611 return true;
1612}
1613
Sebastian Redl76458502009-04-17 16:30:52 +00001614/// \brief Perform an "extended" implicit conversion as returned by
1615/// TryClassUnification.
1616///
1617/// TryClassUnification generates ICSs that include reference bindings.
1618/// PerformImplicitConversion is not suitable for this; it chokes if the
1619/// second part of a standard conversion is ICK_DerivedToBase. This function
1620/// handles the reference binding specially.
1621static bool ConvertForConditional(Sema &Self, Expr *&E,
Mike Stump1eb44332009-09-09 15:08:12 +00001622 const ImplicitConversionSequence &ICS) {
John McCall1d318332010-01-12 00:44:57 +00001623 if (ICS.isStandard() && ICS.Standard.ReferenceBinding) {
Sebastian Redl76458502009-04-17 16:30:52 +00001624 assert(ICS.Standard.DirectBinding &&
1625 "TryClassUnification should never generate indirect ref bindings");
Sebastian Redla5cd2cd2009-04-26 11:21:02 +00001626 // FIXME: CheckReferenceInit should be able to reuse the ICS instead of
1627 // redoing all the work.
1628 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001629 TargetType(ICS)),
Douglas Gregor739d8282009-09-23 23:04:10 +00001630 /*FIXME:*/E->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001631 /*SuppressUserConversions=*/false,
1632 /*AllowExplicit=*/false,
1633 /*ForceRValue=*/false);
Sebastian Redl76458502009-04-17 16:30:52 +00001634 }
John McCall1d318332010-01-12 00:44:57 +00001635 if (ICS.isUserDefined() && ICS.UserDefined.After.ReferenceBinding) {
Sebastian Redl76458502009-04-17 16:30:52 +00001636 assert(ICS.UserDefined.After.DirectBinding &&
1637 "TryClassUnification should never generate indirect ref bindings");
Sebastian Redla5cd2cd2009-04-26 11:21:02 +00001638 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001639 TargetType(ICS)),
Douglas Gregor739d8282009-09-23 23:04:10 +00001640 /*FIXME:*/E->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001641 /*SuppressUserConversions=*/false,
1642 /*AllowExplicit=*/false,
1643 /*ForceRValue=*/false);
Sebastian Redl76458502009-04-17 16:30:52 +00001644 }
Douglas Gregor68647482009-12-16 03:45:30 +00001645 if (Self.PerformImplicitConversion(E, TargetType(ICS), ICS, Sema::AA_Converting))
Sebastian Redl76458502009-04-17 16:30:52 +00001646 return true;
1647 return false;
1648}
1649
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001650/// \brief Check the operands of ?: under C++ semantics.
1651///
1652/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
1653/// extension. In this case, LHS == Cond. (But they're not aliases.)
1654QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
1655 SourceLocation QuestionLoc) {
Mike Stump390b4cc2009-05-16 07:39:55 +00001656 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
1657 // interface pointers.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001658
1659 // C++0x 5.16p1
1660 // The first expression is contextually converted to bool.
1661 if (!Cond->isTypeDependent()) {
1662 if (CheckCXXBooleanCondition(Cond))
1663 return QualType();
1664 }
1665
1666 // Either of the arguments dependent?
1667 if (LHS->isTypeDependent() || RHS->isTypeDependent())
1668 return Context.DependentTy;
1669
John McCallb13c87f2009-11-05 09:23:39 +00001670 CheckSignCompare(LHS, RHS, QuestionLoc, diag::warn_mixed_sign_conditional);
1671
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001672 // C++0x 5.16p2
1673 // If either the second or the third operand has type (cv) void, ...
1674 QualType LTy = LHS->getType();
1675 QualType RTy = RHS->getType();
1676 bool LVoid = LTy->isVoidType();
1677 bool RVoid = RTy->isVoidType();
1678 if (LVoid || RVoid) {
1679 // ... then the [l2r] conversions are performed on the second and third
1680 // operands ...
1681 DefaultFunctionArrayConversion(LHS);
1682 DefaultFunctionArrayConversion(RHS);
1683 LTy = LHS->getType();
1684 RTy = RHS->getType();
1685
1686 // ... and one of the following shall hold:
1687 // -- The second or the third operand (but not both) is a throw-
1688 // expression; the result is of the type of the other and is an rvalue.
1689 bool LThrow = isa<CXXThrowExpr>(LHS);
1690 bool RThrow = isa<CXXThrowExpr>(RHS);
1691 if (LThrow && !RThrow)
1692 return RTy;
1693 if (RThrow && !LThrow)
1694 return LTy;
1695
1696 // -- Both the second and third operands have type void; the result is of
1697 // type void and is an rvalue.
1698 if (LVoid && RVoid)
1699 return Context.VoidTy;
1700
1701 // Neither holds, error.
1702 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
1703 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
1704 << LHS->getSourceRange() << RHS->getSourceRange();
1705 return QualType();
1706 }
1707
1708 // Neither is void.
1709
1710 // C++0x 5.16p3
1711 // Otherwise, if the second and third operand have different types, and
1712 // either has (cv) class type, and attempt is made to convert each of those
1713 // operands to the other.
1714 if (Context.getCanonicalType(LTy) != Context.getCanonicalType(RTy) &&
1715 (LTy->isRecordType() || RTy->isRecordType())) {
1716 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
1717 // These return true if a single direction is already ambiguous.
1718 if (TryClassUnification(*this, LHS, RHS, QuestionLoc, ICSLeftToRight))
1719 return QualType();
1720 if (TryClassUnification(*this, RHS, LHS, QuestionLoc, ICSRightToLeft))
1721 return QualType();
1722
John McCall1d318332010-01-12 00:44:57 +00001723 bool HaveL2R = !ICSLeftToRight.isBad();
1724 bool HaveR2L = !ICSRightToLeft.isBad();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001725 // If both can be converted, [...] the program is ill-formed.
1726 if (HaveL2R && HaveR2L) {
1727 Diag(QuestionLoc, diag::err_conditional_ambiguous)
1728 << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
1729 return QualType();
1730 }
1731
1732 // If exactly one conversion is possible, that conversion is applied to
1733 // the chosen operand and the converted operands are used in place of the
1734 // original operands for the remainder of this section.
1735 if (HaveL2R) {
Sebastian Redl76458502009-04-17 16:30:52 +00001736 if (ConvertForConditional(*this, LHS, ICSLeftToRight))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001737 return QualType();
1738 LTy = LHS->getType();
1739 } else if (HaveR2L) {
Sebastian Redl76458502009-04-17 16:30:52 +00001740 if (ConvertForConditional(*this, RHS, ICSRightToLeft))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001741 return QualType();
1742 RTy = RHS->getType();
1743 }
1744 }
1745
1746 // C++0x 5.16p4
1747 // If the second and third operands are lvalues and have the same type,
1748 // the result is of that type [...]
1749 bool Same = Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy);
1750 if (Same && LHS->isLvalue(Context) == Expr::LV_Valid &&
1751 RHS->isLvalue(Context) == Expr::LV_Valid)
1752 return LTy;
1753
1754 // C++0x 5.16p5
1755 // Otherwise, the result is an rvalue. If the second and third operands
1756 // do not have the same type, and either has (cv) class type, ...
1757 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
1758 // ... overload resolution is used to determine the conversions (if any)
1759 // to be applied to the operands. If the overload resolution fails, the
1760 // program is ill-formed.
1761 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
1762 return QualType();
1763 }
1764
1765 // C++0x 5.16p6
1766 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
1767 // conversions are performed on the second and third operands.
1768 DefaultFunctionArrayConversion(LHS);
1769 DefaultFunctionArrayConversion(RHS);
1770 LTy = LHS->getType();
1771 RTy = RHS->getType();
1772
1773 // After those conversions, one of the following shall hold:
1774 // -- The second and third operands have the same type; the result
1775 // is of that type.
1776 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy))
1777 return LTy;
1778
1779 // -- The second and third operands have arithmetic or enumeration type;
1780 // the usual arithmetic conversions are performed to bring them to a
1781 // common type, and the result is of that type.
1782 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
1783 UsualArithmeticConversions(LHS, RHS);
1784 return LHS->getType();
1785 }
1786
1787 // -- The second and third operands have pointer type, or one has pointer
1788 // type and the other is a null pointer constant; pointer conversions
1789 // and qualification conversions are performed to bring them to their
1790 // composite pointer type. The result is of the composite pointer type.
Eli Friedmande8ac492010-01-02 22:56:07 +00001791 // -- The second and third operands have pointer to member type, or one has
1792 // pointer to member type and the other is a null pointer constant;
1793 // pointer to member conversions and qualification conversions are
1794 // performed to bring them to a common type, whose cv-qualification
1795 // shall match the cv-qualification of either the second or the third
1796 // operand. The result is of the common type.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001797 QualType Composite = FindCompositePointerType(LHS, RHS);
1798 if (!Composite.isNull())
1799 return Composite;
Fariborz Jahanian55016362009-12-10 20:46:08 +00001800
1801 // Similarly, attempt to find composite type of twp objective-c pointers.
1802 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
1803 if (!Composite.isNull())
1804 return Composite;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001805
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001806 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
1807 << LHS->getType() << RHS->getType()
1808 << LHS->getSourceRange() << RHS->getSourceRange();
1809 return QualType();
1810}
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001811
1812/// \brief Find a merged pointer type and convert the two expressions to it.
1813///
Douglas Gregor20b3e992009-08-24 17:42:35 +00001814/// This finds the composite pointer type (or member pointer type) for @p E1
1815/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
1816/// type and returns it.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001817/// It does not emit diagnostics.
1818QualType Sema::FindCompositePointerType(Expr *&E1, Expr *&E2) {
1819 assert(getLangOptions().CPlusPlus && "This function assumes C++");
1820 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001821
Fariborz Jahanian0cedfbd2009-12-08 20:04:24 +00001822 if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
1823 !T2->isAnyPointerType() && !T2->isMemberPointerType())
Douglas Gregor20b3e992009-08-24 17:42:35 +00001824 return QualType();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001825
1826 // C++0x 5.9p2
1827 // Pointer conversions and qualification conversions are performed on
1828 // pointer operands to bring them to their composite pointer type. If
1829 // one operand is a null pointer constant, the composite pointer type is
1830 // the type of the other operand.
Douglas Gregorce940492009-09-25 04:25:58 +00001831 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00001832 if (T2->isMemberPointerType())
1833 ImpCastExprToType(E1, T2, CastExpr::CK_NullToMemberPointer);
1834 else
1835 ImpCastExprToType(E1, T2, CastExpr::CK_IntegralToPointer);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001836 return T2;
1837 }
Douglas Gregorce940492009-09-25 04:25:58 +00001838 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00001839 if (T1->isMemberPointerType())
1840 ImpCastExprToType(E2, T1, CastExpr::CK_NullToMemberPointer);
1841 else
1842 ImpCastExprToType(E2, T1, CastExpr::CK_IntegralToPointer);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001843 return T1;
1844 }
Mike Stump1eb44332009-09-09 15:08:12 +00001845
Douglas Gregor20b3e992009-08-24 17:42:35 +00001846 // Now both have to be pointers or member pointers.
Sebastian Redla439e6f2009-11-16 21:03:45 +00001847 if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
1848 (!T2->isPointerType() && !T2->isMemberPointerType()))
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001849 return QualType();
1850
1851 // Otherwise, of one of the operands has type "pointer to cv1 void," then
1852 // the other has type "pointer to cv2 T" and the composite pointer type is
1853 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
1854 // Otherwise, the composite pointer type is a pointer type similar to the
1855 // type of one of the operands, with a cv-qualification signature that is
1856 // the union of the cv-qualification signatures of the operand types.
1857 // In practice, the first part here is redundant; it's subsumed by the second.
1858 // What we do here is, we build the two possible composite types, and try the
1859 // conversions in both directions. If only one works, or if the two composite
1860 // types are the same, we have succeeded.
John McCall0953e762009-09-24 19:53:00 +00001861 // FIXME: extended qualifiers?
Sebastian Redla439e6f2009-11-16 21:03:45 +00001862 typedef llvm::SmallVector<unsigned, 4> QualifierVector;
1863 QualifierVector QualifierUnion;
1864 typedef llvm::SmallVector<std::pair<const Type *, const Type *>, 4>
1865 ContainingClassVector;
1866 ContainingClassVector MemberOfClass;
1867 QualType Composite1 = Context.getCanonicalType(T1),
1868 Composite2 = Context.getCanonicalType(T2);
Douglas Gregor20b3e992009-08-24 17:42:35 +00001869 do {
1870 const PointerType *Ptr1, *Ptr2;
1871 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
1872 (Ptr2 = Composite2->getAs<PointerType>())) {
1873 Composite1 = Ptr1->getPointeeType();
1874 Composite2 = Ptr2->getPointeeType();
1875 QualifierUnion.push_back(
1876 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
1877 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
1878 continue;
1879 }
Mike Stump1eb44332009-09-09 15:08:12 +00001880
Douglas Gregor20b3e992009-08-24 17:42:35 +00001881 const MemberPointerType *MemPtr1, *MemPtr2;
1882 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
1883 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
1884 Composite1 = MemPtr1->getPointeeType();
1885 Composite2 = MemPtr2->getPointeeType();
1886 QualifierUnion.push_back(
1887 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
1888 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
1889 MemPtr2->getClass()));
1890 continue;
1891 }
Mike Stump1eb44332009-09-09 15:08:12 +00001892
Douglas Gregor20b3e992009-08-24 17:42:35 +00001893 // FIXME: block pointer types?
Mike Stump1eb44332009-09-09 15:08:12 +00001894
Douglas Gregor20b3e992009-08-24 17:42:35 +00001895 // Cannot unwrap any more types.
1896 break;
1897 } while (true);
Mike Stump1eb44332009-09-09 15:08:12 +00001898
Douglas Gregor20b3e992009-08-24 17:42:35 +00001899 // Rewrap the composites as pointers or member pointers with the union CVRs.
Sebastian Redla439e6f2009-11-16 21:03:45 +00001900 ContainingClassVector::reverse_iterator MOC
1901 = MemberOfClass.rbegin();
1902 for (QualifierVector::reverse_iterator
1903 I = QualifierUnion.rbegin(),
1904 E = QualifierUnion.rend();
Douglas Gregor20b3e992009-08-24 17:42:35 +00001905 I != E; (void)++I, ++MOC) {
John McCall0953e762009-09-24 19:53:00 +00001906 Qualifiers Quals = Qualifiers::fromCVRMask(*I);
Douglas Gregor20b3e992009-08-24 17:42:35 +00001907 if (MOC->first && MOC->second) {
1908 // Rebuild member pointer type
John McCall0953e762009-09-24 19:53:00 +00001909 Composite1 = Context.getMemberPointerType(
1910 Context.getQualifiedType(Composite1, Quals),
1911 MOC->first);
1912 Composite2 = Context.getMemberPointerType(
1913 Context.getQualifiedType(Composite2, Quals),
1914 MOC->second);
Douglas Gregor20b3e992009-08-24 17:42:35 +00001915 } else {
1916 // Rebuild pointer type
John McCall0953e762009-09-24 19:53:00 +00001917 Composite1
1918 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
1919 Composite2
1920 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregor20b3e992009-08-24 17:42:35 +00001921 }
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001922 }
1923
Mike Stump1eb44332009-09-09 15:08:12 +00001924 ImplicitConversionSequence E1ToC1 =
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001925 TryImplicitConversion(E1, Composite1,
1926 /*SuppressUserConversions=*/false,
1927 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00001928 /*ForceRValue=*/false,
1929 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00001930 ImplicitConversionSequence E2ToC1 =
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001931 TryImplicitConversion(E2, Composite1,
1932 /*SuppressUserConversions=*/false,
1933 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00001934 /*ForceRValue=*/false,
1935 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00001936
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001937 ImplicitConversionSequence E1ToC2, E2ToC2;
John McCall1d318332010-01-12 00:44:57 +00001938 E1ToC2.setBad();
John McCalladbb8f82010-01-13 09:16:55 +00001939 E2ToC2.setBad();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001940 if (Context.getCanonicalType(Composite1) !=
1941 Context.getCanonicalType(Composite2)) {
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001942 E1ToC2 = TryImplicitConversion(E1, Composite2,
1943 /*SuppressUserConversions=*/false,
1944 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00001945 /*ForceRValue=*/false,
1946 /*InOverloadResolution=*/false);
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001947 E2ToC2 = TryImplicitConversion(E2, Composite2,
1948 /*SuppressUserConversions=*/false,
1949 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00001950 /*ForceRValue=*/false,
1951 /*InOverloadResolution=*/false);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001952 }
1953
John McCall1d318332010-01-12 00:44:57 +00001954 bool ToC1Viable = !E1ToC1.isBad() && !E2ToC1.isBad();
1955 bool ToC2Viable = !E1ToC2.isBad() && !E2ToC2.isBad();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001956 if (ToC1Viable && !ToC2Viable) {
Douglas Gregor68647482009-12-16 03:45:30 +00001957 if (!PerformImplicitConversion(E1, Composite1, E1ToC1, Sema::AA_Converting) &&
1958 !PerformImplicitConversion(E2, Composite1, E2ToC1, Sema::AA_Converting))
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001959 return Composite1;
1960 }
1961 if (ToC2Viable && !ToC1Viable) {
Douglas Gregor68647482009-12-16 03:45:30 +00001962 if (!PerformImplicitConversion(E1, Composite2, E1ToC2, Sema::AA_Converting) &&
1963 !PerformImplicitConversion(E2, Composite2, E2ToC2, Sema::AA_Converting))
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001964 return Composite2;
1965 }
1966 return QualType();
1967}
Anders Carlsson165a0a02009-05-17 18:41:29 +00001968
Anders Carlssondef11992009-05-30 20:36:53 +00001969Sema::OwningExprResult Sema::MaybeBindToTemporary(Expr *E) {
Anders Carlsson089c2602009-08-15 23:41:35 +00001970 if (!Context.getLangOptions().CPlusPlus)
1971 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001972
Douglas Gregor51326552009-12-24 18:51:59 +00001973 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
1974
Ted Kremenek6217b802009-07-29 21:53:49 +00001975 const RecordType *RT = E->getType()->getAs<RecordType>();
Anders Carlssondef11992009-05-30 20:36:53 +00001976 if (!RT)
1977 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001978
Anders Carlssondef11992009-05-30 20:36:53 +00001979 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1980 if (RD->hasTrivialDestructor())
1981 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001982
Anders Carlsson283e4d52009-09-14 01:30:44 +00001983 if (CallExpr *CE = dyn_cast<CallExpr>(E)) {
1984 QualType Ty = CE->getCallee()->getType();
1985 if (const PointerType *PT = Ty->getAs<PointerType>())
1986 Ty = PT->getPointeeType();
1987
John McCall183700f2009-09-21 23:43:11 +00001988 const FunctionType *FTy = Ty->getAs<FunctionType>();
Anders Carlsson283e4d52009-09-14 01:30:44 +00001989 if (FTy->getResultType()->isReferenceType())
1990 return Owned(E);
1991 }
Mike Stump1eb44332009-09-09 15:08:12 +00001992 CXXTemporary *Temp = CXXTemporary::Create(Context,
Anders Carlssondef11992009-05-30 20:36:53 +00001993 RD->getDestructor(Context));
Anders Carlsson860306e2009-05-30 21:21:49 +00001994 ExprTemporaries.push_back(Temp);
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00001995 if (CXXDestructorDecl *Destructor =
1996 const_cast<CXXDestructorDecl*>(RD->getDestructor(Context)))
1997 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
Anders Carlssondef11992009-05-30 20:36:53 +00001998 // FIXME: Add the temporary to the temporaries vector.
1999 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
2000}
2001
Anders Carlsson0ece4912009-12-15 20:51:39 +00002002Expr *Sema::MaybeCreateCXXExprWithTemporaries(Expr *SubExpr) {
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002003 assert(SubExpr && "sub expression can't be null!");
Mike Stump1eb44332009-09-09 15:08:12 +00002004
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00002005 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
2006 assert(ExprTemporaries.size() >= FirstTemporary);
2007 if (ExprTemporaries.size() == FirstTemporary)
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002008 return SubExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00002009
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002010 Expr *E = CXXExprWithTemporaries::Create(Context, SubExpr,
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00002011 &ExprTemporaries[FirstTemporary],
Anders Carlsson0ece4912009-12-15 20:51:39 +00002012 ExprTemporaries.size() - FirstTemporary);
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00002013 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
2014 ExprTemporaries.end());
Mike Stump1eb44332009-09-09 15:08:12 +00002015
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002016 return E;
2017}
2018
Douglas Gregor90f93822009-12-22 22:17:25 +00002019Sema::OwningExprResult
2020Sema::MaybeCreateCXXExprWithTemporaries(OwningExprResult SubExpr) {
2021 if (SubExpr.isInvalid())
2022 return ExprError();
2023
2024 return Owned(MaybeCreateCXXExprWithTemporaries(SubExpr.takeAs<Expr>()));
2025}
2026
Anders Carlsson5ee56e92009-12-16 02:09:40 +00002027FullExpr Sema::CreateFullExpr(Expr *SubExpr) {
2028 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
2029 assert(ExprTemporaries.size() >= FirstTemporary);
2030
2031 unsigned NumTemporaries = ExprTemporaries.size() - FirstTemporary;
2032 CXXTemporary **Temporaries =
2033 NumTemporaries == 0 ? 0 : &ExprTemporaries[FirstTemporary];
2034
2035 FullExpr E = FullExpr::Create(Context, SubExpr, Temporaries, NumTemporaries);
2036
2037 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
2038 ExprTemporaries.end());
2039
2040 return E;
2041}
2042
Mike Stump1eb44332009-09-09 15:08:12 +00002043Sema::OwningExprResult
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002044Sema::ActOnStartCXXMemberReference(Scope *S, ExprArg Base, SourceLocation OpLoc,
2045 tok::TokenKind OpKind, TypeTy *&ObjectType) {
2046 // Since this might be a postfix expression, get rid of ParenListExprs.
2047 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
Mike Stump1eb44332009-09-09 15:08:12 +00002048
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002049 Expr *BaseExpr = (Expr*)Base.get();
2050 assert(BaseExpr && "no record expansion");
Mike Stump1eb44332009-09-09 15:08:12 +00002051
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002052 QualType BaseType = BaseExpr->getType();
2053 if (BaseType->isDependentType()) {
Douglas Gregor43d88632009-11-04 22:49:18 +00002054 // If we have a pointer to a dependent type and are using the -> operator,
2055 // the object type is the type that the pointer points to. We might still
2056 // have enough information about that type to do something useful.
2057 if (OpKind == tok::arrow)
2058 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
2059 BaseType = Ptr->getPointeeType();
2060
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002061 ObjectType = BaseType.getAsOpaquePtr();
2062 return move(Base);
2063 }
Mike Stump1eb44332009-09-09 15:08:12 +00002064
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002065 // C++ [over.match.oper]p8:
Mike Stump1eb44332009-09-09 15:08:12 +00002066 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002067 // returned, with the original second operand.
2068 if (OpKind == tok::arrow) {
John McCallc4e83212009-09-30 01:01:30 +00002069 // The set of types we've considered so far.
John McCall432887f2009-09-30 01:30:54 +00002070 llvm::SmallPtrSet<CanQualType,8> CTypes;
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002071 llvm::SmallVector<SourceLocation, 8> Locations;
John McCall432887f2009-09-30 01:30:54 +00002072 CTypes.insert(Context.getCanonicalType(BaseType));
John McCallc4e83212009-09-30 01:01:30 +00002073
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002074 while (BaseType->isRecordType()) {
Anders Carlsson15ea3782009-10-13 22:43:21 +00002075 Base = BuildOverloadedArrowExpr(S, move(Base), OpLoc);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002076 BaseExpr = (Expr*)Base.get();
2077 if (BaseExpr == NULL)
2078 return ExprError();
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002079 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(BaseExpr))
Anders Carlssonde699e52009-10-13 22:55:59 +00002080 Locations.push_back(OpCall->getDirectCallee()->getLocation());
John McCallc4e83212009-09-30 01:01:30 +00002081 BaseType = BaseExpr->getType();
2082 CanQualType CBaseType = Context.getCanonicalType(BaseType);
John McCall432887f2009-09-30 01:30:54 +00002083 if (!CTypes.insert(CBaseType)) {
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00002084 Diag(OpLoc, diag::err_operator_arrow_circular);
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002085 for (unsigned i = 0; i < Locations.size(); i++)
2086 Diag(Locations[i], diag::note_declared_at);
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00002087 return ExprError();
2088 }
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002089 }
Mike Stump1eb44332009-09-09 15:08:12 +00002090
Douglas Gregor31658df2009-11-20 19:58:21 +00002091 if (BaseType->isPointerType())
2092 BaseType = BaseType->getPointeeType();
2093 }
Mike Stump1eb44332009-09-09 15:08:12 +00002094
2095 // We could end up with various non-record types here, such as extended
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002096 // vector types or Objective-C interfaces. Just return early and let
2097 // ActOnMemberReferenceExpr do the work.
Douglas Gregorc68afe22009-09-03 21:38:09 +00002098 if (!BaseType->isRecordType()) {
2099 // C++ [basic.lookup.classref]p2:
2100 // [...] If the type of the object expression is of pointer to scalar
2101 // type, the unqualified-id is looked up in the context of the complete
2102 // postfix-expression.
2103 ObjectType = 0;
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002104 return move(Base);
Douglas Gregorc68afe22009-09-03 21:38:09 +00002105 }
Mike Stump1eb44332009-09-09 15:08:12 +00002106
Douglas Gregor03c57052009-11-17 05:17:33 +00002107 // The object type must be complete (or dependent).
2108 if (!BaseType->isDependentType() &&
2109 RequireCompleteType(OpLoc, BaseType,
2110 PDiag(diag::err_incomplete_member_access)))
2111 return ExprError();
2112
Douglas Gregorc68afe22009-09-03 21:38:09 +00002113 // C++ [basic.lookup.classref]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00002114 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor03c57052009-11-17 05:17:33 +00002115 // unqualified-id, and the type of the object expression is of a class
Douglas Gregorc68afe22009-09-03 21:38:09 +00002116 // type C (or of pointer to a class type C), the unqualified-id is looked
2117 // up in the scope of class C. [...]
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002118 ObjectType = BaseType.getAsOpaquePtr();
Douglas Gregor03c57052009-11-17 05:17:33 +00002119
Mike Stump1eb44332009-09-09 15:08:12 +00002120 return move(Base);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002121}
2122
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002123CXXMemberCallExpr *Sema::BuildCXXMemberCallExpr(Expr *Exp,
2124 CXXMethodDecl *Method) {
Eli Friedman772fffa2009-12-09 04:53:56 +00002125 if (PerformObjectArgumentInitialization(Exp, Method))
2126 assert(0 && "Calling BuildCXXMemberCallExpr with invalid call?");
2127
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002128 MemberExpr *ME =
2129 new (Context) MemberExpr(Exp, /*IsArrow=*/false, Method,
2130 SourceLocation(), Method->getType());
Eli Friedman772fffa2009-12-09 04:53:56 +00002131 QualType ResultType = Method->getResultType().getNonReferenceType();
Douglas Gregor7edfb692009-11-23 12:27:39 +00002132 MarkDeclarationReferenced(Exp->getLocStart(), Method);
2133 CXXMemberCallExpr *CE =
2134 new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType,
2135 Exp->getLocEnd());
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002136 return CE;
2137}
2138
Anders Carlsson0aebc812009-09-09 21:33:21 +00002139Sema::OwningExprResult Sema::BuildCXXCastArgument(SourceLocation CastLoc,
2140 QualType Ty,
2141 CastExpr::CastKind Kind,
2142 CXXMethodDecl *Method,
2143 ExprArg Arg) {
2144 Expr *From = Arg.takeAs<Expr>();
2145
2146 switch (Kind) {
2147 default: assert(0 && "Unhandled cast kind!");
2148 case CastExpr::CK_ConstructorConversion: {
Douglas Gregor39da0b82009-09-09 23:08:42 +00002149 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
2150
2151 if (CompleteConstructorCall(cast<CXXConstructorDecl>(Method),
2152 MultiExprArg(*this, (void **)&From, 1),
2153 CastLoc, ConstructorArgs))
2154 return ExprError();
Anders Carlsson4fa26842009-10-18 21:20:14 +00002155
2156 OwningExprResult Result =
2157 BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
2158 move_arg(ConstructorArgs));
2159 if (Result.isInvalid())
2160 return ExprError();
2161
2162 return MaybeBindToTemporary(Result.takeAs<Expr>());
Anders Carlsson0aebc812009-09-09 21:33:21 +00002163 }
2164
2165 case CastExpr::CK_UserDefinedConversion: {
Anders Carlssonaac6e3a2009-09-15 07:42:44 +00002166 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
Eli Friedman772fffa2009-12-09 04:53:56 +00002167
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002168 // Create an implicit call expr that calls it.
2169 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(From, Method);
Anders Carlsson4fa26842009-10-18 21:20:14 +00002170 return MaybeBindToTemporary(CE);
Anders Carlsson0aebc812009-09-09 21:33:21 +00002171 }
Anders Carlsson0aebc812009-09-09 21:33:21 +00002172 }
2173}
2174
Anders Carlsson165a0a02009-05-17 18:41:29 +00002175Sema::OwningExprResult Sema::ActOnFinishFullExpr(ExprArg Arg) {
2176 Expr *FullExpr = Arg.takeAs<Expr>();
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002177 if (FullExpr)
Anders Carlsson0ece4912009-12-15 20:51:39 +00002178 FullExpr = MaybeCreateCXXExprWithTemporaries(FullExpr);
Anders Carlssonec773872009-08-25 23:46:41 +00002179
Anders Carlsson165a0a02009-05-17 18:41:29 +00002180 return Owned(FullExpr);
2181}