blob: 9eeda54299ae98635db7d27362b3a513bb4bbc8c [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:
John McCall86ff3082010-02-04 22:26:26 +000075 // [...] If the type of the expression is a class type, the class
76 // shall be completely-defined.
77 if (RequireCompleteType(OpLoc, T, diag::err_incomplete_typeid))
78 return ExprError();
79
80 // C++ [expr.typeid]p3:
Douglas Gregorf57f2072009-12-23 20:51:04 +000081 // When typeid is applied to an expression other than an lvalue of a
82 // polymorphic class type [...] [the] expression is an unevaluated
83 // operand. [...]
84 if (RecordD->isPolymorphic() && E->isLvalue(Context) == Expr::LV_Valid)
Douglas Gregorac7610d2009-06-22 20:57:11 +000085 isUnevaluatedOperand = false;
Douglas Gregorf57f2072009-12-23 20:51:04 +000086 }
87
88 // C++ [expr.typeid]p4:
89 // [...] If the type of the type-id is a reference to a possibly
90 // cv-qualified type, the result of the typeid expression refers to a
91 // std::type_info object representing the cv-unqualified referenced
92 // type.
93 if (T.hasQualifiers()) {
94 ImpCastExprToType(E, T.getUnqualifiedType(), CastExpr::CK_NoOp,
95 E->isLvalue(Context));
96 TyOrExpr = E;
Douglas Gregorac7610d2009-06-22 20:57:11 +000097 }
98 }
Mike Stump1eb44332009-09-09 15:08:12 +000099
Douglas Gregor2afce722009-11-26 00:44:06 +0000100 // If this is an unevaluated operand, clear out the set of
101 // declaration references we have been computing and eliminate any
102 // temporaries introduced in its computation.
Douglas Gregorac7610d2009-06-22 20:57:11 +0000103 if (isUnevaluatedOperand)
Douglas Gregor2afce722009-11-26 00:44:06 +0000104 ExprEvalContexts.back().Context = Unevaluated;
Douglas Gregorac7610d2009-06-22 20:57:11 +0000105 }
Mike Stump1eb44332009-09-09 15:08:12 +0000106
Sebastian Redlf53597f2009-03-15 17:47:39 +0000107 return Owned(new (Context) CXXTypeidExpr(isType, TyOrExpr,
108 TypeInfoType.withConst(),
109 SourceRange(OpLoc, RParenLoc)));
Sebastian Redlc42e1182008-11-11 11:37:55 +0000110}
111
Steve Naroff1b273c42007-09-16 14:56:35 +0000112/// ActOnCXXBoolLiteral - Parse {true,false} literals.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000113Action::OwningExprResult
Steve Naroff1b273c42007-09-16 14:56:35 +0000114Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor2f639b92008-10-24 15:36:09 +0000115 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000116 "Unknown C++ Boolean value!");
Sebastian Redlf53597f2009-03-15 17:47:39 +0000117 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
118 Context.BoolTy, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000119}
Chris Lattner50dd2892008-02-26 00:51:44 +0000120
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000121/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
122Action::OwningExprResult
123Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
124 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
125}
126
Chris Lattner50dd2892008-02-26 00:51:44 +0000127/// ActOnCXXThrow - Parse throw expressions.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000128Action::OwningExprResult
129Sema::ActOnCXXThrow(SourceLocation OpLoc, ExprArg E) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000130 Expr *Ex = E.takeAs<Expr>();
131 if (Ex && !Ex->isTypeDependent() && CheckCXXThrowOperand(OpLoc, Ex))
132 return ExprError();
133 return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc));
134}
135
136/// CheckCXXThrowOperand - Validate the operand of a throw.
137bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *&E) {
138 // C++ [except.throw]p3:
Douglas Gregor154fe982009-12-23 22:04:40 +0000139 // A throw-expression initializes a temporary object, called the exception
140 // object, the type of which is determined by removing any top-level
141 // cv-qualifiers from the static type of the operand of throw and adjusting
142 // the type from "array of T" or "function returning T" to "pointer to T"
143 // or "pointer to function returning T", [...]
144 if (E->getType().hasQualifiers())
145 ImpCastExprToType(E, E->getType().getUnqualifiedType(), CastExpr::CK_NoOp,
146 E->isLvalue(Context) == Expr::LV_Valid);
147
Sebastian Redl972041f2009-04-27 20:27:31 +0000148 DefaultFunctionArrayConversion(E);
149
150 // If the type of the exception would be an incomplete type or a pointer
151 // to an incomplete type other than (cv) void the program is ill-formed.
152 QualType Ty = E->getType();
153 int isPointer = 0;
Ted Kremenek6217b802009-07-29 21:53:49 +0000154 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000155 Ty = Ptr->getPointeeType();
156 isPointer = 1;
157 }
158 if (!isPointer || !Ty->isVoidType()) {
159 if (RequireCompleteType(ThrowLoc, Ty,
Anders Carlssond497ba72009-08-26 22:59:12 +0000160 PDiag(isPointer ? diag::err_throw_incomplete_ptr
161 : diag::err_throw_incomplete)
162 << E->getSourceRange()))
Sebastian Redl972041f2009-04-27 20:27:31 +0000163 return true;
164 }
165
166 // FIXME: Construct a temporary here.
167 return false;
Chris Lattner50dd2892008-02-26 00:51:44 +0000168}
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000169
Sebastian Redlf53597f2009-03-15 17:47:39 +0000170Action::OwningExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000171 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
172 /// is a non-lvalue expression whose value is the address of the object for
173 /// which the function is called.
174
Sebastian Redlf53597f2009-03-15 17:47:39 +0000175 if (!isa<FunctionDecl>(CurContext))
176 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000177
178 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext))
179 if (MD->isInstance())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000180 return Owned(new (Context) CXXThisExpr(ThisLoc,
Douglas Gregor828a1972010-01-07 23:12:05 +0000181 MD->getThisType(Context),
182 /*isImplicit=*/false));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000183
Sebastian Redlf53597f2009-03-15 17:47:39 +0000184 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000185}
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000186
187/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
188/// Can be interpreted either as function-style casting ("int(x)")
189/// or class type construction ("ClassType(x,y,z)")
190/// or creation of a value-initialized type ("int()").
Sebastian Redlf53597f2009-03-15 17:47:39 +0000191Action::OwningExprResult
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000192Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep,
193 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000194 MultiExprArg exprs,
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000195 SourceLocation *CommaLocs,
196 SourceLocation RParenLoc) {
Douglas Gregorae4c77d2010-02-05 19:11:37 +0000197 if (!TypeRep)
198 return ExprError();
199
John McCall9d125032010-01-15 18:39:57 +0000200 TypeSourceInfo *TInfo;
201 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
202 if (!TInfo)
203 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
Sebastian Redlf53597f2009-03-15 17:47:39 +0000204 unsigned NumExprs = exprs.size();
205 Expr **Exprs = (Expr**)exprs.get();
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000206 SourceLocation TyBeginLoc = TypeRange.getBegin();
207 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
208
Sebastian Redlf53597f2009-03-15 17:47:39 +0000209 if (Ty->isDependentType() ||
Douglas Gregorba498172009-03-13 21:01:28 +0000210 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
Sebastian Redlf53597f2009-03-15 17:47:39 +0000211 exprs.release();
Mike Stump1eb44332009-09-09 15:08:12 +0000212
213 return Owned(CXXUnresolvedConstructExpr::Create(Context,
214 TypeRange.getBegin(), Ty,
Douglas Gregord81e6ca2009-05-20 18:46:25 +0000215 LParenLoc,
216 Exprs, NumExprs,
217 RParenLoc));
Douglas Gregorba498172009-03-13 21:01:28 +0000218 }
219
Anders Carlssonbb60a502009-08-27 03:53:50 +0000220 if (Ty->isArrayType())
221 return ExprError(Diag(TyBeginLoc,
222 diag::err_value_init_for_array_type) << FullRange);
223 if (!Ty->isVoidType() &&
224 RequireCompleteType(TyBeginLoc, Ty,
225 PDiag(diag::err_invalid_incomplete_type_use)
226 << FullRange))
227 return ExprError();
Fariborz Jahanianf071e9b2009-10-23 21:01:39 +0000228
Anders Carlssonbb60a502009-08-27 03:53:50 +0000229 if (RequireNonAbstractType(TyBeginLoc, Ty,
230 diag::err_allocation_of_abstract_type))
231 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000232
233
Douglas Gregor506ae412009-01-16 18:33:17 +0000234 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000235 // If the expression list is a single expression, the type conversion
236 // expression is equivalent (in definedness, and if defined in meaning) to the
237 // corresponding cast expression.
238 //
239 if (NumExprs == 1) {
Anders Carlssoncdb61972009-08-07 22:21:05 +0000240 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Anders Carlsson0aebc812009-09-09 21:33:21 +0000241 CXXMethodDecl *Method = 0;
242 if (CheckCastTypes(TypeRange, Ty, Exprs[0], Kind, Method,
243 /*FunctionalStyle=*/true))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000244 return ExprError();
Anders Carlsson0aebc812009-09-09 21:33:21 +0000245
246 exprs.release();
247 if (Method) {
248 OwningExprResult CastArg
249 = BuildCXXCastArgument(TypeRange.getBegin(), Ty.getNonReferenceType(),
250 Kind, Method, Owned(Exprs[0]));
251 if (CastArg.isInvalid())
252 return ExprError();
253
254 Exprs[0] = CastArg.takeAs<Expr>();
Fariborz Jahanian4fc7ab32009-08-28 15:11:24 +0000255 }
Anders Carlsson0aebc812009-09-09 21:33:21 +0000256
257 return Owned(new (Context) CXXFunctionalCastExpr(Ty.getNonReferenceType(),
John McCall9d125032010-01-15 18:39:57 +0000258 TInfo, TyBeginLoc, Kind,
Anders Carlsson0aebc812009-09-09 21:33:21 +0000259 Exprs[0], RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000260 }
261
Ted Kremenek6217b802009-07-29 21:53:49 +0000262 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Douglas Gregor506ae412009-01-16 18:33:17 +0000263 CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
Sebastian Redlf53597f2009-03-15 17:47:39 +0000264
Mike Stump1eb44332009-09-09 15:08:12 +0000265 if (NumExprs > 1 || !Record->hasTrivialConstructor() ||
Anders Carlssone7624a72009-08-27 05:08:22 +0000266 !Record->hasTrivialDestructor()) {
Eli Friedman6997aae2010-01-31 20:58:15 +0000267 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty);
268 InitializationKind Kind
269 = NumExprs ? InitializationKind::CreateDirect(TypeRange.getBegin(),
270 LParenLoc, RParenLoc)
271 : InitializationKind::CreateValue(TypeRange.getBegin(),
272 LParenLoc, RParenLoc);
273 InitializationSequence InitSeq(*this, Entity, Kind, Exprs, NumExprs);
274 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
275 move(exprs));
Douglas Gregor506ae412009-01-16 18:33:17 +0000276
Eli Friedman6997aae2010-01-31 20:58:15 +0000277 // FIXME: Improve AST representation?
278 return move(Result);
Douglas Gregor506ae412009-01-16 18:33:17 +0000279 }
280
281 // Fall through to value-initialize an object of class type that
282 // doesn't have a user-declared default constructor.
283 }
284
285 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000286 // If the expression list specifies more than a single value, the type shall
287 // be a class with a suitably declared constructor.
288 //
289 if (NumExprs > 1)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000290 return ExprError(Diag(CommaLocs[0],
291 diag::err_builtin_func_cast_more_than_one_arg)
292 << FullRange);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000293
294 assert(NumExprs == 0 && "Expected 0 expressions");
Douglas Gregor506ae412009-01-16 18:33:17 +0000295 // C++ [expr.type.conv]p2:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000296 // The expression T(), where T is a simple-type-specifier for a non-array
297 // complete object type or the (possibly cv-qualified) void type, creates an
298 // rvalue of the specified type, which is value-initialized.
299 //
Sebastian Redlf53597f2009-03-15 17:47:39 +0000300 exprs.release();
301 return Owned(new (Context) CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000302}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000303
304
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000305/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
306/// @code new (memory) int[size][4] @endcode
307/// or
308/// @code ::new Foo(23, "hello") @endcode
309/// For the interpretation of this heap of arguments, consult the base version.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000310Action::OwningExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000311Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000312 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000313 SourceLocation PlacementRParen, bool ParenTypeId,
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000314 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000315 MultiExprArg ConstructorArgs,
Mike Stump1eb44332009-09-09 15:08:12 +0000316 SourceLocation ConstructorRParen) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000317 Expr *ArraySize = 0;
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000318 // If the specified type is an array, unwrap it and save the expression.
319 if (D.getNumTypeObjects() > 0 &&
320 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
321 DeclaratorChunk &Chunk = D.getTypeObject(0);
322 if (Chunk.Arr.hasStatic)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000323 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
324 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000325 if (!Chunk.Arr.NumElts)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000326 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
327 << D.getSourceRange());
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000328
329 if (ParenTypeId) {
330 // Can't have dynamic array size when the type-id is in parentheses.
331 Expr *NumElts = (Expr *)Chunk.Arr.NumElts;
332 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
333 !NumElts->isIntegerConstantExpr(Context)) {
334 Diag(D.getTypeObject(0).Loc, diag::err_new_paren_array_nonconst)
335 << NumElts->getSourceRange();
336 return ExprError();
337 }
338 }
339
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000340 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000341 D.DropFirstTypeObject();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000342 }
343
Douglas Gregor043cad22009-09-11 00:18:58 +0000344 // Every dimension shall be of constant size.
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000345 if (ArraySize) {
346 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor043cad22009-09-11 00:18:58 +0000347 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
348 break;
349
350 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
351 if (Expr *NumElts = (Expr *)Array.NumElts) {
352 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
353 !NumElts->isIntegerConstantExpr(Context)) {
354 Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst)
355 << NumElts->getSourceRange();
356 return ExprError();
357 }
358 }
359 }
360 }
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000361
John McCalla93c9342009-12-07 02:54:59 +0000362 //FIXME: Store TypeSourceInfo in CXXNew expression.
363 TypeSourceInfo *TInfo = 0;
364 QualType AllocType = GetTypeForDeclarator(D, /*Scope=*/0, &TInfo);
Chris Lattnereaaebc72009-04-25 08:06:05 +0000365 if (D.isInvalidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000366 return ExprError();
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000367
Mike Stump1eb44332009-09-09 15:08:12 +0000368 return BuildCXXNew(StartLoc, UseGlobal,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000369 PlacementLParen,
Mike Stump1eb44332009-09-09 15:08:12 +0000370 move(PlacementArgs),
Douglas Gregor3433cf72009-05-21 00:00:09 +0000371 PlacementRParen,
372 ParenTypeId,
Mike Stump1eb44332009-09-09 15:08:12 +0000373 AllocType,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000374 D.getSourceRange().getBegin(),
375 D.getSourceRange(),
376 Owned(ArraySize),
377 ConstructorLParen,
378 move(ConstructorArgs),
379 ConstructorRParen);
380}
381
Mike Stump1eb44332009-09-09 15:08:12 +0000382Sema::OwningExprResult
Douglas Gregor3433cf72009-05-21 00:00:09 +0000383Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
384 SourceLocation PlacementLParen,
385 MultiExprArg PlacementArgs,
386 SourceLocation PlacementRParen,
Mike Stump1eb44332009-09-09 15:08:12 +0000387 bool ParenTypeId,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000388 QualType AllocType,
389 SourceLocation TypeLoc,
390 SourceRange TypeRange,
391 ExprArg ArraySizeE,
392 SourceLocation ConstructorLParen,
393 MultiExprArg ConstructorArgs,
394 SourceLocation ConstructorRParen) {
395 if (CheckAllocatedType(AllocType, TypeLoc, TypeRange))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000396 return ExprError();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000397
Douglas Gregor3433cf72009-05-21 00:00:09 +0000398 QualType ResultType = Context.getPointerType(AllocType);
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000399
400 // That every array dimension except the first is constant was already
401 // checked by the type check above.
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000402
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000403 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
404 // or enumeration type with a non-negative value."
Douglas Gregor3433cf72009-05-21 00:00:09 +0000405 Expr *ArraySize = (Expr *)ArraySizeE.get();
Sebastian Redl28507842009-02-26 14:39:58 +0000406 if (ArraySize && !ArraySize->isTypeDependent()) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000407 QualType SizeType = ArraySize->getType();
408 if (!SizeType->isIntegralType() && !SizeType->isEnumeralType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000409 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
410 diag::err_array_size_not_integral)
411 << SizeType << ArraySize->getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000412 // Let's see if this is a constant < 0. If so, we reject it out of hand.
413 // We don't care about special rules, so we tell the machinery it's not
414 // evaluated - it gives us a result in more cases.
Sebastian Redl28507842009-02-26 14:39:58 +0000415 if (!ArraySize->isValueDependent()) {
416 llvm::APSInt Value;
417 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
418 if (Value < llvm::APSInt(
Anders Carlssonac18b2e2009-09-23 00:37:25 +0000419 llvm::APInt::getNullValue(Value.getBitWidth()),
420 Value.isUnsigned()))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000421 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
422 diag::err_typecheck_negative_array_size)
423 << ArraySize->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +0000424 }
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000425 }
Anders Carlssonac18b2e2009-09-23 00:37:25 +0000426
Eli Friedman73c39ab2009-10-20 08:27:19 +0000427 ImpCastExprToType(ArraySize, Context.getSizeType(),
428 CastExpr::CK_IntegralCast);
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000429 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000430
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000431 FunctionDecl *OperatorNew = 0;
432 FunctionDecl *OperatorDelete = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000433 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
434 unsigned NumPlaceArgs = PlacementArgs.size();
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000435
Sebastian Redl28507842009-02-26 14:39:58 +0000436 if (!AllocType->isDependentType() &&
437 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
438 FindAllocationFunctions(StartLoc,
Sebastian Redl00e68e22009-02-09 18:24:27 +0000439 SourceRange(PlacementLParen, PlacementRParen),
440 UseGlobal, AllocType, ArraySize, PlaceArgs,
441 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000442 return ExprError();
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000443 llvm::SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000444 if (OperatorNew) {
445 // Add default arguments, if any.
446 const FunctionProtoType *Proto =
447 OperatorNew->getType()->getAs<FunctionProtoType>();
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +0000448 VariadicCallType CallType =
449 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000450 bool Invalid = GatherArgumentsForCall(PlacementLParen, OperatorNew,
451 Proto, 1, PlaceArgs, NumPlaceArgs,
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +0000452 AllPlaceArgs, CallType);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000453 if (Invalid)
454 return ExprError();
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000455
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000456 NumPlaceArgs = AllPlaceArgs.size();
457 if (NumPlaceArgs > 0)
458 PlaceArgs = &AllPlaceArgs[0];
459 }
460
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000461 bool Init = ConstructorLParen.isValid();
462 // --- Choosing a constructor ---
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000463 CXXConstructorDecl *Constructor = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000464 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
465 unsigned NumConsArgs = ConstructorArgs.size();
Eli Friedmana8ce9ec2009-11-08 22:15:39 +0000466 ASTOwningVector<&ActionBase::DeleteExpr> ConvertedConstructorArgs(*this);
467
Douglas Gregor99a2e602009-12-16 01:38:02 +0000468 if (!AllocType->isDependentType() &&
469 !Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) {
470 // C++0x [expr.new]p15:
471 // A new-expression that creates an object of type T initializes that
472 // object as follows:
473 InitializationKind Kind
474 // - If the new-initializer is omitted, the object is default-
475 // initialized (8.5); if no initialization is performed,
476 // the object has indeterminate value
477 = !Init? InitializationKind::CreateDefault(TypeLoc)
478 // - Otherwise, the new-initializer is interpreted according to the
479 // initialization rules of 8.5 for direct-initialization.
480 : InitializationKind::CreateDirect(TypeLoc,
481 ConstructorLParen,
482 ConstructorRParen);
483
Douglas Gregor99a2e602009-12-16 01:38:02 +0000484 InitializedEntity Entity
Douglas Gregord6542d82009-12-22 15:35:07 +0000485 = InitializedEntity::InitializeNew(StartLoc, AllocType);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000486 InitializationSequence InitSeq(*this, Entity, Kind, ConsArgs, NumConsArgs);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000487 OwningExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
488 move(ConstructorArgs));
489 if (FullInit.isInvalid())
490 return ExprError();
491
492 // FullInit is our initializer; walk through it to determine if it's a
493 // constructor call, which CXXNewExpr handles directly.
494 if (Expr *FullInitExpr = (Expr *)FullInit.get()) {
495 if (CXXBindTemporaryExpr *Binder
496 = dyn_cast<CXXBindTemporaryExpr>(FullInitExpr))
497 FullInitExpr = Binder->getSubExpr();
498 if (CXXConstructExpr *Construct
499 = dyn_cast<CXXConstructExpr>(FullInitExpr)) {
500 Constructor = Construct->getConstructor();
501 for (CXXConstructExpr::arg_iterator A = Construct->arg_begin(),
502 AEnd = Construct->arg_end();
503 A != AEnd; ++A)
504 ConvertedConstructorArgs.push_back(A->Retain());
505 } else {
506 // Take the converted initializer.
507 ConvertedConstructorArgs.push_back(FullInit.release());
508 }
509 } else {
510 // No initialization required.
511 }
512
513 // Take the converted arguments and use them for the new expression.
Douglas Gregor39da0b82009-09-09 23:08:42 +0000514 NumConsArgs = ConvertedConstructorArgs.size();
515 ConsArgs = (Expr **)ConvertedConstructorArgs.take();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000516 }
Douglas Gregor99a2e602009-12-16 01:38:02 +0000517
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000518 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
Douglas Gregor089407b2009-10-17 21:40:42 +0000519
Sebastian Redlf53597f2009-03-15 17:47:39 +0000520 PlacementArgs.release();
521 ConstructorArgs.release();
Douglas Gregor3433cf72009-05-21 00:00:09 +0000522 ArraySizeE.release();
Ted Kremenekad7fe862010-02-11 22:51:03 +0000523 return Owned(new (Context) CXXNewExpr(Context, UseGlobal, OperatorNew,
524 PlaceArgs, NumPlaceArgs, ParenTypeId,
525 ArraySize, Constructor, Init,
526 ConsArgs, NumConsArgs, OperatorDelete,
527 ResultType, StartLoc,
528 Init ? ConstructorRParen :
529 SourceLocation()));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000530}
531
532/// CheckAllocatedType - Checks that a type is suitable as the allocated type
533/// in a new-expression.
534/// dimension off and stores the size expression in ArraySize.
Douglas Gregor3433cf72009-05-21 00:00:09 +0000535bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +0000536 SourceRange R) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000537 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
538 // abstract class type or array thereof.
Douglas Gregore7450f52009-03-24 19:52:54 +0000539 if (AllocType->isFunctionType())
Douglas Gregor3433cf72009-05-21 00:00:09 +0000540 return Diag(Loc, diag::err_bad_new_type)
541 << AllocType << 0 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +0000542 else if (AllocType->isReferenceType())
Douglas Gregor3433cf72009-05-21 00:00:09 +0000543 return Diag(Loc, diag::err_bad_new_type)
544 << AllocType << 1 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +0000545 else if (!AllocType->isDependentType() &&
Douglas Gregor3433cf72009-05-21 00:00:09 +0000546 RequireCompleteType(Loc, AllocType,
Anders Carlssonb7906612009-08-26 23:45:07 +0000547 PDiag(diag::err_new_incomplete_type)
548 << R))
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000549 return true;
Douglas Gregor3433cf72009-05-21 00:00:09 +0000550 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregore7450f52009-03-24 19:52:54 +0000551 diag::err_allocation_of_abstract_type))
552 return true;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000553
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000554 return false;
555}
556
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000557/// FindAllocationFunctions - Finds the overloads of operator new and delete
558/// that are appropriate for the allocation.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000559bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
560 bool UseGlobal, QualType AllocType,
561 bool IsArray, Expr **PlaceArgs,
562 unsigned NumPlaceArgs,
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000563 FunctionDecl *&OperatorNew,
Mike Stump1eb44332009-09-09 15:08:12 +0000564 FunctionDecl *&OperatorDelete) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000565 // --- Choosing an allocation function ---
566 // C++ 5.3.4p8 - 14 & 18
567 // 1) If UseGlobal is true, only look in the global scope. Else, also look
568 // in the scope of the allocated class.
569 // 2) If an array size is given, look for operator new[], else look for
570 // operator new.
571 // 3) The first argument is always size_t. Append the arguments from the
572 // placement form.
573 // FIXME: Also find the appropriate delete operator.
574
575 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
576 // We don't care about the actual value of this argument.
577 // FIXME: Should the Sema create the expression and embed it in the syntax
578 // tree? Or should the consumer just recalculate the value?
Anders Carlssond67c4c32009-08-16 20:29:29 +0000579 IntegerLiteral Size(llvm::APInt::getNullValue(
580 Context.Target.getPointerWidth(0)),
581 Context.getSizeType(),
582 SourceLocation());
583 AllocArgs[0] = &Size;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000584 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
585
586 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
587 IsArray ? OO_Array_New : OO_New);
588 if (AllocType->isRecordType() && !UseGlobal) {
Mike Stump1eb44332009-09-09 15:08:12 +0000589 CXXRecordDecl *Record
Ted Kremenek6217b802009-07-29 21:53:49 +0000590 = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl());
Sebastian Redl7f662392008-12-04 22:20:51 +0000591 // FIXME: We fail to find inherited overloads.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000592 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000593 AllocArgs.size(), Record, /*AllowMissing=*/true,
594 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000595 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000596 }
597 if (!OperatorNew) {
598 // Didn't find a member overload. Look for a global one.
599 DeclareGlobalNewDelete();
Sebastian Redl7f662392008-12-04 22:20:51 +0000600 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl00e68e22009-02-09 18:24:27 +0000601 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000602 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
603 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000604 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000605 }
606
Anders Carlssond9583892009-05-31 20:26:12 +0000607 // FindAllocationOverload can change the passed in arguments, so we need to
608 // copy them back.
609 if (NumPlaceArgs > 0)
610 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
Mike Stump1eb44332009-09-09 15:08:12 +0000611
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000612 return false;
613}
614
Sebastian Redl7f662392008-12-04 22:20:51 +0000615/// FindAllocationOverload - Find an fitting overload for the allocation
616/// function in the specified scope.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000617bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
618 DeclarationName Name, Expr** Args,
619 unsigned NumArgs, DeclContext *Ctx,
Mike Stump1eb44332009-09-09 15:08:12 +0000620 bool AllowMissing, FunctionDecl *&Operator) {
John McCalla24dc2e2009-11-17 02:14:36 +0000621 LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
622 LookupQualifiedName(R, Ctx);
John McCallf36e02d2009-10-09 21:13:30 +0000623 if (R.empty()) {
Sebastian Redl7f662392008-12-04 22:20:51 +0000624 if (AllowMissing)
625 return false;
Sebastian Redl7f662392008-12-04 22:20:51 +0000626 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +0000627 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +0000628 }
629
John McCallf36e02d2009-10-09 21:13:30 +0000630 // FIXME: handle ambiguity
631
John McCall5769d612010-02-08 23:07:23 +0000632 OverloadCandidateSet Candidates(StartLoc);
Douglas Gregor5d64e5b2009-09-30 00:03:47 +0000633 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
634 Alloc != AllocEnd; ++Alloc) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000635 // Even member operator new/delete are implicitly treated as
636 // static, so don't use AddMemberCandidate.
Chandler Carruth4a73ea92010-02-03 11:02:14 +0000637
638 if (FunctionTemplateDecl *FnTemplate =
639 dyn_cast<FunctionTemplateDecl>((*Alloc)->getUnderlyingDecl())) {
640 AddTemplateOverloadCandidate(FnTemplate, Alloc.getAccess(),
641 /*ExplicitTemplateArgs=*/0, Args, NumArgs,
642 Candidates,
643 /*SuppressUserConversions=*/false);
Douglas Gregor90916562009-09-29 18:16:17 +0000644 continue;
Chandler Carruth4a73ea92010-02-03 11:02:14 +0000645 }
646
647 FunctionDecl *Fn = cast<FunctionDecl>((*Alloc)->getUnderlyingDecl());
648 AddOverloadCandidate(Fn, Alloc.getAccess(), Args, NumArgs, Candidates,
649 /*SuppressUserConversions=*/false);
Sebastian Redl7f662392008-12-04 22:20:51 +0000650 }
651
652 // Do the resolution.
653 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +0000654 switch(BestViableFunction(Candidates, StartLoc, Best)) {
Sebastian Redl7f662392008-12-04 22:20:51 +0000655 case OR_Success: {
656 // Got one!
657 FunctionDecl *FnDecl = Best->Function;
658 // The first argument is size_t, and the first parameter must be size_t,
659 // too. This is checked on declaration and can be assumed. (It can't be
660 // asserted on, though, since invalid decls are left in there.)
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000661 // Whatch out for variadic allocator function.
662 unsigned NumArgsInFnDecl = FnDecl->getNumParams();
663 for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) {
Anders Carlssonfc27d262009-05-31 19:49:47 +0000664 if (PerformCopyInitialization(Args[i],
Sebastian Redl7f662392008-12-04 22:20:51 +0000665 FnDecl->getParamDecl(i)->getType(),
Douglas Gregor68647482009-12-16 03:45:30 +0000666 AA_Passing))
Sebastian Redl7f662392008-12-04 22:20:51 +0000667 return true;
668 }
669 Operator = FnDecl;
670 return false;
671 }
672
673 case OR_No_Viable_Function:
Sebastian Redl7f662392008-12-04 22:20:51 +0000674 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +0000675 << Name << Range;
John McCallcbce6062010-01-12 07:18:19 +0000676 PrintOverloadCandidates(Candidates, OCD_AllCandidates, Args, NumArgs);
Sebastian Redl7f662392008-12-04 22:20:51 +0000677 return true;
678
679 case OR_Ambiguous:
Sebastian Redl7f662392008-12-04 22:20:51 +0000680 Diag(StartLoc, diag::err_ovl_ambiguous_call)
Sebastian Redl00e68e22009-02-09 18:24:27 +0000681 << Name << Range;
John McCallcbce6062010-01-12 07:18:19 +0000682 PrintOverloadCandidates(Candidates, OCD_ViableCandidates, Args, NumArgs);
Sebastian Redl7f662392008-12-04 22:20:51 +0000683 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000684
685 case OR_Deleted:
686 Diag(StartLoc, diag::err_ovl_deleted_call)
687 << Best->Function->isDeleted()
688 << Name << Range;
John McCallcbce6062010-01-12 07:18:19 +0000689 PrintOverloadCandidates(Candidates, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000690 return true;
Sebastian Redl7f662392008-12-04 22:20:51 +0000691 }
692 assert(false && "Unreachable, bad result from BestViableFunction");
693 return true;
694}
695
696
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000697/// DeclareGlobalNewDelete - Declare the global forms of operator new and
698/// delete. These are:
699/// @code
700/// void* operator new(std::size_t) throw(std::bad_alloc);
701/// void* operator new[](std::size_t) throw(std::bad_alloc);
702/// void operator delete(void *) throw();
703/// void operator delete[](void *) throw();
704/// @endcode
705/// Note that the placement and nothrow forms of new are *not* implicitly
706/// declared. Their use requires including \<new\>.
Mike Stump1eb44332009-09-09 15:08:12 +0000707void Sema::DeclareGlobalNewDelete() {
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000708 if (GlobalNewDeleteDeclared)
709 return;
Douglas Gregor7adb10f2009-09-15 22:30:29 +0000710
711 // C++ [basic.std.dynamic]p2:
712 // [...] The following allocation and deallocation functions (18.4) are
713 // implicitly declared in global scope in each translation unit of a
714 // program
715 //
716 // void* operator new(std::size_t) throw(std::bad_alloc);
717 // void* operator new[](std::size_t) throw(std::bad_alloc);
718 // void operator delete(void*) throw();
719 // void operator delete[](void*) throw();
720 //
721 // These implicit declarations introduce only the function names operator
722 // new, operator new[], operator delete, operator delete[].
723 //
724 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
725 // "std" or "bad_alloc" as necessary to form the exception specification.
726 // However, we do not make these implicit declarations visible to name
727 // lookup.
728 if (!StdNamespace) {
729 // The "std" namespace has not yet been defined, so build one implicitly.
730 StdNamespace = NamespaceDecl::Create(Context,
731 Context.getTranslationUnitDecl(),
732 SourceLocation(),
733 &PP.getIdentifierTable().get("std"));
734 StdNamespace->setImplicit(true);
735 }
736
737 if (!StdBadAlloc) {
738 // The "std::bad_alloc" class has not yet been declared, so build it
739 // implicitly.
740 StdBadAlloc = CXXRecordDecl::Create(Context, TagDecl::TK_class,
741 StdNamespace,
742 SourceLocation(),
743 &PP.getIdentifierTable().get("bad_alloc"),
744 SourceLocation(), 0);
745 StdBadAlloc->setImplicit(true);
746 }
747
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000748 GlobalNewDeleteDeclared = true;
749
750 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
751 QualType SizeT = Context.getSizeType();
Nuno Lopesfc284482009-12-16 16:59:22 +0000752 bool AssumeSaneOperatorNew = getLangOptions().AssumeSaneOperatorNew;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000753
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000754 DeclareGlobalAllocationFunction(
755 Context.DeclarationNames.getCXXOperatorName(OO_New),
Nuno Lopesfc284482009-12-16 16:59:22 +0000756 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000757 DeclareGlobalAllocationFunction(
758 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
Nuno Lopesfc284482009-12-16 16:59:22 +0000759 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000760 DeclareGlobalAllocationFunction(
761 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
762 Context.VoidTy, VoidPtr);
763 DeclareGlobalAllocationFunction(
764 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
765 Context.VoidTy, VoidPtr);
766}
767
768/// DeclareGlobalAllocationFunction - Declares a single implicit global
769/// allocation function if it doesn't already exist.
770void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Nuno Lopesfc284482009-12-16 16:59:22 +0000771 QualType Return, QualType Argument,
772 bool AddMallocAttr) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000773 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
774
775 // Check if this function is already declared.
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000776 {
Douglas Gregor5cc37092008-12-23 22:05:29 +0000777 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000778 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000779 Alloc != AllocEnd; ++Alloc) {
Chandler Carruth4a73ea92010-02-03 11:02:14 +0000780 // Only look at non-template functions, as it is the predefined,
781 // non-templated allocation function we are trying to declare here.
782 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
783 QualType InitialParamType =
Douglas Gregor6e790ab2009-12-22 23:42:49 +0000784 Context.getCanonicalType(
Chandler Carruth4a73ea92010-02-03 11:02:14 +0000785 Func->getParamDecl(0)->getType().getUnqualifiedType());
786 // FIXME: Do we need to check for default arguments here?
787 if (Func->getNumParams() == 1 && InitialParamType == Argument)
788 return;
789 }
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000790 }
791 }
792
Douglas Gregor7adb10f2009-09-15 22:30:29 +0000793 QualType BadAllocType;
794 bool HasBadAllocExceptionSpec
795 = (Name.getCXXOverloadedOperator() == OO_New ||
796 Name.getCXXOverloadedOperator() == OO_Array_New);
797 if (HasBadAllocExceptionSpec) {
798 assert(StdBadAlloc && "Must have std::bad_alloc declared");
799 BadAllocType = Context.getTypeDeclType(StdBadAlloc);
800 }
801
802 QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0,
803 true, false,
804 HasBadAllocExceptionSpec? 1 : 0,
805 &BadAllocType);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000806 FunctionDecl *Alloc =
807 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
John McCalla93c9342009-12-07 02:54:59 +0000808 FnType, /*TInfo=*/0, FunctionDecl::None, false, true);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000809 Alloc->setImplicit();
Nuno Lopesfc284482009-12-16 16:59:22 +0000810
811 if (AddMallocAttr)
812 Alloc->addAttr(::new (Context) MallocAttr());
813
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000814 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
John McCalla93c9342009-12-07 02:54:59 +0000815 0, Argument, /*TInfo=*/0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000816 VarDecl::None, 0);
Douglas Gregor838db382010-02-11 01:19:42 +0000817 Alloc->setParams(&Param, 1);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000818
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000819 // FIXME: Also add this declaration to the IdentifierResolver, but
820 // make sure it is at the end of the chain to coincide with the
821 // global scope.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000822 ((DeclContext *)TUScope->getEntity())->addDecl(Alloc);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000823}
824
Anders Carlsson78f74552009-11-15 18:45:20 +0000825bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
826 DeclarationName Name,
Anders Carlsson5ec02ae2009-12-02 17:15:43 +0000827 FunctionDecl* &Operator) {
John McCalla24dc2e2009-11-17 02:14:36 +0000828 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlsson78f74552009-11-15 18:45:20 +0000829 // Try to find operator delete/operator delete[] in class scope.
John McCalla24dc2e2009-11-17 02:14:36 +0000830 LookupQualifiedName(Found, RD);
Anders Carlsson78f74552009-11-15 18:45:20 +0000831
John McCalla24dc2e2009-11-17 02:14:36 +0000832 if (Found.isAmbiguous())
Anders Carlsson78f74552009-11-15 18:45:20 +0000833 return true;
Anders Carlsson78f74552009-11-15 18:45:20 +0000834
835 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
836 F != FEnd; ++F) {
837 if (CXXMethodDecl *Delete = dyn_cast<CXXMethodDecl>(*F))
838 if (Delete->isUsualDeallocationFunction()) {
839 Operator = Delete;
840 return false;
841 }
842 }
843
844 // We did find operator delete/operator delete[] declarations, but
845 // none of them were suitable.
846 if (!Found.empty()) {
847 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
848 << Name << RD;
849
850 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
851 F != FEnd; ++F) {
852 Diag((*F)->getLocation(),
853 diag::note_delete_member_function_declared_here)
854 << Name;
855 }
856
857 return true;
858 }
859
860 // Look for a global declaration.
861 DeclareGlobalNewDelete();
862 DeclContext *TUDecl = Context.getTranslationUnitDecl();
863
864 CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation());
865 Expr* DeallocArgs[1];
866 DeallocArgs[0] = &Null;
867 if (FindAllocationOverload(StartLoc, SourceRange(), Name,
868 DeallocArgs, 1, TUDecl, /*AllowMissing=*/false,
869 Operator))
870 return true;
871
872 assert(Operator && "Did not find a deallocation function!");
873 return false;
874}
875
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000876/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
877/// @code ::delete ptr; @endcode
878/// or
879/// @code delete [] ptr; @endcode
Sebastian Redlf53597f2009-03-15 17:47:39 +0000880Action::OwningExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000881Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
Mike Stump1eb44332009-09-09 15:08:12 +0000882 bool ArrayForm, ExprArg Operand) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000883 // C++ [expr.delete]p1:
884 // The operand shall have a pointer type, or a class type having a single
885 // conversion function to a pointer type. The result has type void.
886 //
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000887 // DR599 amends "pointer type" to "pointer to object type" in both cases.
888
Anders Carlssond67c4c32009-08-16 20:29:29 +0000889 FunctionDecl *OperatorDelete = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000890
Sebastian Redlf53597f2009-03-15 17:47:39 +0000891 Expr *Ex = (Expr *)Operand.get();
Sebastian Redl28507842009-02-26 14:39:58 +0000892 if (!Ex->isTypeDependent()) {
893 QualType Type = Ex->getType();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000894
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000895 if (const RecordType *Record = Type->getAs<RecordType>()) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000896 llvm::SmallVector<CXXConversionDecl *, 4> ObjectPtrConversions;
Fariborz Jahanian53462782009-09-11 21:44:33 +0000897 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
John McCalleec51cf2010-01-20 00:46:10 +0000898 const UnresolvedSetImpl *Conversions = RD->getVisibleConversionFunctions();
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000899
John McCalleec51cf2010-01-20 00:46:10 +0000900 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +0000901 E = Conversions->end(); I != E; ++I) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000902 // Skip over templated conversion functions; they aren't considered.
John McCallba135432009-11-21 08:51:07 +0000903 if (isa<FunctionTemplateDecl>(*I))
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000904 continue;
905
John McCallba135432009-11-21 08:51:07 +0000906 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*I);
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000907
908 QualType ConvType = Conv->getConversionType().getNonReferenceType();
909 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
910 if (ConvPtrType->getPointeeType()->isObjectType())
Fariborz Jahanian8b915e72009-09-15 22:15:23 +0000911 ObjectPtrConversions.push_back(Conv);
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000912 }
Fariborz Jahanian8b915e72009-09-15 22:15:23 +0000913 if (ObjectPtrConversions.size() == 1) {
914 // We have a single conversion to a pointer-to-object type. Perform
915 // that conversion.
916 Operand.release();
917 if (!PerformImplicitConversion(Ex,
918 ObjectPtrConversions.front()->getConversionType(),
Douglas Gregor68647482009-12-16 03:45:30 +0000919 AA_Converting)) {
Fariborz Jahanian8b915e72009-09-15 22:15:23 +0000920 Operand = Owned(Ex);
921 Type = Ex->getType();
922 }
923 }
924 else if (ObjectPtrConversions.size() > 1) {
925 Diag(StartLoc, diag::err_ambiguous_delete_operand)
926 << Type << Ex->getSourceRange();
927 for (unsigned i= 0; i < ObjectPtrConversions.size(); i++) {
928 CXXConversionDecl *Conv = ObjectPtrConversions[i];
John McCallb1622a12010-01-06 09:43:14 +0000929 NoteOverloadCandidate(Conv);
Fariborz Jahanian8b915e72009-09-15 22:15:23 +0000930 }
931 return ExprError();
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000932 }
Sebastian Redl28507842009-02-26 14:39:58 +0000933 }
934
Sebastian Redlf53597f2009-03-15 17:47:39 +0000935 if (!Type->isPointerType())
936 return ExprError(Diag(StartLoc, diag::err_delete_operand)
937 << Type << Ex->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +0000938
Ted Kremenek6217b802009-07-29 21:53:49 +0000939 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Douglas Gregor8dcb29d2009-03-24 20:13:58 +0000940 if (Pointee->isFunctionType() || Pointee->isVoidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000941 return ExprError(Diag(StartLoc, diag::err_delete_operand)
942 << Type << Ex->getSourceRange());
Douglas Gregor8dcb29d2009-03-24 20:13:58 +0000943 else if (!Pointee->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +0000944 RequireCompleteType(StartLoc, Pointee,
Anders Carlssonb7906612009-08-26 23:45:07 +0000945 PDiag(diag::warn_delete_incomplete)
946 << Ex->getSourceRange()))
Douglas Gregor8dcb29d2009-03-24 20:13:58 +0000947 return ExprError();
Sebastian Redl28507842009-02-26 14:39:58 +0000948
Douglas Gregor1070c9f2009-09-29 21:38:53 +0000949 // C++ [expr.delete]p2:
950 // [Note: a pointer to a const type can be the operand of a
951 // delete-expression; it is not necessary to cast away the constness
952 // (5.2.11) of the pointer expression before it is used as the operand
953 // of the delete-expression. ]
954 ImpCastExprToType(Ex, Context.getPointerType(Context.VoidTy),
955 CastExpr::CK_NoOp);
956
957 // Update the operand.
958 Operand.take();
959 Operand = ExprArg(*this, Ex);
960
Anders Carlssond67c4c32009-08-16 20:29:29 +0000961 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
962 ArrayForm ? OO_Array_Delete : OO_Delete);
963
Anders Carlsson78f74552009-11-15 18:45:20 +0000964 if (const RecordType *RT = Pointee->getAs<RecordType>()) {
965 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
966
967 if (!UseGlobal &&
968 FindDeallocationFunction(StartLoc, RD, DeleteName, OperatorDelete))
Anders Carlsson0ba63ea2009-11-14 03:17:38 +0000969 return ExprError();
Anders Carlsson0ba63ea2009-11-14 03:17:38 +0000970
Anders Carlsson78f74552009-11-15 18:45:20 +0000971 if (!RD->hasTrivialDestructor())
972 if (const CXXDestructorDecl *Dtor = RD->getDestructor(Context))
Mike Stump1eb44332009-09-09 15:08:12 +0000973 MarkDeclarationReferenced(StartLoc,
Fariborz Jahanian34374e62009-09-03 23:18:17 +0000974 const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssond67c4c32009-08-16 20:29:29 +0000975 }
Anders Carlsson78f74552009-11-15 18:45:20 +0000976
Anders Carlssond67c4c32009-08-16 20:29:29 +0000977 if (!OperatorDelete) {
Anders Carlsson78f74552009-11-15 18:45:20 +0000978 // Look for a global declaration.
Anders Carlssond67c4c32009-08-16 20:29:29 +0000979 DeclareGlobalNewDelete();
980 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000981 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
Douglas Gregor90916562009-09-29 18:16:17 +0000982 &Ex, 1, TUDecl, /*AllowMissing=*/false,
Anders Carlssond67c4c32009-08-16 20:29:29 +0000983 OperatorDelete))
984 return ExprError();
985 }
Mike Stump1eb44332009-09-09 15:08:12 +0000986
Sebastian Redl28507842009-02-26 14:39:58 +0000987 // FIXME: Check access and ambiguity of operator delete and destructor.
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000988 }
989
Sebastian Redlf53597f2009-03-15 17:47:39 +0000990 Operand.release();
991 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
Anders Carlssond67c4c32009-08-16 20:29:29 +0000992 OperatorDelete, Ex, StartLoc));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000993}
994
Douglas Gregor8cfe5a72009-11-23 23:44:04 +0000995/// \brief Check the use of the given variable as a C++ condition in an if,
996/// while, do-while, or switch statement.
997Action::OwningExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar) {
998 QualType T = ConditionVar->getType();
999
1000 // C++ [stmt.select]p2:
1001 // The declarator shall not specify a function or an array.
1002 if (T->isFunctionType())
1003 return ExprError(Diag(ConditionVar->getLocation(),
1004 diag::err_invalid_use_of_function_type)
1005 << ConditionVar->getSourceRange());
1006 else if (T->isArrayType())
1007 return ExprError(Diag(ConditionVar->getLocation(),
1008 diag::err_invalid_use_of_array_type)
1009 << ConditionVar->getSourceRange());
Douglas Gregora7605db2009-11-24 16:07:02 +00001010
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001011 return Owned(DeclRefExpr::Create(Context, 0, SourceRange(), ConditionVar,
1012 ConditionVar->getLocation(),
1013 ConditionVar->getType().getNonReferenceType()));
1014}
1015
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001016/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
1017bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
1018 // C++ 6.4p4:
1019 // The value of a condition that is an initialized declaration in a statement
1020 // other than a switch statement is the value of the declared variable
1021 // implicitly converted to type bool. If that conversion is ill-formed, the
1022 // program is ill-formed.
1023 // The value of a condition that is an expression is the value of the
1024 // expression, implicitly converted to bool.
1025 //
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001026 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001027}
Douglas Gregor77a52232008-09-12 00:47:35 +00001028
1029/// Helper function to determine whether this is the (deprecated) C++
1030/// conversion from a string literal to a pointer to non-const char or
1031/// non-const wchar_t (for narrow and wide string literals,
1032/// respectively).
Mike Stump1eb44332009-09-09 15:08:12 +00001033bool
Douglas Gregor77a52232008-09-12 00:47:35 +00001034Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
1035 // Look inside the implicit cast, if it exists.
1036 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
1037 From = Cast->getSubExpr();
1038
1039 // A string literal (2.13.4) that is not a wide string literal can
1040 // be converted to an rvalue of type "pointer to char"; a wide
1041 // string literal can be converted to an rvalue of type "pointer
1042 // to wchar_t" (C++ 4.2p2).
1043 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From))
Ted Kremenek6217b802009-07-29 21:53:49 +00001044 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump1eb44332009-09-09 15:08:12 +00001045 if (const BuiltinType *ToPointeeType
John McCall183700f2009-09-21 23:43:11 +00001046 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregor77a52232008-09-12 00:47:35 +00001047 // This conversion is considered only when there is an
1048 // explicit appropriate pointer target type (C++ 4.2p2).
John McCall0953e762009-09-24 19:53:00 +00001049 if (!ToPtrType->getPointeeType().hasQualifiers() &&
Douglas Gregor77a52232008-09-12 00:47:35 +00001050 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
1051 (!StrLit->isWide() &&
1052 (ToPointeeType->getKind() == BuiltinType::Char_U ||
1053 ToPointeeType->getKind() == BuiltinType::Char_S))))
1054 return true;
1055 }
1056
1057 return false;
1058}
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001059
1060/// PerformImplicitConversion - Perform an implicit conversion of the
1061/// expression From to the type ToType. Returns true if there was an
1062/// error, false otherwise. The expression From is replaced with the
Douglas Gregor45920e82008-12-19 17:40:08 +00001063/// converted expression. Flavor is the kind of conversion we're
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001064/// performing, used in the error message. If @p AllowExplicit,
Sebastian Redle2b68332009-04-12 17:16:29 +00001065/// explicit user-defined conversions are permitted. @p Elidable should be true
1066/// when called for copies which may be elided (C++ 12.8p15). C++0x overload
1067/// resolution works differently in that case.
1068bool
Douglas Gregor45920e82008-12-19 17:40:08 +00001069Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor68647482009-12-16 03:45:30 +00001070 AssignmentAction Action, bool AllowExplicit,
Mike Stump1eb44332009-09-09 15:08:12 +00001071 bool Elidable) {
Sebastian Redle2b68332009-04-12 17:16:29 +00001072 ImplicitConversionSequence ICS;
Douglas Gregor68647482009-12-16 03:45:30 +00001073 return PerformImplicitConversion(From, ToType, Action, AllowExplicit,
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00001074 Elidable, ICS);
1075}
1076
1077bool
1078Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor68647482009-12-16 03:45:30 +00001079 AssignmentAction Action, bool AllowExplicit,
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00001080 bool Elidable,
1081 ImplicitConversionSequence& ICS) {
John McCall1d318332010-01-12 00:44:57 +00001082 ICS.setBad();
John McCalladbb8f82010-01-13 09:16:55 +00001083 ICS.Bad.init(BadConversionSequence::no_conversion, From, ToType);
Sebastian Redle2b68332009-04-12 17:16:29 +00001084 if (Elidable && getLangOptions().CPlusPlus0x) {
Mike Stump1eb44332009-09-09 15:08:12 +00001085 ICS = TryImplicitConversion(From, ToType,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001086 /*SuppressUserConversions=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +00001087 AllowExplicit,
Anders Carlsson08972922009-08-28 15:33:32 +00001088 /*ForceRValue=*/true,
1089 /*InOverloadResolution=*/false);
Sebastian Redle2b68332009-04-12 17:16:29 +00001090 }
John McCall1d318332010-01-12 00:44:57 +00001091 if (ICS.isBad()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001092 ICS = TryImplicitConversion(From, ToType,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001093 /*SuppressUserConversions=*/false,
1094 AllowExplicit,
Anders Carlsson08972922009-08-28 15:33:32 +00001095 /*ForceRValue=*/false,
1096 /*InOverloadResolution=*/false);
Sebastian Redle2b68332009-04-12 17:16:29 +00001097 }
Douglas Gregor68647482009-12-16 03:45:30 +00001098 return PerformImplicitConversion(From, ToType, ICS, Action);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001099}
1100
1101/// PerformImplicitConversion - Perform an implicit conversion of the
1102/// expression From to the type ToType using the pre-computed implicit
1103/// conversion sequence ICS. Returns true if there was an error, false
1104/// otherwise. The expression From is replaced with the converted
Douglas Gregor68647482009-12-16 03:45:30 +00001105/// expression. Action is the kind of conversion we're performing,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001106/// used in the error message.
1107bool
1108Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
1109 const ImplicitConversionSequence &ICS,
Douglas Gregor68647482009-12-16 03:45:30 +00001110 AssignmentAction Action, bool IgnoreBaseAccess) {
John McCall1d318332010-01-12 00:44:57 +00001111 switch (ICS.getKind()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001112 case ImplicitConversionSequence::StandardConversion:
Douglas Gregor68647482009-12-16 03:45:30 +00001113 if (PerformImplicitConversion(From, ToType, ICS.Standard, Action,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001114 IgnoreBaseAccess))
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001115 return true;
1116 break;
1117
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001118 case ImplicitConversionSequence::UserDefinedConversion: {
1119
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00001120 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
1121 CastExpr::CastKind CastKind = CastExpr::CK_Unknown;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001122 QualType BeforeToType;
1123 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00001124 CastKind = CastExpr::CK_UserDefinedConversion;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001125
1126 // If the user-defined conversion is specified by a conversion function,
1127 // the initial standard conversion sequence converts the source type to
1128 // the implicit object parameter of the conversion function.
1129 BeforeToType = Context.getTagDeclType(Conv->getParent());
1130 } else if (const CXXConstructorDecl *Ctor =
1131 dyn_cast<CXXConstructorDecl>(FD)) {
Anders Carlsson0aebc812009-09-09 21:33:21 +00001132 CastKind = CastExpr::CK_ConstructorConversion;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001133 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregore44201a2009-11-20 02:31:03 +00001134 if (!ICS.UserDefined.EllipsisConversion) {
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001135 // If the user-defined conversion is specified by a constructor, the
1136 // initial standard conversion sequence converts the source type to the
1137 // type required by the argument of the constructor
Douglas Gregore44201a2009-11-20 02:31:03 +00001138 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
1139 }
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001140 }
Anders Carlsson0aebc812009-09-09 21:33:21 +00001141 else
1142 assert(0 && "Unknown conversion function kind!");
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001143 // Whatch out for elipsis conversion.
Fariborz Jahanian4c0cea22009-11-06 00:55:14 +00001144 if (!ICS.UserDefined.EllipsisConversion) {
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001145 if (PerformImplicitConversion(From, BeforeToType,
Douglas Gregor68647482009-12-16 03:45:30 +00001146 ICS.UserDefined.Before, AA_Converting,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001147 IgnoreBaseAccess))
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001148 return true;
1149 }
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001150
Anders Carlsson0aebc812009-09-09 21:33:21 +00001151 OwningExprResult CastArg
1152 = BuildCXXCastArgument(From->getLocStart(),
1153 ToType.getNonReferenceType(),
1154 CastKind, cast<CXXMethodDecl>(FD),
1155 Owned(From));
1156
1157 if (CastArg.isInvalid())
1158 return true;
Eli Friedmand8889622009-11-27 04:41:50 +00001159
1160 From = CastArg.takeAs<Expr>();
1161
Eli Friedmand8889622009-11-27 04:41:50 +00001162 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
Douglas Gregor68647482009-12-16 03:45:30 +00001163 AA_Converting, IgnoreBaseAccess);
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001164 }
John McCall1d318332010-01-12 00:44:57 +00001165
1166 case ImplicitConversionSequence::AmbiguousConversion:
1167 DiagnoseAmbiguousConversion(ICS, From->getExprLoc(),
1168 PDiag(diag::err_typecheck_ambiguous_condition)
1169 << From->getSourceRange());
1170 return true;
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001171
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001172 case ImplicitConversionSequence::EllipsisConversion:
1173 assert(false && "Cannot perform an ellipsis conversion");
Douglas Gregor60d62c22008-10-31 16:23:19 +00001174 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001175
1176 case ImplicitConversionSequence::BadConversion:
1177 return true;
1178 }
1179
1180 // Everything went well.
1181 return false;
1182}
1183
1184/// PerformImplicitConversion - Perform an implicit conversion of the
1185/// expression From to the type ToType by following the standard
1186/// conversion sequence SCS. Returns true if there was an error, false
1187/// otherwise. The expression From is replaced with the converted
Douglas Gregor45920e82008-12-19 17:40:08 +00001188/// expression. Flavor is the context in which we're performing this
1189/// conversion, for use in error messages.
Mike Stump1eb44332009-09-09 15:08:12 +00001190bool
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001191Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor45920e82008-12-19 17:40:08 +00001192 const StandardConversionSequence& SCS,
Douglas Gregor68647482009-12-16 03:45:30 +00001193 AssignmentAction Action, bool IgnoreBaseAccess) {
Mike Stump390b4cc2009-05-16 07:39:55 +00001194 // Overall FIXME: we are recomputing too many types here and doing far too
1195 // much extra work. What this means is that we need to keep track of more
1196 // information that is computed when we try the implicit conversion initially,
1197 // so that we don't need to recompute anything here.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001198 QualType FromType = From->getType();
1199
Douglas Gregor225c41e2008-11-03 19:09:14 +00001200 if (SCS.CopyConstructor) {
Anders Carlsson7c3e8a12009-05-19 04:45:15 +00001201 // FIXME: When can ToType be a reference type?
1202 assert(!ToType->isReferenceType());
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00001203 if (SCS.Second == ICK_Derived_To_Base) {
1204 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1205 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
1206 MultiExprArg(*this, (void **)&From, 1),
1207 /*FIXME:ConstructLoc*/SourceLocation(),
1208 ConstructorArgs))
1209 return true;
1210 OwningExprResult FromResult =
1211 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1212 ToType, SCS.CopyConstructor,
1213 move_arg(ConstructorArgs));
1214 if (FromResult.isInvalid())
1215 return true;
1216 From = FromResult.takeAs<Expr>();
1217 return false;
1218 }
Mike Stump1eb44332009-09-09 15:08:12 +00001219 OwningExprResult FromResult =
1220 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1221 ToType, SCS.CopyConstructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00001222 MultiExprArg(*this, (void**)&From, 1));
Mike Stump1eb44332009-09-09 15:08:12 +00001223
Anders Carlssonda3f4e22009-08-25 05:12:04 +00001224 if (FromResult.isInvalid())
1225 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001226
Anders Carlssonda3f4e22009-08-25 05:12:04 +00001227 From = FromResult.takeAs<Expr>();
Douglas Gregor225c41e2008-11-03 19:09:14 +00001228 return false;
1229 }
1230
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001231 // Perform the first implicit conversion.
1232 switch (SCS.First) {
1233 case ICK_Identity:
1234 case ICK_Lvalue_To_Rvalue:
1235 // Nothing to do.
1236 break;
1237
1238 case ICK_Array_To_Pointer:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001239 FromType = Context.getArrayDecayedType(FromType);
Anders Carlsson82495762009-08-08 21:04:35 +00001240 ImpCastExprToType(From, FromType, CastExpr::CK_ArrayToPointerDecay);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001241 break;
1242
1243 case ICK_Function_To_Pointer:
Douglas Gregor063daf62009-03-13 18:40:31 +00001244 if (Context.getCanonicalType(FromType) == Context.OverloadTy) {
Douglas Gregor904eed32008-11-10 20:40:00 +00001245 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, true);
1246 if (!Fn)
1247 return true;
1248
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001249 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
1250 return true;
1251
Anders Carlsson96ad5332009-10-21 17:16:23 +00001252 From = FixOverloadedFunctionReference(From, Fn);
Douglas Gregor904eed32008-11-10 20:40:00 +00001253 FromType = From->getType();
Anders Carlsson96ad5332009-10-21 17:16:23 +00001254
Sebastian Redl759986e2009-10-17 20:50:27 +00001255 // If there's already an address-of operator in the expression, we have
1256 // the right type already, and the code below would just introduce an
1257 // invalid additional pointer level.
Anders Carlsson96ad5332009-10-21 17:16:23 +00001258 if (FromType->isPointerType() || FromType->isMemberFunctionPointerType())
Sebastian Redl759986e2009-10-17 20:50:27 +00001259 break;
Douglas Gregor904eed32008-11-10 20:40:00 +00001260 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001261 FromType = Context.getPointerType(FromType);
Anders Carlssonb633c4e2009-09-01 20:37:18 +00001262 ImpCastExprToType(From, FromType, CastExpr::CK_FunctionToPointerDecay);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001263 break;
1264
1265 default:
1266 assert(false && "Improper first standard conversion");
1267 break;
1268 }
1269
1270 // Perform the second implicit conversion
1271 switch (SCS.Second) {
1272 case ICK_Identity:
Sebastian Redl2c7588f2009-10-10 12:04:10 +00001273 // If both sides are functions (or pointers/references to them), there could
1274 // be incompatible exception declarations.
1275 if (CheckExceptionSpecCompatibility(From, ToType))
1276 return true;
1277 // Nothing else to do.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001278 break;
1279
Douglas Gregor43c79c22009-12-09 00:47:37 +00001280 case ICK_NoReturn_Adjustment:
1281 // If both sides are functions (or pointers/references to them), there could
1282 // be incompatible exception declarations.
1283 if (CheckExceptionSpecCompatibility(From, ToType))
1284 return true;
1285
1286 ImpCastExprToType(From, Context.getNoReturnType(From->getType(), false),
1287 CastExpr::CK_NoOp);
1288 break;
1289
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001290 case ICK_Integral_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001291 case ICK_Integral_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001292 ImpCastExprToType(From, ToType, CastExpr::CK_IntegralCast);
1293 break;
1294
1295 case ICK_Floating_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001296 case ICK_Floating_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001297 ImpCastExprToType(From, ToType, CastExpr::CK_FloatingCast);
1298 break;
1299
1300 case ICK_Complex_Promotion:
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001301 case ICK_Complex_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001302 ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1303 break;
1304
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001305 case ICK_Floating_Integral:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001306 if (ToType->isFloatingType())
1307 ImpCastExprToType(From, ToType, CastExpr::CK_IntegralToFloating);
1308 else
1309 ImpCastExprToType(From, ToType, CastExpr::CK_FloatingToIntegral);
1310 break;
1311
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001312 case ICK_Complex_Real:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001313 ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1314 break;
1315
Douglas Gregorf9201e02009-02-11 23:02:49 +00001316 case ICK_Compatible_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001317 ImpCastExprToType(From, ToType, CastExpr::CK_NoOp);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001318 break;
1319
Anders Carlsson61faec12009-09-12 04:46:44 +00001320 case ICK_Pointer_Conversion: {
Douglas Gregor45920e82008-12-19 17:40:08 +00001321 if (SCS.IncompatibleObjC) {
1322 // Diagnose incompatible Objective-C conversions
Mike Stump1eb44332009-09-09 15:08:12 +00001323 Diag(From->getSourceRange().getBegin(),
Douglas Gregor45920e82008-12-19 17:40:08 +00001324 diag::ext_typecheck_convert_incompatible_pointer)
Douglas Gregor68647482009-12-16 03:45:30 +00001325 << From->getType() << ToType << Action
Douglas Gregor45920e82008-12-19 17:40:08 +00001326 << From->getSourceRange();
1327 }
1328
Anders Carlsson61faec12009-09-12 04:46:44 +00001329
1330 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001331 if (CheckPointerConversion(From, ToType, Kind, IgnoreBaseAccess))
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001332 return true;
Anders Carlsson61faec12009-09-12 04:46:44 +00001333 ImpCastExprToType(From, ToType, Kind);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001334 break;
Anders Carlsson61faec12009-09-12 04:46:44 +00001335 }
1336
1337 case ICK_Pointer_Member: {
1338 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001339 if (CheckMemberPointerConversion(From, ToType, Kind, IgnoreBaseAccess))
Anders Carlsson61faec12009-09-12 04:46:44 +00001340 return true;
Sebastian Redl2c7588f2009-10-10 12:04:10 +00001341 if (CheckExceptionSpecCompatibility(From, ToType))
1342 return true;
Anders Carlsson61faec12009-09-12 04:46:44 +00001343 ImpCastExprToType(From, ToType, Kind);
1344 break;
1345 }
Anders Carlssonbc0e0782009-11-23 20:04:44 +00001346 case ICK_Boolean_Conversion: {
1347 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
1348 if (FromType->isMemberPointerType())
1349 Kind = CastExpr::CK_MemberPointerToBoolean;
1350
1351 ImpCastExprToType(From, Context.BoolTy, Kind);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001352 break;
Anders Carlssonbc0e0782009-11-23 20:04:44 +00001353 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001354
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001355 case ICK_Derived_To_Base:
1356 if (CheckDerivedToBaseConversion(From->getType(),
1357 ToType.getNonReferenceType(),
1358 From->getLocStart(),
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001359 From->getSourceRange(),
1360 IgnoreBaseAccess))
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001361 return true;
1362 ImpCastExprToType(From, ToType.getNonReferenceType(),
1363 CastExpr::CK_DerivedToBase);
1364 break;
1365
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001366 default:
1367 assert(false && "Improper second standard conversion");
1368 break;
1369 }
1370
1371 switch (SCS.Third) {
1372 case ICK_Identity:
1373 // Nothing to do.
1374 break;
1375
1376 case ICK_Qualification:
Mike Stump390b4cc2009-05-16 07:39:55 +00001377 // FIXME: Not sure about lvalue vs rvalue here in the presence of rvalue
1378 // references.
Mike Stump1eb44332009-09-09 15:08:12 +00001379 ImpCastExprToType(From, ToType.getNonReferenceType(),
Eli Friedman73c39ab2009-10-20 08:27:19 +00001380 CastExpr::CK_NoOp,
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001381 ToType->isLValueReferenceType());
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001382 break;
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001383
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001384 default:
1385 assert(false && "Improper second standard conversion");
1386 break;
1387 }
1388
1389 return false;
1390}
1391
Sebastian Redl64b45f72009-01-05 20:52:13 +00001392Sema::OwningExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
1393 SourceLocation KWLoc,
1394 SourceLocation LParen,
1395 TypeTy *Ty,
1396 SourceLocation RParen) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00001397 QualType T = GetTypeFromParser(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00001398
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001399 // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
1400 // all traits except __is_class, __is_enum and __is_union require a the type
1401 // to be complete.
1402 if (OTT != UTT_IsClass && OTT != UTT_IsEnum && OTT != UTT_IsUnion) {
Mike Stump1eb44332009-09-09 15:08:12 +00001403 if (RequireCompleteType(KWLoc, T,
Anders Carlssond497ba72009-08-26 22:59:12 +00001404 diag::err_incomplete_type_used_in_type_trait_expr))
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001405 return ExprError();
1406 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00001407
1408 // There is no point in eagerly computing the value. The traits are designed
1409 // to be used from type trait templates, so Ty will be a template parameter
1410 // 99% of the time.
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001411 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT, T,
1412 RParen, Context.BoolTy));
Sebastian Redl64b45f72009-01-05 20:52:13 +00001413}
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001414
1415QualType Sema::CheckPointerToMemberOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00001416 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001417 const char *OpSpelling = isIndirect ? "->*" : ".*";
1418 // C++ 5.5p2
1419 // The binary operator .* [p3: ->*] binds its second operand, which shall
1420 // be of type "pointer to member of T" (where T is a completely-defined
1421 // class type) [...]
1422 QualType RType = rex->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001423 const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
Douglas Gregore7450f52009-03-24 19:52:54 +00001424 if (!MemPtr) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001425 Diag(Loc, diag::err_bad_memptr_rhs)
1426 << OpSpelling << RType << rex->getSourceRange();
1427 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00001428 }
Douglas Gregore7450f52009-03-24 19:52:54 +00001429
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001430 QualType Class(MemPtr->getClass(), 0);
1431
1432 // C++ 5.5p2
1433 // [...] to its first operand, which shall be of class T or of a class of
1434 // which T is an unambiguous and accessible base class. [p3: a pointer to
1435 // such a class]
1436 QualType LType = lex->getType();
1437 if (isIndirect) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001438 if (const PointerType *Ptr = LType->getAs<PointerType>())
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001439 LType = Ptr->getPointeeType().getNonReferenceType();
1440 else {
1441 Diag(Loc, diag::err_bad_memptr_lhs)
Fariborz Jahanianef78ac62009-10-26 20:45:27 +00001442 << OpSpelling << 1 << LType
1443 << CodeModificationHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001444 return QualType();
1445 }
1446 }
1447
Douglas Gregora4923eb2009-11-16 21:35:15 +00001448 if (!Context.hasSameUnqualifiedType(Class, LType)) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001449 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1450 /*DetectVirtual=*/false);
Mike Stump390b4cc2009-05-16 07:39:55 +00001451 // FIXME: Would it be useful to print full ambiguity paths, or is that
1452 // overkill?
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001453 if (!IsDerivedFrom(LType, Class, Paths) ||
1454 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
1455 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Eli Friedman3005efe2010-01-16 00:00:48 +00001456 << (int)isIndirect << lex->getType();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001457 return QualType();
1458 }
Eli Friedman3005efe2010-01-16 00:00:48 +00001459 // Cast LHS to type of use.
1460 QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
1461 bool isLValue = !isIndirect && lex->isLvalue(Context) == Expr::LV_Valid;
1462 ImpCastExprToType(lex, UseType, CastExpr::CK_DerivedToBase, isLValue);
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001463 }
1464
Fariborz Jahanian19d70732009-11-18 22:16:17 +00001465 if (isa<CXXZeroInitValueExpr>(rex->IgnoreParens())) {
Fariborz Jahanian05ebda92009-11-18 21:54:48 +00001466 // Diagnose use of pointer-to-member type which when used as
1467 // the functional cast in a pointer-to-member expression.
1468 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
1469 return QualType();
1470 }
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001471 // C++ 5.5p2
1472 // The result is an object or a function of the type specified by the
1473 // second operand.
1474 // The cv qualifiers are the union of those in the pointer and the left side,
1475 // in accordance with 5.5p5 and 5.2.5.
1476 // FIXME: This returns a dereferenced member function pointer as a normal
1477 // function type. However, the only operation valid on such functions is
Mike Stump390b4cc2009-05-16 07:39:55 +00001478 // calling them. There's also a GCC extension to get a function pointer to the
1479 // thing, which is another complication, because this type - unlike the type
1480 // that is the result of this expression - takes the class as the first
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001481 // argument.
1482 // We probably need a "MemberFunctionClosureType" or something like that.
1483 QualType Result = MemPtr->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00001484 Result = Context.getCVRQualifiedType(Result, LType.getCVRQualifiers());
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001485 return Result;
1486}
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001487
1488/// \brief Get the target type of a standard or user-defined conversion.
1489static QualType TargetType(const ImplicitConversionSequence &ICS) {
John McCall1d318332010-01-12 00:44:57 +00001490 switch (ICS.getKind()) {
1491 case ImplicitConversionSequence::StandardConversion:
Douglas Gregorad323a82010-01-27 03:51:04 +00001492 return ICS.Standard.getToType(2);
John McCall1d318332010-01-12 00:44:57 +00001493 case ImplicitConversionSequence::UserDefinedConversion:
Douglas Gregorad323a82010-01-27 03:51:04 +00001494 return ICS.UserDefined.After.getToType(2);
John McCall1d318332010-01-12 00:44:57 +00001495 case ImplicitConversionSequence::AmbiguousConversion:
1496 return ICS.Ambiguous.getToType();
1497 case ImplicitConversionSequence::EllipsisConversion:
1498 case ImplicitConversionSequence::BadConversion:
1499 llvm_unreachable("function not valid for ellipsis or bad conversions");
1500 }
1501 return QualType(); // silence warnings
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001502}
1503
1504/// \brief Try to convert a type to another according to C++0x 5.16p3.
1505///
1506/// This is part of the parameter validation for the ? operator. If either
1507/// value operand is a class type, the two operands are attempted to be
1508/// converted to each other. This function does the conversion in one direction.
1509/// It emits a diagnostic and returns true only if it finds an ambiguous
1510/// conversion.
1511static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
1512 SourceLocation QuestionLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00001513 ImplicitConversionSequence &ICS) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001514 // C++0x 5.16p3
1515 // The process for determining whether an operand expression E1 of type T1
1516 // can be converted to match an operand expression E2 of type T2 is defined
1517 // as follows:
1518 // -- If E2 is an lvalue:
1519 if (To->isLvalue(Self.Context) == Expr::LV_Valid) {
1520 // E1 can be converted to match E2 if E1 can be implicitly converted to
1521 // type "lvalue reference to T2", subject to the constraint that in the
1522 // conversion the reference must bind directly to E1.
1523 if (!Self.CheckReferenceInit(From,
1524 Self.Context.getLValueReferenceType(To->getType()),
Douglas Gregor739d8282009-09-23 23:04:10 +00001525 To->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001526 /*SuppressUserConversions=*/false,
1527 /*AllowExplicit=*/false,
1528 /*ForceRValue=*/false,
1529 &ICS))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001530 {
John McCall1d318332010-01-12 00:44:57 +00001531 assert((ICS.isStandard() || ICS.isUserDefined()) &&
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001532 "expected a definite conversion");
1533 bool DirectBinding =
John McCall1d318332010-01-12 00:44:57 +00001534 ICS.isStandard() ? ICS.Standard.DirectBinding
1535 : ICS.UserDefined.After.DirectBinding;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001536 if (DirectBinding)
1537 return false;
1538 }
1539 }
John McCall1d318332010-01-12 00:44:57 +00001540 ICS.setBad();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001541 // -- If E2 is an rvalue, or if the conversion above cannot be done:
1542 // -- if E1 and E2 have class type, and the underlying class types are
1543 // the same or one is a base class of the other:
1544 QualType FTy = From->getType();
1545 QualType TTy = To->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001546 const RecordType *FRec = FTy->getAs<RecordType>();
1547 const RecordType *TRec = TTy->getAs<RecordType>();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001548 bool FDerivedFromT = FRec && TRec && Self.IsDerivedFrom(FTy, TTy);
1549 if (FRec && TRec && (FRec == TRec ||
1550 FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
1551 // E1 can be converted to match E2 if the class of T2 is the
1552 // same type as, or a base class of, the class of T1, and
1553 // [cv2 > cv1].
1554 if ((FRec == TRec || FDerivedFromT) && TTy.isAtLeastAsQualifiedAs(FTy)) {
1555 // Could still fail if there's no copy constructor.
1556 // FIXME: Is this a hard error then, or just a conversion failure? The
1557 // standard doesn't say.
Mike Stump1eb44332009-09-09 15:08:12 +00001558 ICS = Self.TryCopyInitialization(From, TTy,
Anders Carlssond28b4282009-08-27 17:18:13 +00001559 /*SuppressUserConversions=*/false,
Anders Carlsson7b361b52009-08-27 17:37:39 +00001560 /*ForceRValue=*/false,
1561 /*InOverloadResolution=*/false);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001562 }
1563 } else {
1564 // -- Otherwise: E1 can be converted to match E2 if E1 can be
1565 // implicitly converted to the type that expression E2 would have
1566 // if E2 were converted to an rvalue.
1567 // First find the decayed type.
1568 if (TTy->isFunctionType())
1569 TTy = Self.Context.getPointerType(TTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001570 else if (TTy->isArrayType())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001571 TTy = Self.Context.getArrayDecayedType(TTy);
1572
1573 // Now try the implicit conversion.
1574 // FIXME: This doesn't detect ambiguities.
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001575 ICS = Self.TryImplicitConversion(From, TTy,
1576 /*SuppressUserConversions=*/false,
1577 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00001578 /*ForceRValue=*/false,
1579 /*InOverloadResolution=*/false);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001580 }
1581 return false;
1582}
1583
1584/// \brief Try to find a common type for two according to C++0x 5.16p5.
1585///
1586/// This is part of the parameter validation for the ? operator. If either
1587/// value operand is a class type, overload resolution is used to find a
1588/// conversion to a common type.
1589static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
1590 SourceLocation Loc) {
1591 Expr *Args[2] = { LHS, RHS };
John McCall5769d612010-02-08 23:07:23 +00001592 OverloadCandidateSet CandidateSet(Loc);
Douglas Gregor573d9c32009-10-21 23:19:44 +00001593 Self.AddBuiltinOperatorCandidates(OO_Conditional, Loc, Args, 2, CandidateSet);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001594
1595 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00001596 switch (Self.BestViableFunction(CandidateSet, Loc, Best)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00001597 case OR_Success:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001598 // We found a match. Perform the conversions on the arguments and move on.
1599 if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00001600 Best->Conversions[0], Sema::AA_Converting) ||
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001601 Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor68647482009-12-16 03:45:30 +00001602 Best->Conversions[1], Sema::AA_Converting))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001603 break;
1604 return false;
1605
Douglas Gregor20093b42009-12-09 23:02:17 +00001606 case OR_No_Viable_Function:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001607 Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
1608 << LHS->getType() << RHS->getType()
1609 << LHS->getSourceRange() << RHS->getSourceRange();
1610 return true;
1611
Douglas Gregor20093b42009-12-09 23:02:17 +00001612 case OR_Ambiguous:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001613 Self.Diag(Loc, diag::err_conditional_ambiguous_ovl)
1614 << LHS->getType() << RHS->getType()
1615 << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stump390b4cc2009-05-16 07:39:55 +00001616 // FIXME: Print the possible common types by printing the return types of
1617 // the viable candidates.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001618 break;
1619
Douglas Gregor20093b42009-12-09 23:02:17 +00001620 case OR_Deleted:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001621 assert(false && "Conditional operator has only built-in overloads");
1622 break;
1623 }
1624 return true;
1625}
1626
Sebastian Redl76458502009-04-17 16:30:52 +00001627/// \brief Perform an "extended" implicit conversion as returned by
1628/// TryClassUnification.
1629///
1630/// TryClassUnification generates ICSs that include reference bindings.
1631/// PerformImplicitConversion is not suitable for this; it chokes if the
1632/// second part of a standard conversion is ICK_DerivedToBase. This function
1633/// handles the reference binding specially.
1634static bool ConvertForConditional(Sema &Self, Expr *&E,
Mike Stump1eb44332009-09-09 15:08:12 +00001635 const ImplicitConversionSequence &ICS) {
John McCall1d318332010-01-12 00:44:57 +00001636 if (ICS.isStandard() && ICS.Standard.ReferenceBinding) {
Sebastian Redl76458502009-04-17 16:30:52 +00001637 assert(ICS.Standard.DirectBinding &&
1638 "TryClassUnification should never generate indirect ref bindings");
Sebastian Redla5cd2cd2009-04-26 11:21:02 +00001639 // FIXME: CheckReferenceInit should be able to reuse the ICS instead of
1640 // redoing all the work.
1641 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001642 TargetType(ICS)),
Douglas Gregor739d8282009-09-23 23:04:10 +00001643 /*FIXME:*/E->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001644 /*SuppressUserConversions=*/false,
1645 /*AllowExplicit=*/false,
1646 /*ForceRValue=*/false);
Sebastian Redl76458502009-04-17 16:30:52 +00001647 }
John McCall1d318332010-01-12 00:44:57 +00001648 if (ICS.isUserDefined() && ICS.UserDefined.After.ReferenceBinding) {
Sebastian Redl76458502009-04-17 16:30:52 +00001649 assert(ICS.UserDefined.After.DirectBinding &&
1650 "TryClassUnification should never generate indirect ref bindings");
Sebastian Redla5cd2cd2009-04-26 11:21:02 +00001651 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001652 TargetType(ICS)),
Douglas Gregor739d8282009-09-23 23:04:10 +00001653 /*FIXME:*/E->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001654 /*SuppressUserConversions=*/false,
1655 /*AllowExplicit=*/false,
1656 /*ForceRValue=*/false);
Sebastian Redl76458502009-04-17 16:30:52 +00001657 }
Douglas Gregor68647482009-12-16 03:45:30 +00001658 if (Self.PerformImplicitConversion(E, TargetType(ICS), ICS, Sema::AA_Converting))
Sebastian Redl76458502009-04-17 16:30:52 +00001659 return true;
1660 return false;
1661}
1662
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001663/// \brief Check the operands of ?: under C++ semantics.
1664///
1665/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
1666/// extension. In this case, LHS == Cond. (But they're not aliases.)
1667QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
1668 SourceLocation QuestionLoc) {
Mike Stump390b4cc2009-05-16 07:39:55 +00001669 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
1670 // interface pointers.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001671
1672 // C++0x 5.16p1
1673 // The first expression is contextually converted to bool.
1674 if (!Cond->isTypeDependent()) {
1675 if (CheckCXXBooleanCondition(Cond))
1676 return QualType();
1677 }
1678
1679 // Either of the arguments dependent?
1680 if (LHS->isTypeDependent() || RHS->isTypeDependent())
1681 return Context.DependentTy;
1682
John McCallb13c87f2009-11-05 09:23:39 +00001683 CheckSignCompare(LHS, RHS, QuestionLoc, diag::warn_mixed_sign_conditional);
1684
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001685 // C++0x 5.16p2
1686 // If either the second or the third operand has type (cv) void, ...
1687 QualType LTy = LHS->getType();
1688 QualType RTy = RHS->getType();
1689 bool LVoid = LTy->isVoidType();
1690 bool RVoid = RTy->isVoidType();
1691 if (LVoid || RVoid) {
1692 // ... then the [l2r] conversions are performed on the second and third
1693 // operands ...
Douglas Gregora873dfc2010-02-03 00:27:59 +00001694 DefaultFunctionArrayLvalueConversion(LHS);
1695 DefaultFunctionArrayLvalueConversion(RHS);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001696 LTy = LHS->getType();
1697 RTy = RHS->getType();
1698
1699 // ... and one of the following shall hold:
1700 // -- The second or the third operand (but not both) is a throw-
1701 // expression; the result is of the type of the other and is an rvalue.
1702 bool LThrow = isa<CXXThrowExpr>(LHS);
1703 bool RThrow = isa<CXXThrowExpr>(RHS);
1704 if (LThrow && !RThrow)
1705 return RTy;
1706 if (RThrow && !LThrow)
1707 return LTy;
1708
1709 // -- Both the second and third operands have type void; the result is of
1710 // type void and is an rvalue.
1711 if (LVoid && RVoid)
1712 return Context.VoidTy;
1713
1714 // Neither holds, error.
1715 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
1716 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
1717 << LHS->getSourceRange() << RHS->getSourceRange();
1718 return QualType();
1719 }
1720
1721 // Neither is void.
1722
1723 // C++0x 5.16p3
1724 // Otherwise, if the second and third operand have different types, and
1725 // either has (cv) class type, and attempt is made to convert each of those
1726 // operands to the other.
1727 if (Context.getCanonicalType(LTy) != Context.getCanonicalType(RTy) &&
1728 (LTy->isRecordType() || RTy->isRecordType())) {
1729 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
1730 // These return true if a single direction is already ambiguous.
1731 if (TryClassUnification(*this, LHS, RHS, QuestionLoc, ICSLeftToRight))
1732 return QualType();
1733 if (TryClassUnification(*this, RHS, LHS, QuestionLoc, ICSRightToLeft))
1734 return QualType();
1735
John McCall1d318332010-01-12 00:44:57 +00001736 bool HaveL2R = !ICSLeftToRight.isBad();
1737 bool HaveR2L = !ICSRightToLeft.isBad();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001738 // If both can be converted, [...] the program is ill-formed.
1739 if (HaveL2R && HaveR2L) {
1740 Diag(QuestionLoc, diag::err_conditional_ambiguous)
1741 << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
1742 return QualType();
1743 }
1744
1745 // If exactly one conversion is possible, that conversion is applied to
1746 // the chosen operand and the converted operands are used in place of the
1747 // original operands for the remainder of this section.
1748 if (HaveL2R) {
Sebastian Redl76458502009-04-17 16:30:52 +00001749 if (ConvertForConditional(*this, LHS, ICSLeftToRight))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001750 return QualType();
1751 LTy = LHS->getType();
1752 } else if (HaveR2L) {
Sebastian Redl76458502009-04-17 16:30:52 +00001753 if (ConvertForConditional(*this, RHS, ICSRightToLeft))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001754 return QualType();
1755 RTy = RHS->getType();
1756 }
1757 }
1758
1759 // C++0x 5.16p4
1760 // If the second and third operands are lvalues and have the same type,
1761 // the result is of that type [...]
1762 bool Same = Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy);
1763 if (Same && LHS->isLvalue(Context) == Expr::LV_Valid &&
1764 RHS->isLvalue(Context) == Expr::LV_Valid)
1765 return LTy;
1766
1767 // C++0x 5.16p5
1768 // Otherwise, the result is an rvalue. If the second and third operands
1769 // do not have the same type, and either has (cv) class type, ...
1770 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
1771 // ... overload resolution is used to determine the conversions (if any)
1772 // to be applied to the operands. If the overload resolution fails, the
1773 // program is ill-formed.
1774 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
1775 return QualType();
1776 }
1777
1778 // C++0x 5.16p6
1779 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
1780 // conversions are performed on the second and third operands.
Douglas Gregora873dfc2010-02-03 00:27:59 +00001781 DefaultFunctionArrayLvalueConversion(LHS);
1782 DefaultFunctionArrayLvalueConversion(RHS);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001783 LTy = LHS->getType();
1784 RTy = RHS->getType();
1785
1786 // After those conversions, one of the following shall hold:
1787 // -- The second and third operands have the same type; the result
1788 // is of that type.
1789 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy))
1790 return LTy;
1791
1792 // -- The second and third operands have arithmetic or enumeration type;
1793 // the usual arithmetic conversions are performed to bring them to a
1794 // common type, and the result is of that type.
1795 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
1796 UsualArithmeticConversions(LHS, RHS);
1797 return LHS->getType();
1798 }
1799
1800 // -- The second and third operands have pointer type, or one has pointer
1801 // type and the other is a null pointer constant; pointer conversions
1802 // and qualification conversions are performed to bring them to their
1803 // composite pointer type. The result is of the composite pointer type.
Eli Friedmande8ac492010-01-02 22:56:07 +00001804 // -- The second and third operands have pointer to member type, or one has
1805 // pointer to member type and the other is a null pointer constant;
1806 // pointer to member conversions and qualification conversions are
1807 // performed to bring them to a common type, whose cv-qualification
1808 // shall match the cv-qualification of either the second or the third
1809 // operand. The result is of the common type.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001810 QualType Composite = FindCompositePointerType(LHS, RHS);
1811 if (!Composite.isNull())
1812 return Composite;
Fariborz Jahanian55016362009-12-10 20:46:08 +00001813
1814 // Similarly, attempt to find composite type of twp objective-c pointers.
1815 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
1816 if (!Composite.isNull())
1817 return Composite;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001818
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001819 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
1820 << LHS->getType() << RHS->getType()
1821 << LHS->getSourceRange() << RHS->getSourceRange();
1822 return QualType();
1823}
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001824
1825/// \brief Find a merged pointer type and convert the two expressions to it.
1826///
Douglas Gregor20b3e992009-08-24 17:42:35 +00001827/// This finds the composite pointer type (or member pointer type) for @p E1
1828/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
1829/// type and returns it.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001830/// It does not emit diagnostics.
1831QualType Sema::FindCompositePointerType(Expr *&E1, Expr *&E2) {
1832 assert(getLangOptions().CPlusPlus && "This function assumes C++");
1833 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001834
Fariborz Jahanian0cedfbd2009-12-08 20:04:24 +00001835 if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
1836 !T2->isAnyPointerType() && !T2->isMemberPointerType())
Douglas Gregor20b3e992009-08-24 17:42:35 +00001837 return QualType();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001838
1839 // C++0x 5.9p2
1840 // Pointer conversions and qualification conversions are performed on
1841 // pointer operands to bring them to their composite pointer type. If
1842 // one operand is a null pointer constant, the composite pointer type is
1843 // the type of the other operand.
Douglas Gregorce940492009-09-25 04:25:58 +00001844 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00001845 if (T2->isMemberPointerType())
1846 ImpCastExprToType(E1, T2, CastExpr::CK_NullToMemberPointer);
1847 else
1848 ImpCastExprToType(E1, T2, CastExpr::CK_IntegralToPointer);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001849 return T2;
1850 }
Douglas Gregorce940492009-09-25 04:25:58 +00001851 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00001852 if (T1->isMemberPointerType())
1853 ImpCastExprToType(E2, T1, CastExpr::CK_NullToMemberPointer);
1854 else
1855 ImpCastExprToType(E2, T1, CastExpr::CK_IntegralToPointer);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001856 return T1;
1857 }
Mike Stump1eb44332009-09-09 15:08:12 +00001858
Douglas Gregor20b3e992009-08-24 17:42:35 +00001859 // Now both have to be pointers or member pointers.
Sebastian Redla439e6f2009-11-16 21:03:45 +00001860 if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
1861 (!T2->isPointerType() && !T2->isMemberPointerType()))
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001862 return QualType();
1863
1864 // Otherwise, of one of the operands has type "pointer to cv1 void," then
1865 // the other has type "pointer to cv2 T" and the composite pointer type is
1866 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
1867 // Otherwise, the composite pointer type is a pointer type similar to the
1868 // type of one of the operands, with a cv-qualification signature that is
1869 // the union of the cv-qualification signatures of the operand types.
1870 // In practice, the first part here is redundant; it's subsumed by the second.
1871 // What we do here is, we build the two possible composite types, and try the
1872 // conversions in both directions. If only one works, or if the two composite
1873 // types are the same, we have succeeded.
John McCall0953e762009-09-24 19:53:00 +00001874 // FIXME: extended qualifiers?
Sebastian Redla439e6f2009-11-16 21:03:45 +00001875 typedef llvm::SmallVector<unsigned, 4> QualifierVector;
1876 QualifierVector QualifierUnion;
1877 typedef llvm::SmallVector<std::pair<const Type *, const Type *>, 4>
1878 ContainingClassVector;
1879 ContainingClassVector MemberOfClass;
1880 QualType Composite1 = Context.getCanonicalType(T1),
1881 Composite2 = Context.getCanonicalType(T2);
Douglas Gregor20b3e992009-08-24 17:42:35 +00001882 do {
1883 const PointerType *Ptr1, *Ptr2;
1884 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
1885 (Ptr2 = Composite2->getAs<PointerType>())) {
1886 Composite1 = Ptr1->getPointeeType();
1887 Composite2 = Ptr2->getPointeeType();
1888 QualifierUnion.push_back(
1889 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
1890 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
1891 continue;
1892 }
Mike Stump1eb44332009-09-09 15:08:12 +00001893
Douglas Gregor20b3e992009-08-24 17:42:35 +00001894 const MemberPointerType *MemPtr1, *MemPtr2;
1895 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
1896 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
1897 Composite1 = MemPtr1->getPointeeType();
1898 Composite2 = MemPtr2->getPointeeType();
1899 QualifierUnion.push_back(
1900 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
1901 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
1902 MemPtr2->getClass()));
1903 continue;
1904 }
Mike Stump1eb44332009-09-09 15:08:12 +00001905
Douglas Gregor20b3e992009-08-24 17:42:35 +00001906 // FIXME: block pointer types?
Mike Stump1eb44332009-09-09 15:08:12 +00001907
Douglas Gregor20b3e992009-08-24 17:42:35 +00001908 // Cannot unwrap any more types.
1909 break;
1910 } while (true);
Mike Stump1eb44332009-09-09 15:08:12 +00001911
Douglas Gregor20b3e992009-08-24 17:42:35 +00001912 // Rewrap the composites as pointers or member pointers with the union CVRs.
Sebastian Redla439e6f2009-11-16 21:03:45 +00001913 ContainingClassVector::reverse_iterator MOC
1914 = MemberOfClass.rbegin();
1915 for (QualifierVector::reverse_iterator
1916 I = QualifierUnion.rbegin(),
1917 E = QualifierUnion.rend();
Douglas Gregor20b3e992009-08-24 17:42:35 +00001918 I != E; (void)++I, ++MOC) {
John McCall0953e762009-09-24 19:53:00 +00001919 Qualifiers Quals = Qualifiers::fromCVRMask(*I);
Douglas Gregor20b3e992009-08-24 17:42:35 +00001920 if (MOC->first && MOC->second) {
1921 // Rebuild member pointer type
John McCall0953e762009-09-24 19:53:00 +00001922 Composite1 = Context.getMemberPointerType(
1923 Context.getQualifiedType(Composite1, Quals),
1924 MOC->first);
1925 Composite2 = Context.getMemberPointerType(
1926 Context.getQualifiedType(Composite2, Quals),
1927 MOC->second);
Douglas Gregor20b3e992009-08-24 17:42:35 +00001928 } else {
1929 // Rebuild pointer type
John McCall0953e762009-09-24 19:53:00 +00001930 Composite1
1931 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
1932 Composite2
1933 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregor20b3e992009-08-24 17:42:35 +00001934 }
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001935 }
1936
Mike Stump1eb44332009-09-09 15:08:12 +00001937 ImplicitConversionSequence E1ToC1 =
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001938 TryImplicitConversion(E1, Composite1,
1939 /*SuppressUserConversions=*/false,
1940 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00001941 /*ForceRValue=*/false,
1942 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00001943 ImplicitConversionSequence E2ToC1 =
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001944 TryImplicitConversion(E2, Composite1,
1945 /*SuppressUserConversions=*/false,
1946 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00001947 /*ForceRValue=*/false,
1948 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00001949
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001950 ImplicitConversionSequence E1ToC2, E2ToC2;
John McCall1d318332010-01-12 00:44:57 +00001951 E1ToC2.setBad();
John McCalladbb8f82010-01-13 09:16:55 +00001952 E2ToC2.setBad();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001953 if (Context.getCanonicalType(Composite1) !=
1954 Context.getCanonicalType(Composite2)) {
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001955 E1ToC2 = TryImplicitConversion(E1, Composite2,
1956 /*SuppressUserConversions=*/false,
1957 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00001958 /*ForceRValue=*/false,
1959 /*InOverloadResolution=*/false);
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001960 E2ToC2 = TryImplicitConversion(E2, Composite2,
1961 /*SuppressUserConversions=*/false,
1962 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00001963 /*ForceRValue=*/false,
1964 /*InOverloadResolution=*/false);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001965 }
1966
John McCall1d318332010-01-12 00:44:57 +00001967 bool ToC1Viable = !E1ToC1.isBad() && !E2ToC1.isBad();
1968 bool ToC2Viable = !E1ToC2.isBad() && !E2ToC2.isBad();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001969 if (ToC1Viable && !ToC2Viable) {
Douglas Gregor68647482009-12-16 03:45:30 +00001970 if (!PerformImplicitConversion(E1, Composite1, E1ToC1, Sema::AA_Converting) &&
1971 !PerformImplicitConversion(E2, Composite1, E2ToC1, Sema::AA_Converting))
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001972 return Composite1;
1973 }
1974 if (ToC2Viable && !ToC1Viable) {
Douglas Gregor68647482009-12-16 03:45:30 +00001975 if (!PerformImplicitConversion(E1, Composite2, E1ToC2, Sema::AA_Converting) &&
1976 !PerformImplicitConversion(E2, Composite2, E2ToC2, Sema::AA_Converting))
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001977 return Composite2;
1978 }
1979 return QualType();
1980}
Anders Carlsson165a0a02009-05-17 18:41:29 +00001981
Anders Carlssondef11992009-05-30 20:36:53 +00001982Sema::OwningExprResult Sema::MaybeBindToTemporary(Expr *E) {
Anders Carlsson089c2602009-08-15 23:41:35 +00001983 if (!Context.getLangOptions().CPlusPlus)
1984 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001985
Douglas Gregor51326552009-12-24 18:51:59 +00001986 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
1987
Ted Kremenek6217b802009-07-29 21:53:49 +00001988 const RecordType *RT = E->getType()->getAs<RecordType>();
Anders Carlssondef11992009-05-30 20:36:53 +00001989 if (!RT)
1990 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001991
John McCall86ff3082010-02-04 22:26:26 +00001992 // If this is the result of a call expression, our source might
1993 // actually be a reference, in which case we shouldn't bind.
Anders Carlsson283e4d52009-09-14 01:30:44 +00001994 if (CallExpr *CE = dyn_cast<CallExpr>(E)) {
1995 QualType Ty = CE->getCallee()->getType();
1996 if (const PointerType *PT = Ty->getAs<PointerType>())
1997 Ty = PT->getPointeeType();
1998
John McCall183700f2009-09-21 23:43:11 +00001999 const FunctionType *FTy = Ty->getAs<FunctionType>();
Anders Carlsson283e4d52009-09-14 01:30:44 +00002000 if (FTy->getResultType()->isReferenceType())
2001 return Owned(E);
2002 }
John McCall86ff3082010-02-04 22:26:26 +00002003
2004 // That should be enough to guarantee that this type is complete.
2005 // If it has a trivial destructor, we can avoid the extra copy.
2006 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2007 if (RD->hasTrivialDestructor())
2008 return Owned(E);
2009
Mike Stump1eb44332009-09-09 15:08:12 +00002010 CXXTemporary *Temp = CXXTemporary::Create(Context,
Anders Carlssondef11992009-05-30 20:36:53 +00002011 RD->getDestructor(Context));
Anders Carlsson860306e2009-05-30 21:21:49 +00002012 ExprTemporaries.push_back(Temp);
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00002013 if (CXXDestructorDecl *Destructor =
2014 const_cast<CXXDestructorDecl*>(RD->getDestructor(Context)))
2015 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
Anders Carlssondef11992009-05-30 20:36:53 +00002016 // FIXME: Add the temporary to the temporaries vector.
2017 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
2018}
2019
Anders Carlsson0ece4912009-12-15 20:51:39 +00002020Expr *Sema::MaybeCreateCXXExprWithTemporaries(Expr *SubExpr) {
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002021 assert(SubExpr && "sub expression can't be null!");
Mike Stump1eb44332009-09-09 15:08:12 +00002022
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00002023 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
2024 assert(ExprTemporaries.size() >= FirstTemporary);
2025 if (ExprTemporaries.size() == FirstTemporary)
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002026 return SubExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00002027
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002028 Expr *E = CXXExprWithTemporaries::Create(Context, SubExpr,
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00002029 &ExprTemporaries[FirstTemporary],
Anders Carlsson0ece4912009-12-15 20:51:39 +00002030 ExprTemporaries.size() - FirstTemporary);
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00002031 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
2032 ExprTemporaries.end());
Mike Stump1eb44332009-09-09 15:08:12 +00002033
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002034 return E;
2035}
2036
Douglas Gregor90f93822009-12-22 22:17:25 +00002037Sema::OwningExprResult
2038Sema::MaybeCreateCXXExprWithTemporaries(OwningExprResult SubExpr) {
2039 if (SubExpr.isInvalid())
2040 return ExprError();
2041
2042 return Owned(MaybeCreateCXXExprWithTemporaries(SubExpr.takeAs<Expr>()));
2043}
2044
Anders Carlsson5ee56e92009-12-16 02:09:40 +00002045FullExpr Sema::CreateFullExpr(Expr *SubExpr) {
2046 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
2047 assert(ExprTemporaries.size() >= FirstTemporary);
2048
2049 unsigned NumTemporaries = ExprTemporaries.size() - FirstTemporary;
2050 CXXTemporary **Temporaries =
2051 NumTemporaries == 0 ? 0 : &ExprTemporaries[FirstTemporary];
2052
2053 FullExpr E = FullExpr::Create(Context, SubExpr, Temporaries, NumTemporaries);
2054
2055 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
2056 ExprTemporaries.end());
2057
2058 return E;
2059}
2060
Mike Stump1eb44332009-09-09 15:08:12 +00002061Sema::OwningExprResult
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002062Sema::ActOnStartCXXMemberReference(Scope *S, ExprArg Base, SourceLocation OpLoc,
2063 tok::TokenKind OpKind, TypeTy *&ObjectType) {
2064 // Since this might be a postfix expression, get rid of ParenListExprs.
2065 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
Mike Stump1eb44332009-09-09 15:08:12 +00002066
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002067 Expr *BaseExpr = (Expr*)Base.get();
2068 assert(BaseExpr && "no record expansion");
Mike Stump1eb44332009-09-09 15:08:12 +00002069
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002070 QualType BaseType = BaseExpr->getType();
2071 if (BaseType->isDependentType()) {
Douglas Gregor43d88632009-11-04 22:49:18 +00002072 // If we have a pointer to a dependent type and are using the -> operator,
2073 // the object type is the type that the pointer points to. We might still
2074 // have enough information about that type to do something useful.
2075 if (OpKind == tok::arrow)
2076 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
2077 BaseType = Ptr->getPointeeType();
2078
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002079 ObjectType = BaseType.getAsOpaquePtr();
2080 return move(Base);
2081 }
Mike Stump1eb44332009-09-09 15:08:12 +00002082
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002083 // C++ [over.match.oper]p8:
Mike Stump1eb44332009-09-09 15:08:12 +00002084 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002085 // returned, with the original second operand.
2086 if (OpKind == tok::arrow) {
John McCallc4e83212009-09-30 01:01:30 +00002087 // The set of types we've considered so far.
John McCall432887f2009-09-30 01:30:54 +00002088 llvm::SmallPtrSet<CanQualType,8> CTypes;
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002089 llvm::SmallVector<SourceLocation, 8> Locations;
John McCall432887f2009-09-30 01:30:54 +00002090 CTypes.insert(Context.getCanonicalType(BaseType));
John McCallc4e83212009-09-30 01:01:30 +00002091
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002092 while (BaseType->isRecordType()) {
Anders Carlsson15ea3782009-10-13 22:43:21 +00002093 Base = BuildOverloadedArrowExpr(S, move(Base), OpLoc);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002094 BaseExpr = (Expr*)Base.get();
2095 if (BaseExpr == NULL)
2096 return ExprError();
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002097 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(BaseExpr))
Anders Carlssonde699e52009-10-13 22:55:59 +00002098 Locations.push_back(OpCall->getDirectCallee()->getLocation());
John McCallc4e83212009-09-30 01:01:30 +00002099 BaseType = BaseExpr->getType();
2100 CanQualType CBaseType = Context.getCanonicalType(BaseType);
John McCall432887f2009-09-30 01:30:54 +00002101 if (!CTypes.insert(CBaseType)) {
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00002102 Diag(OpLoc, diag::err_operator_arrow_circular);
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002103 for (unsigned i = 0; i < Locations.size(); i++)
2104 Diag(Locations[i], diag::note_declared_at);
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00002105 return ExprError();
2106 }
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002107 }
Mike Stump1eb44332009-09-09 15:08:12 +00002108
Douglas Gregor31658df2009-11-20 19:58:21 +00002109 if (BaseType->isPointerType())
2110 BaseType = BaseType->getPointeeType();
2111 }
Mike Stump1eb44332009-09-09 15:08:12 +00002112
2113 // We could end up with various non-record types here, such as extended
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002114 // vector types or Objective-C interfaces. Just return early and let
2115 // ActOnMemberReferenceExpr do the work.
Douglas Gregorc68afe22009-09-03 21:38:09 +00002116 if (!BaseType->isRecordType()) {
2117 // C++ [basic.lookup.classref]p2:
2118 // [...] If the type of the object expression is of pointer to scalar
2119 // type, the unqualified-id is looked up in the context of the complete
2120 // postfix-expression.
2121 ObjectType = 0;
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002122 return move(Base);
Douglas Gregorc68afe22009-09-03 21:38:09 +00002123 }
Mike Stump1eb44332009-09-09 15:08:12 +00002124
Douglas Gregor03c57052009-11-17 05:17:33 +00002125 // The object type must be complete (or dependent).
2126 if (!BaseType->isDependentType() &&
2127 RequireCompleteType(OpLoc, BaseType,
2128 PDiag(diag::err_incomplete_member_access)))
2129 return ExprError();
2130
Douglas Gregorc68afe22009-09-03 21:38:09 +00002131 // C++ [basic.lookup.classref]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00002132 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor03c57052009-11-17 05:17:33 +00002133 // unqualified-id, and the type of the object expression is of a class
Douglas Gregorc68afe22009-09-03 21:38:09 +00002134 // type C (or of pointer to a class type C), the unqualified-id is looked
2135 // up in the scope of class C. [...]
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002136 ObjectType = BaseType.getAsOpaquePtr();
Douglas Gregor03c57052009-11-17 05:17:33 +00002137
Mike Stump1eb44332009-09-09 15:08:12 +00002138 return move(Base);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002139}
2140
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002141CXXMemberCallExpr *Sema::BuildCXXMemberCallExpr(Expr *Exp,
2142 CXXMethodDecl *Method) {
Eli Friedman772fffa2009-12-09 04:53:56 +00002143 if (PerformObjectArgumentInitialization(Exp, Method))
2144 assert(0 && "Calling BuildCXXMemberCallExpr with invalid call?");
2145
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002146 MemberExpr *ME =
2147 new (Context) MemberExpr(Exp, /*IsArrow=*/false, Method,
2148 SourceLocation(), Method->getType());
Eli Friedman772fffa2009-12-09 04:53:56 +00002149 QualType ResultType = Method->getResultType().getNonReferenceType();
Douglas Gregor7edfb692009-11-23 12:27:39 +00002150 MarkDeclarationReferenced(Exp->getLocStart(), Method);
2151 CXXMemberCallExpr *CE =
2152 new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType,
2153 Exp->getLocEnd());
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002154 return CE;
2155}
2156
Anders Carlsson0aebc812009-09-09 21:33:21 +00002157Sema::OwningExprResult Sema::BuildCXXCastArgument(SourceLocation CastLoc,
2158 QualType Ty,
2159 CastExpr::CastKind Kind,
2160 CXXMethodDecl *Method,
2161 ExprArg Arg) {
2162 Expr *From = Arg.takeAs<Expr>();
2163
2164 switch (Kind) {
2165 default: assert(0 && "Unhandled cast kind!");
2166 case CastExpr::CK_ConstructorConversion: {
Douglas Gregor39da0b82009-09-09 23:08:42 +00002167 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
2168
2169 if (CompleteConstructorCall(cast<CXXConstructorDecl>(Method),
2170 MultiExprArg(*this, (void **)&From, 1),
2171 CastLoc, ConstructorArgs))
2172 return ExprError();
Anders Carlsson4fa26842009-10-18 21:20:14 +00002173
2174 OwningExprResult Result =
2175 BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
2176 move_arg(ConstructorArgs));
2177 if (Result.isInvalid())
2178 return ExprError();
2179
2180 return MaybeBindToTemporary(Result.takeAs<Expr>());
Anders Carlsson0aebc812009-09-09 21:33:21 +00002181 }
2182
2183 case CastExpr::CK_UserDefinedConversion: {
Anders Carlssonaac6e3a2009-09-15 07:42:44 +00002184 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
Eli Friedman772fffa2009-12-09 04:53:56 +00002185
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002186 // Create an implicit call expr that calls it.
2187 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(From, Method);
Anders Carlsson4fa26842009-10-18 21:20:14 +00002188 return MaybeBindToTemporary(CE);
Anders Carlsson0aebc812009-09-09 21:33:21 +00002189 }
Anders Carlsson0aebc812009-09-09 21:33:21 +00002190 }
2191}
2192
Anders Carlsson165a0a02009-05-17 18:41:29 +00002193Sema::OwningExprResult Sema::ActOnFinishFullExpr(ExprArg Arg) {
2194 Expr *FullExpr = Arg.takeAs<Expr>();
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002195 if (FullExpr)
Anders Carlsson0ece4912009-12-15 20:51:39 +00002196 FullExpr = MaybeCreateCXXExprWithTemporaries(FullExpr);
Anders Carlssonec773872009-08-25 23:46:41 +00002197
Anders Carlsson165a0a02009-05-17 18:41:29 +00002198 return Owned(FullExpr);
2199}