blob: 9033137898592b57e83617c7e68581288702e536 [file] [log] [blame]
Chris Lattner29375652006-12-04 18:06:35 +00001//===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner29375652006-12-04 18:06:35 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Douglas Gregor3e1e5272009-12-09 23:02:17 +000015#include "SemaInit.h"
John McCall5cebab12009-11-18 07:57:50 +000016#include "Lookup.h"
Steve Naroffaac94152007-08-25 14:02:58 +000017#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000018#include "clang/AST/CXXInheritance.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000019#include "clang/AST/ExprCXX.h"
20#include "clang/Basic/PartialDiagnostic.h"
Sebastian Redlfaf68082008-12-03 20:26:15 +000021#include "clang/Basic/TargetInfo.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000022#include "clang/Lex/Preprocessor.h"
23#include "clang/Parse/DeclSpec.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000024#include "llvm/ADT/STLExtras.h"
Chris Lattner29375652006-12-04 18:06:35 +000025using namespace clang;
26
Sebastian Redlc4704762008-11-11 11:37:55 +000027/// ActOnCXXTypeidOfType - Parse typeid( type-id ).
Sebastian Redl6d4256c2009-03-15 17:47:39 +000028Action::OwningExprResult
Sebastian Redlc4704762008-11-11 11:37:55 +000029Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
30 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Douglas Gregor87f54062009-09-15 22:30:29 +000031 if (!StdNamespace)
Sebastian Redl6d4256c2009-03-15 17:47:39 +000032 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +000033
Douglas Gregorf45f6822009-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 Kyrtzidisc7148c92009-08-19 01:28:28 +000038 // FIXME: Preserve type source info.
Douglas Gregorf45f6822009-12-23 20:51:04 +000039 // FIXME: Preserve the type before we stripped the cv-qualifiers?
Douglas Gregor721fb2b2009-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 Gregorf45f6822009-12-23 20:51:04 +000056 }
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +000057
Chris Lattnerec7f7732008-11-20 05:51:55 +000058 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
John McCall27b18f82009-11-17 02:14:36 +000059 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
60 LookupQualifiedName(R, StdNamespace);
John McCall67c00872009-12-02 08:25:40 +000061 RecordDecl *TypeInfoRecordDecl = R.getAsSingle<RecordDecl>();
Chris Lattnerec7f7732008-11-20 05:51:55 +000062 if (!TypeInfoRecordDecl)
Sebastian Redl6d4256c2009-03-15 17:47:39 +000063 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Sebastian Redlc4704762008-11-11 11:37:55 +000064
65 QualType TypeInfoType = Context.getTypeDeclType(TypeInfoRecordDecl);
66
Douglas Gregor0b6a6242009-06-22 20:57:11 +000067 if (!isType) {
Douglas Gregor0b6a6242009-06-22 20:57:11 +000068 bool isUnevaluatedOperand = true;
69 Expr *E = static_cast<Expr *>(TyOrExpr);
Douglas Gregorf45f6822009-12-23 20:51:04 +000070 if (E && !E->isTypeDependent()) {
Douglas Gregor0b6a6242009-06-22 20:57:11 +000071 QualType T = E->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +000072 if (const RecordType *RecordT = T->getAs<RecordType>()) {
Douglas Gregor0b6a6242009-06-22 20:57:11 +000073 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
Douglas Gregorf45f6822009-12-23 20:51:04 +000074 // C++ [expr.typeid]p3:
John McCall67da35c2010-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 Gregorf45f6822009-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 Gregor0b6a6242009-06-22 20:57:11 +000085 isUnevaluatedOperand = false;
Douglas Gregorf45f6822009-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 Gregor0b6a6242009-06-22 20:57:11 +000097 }
98 }
Mike Stump11289f42009-09-09 15:08:12 +000099
Douglas Gregorff790f12009-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 Gregor0b6a6242009-06-22 20:57:11 +0000103 if (isUnevaluatedOperand)
Douglas Gregorff790f12009-11-26 00:44:06 +0000104 ExprEvalContexts.back().Context = Unevaluated;
Douglas Gregor0b6a6242009-06-22 20:57:11 +0000105 }
Mike Stump11289f42009-09-09 15:08:12 +0000106
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000107 return Owned(new (Context) CXXTypeidExpr(isType, TyOrExpr,
108 TypeInfoType.withConst(),
109 SourceRange(OpLoc, RParenLoc)));
Sebastian Redlc4704762008-11-11 11:37:55 +0000110}
111
Steve Naroff66356bd2007-09-16 14:56:35 +0000112/// ActOnCXXBoolLiteral - Parse {true,false} literals.
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000113Action::OwningExprResult
Steve Naroff66356bd2007-09-16 14:56:35 +0000114Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor08d918a2008-10-24 15:36:09 +0000115 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Bill Wendlingbf313b02007-02-13 20:09:46 +0000116 "Unknown C++ Boolean value!");
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000117 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
118 Context.BoolTy, OpLoc));
Bill Wendling4073ed52007-02-13 01:51:42 +0000119}
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000120
Sebastian Redl576fd422009-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 Lattnerb7e656b2008-02-26 00:51:44 +0000127/// ActOnCXXThrow - Parse throw expressions.
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000128Action::OwningExprResult
129Sema::ActOnCXXThrow(SourceLocation OpLoc, ExprArg E) {
Sebastian Redl4de47b42009-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 Gregor247894b2009-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 Redl4de47b42009-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 Kremenekc23c7e62009-07-29 21:53:49 +0000154 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl4de47b42009-04-27 20:27:31 +0000155 Ty = Ptr->getPointeeType();
156 isPointer = 1;
157 }
158 if (!isPointer || !Ty->isVoidType()) {
159 if (RequireCompleteType(ThrowLoc, Ty,
Anders Carlsson029fc692009-08-26 22:59:12 +0000160 PDiag(isPointer ? diag::err_throw_incomplete_ptr
161 : diag::err_throw_incomplete)
162 << E->getSourceRange()))
Sebastian Redl4de47b42009-04-27 20:27:31 +0000163 return true;
164 }
165
166 // FIXME: Construct a temporary here.
167 return false;
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000168}
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000169
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000170Action::OwningExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
Argyrios Kyrtzidised983422008-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 Redl6d4256c2009-03-15 17:47:39 +0000175 if (!isa<FunctionDecl>(CurContext))
176 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000177
178 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext))
179 if (MD->isInstance())
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000180 return Owned(new (Context) CXXThisExpr(ThisLoc,
Douglas Gregorb15af892010-01-07 23:12:05 +0000181 MD->getThisType(Context),
182 /*isImplicit=*/false));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000183
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000184 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000185}
Argyrios Kyrtzidis857fcc22008-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 Redl6d4256c2009-03-15 17:47:39 +0000191Action::OwningExprResult
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000192Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep,
193 SourceLocation LParenLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000194 MultiExprArg exprs,
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000195 SourceLocation *CommaLocs,
196 SourceLocation RParenLoc) {
197 assert(TypeRep && "Missing type!");
John McCall97513962010-01-15 18:39:57 +0000198 TypeSourceInfo *TInfo;
199 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
200 if (!TInfo)
201 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000202 unsigned NumExprs = exprs.size();
203 Expr **Exprs = (Expr**)exprs.get();
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000204 SourceLocation TyBeginLoc = TypeRange.getBegin();
205 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
206
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000207 if (Ty->isDependentType() ||
Douglas Gregor0950e412009-03-13 21:01:28 +0000208 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000209 exprs.release();
Mike Stump11289f42009-09-09 15:08:12 +0000210
211 return Owned(CXXUnresolvedConstructExpr::Create(Context,
212 TypeRange.getBegin(), Ty,
Douglas Gregorce934142009-05-20 18:46:25 +0000213 LParenLoc,
214 Exprs, NumExprs,
215 RParenLoc));
Douglas Gregor0950e412009-03-13 21:01:28 +0000216 }
217
Anders Carlsson55243162009-08-27 03:53:50 +0000218 if (Ty->isArrayType())
219 return ExprError(Diag(TyBeginLoc,
220 diag::err_value_init_for_array_type) << FullRange);
221 if (!Ty->isVoidType() &&
222 RequireCompleteType(TyBeginLoc, Ty,
223 PDiag(diag::err_invalid_incomplete_type_use)
224 << FullRange))
225 return ExprError();
Fariborz Jahanian9a14b842009-10-23 21:01:39 +0000226
Anders Carlsson55243162009-08-27 03:53:50 +0000227 if (RequireNonAbstractType(TyBeginLoc, Ty,
228 diag::err_allocation_of_abstract_type))
229 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +0000230
231
Douglas Gregordd04d332009-01-16 18:33:17 +0000232 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000233 // If the expression list is a single expression, the type conversion
234 // expression is equivalent (in definedness, and if defined in meaning) to the
235 // corresponding cast expression.
236 //
237 if (NumExprs == 1) {
Anders Carlssonf10e4142009-08-07 22:21:05 +0000238 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Anders Carlssone9766d52009-09-09 21:33:21 +0000239 CXXMethodDecl *Method = 0;
240 if (CheckCastTypes(TypeRange, Ty, Exprs[0], Kind, Method,
241 /*FunctionalStyle=*/true))
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000242 return ExprError();
Anders Carlssone9766d52009-09-09 21:33:21 +0000243
244 exprs.release();
245 if (Method) {
246 OwningExprResult CastArg
247 = BuildCXXCastArgument(TypeRange.getBegin(), Ty.getNonReferenceType(),
248 Kind, Method, Owned(Exprs[0]));
249 if (CastArg.isInvalid())
250 return ExprError();
251
252 Exprs[0] = CastArg.takeAs<Expr>();
Fariborz Jahanian8b899e42009-08-28 15:11:24 +0000253 }
Anders Carlssone9766d52009-09-09 21:33:21 +0000254
255 return Owned(new (Context) CXXFunctionalCastExpr(Ty.getNonReferenceType(),
John McCall97513962010-01-15 18:39:57 +0000256 TInfo, TyBeginLoc, Kind,
Anders Carlssone9766d52009-09-09 21:33:21 +0000257 Exprs[0], RParenLoc));
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000258 }
259
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000260 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Douglas Gregordd04d332009-01-16 18:33:17 +0000261 CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000262
Mike Stump11289f42009-09-09 15:08:12 +0000263 if (NumExprs > 1 || !Record->hasTrivialConstructor() ||
Anders Carlsson574315a2009-08-27 05:08:22 +0000264 !Record->hasTrivialDestructor()) {
Eli Friedmana6824272010-01-31 20:58:15 +0000265 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty);
266 InitializationKind Kind
267 = NumExprs ? InitializationKind::CreateDirect(TypeRange.getBegin(),
268 LParenLoc, RParenLoc)
269 : InitializationKind::CreateValue(TypeRange.getBegin(),
270 LParenLoc, RParenLoc);
271 InitializationSequence InitSeq(*this, Entity, Kind, Exprs, NumExprs);
272 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
273 move(exprs));
Douglas Gregordd04d332009-01-16 18:33:17 +0000274
Eli Friedmana6824272010-01-31 20:58:15 +0000275 // FIXME: Improve AST representation?
276 return move(Result);
Douglas Gregordd04d332009-01-16 18:33:17 +0000277 }
278
279 // Fall through to value-initialize an object of class type that
280 // doesn't have a user-declared default constructor.
281 }
282
283 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000284 // If the expression list specifies more than a single value, the type shall
285 // be a class with a suitably declared constructor.
286 //
287 if (NumExprs > 1)
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000288 return ExprError(Diag(CommaLocs[0],
289 diag::err_builtin_func_cast_more_than_one_arg)
290 << FullRange);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000291
292 assert(NumExprs == 0 && "Expected 0 expressions");
Douglas Gregordd04d332009-01-16 18:33:17 +0000293 // C++ [expr.type.conv]p2:
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000294 // The expression T(), where T is a simple-type-specifier for a non-array
295 // complete object type or the (possibly cv-qualified) void type, creates an
296 // rvalue of the specified type, which is value-initialized.
297 //
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000298 exprs.release();
299 return Owned(new (Context) CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc));
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000300}
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +0000301
302
Sebastian Redlbd150f42008-11-21 19:14:01 +0000303/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
304/// @code new (memory) int[size][4] @endcode
305/// or
306/// @code ::new Foo(23, "hello") @endcode
307/// For the interpretation of this heap of arguments, consult the base version.
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000308Action::OwningExprResult
Sebastian Redlbd150f42008-11-21 19:14:01 +0000309Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000310 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
Sebastian Redlbd150f42008-11-21 19:14:01 +0000311 SourceLocation PlacementRParen, bool ParenTypeId,
Sebastian Redl351bb782008-12-02 14:43:59 +0000312 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000313 MultiExprArg ConstructorArgs,
Mike Stump11289f42009-09-09 15:08:12 +0000314 SourceLocation ConstructorRParen) {
Sebastian Redl351bb782008-12-02 14:43:59 +0000315 Expr *ArraySize = 0;
Sebastian Redl351bb782008-12-02 14:43:59 +0000316 // If the specified type is an array, unwrap it and save the expression.
317 if (D.getNumTypeObjects() > 0 &&
318 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
319 DeclaratorChunk &Chunk = D.getTypeObject(0);
320 if (Chunk.Arr.hasStatic)
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000321 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
322 << D.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +0000323 if (!Chunk.Arr.NumElts)
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000324 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
325 << D.getSourceRange());
Sebastian Redld7b3d7d2009-10-25 21:45:37 +0000326
327 if (ParenTypeId) {
328 // Can't have dynamic array size when the type-id is in parentheses.
329 Expr *NumElts = (Expr *)Chunk.Arr.NumElts;
330 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
331 !NumElts->isIntegerConstantExpr(Context)) {
332 Diag(D.getTypeObject(0).Loc, diag::err_new_paren_array_nonconst)
333 << NumElts->getSourceRange();
334 return ExprError();
335 }
336 }
337
Sebastian Redl351bb782008-12-02 14:43:59 +0000338 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redld7b3d7d2009-10-25 21:45:37 +0000339 D.DropFirstTypeObject();
Sebastian Redl351bb782008-12-02 14:43:59 +0000340 }
341
Douglas Gregor73341c42009-09-11 00:18:58 +0000342 // Every dimension shall be of constant size.
Sebastian Redld7b3d7d2009-10-25 21:45:37 +0000343 if (ArraySize) {
344 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor73341c42009-09-11 00:18:58 +0000345 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
346 break;
347
348 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
349 if (Expr *NumElts = (Expr *)Array.NumElts) {
350 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
351 !NumElts->isIntegerConstantExpr(Context)) {
352 Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst)
353 << NumElts->getSourceRange();
354 return ExprError();
355 }
356 }
357 }
358 }
Sebastian Redld7b3d7d2009-10-25 21:45:37 +0000359
John McCallbcd03502009-12-07 02:54:59 +0000360 //FIXME: Store TypeSourceInfo in CXXNew expression.
361 TypeSourceInfo *TInfo = 0;
362 QualType AllocType = GetTypeForDeclarator(D, /*Scope=*/0, &TInfo);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +0000363 if (D.isInvalidType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000364 return ExprError();
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +0000365
Mike Stump11289f42009-09-09 15:08:12 +0000366 return BuildCXXNew(StartLoc, UseGlobal,
Douglas Gregord0fefba2009-05-21 00:00:09 +0000367 PlacementLParen,
Mike Stump11289f42009-09-09 15:08:12 +0000368 move(PlacementArgs),
Douglas Gregord0fefba2009-05-21 00:00:09 +0000369 PlacementRParen,
370 ParenTypeId,
Mike Stump11289f42009-09-09 15:08:12 +0000371 AllocType,
Douglas Gregord0fefba2009-05-21 00:00:09 +0000372 D.getSourceRange().getBegin(),
373 D.getSourceRange(),
374 Owned(ArraySize),
375 ConstructorLParen,
376 move(ConstructorArgs),
377 ConstructorRParen);
378}
379
Mike Stump11289f42009-09-09 15:08:12 +0000380Sema::OwningExprResult
Douglas Gregord0fefba2009-05-21 00:00:09 +0000381Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
382 SourceLocation PlacementLParen,
383 MultiExprArg PlacementArgs,
384 SourceLocation PlacementRParen,
Mike Stump11289f42009-09-09 15:08:12 +0000385 bool ParenTypeId,
Douglas Gregord0fefba2009-05-21 00:00:09 +0000386 QualType AllocType,
387 SourceLocation TypeLoc,
388 SourceRange TypeRange,
389 ExprArg ArraySizeE,
390 SourceLocation ConstructorLParen,
391 MultiExprArg ConstructorArgs,
392 SourceLocation ConstructorRParen) {
393 if (CheckAllocatedType(AllocType, TypeLoc, TypeRange))
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000394 return ExprError();
Sebastian Redl351bb782008-12-02 14:43:59 +0000395
Douglas Gregord0fefba2009-05-21 00:00:09 +0000396 QualType ResultType = Context.getPointerType(AllocType);
Sebastian Redlbd150f42008-11-21 19:14:01 +0000397
398 // That every array dimension except the first is constant was already
399 // checked by the type check above.
Sebastian Redl351bb782008-12-02 14:43:59 +0000400
Sebastian Redlbd150f42008-11-21 19:14:01 +0000401 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
402 // or enumeration type with a non-negative value."
Douglas Gregord0fefba2009-05-21 00:00:09 +0000403 Expr *ArraySize = (Expr *)ArraySizeE.get();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +0000404 if (ArraySize && !ArraySize->isTypeDependent()) {
Sebastian Redl351bb782008-12-02 14:43:59 +0000405 QualType SizeType = ArraySize->getType();
406 if (!SizeType->isIntegralType() && !SizeType->isEnumeralType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000407 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
408 diag::err_array_size_not_integral)
409 << SizeType << ArraySize->getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +0000410 // Let's see if this is a constant < 0. If so, we reject it out of hand.
411 // We don't care about special rules, so we tell the machinery it's not
412 // evaluated - it gives us a result in more cases.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +0000413 if (!ArraySize->isValueDependent()) {
414 llvm::APSInt Value;
415 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
416 if (Value < llvm::APSInt(
Anders Carlsson8ab20bb2009-09-23 00:37:25 +0000417 llvm::APInt::getNullValue(Value.getBitWidth()),
418 Value.isUnsigned()))
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000419 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
420 diag::err_typecheck_negative_array_size)
421 << ArraySize->getSourceRange());
Sebastian Redl8d2ccae2009-02-26 14:39:58 +0000422 }
Sebastian Redl351bb782008-12-02 14:43:59 +0000423 }
Anders Carlsson8ab20bb2009-09-23 00:37:25 +0000424
Eli Friedman06ed2a52009-10-20 08:27:19 +0000425 ImpCastExprToType(ArraySize, Context.getSizeType(),
426 CastExpr::CK_IntegralCast);
Sebastian Redl351bb782008-12-02 14:43:59 +0000427 }
Sebastian Redlbd150f42008-11-21 19:14:01 +0000428
Sebastian Redlbd150f42008-11-21 19:14:01 +0000429 FunctionDecl *OperatorNew = 0;
430 FunctionDecl *OperatorDelete = 0;
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000431 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
432 unsigned NumPlaceArgs = PlacementArgs.size();
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +0000433
Sebastian Redl8d2ccae2009-02-26 14:39:58 +0000434 if (!AllocType->isDependentType() &&
435 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
436 FindAllocationFunctions(StartLoc,
Sebastian Redl1df2bbe2009-02-09 18:24:27 +0000437 SourceRange(PlacementLParen, PlacementRParen),
438 UseGlobal, AllocType, ArraySize, PlaceArgs,
439 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000440 return ExprError();
Fariborz Jahanian835026e2009-11-24 18:29:37 +0000441 llvm::SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +0000442 if (OperatorNew) {
443 // Add default arguments, if any.
444 const FunctionProtoType *Proto =
445 OperatorNew->getType()->getAs<FunctionProtoType>();
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +0000446 VariadicCallType CallType =
447 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
Fariborz Jahanian835026e2009-11-24 18:29:37 +0000448 bool Invalid = GatherArgumentsForCall(PlacementLParen, OperatorNew,
449 Proto, 1, PlaceArgs, NumPlaceArgs,
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +0000450 AllPlaceArgs, CallType);
Fariborz Jahanian835026e2009-11-24 18:29:37 +0000451 if (Invalid)
452 return ExprError();
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +0000453
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +0000454 NumPlaceArgs = AllPlaceArgs.size();
455 if (NumPlaceArgs > 0)
456 PlaceArgs = &AllPlaceArgs[0];
457 }
458
Sebastian Redlbd150f42008-11-21 19:14:01 +0000459 bool Init = ConstructorLParen.isValid();
460 // --- Choosing a constructor ---
Sebastian Redlbd150f42008-11-21 19:14:01 +0000461 CXXConstructorDecl *Constructor = 0;
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000462 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
463 unsigned NumConsArgs = ConstructorArgs.size();
Eli Friedmanfd8d4e12009-11-08 22:15:39 +0000464 ASTOwningVector<&ActionBase::DeleteExpr> ConvertedConstructorArgs(*this);
465
Douglas Gregor85dabae2009-12-16 01:38:02 +0000466 if (!AllocType->isDependentType() &&
467 !Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) {
468 // C++0x [expr.new]p15:
469 // A new-expression that creates an object of type T initializes that
470 // object as follows:
471 InitializationKind Kind
472 // - If the new-initializer is omitted, the object is default-
473 // initialized (8.5); if no initialization is performed,
474 // the object has indeterminate value
475 = !Init? InitializationKind::CreateDefault(TypeLoc)
476 // - Otherwise, the new-initializer is interpreted according to the
477 // initialization rules of 8.5 for direct-initialization.
478 : InitializationKind::CreateDirect(TypeLoc,
479 ConstructorLParen,
480 ConstructorRParen);
481
Douglas Gregor85dabae2009-12-16 01:38:02 +0000482 InitializedEntity Entity
Douglas Gregor1b303932009-12-22 15:35:07 +0000483 = InitializedEntity::InitializeNew(StartLoc, AllocType);
Douglas Gregor85dabae2009-12-16 01:38:02 +0000484 InitializationSequence InitSeq(*this, Entity, Kind, ConsArgs, NumConsArgs);
Douglas Gregor85dabae2009-12-16 01:38:02 +0000485 OwningExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
486 move(ConstructorArgs));
487 if (FullInit.isInvalid())
488 return ExprError();
489
490 // FullInit is our initializer; walk through it to determine if it's a
491 // constructor call, which CXXNewExpr handles directly.
492 if (Expr *FullInitExpr = (Expr *)FullInit.get()) {
493 if (CXXBindTemporaryExpr *Binder
494 = dyn_cast<CXXBindTemporaryExpr>(FullInitExpr))
495 FullInitExpr = Binder->getSubExpr();
496 if (CXXConstructExpr *Construct
497 = dyn_cast<CXXConstructExpr>(FullInitExpr)) {
498 Constructor = Construct->getConstructor();
499 for (CXXConstructExpr::arg_iterator A = Construct->arg_begin(),
500 AEnd = Construct->arg_end();
501 A != AEnd; ++A)
502 ConvertedConstructorArgs.push_back(A->Retain());
503 } else {
504 // Take the converted initializer.
505 ConvertedConstructorArgs.push_back(FullInit.release());
506 }
507 } else {
508 // No initialization required.
509 }
510
511 // Take the converted arguments and use them for the new expression.
Douglas Gregor5d3507d2009-09-09 23:08:42 +0000512 NumConsArgs = ConvertedConstructorArgs.size();
513 ConsArgs = (Expr **)ConvertedConstructorArgs.take();
Sebastian Redlbd150f42008-11-21 19:14:01 +0000514 }
Douglas Gregor85dabae2009-12-16 01:38:02 +0000515
Sebastian Redlbd150f42008-11-21 19:14:01 +0000516 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
Douglas Gregor4bbd1ac2009-10-17 21:40:42 +0000517
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000518 PlacementArgs.release();
519 ConstructorArgs.release();
Douglas Gregord0fefba2009-05-21 00:00:09 +0000520 ArraySizeE.release();
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000521 return Owned(new (Context) CXXNewExpr(UseGlobal, OperatorNew, PlaceArgs,
Ted Kremenek5a201952009-02-07 01:47:29 +0000522 NumPlaceArgs, ParenTypeId, ArraySize, Constructor, Init,
Sebastian Redlbd150f42008-11-21 19:14:01 +0000523 ConsArgs, NumConsArgs, OperatorDelete, ResultType,
Mike Stump11289f42009-09-09 15:08:12 +0000524 StartLoc, Init ? ConstructorRParen : SourceLocation()));
Sebastian Redlbd150f42008-11-21 19:14:01 +0000525}
526
527/// CheckAllocatedType - Checks that a type is suitable as the allocated type
528/// in a new-expression.
529/// dimension off and stores the size expression in ArraySize.
Douglas Gregord0fefba2009-05-21 00:00:09 +0000530bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +0000531 SourceRange R) {
Sebastian Redlbd150f42008-11-21 19:14:01 +0000532 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
533 // abstract class type or array thereof.
Douglas Gregorac1fb652009-03-24 19:52:54 +0000534 if (AllocType->isFunctionType())
Douglas Gregord0fefba2009-05-21 00:00:09 +0000535 return Diag(Loc, diag::err_bad_new_type)
536 << AllocType << 0 << R;
Douglas Gregorac1fb652009-03-24 19:52:54 +0000537 else if (AllocType->isReferenceType())
Douglas Gregord0fefba2009-05-21 00:00:09 +0000538 return Diag(Loc, diag::err_bad_new_type)
539 << AllocType << 1 << R;
Douglas Gregorac1fb652009-03-24 19:52:54 +0000540 else if (!AllocType->isDependentType() &&
Douglas Gregord0fefba2009-05-21 00:00:09 +0000541 RequireCompleteType(Loc, AllocType,
Anders Carlssond624e162009-08-26 23:45:07 +0000542 PDiag(diag::err_new_incomplete_type)
543 << R))
Sebastian Redlbd150f42008-11-21 19:14:01 +0000544 return true;
Douglas Gregord0fefba2009-05-21 00:00:09 +0000545 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregorac1fb652009-03-24 19:52:54 +0000546 diag::err_allocation_of_abstract_type))
547 return true;
Sebastian Redlbd150f42008-11-21 19:14:01 +0000548
Sebastian Redlbd150f42008-11-21 19:14:01 +0000549 return false;
550}
551
Sebastian Redlfaf68082008-12-03 20:26:15 +0000552/// FindAllocationFunctions - Finds the overloads of operator new and delete
553/// that are appropriate for the allocation.
Sebastian Redl1df2bbe2009-02-09 18:24:27 +0000554bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
555 bool UseGlobal, QualType AllocType,
556 bool IsArray, Expr **PlaceArgs,
557 unsigned NumPlaceArgs,
Sebastian Redlfaf68082008-12-03 20:26:15 +0000558 FunctionDecl *&OperatorNew,
Mike Stump11289f42009-09-09 15:08:12 +0000559 FunctionDecl *&OperatorDelete) {
Sebastian Redlfaf68082008-12-03 20:26:15 +0000560 // --- Choosing an allocation function ---
561 // C++ 5.3.4p8 - 14 & 18
562 // 1) If UseGlobal is true, only look in the global scope. Else, also look
563 // in the scope of the allocated class.
564 // 2) If an array size is given, look for operator new[], else look for
565 // operator new.
566 // 3) The first argument is always size_t. Append the arguments from the
567 // placement form.
568 // FIXME: Also find the appropriate delete operator.
569
570 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
571 // We don't care about the actual value of this argument.
572 // FIXME: Should the Sema create the expression and embed it in the syntax
573 // tree? Or should the consumer just recalculate the value?
Anders Carlssona471db02009-08-16 20:29:29 +0000574 IntegerLiteral Size(llvm::APInt::getNullValue(
575 Context.Target.getPointerWidth(0)),
576 Context.getSizeType(),
577 SourceLocation());
578 AllocArgs[0] = &Size;
Sebastian Redlfaf68082008-12-03 20:26:15 +0000579 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
580
581 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
582 IsArray ? OO_Array_New : OO_New);
583 if (AllocType->isRecordType() && !UseGlobal) {
Mike Stump11289f42009-09-09 15:08:12 +0000584 CXXRecordDecl *Record
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000585 = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl());
Sebastian Redl33a31012008-12-04 22:20:51 +0000586 // FIXME: We fail to find inherited overloads.
Sebastian Redl1df2bbe2009-02-09 18:24:27 +0000587 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl33a31012008-12-04 22:20:51 +0000588 AllocArgs.size(), Record, /*AllowMissing=*/true,
589 OperatorNew))
Sebastian Redlfaf68082008-12-03 20:26:15 +0000590 return true;
Sebastian Redlfaf68082008-12-03 20:26:15 +0000591 }
592 if (!OperatorNew) {
593 // Didn't find a member overload. Look for a global one.
594 DeclareGlobalNewDelete();
Sebastian Redl33a31012008-12-04 22:20:51 +0000595 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl1df2bbe2009-02-09 18:24:27 +0000596 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl33a31012008-12-04 22:20:51 +0000597 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
598 OperatorNew))
Sebastian Redlfaf68082008-12-03 20:26:15 +0000599 return true;
Sebastian Redlfaf68082008-12-03 20:26:15 +0000600 }
601
Anders Carlsson6f9dabf2009-05-31 20:26:12 +0000602 // FindAllocationOverload can change the passed in arguments, so we need to
603 // copy them back.
604 if (NumPlaceArgs > 0)
605 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
Mike Stump11289f42009-09-09 15:08:12 +0000606
Sebastian Redlfaf68082008-12-03 20:26:15 +0000607 return false;
608}
609
Sebastian Redl33a31012008-12-04 22:20:51 +0000610/// FindAllocationOverload - Find an fitting overload for the allocation
611/// function in the specified scope.
Sebastian Redl1df2bbe2009-02-09 18:24:27 +0000612bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
613 DeclarationName Name, Expr** Args,
614 unsigned NumArgs, DeclContext *Ctx,
Mike Stump11289f42009-09-09 15:08:12 +0000615 bool AllowMissing, FunctionDecl *&Operator) {
John McCall27b18f82009-11-17 02:14:36 +0000616 LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
617 LookupQualifiedName(R, Ctx);
John McCall9f3059a2009-10-09 21:13:30 +0000618 if (R.empty()) {
Sebastian Redl33a31012008-12-04 22:20:51 +0000619 if (AllowMissing)
620 return false;
Sebastian Redl33a31012008-12-04 22:20:51 +0000621 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner45d9d602009-02-17 07:29:20 +0000622 << Name << Range;
Sebastian Redl33a31012008-12-04 22:20:51 +0000623 }
624
John McCall9f3059a2009-10-09 21:13:30 +0000625 // FIXME: handle ambiguity
626
Sebastian Redl33a31012008-12-04 22:20:51 +0000627 OverloadCandidateSet Candidates;
Douglas Gregor80a6cc52009-09-30 00:03:47 +0000628 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
629 Alloc != AllocEnd; ++Alloc) {
Douglas Gregor55297ac2008-12-23 00:26:44 +0000630 // Even member operator new/delete are implicitly treated as
631 // static, so don't use AddMemberCandidate.
Chandler Carruth93538422010-02-03 11:02:14 +0000632
633 if (FunctionTemplateDecl *FnTemplate =
634 dyn_cast<FunctionTemplateDecl>((*Alloc)->getUnderlyingDecl())) {
635 AddTemplateOverloadCandidate(FnTemplate, Alloc.getAccess(),
636 /*ExplicitTemplateArgs=*/0, Args, NumArgs,
637 Candidates,
638 /*SuppressUserConversions=*/false);
Douglas Gregorbb3e12f2009-09-29 18:16:17 +0000639 continue;
Chandler Carruth93538422010-02-03 11:02:14 +0000640 }
641
642 FunctionDecl *Fn = cast<FunctionDecl>((*Alloc)->getUnderlyingDecl());
643 AddOverloadCandidate(Fn, Alloc.getAccess(), Args, NumArgs, Candidates,
644 /*SuppressUserConversions=*/false);
Sebastian Redl33a31012008-12-04 22:20:51 +0000645 }
646
647 // Do the resolution.
648 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +0000649 switch(BestViableFunction(Candidates, StartLoc, Best)) {
Sebastian Redl33a31012008-12-04 22:20:51 +0000650 case OR_Success: {
651 // Got one!
652 FunctionDecl *FnDecl = Best->Function;
653 // The first argument is size_t, and the first parameter must be size_t,
654 // too. This is checked on declaration and can be assumed. (It can't be
655 // asserted on, though, since invalid decls are left in there.)
Fariborz Jahanian835026e2009-11-24 18:29:37 +0000656 // Whatch out for variadic allocator function.
657 unsigned NumArgsInFnDecl = FnDecl->getNumParams();
658 for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) {
Anders Carlsson24187122009-05-31 19:49:47 +0000659 if (PerformCopyInitialization(Args[i],
Sebastian Redl33a31012008-12-04 22:20:51 +0000660 FnDecl->getParamDecl(i)->getType(),
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +0000661 AA_Passing))
Sebastian Redl33a31012008-12-04 22:20:51 +0000662 return true;
663 }
664 Operator = FnDecl;
665 return false;
666 }
667
668 case OR_No_Viable_Function:
Sebastian Redl33a31012008-12-04 22:20:51 +0000669 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner45d9d602009-02-17 07:29:20 +0000670 << Name << Range;
John McCallad907772010-01-12 07:18:19 +0000671 PrintOverloadCandidates(Candidates, OCD_AllCandidates, Args, NumArgs);
Sebastian Redl33a31012008-12-04 22:20:51 +0000672 return true;
673
674 case OR_Ambiguous:
Sebastian Redl33a31012008-12-04 22:20:51 +0000675 Diag(StartLoc, diag::err_ovl_ambiguous_call)
Sebastian Redl1df2bbe2009-02-09 18:24:27 +0000676 << Name << Range;
John McCallad907772010-01-12 07:18:19 +0000677 PrintOverloadCandidates(Candidates, OCD_ViableCandidates, Args, NumArgs);
Sebastian Redl33a31012008-12-04 22:20:51 +0000678 return true;
Douglas Gregor171c45a2009-02-18 21:56:37 +0000679
680 case OR_Deleted:
681 Diag(StartLoc, diag::err_ovl_deleted_call)
682 << Best->Function->isDeleted()
683 << Name << Range;
John McCallad907772010-01-12 07:18:19 +0000684 PrintOverloadCandidates(Candidates, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +0000685 return true;
Sebastian Redl33a31012008-12-04 22:20:51 +0000686 }
687 assert(false && "Unreachable, bad result from BestViableFunction");
688 return true;
689}
690
691
Sebastian Redlfaf68082008-12-03 20:26:15 +0000692/// DeclareGlobalNewDelete - Declare the global forms of operator new and
693/// delete. These are:
694/// @code
695/// void* operator new(std::size_t) throw(std::bad_alloc);
696/// void* operator new[](std::size_t) throw(std::bad_alloc);
697/// void operator delete(void *) throw();
698/// void operator delete[](void *) throw();
699/// @endcode
700/// Note that the placement and nothrow forms of new are *not* implicitly
701/// declared. Their use requires including \<new\>.
Mike Stump11289f42009-09-09 15:08:12 +0000702void Sema::DeclareGlobalNewDelete() {
Sebastian Redlfaf68082008-12-03 20:26:15 +0000703 if (GlobalNewDeleteDeclared)
704 return;
Douglas Gregor87f54062009-09-15 22:30:29 +0000705
706 // C++ [basic.std.dynamic]p2:
707 // [...] The following allocation and deallocation functions (18.4) are
708 // implicitly declared in global scope in each translation unit of a
709 // program
710 //
711 // void* operator new(std::size_t) throw(std::bad_alloc);
712 // void* operator new[](std::size_t) throw(std::bad_alloc);
713 // void operator delete(void*) throw();
714 // void operator delete[](void*) throw();
715 //
716 // These implicit declarations introduce only the function names operator
717 // new, operator new[], operator delete, operator delete[].
718 //
719 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
720 // "std" or "bad_alloc" as necessary to form the exception specification.
721 // However, we do not make these implicit declarations visible to name
722 // lookup.
723 if (!StdNamespace) {
724 // The "std" namespace has not yet been defined, so build one implicitly.
725 StdNamespace = NamespaceDecl::Create(Context,
726 Context.getTranslationUnitDecl(),
727 SourceLocation(),
728 &PP.getIdentifierTable().get("std"));
729 StdNamespace->setImplicit(true);
730 }
731
732 if (!StdBadAlloc) {
733 // The "std::bad_alloc" class has not yet been declared, so build it
734 // implicitly.
735 StdBadAlloc = CXXRecordDecl::Create(Context, TagDecl::TK_class,
736 StdNamespace,
737 SourceLocation(),
738 &PP.getIdentifierTable().get("bad_alloc"),
739 SourceLocation(), 0);
740 StdBadAlloc->setImplicit(true);
741 }
742
Sebastian Redlfaf68082008-12-03 20:26:15 +0000743 GlobalNewDeleteDeclared = true;
744
745 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
746 QualType SizeT = Context.getSizeType();
Nuno Lopes13c88c72009-12-16 16:59:22 +0000747 bool AssumeSaneOperatorNew = getLangOptions().AssumeSaneOperatorNew;
Sebastian Redlfaf68082008-12-03 20:26:15 +0000748
Sebastian Redlfaf68082008-12-03 20:26:15 +0000749 DeclareGlobalAllocationFunction(
750 Context.DeclarationNames.getCXXOperatorName(OO_New),
Nuno Lopes13c88c72009-12-16 16:59:22 +0000751 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlfaf68082008-12-03 20:26:15 +0000752 DeclareGlobalAllocationFunction(
753 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
Nuno Lopes13c88c72009-12-16 16:59:22 +0000754 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlfaf68082008-12-03 20:26:15 +0000755 DeclareGlobalAllocationFunction(
756 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
757 Context.VoidTy, VoidPtr);
758 DeclareGlobalAllocationFunction(
759 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
760 Context.VoidTy, VoidPtr);
761}
762
763/// DeclareGlobalAllocationFunction - Declares a single implicit global
764/// allocation function if it doesn't already exist.
765void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Nuno Lopes13c88c72009-12-16 16:59:22 +0000766 QualType Return, QualType Argument,
767 bool AddMallocAttr) {
Sebastian Redlfaf68082008-12-03 20:26:15 +0000768 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
769
770 // Check if this function is already declared.
Douglas Gregor8b9ccca2008-12-23 21:05:05 +0000771 {
Douglas Gregor17eb26b2008-12-23 22:05:29 +0000772 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000773 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor8b9ccca2008-12-23 21:05:05 +0000774 Alloc != AllocEnd; ++Alloc) {
Chandler Carruth93538422010-02-03 11:02:14 +0000775 // Only look at non-template functions, as it is the predefined,
776 // non-templated allocation function we are trying to declare here.
777 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
778 QualType InitialParamType =
Douglas Gregor684d7bd2009-12-22 23:42:49 +0000779 Context.getCanonicalType(
Chandler Carruth93538422010-02-03 11:02:14 +0000780 Func->getParamDecl(0)->getType().getUnqualifiedType());
781 // FIXME: Do we need to check for default arguments here?
782 if (Func->getNumParams() == 1 && InitialParamType == Argument)
783 return;
784 }
Sebastian Redlfaf68082008-12-03 20:26:15 +0000785 }
786 }
787
Douglas Gregor87f54062009-09-15 22:30:29 +0000788 QualType BadAllocType;
789 bool HasBadAllocExceptionSpec
790 = (Name.getCXXOverloadedOperator() == OO_New ||
791 Name.getCXXOverloadedOperator() == OO_Array_New);
792 if (HasBadAllocExceptionSpec) {
793 assert(StdBadAlloc && "Must have std::bad_alloc declared");
794 BadAllocType = Context.getTypeDeclType(StdBadAlloc);
795 }
796
797 QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0,
798 true, false,
799 HasBadAllocExceptionSpec? 1 : 0,
800 &BadAllocType);
Sebastian Redlfaf68082008-12-03 20:26:15 +0000801 FunctionDecl *Alloc =
802 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
John McCallbcd03502009-12-07 02:54:59 +0000803 FnType, /*TInfo=*/0, FunctionDecl::None, false, true);
Sebastian Redlfaf68082008-12-03 20:26:15 +0000804 Alloc->setImplicit();
Nuno Lopes13c88c72009-12-16 16:59:22 +0000805
806 if (AddMallocAttr)
807 Alloc->addAttr(::new (Context) MallocAttr());
808
Sebastian Redlfaf68082008-12-03 20:26:15 +0000809 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
John McCallbcd03502009-12-07 02:54:59 +0000810 0, Argument, /*TInfo=*/0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +0000811 VarDecl::None, 0);
Ted Kremenek4ba36fc2009-01-14 00:42:25 +0000812 Alloc->setParams(Context, &Param, 1);
Sebastian Redlfaf68082008-12-03 20:26:15 +0000813
Douglas Gregor8b9ccca2008-12-23 21:05:05 +0000814 // FIXME: Also add this declaration to the IdentifierResolver, but
815 // make sure it is at the end of the chain to coincide with the
816 // global scope.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000817 ((DeclContext *)TUScope->getEntity())->addDecl(Alloc);
Sebastian Redlfaf68082008-12-03 20:26:15 +0000818}
819
Anders Carlssone1d34ba02009-11-15 18:45:20 +0000820bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
821 DeclarationName Name,
Anders Carlssonf98849e2009-12-02 17:15:43 +0000822 FunctionDecl* &Operator) {
John McCall27b18f82009-11-17 02:14:36 +0000823 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlssone1d34ba02009-11-15 18:45:20 +0000824 // Try to find operator delete/operator delete[] in class scope.
John McCall27b18f82009-11-17 02:14:36 +0000825 LookupQualifiedName(Found, RD);
Anders Carlssone1d34ba02009-11-15 18:45:20 +0000826
John McCall27b18f82009-11-17 02:14:36 +0000827 if (Found.isAmbiguous())
Anders Carlssone1d34ba02009-11-15 18:45:20 +0000828 return true;
Anders Carlssone1d34ba02009-11-15 18:45:20 +0000829
830 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
831 F != FEnd; ++F) {
832 if (CXXMethodDecl *Delete = dyn_cast<CXXMethodDecl>(*F))
833 if (Delete->isUsualDeallocationFunction()) {
834 Operator = Delete;
835 return false;
836 }
837 }
838
839 // We did find operator delete/operator delete[] declarations, but
840 // none of them were suitable.
841 if (!Found.empty()) {
842 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
843 << Name << RD;
844
845 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
846 F != FEnd; ++F) {
847 Diag((*F)->getLocation(),
848 diag::note_delete_member_function_declared_here)
849 << Name;
850 }
851
852 return true;
853 }
854
855 // Look for a global declaration.
856 DeclareGlobalNewDelete();
857 DeclContext *TUDecl = Context.getTranslationUnitDecl();
858
859 CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation());
860 Expr* DeallocArgs[1];
861 DeallocArgs[0] = &Null;
862 if (FindAllocationOverload(StartLoc, SourceRange(), Name,
863 DeallocArgs, 1, TUDecl, /*AllowMissing=*/false,
864 Operator))
865 return true;
866
867 assert(Operator && "Did not find a deallocation function!");
868 return false;
869}
870
Sebastian Redlbd150f42008-11-21 19:14:01 +0000871/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
872/// @code ::delete ptr; @endcode
873/// or
874/// @code delete [] ptr; @endcode
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000875Action::OwningExprResult
Sebastian Redlbd150f42008-11-21 19:14:01 +0000876Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
Mike Stump11289f42009-09-09 15:08:12 +0000877 bool ArrayForm, ExprArg Operand) {
Douglas Gregor0fea62d2009-09-09 23:39:55 +0000878 // C++ [expr.delete]p1:
879 // The operand shall have a pointer type, or a class type having a single
880 // conversion function to a pointer type. The result has type void.
881 //
Sebastian Redlbd150f42008-11-21 19:14:01 +0000882 // DR599 amends "pointer type" to "pointer to object type" in both cases.
883
Anders Carlssona471db02009-08-16 20:29:29 +0000884 FunctionDecl *OperatorDelete = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000885
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000886 Expr *Ex = (Expr *)Operand.get();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +0000887 if (!Ex->isTypeDependent()) {
888 QualType Type = Ex->getType();
Sebastian Redlbd150f42008-11-21 19:14:01 +0000889
Douglas Gregor0fea62d2009-09-09 23:39:55 +0000890 if (const RecordType *Record = Type->getAs<RecordType>()) {
Douglas Gregor0fea62d2009-09-09 23:39:55 +0000891 llvm::SmallVector<CXXConversionDecl *, 4> ObjectPtrConversions;
Fariborz Jahanianb54ccb22009-09-11 21:44:33 +0000892 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
John McCallad371252010-01-20 00:46:10 +0000893 const UnresolvedSetImpl *Conversions = RD->getVisibleConversionFunctions();
Douglas Gregor0fea62d2009-09-09 23:39:55 +0000894
John McCallad371252010-01-20 00:46:10 +0000895 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +0000896 E = Conversions->end(); I != E; ++I) {
Douglas Gregor0fea62d2009-09-09 23:39:55 +0000897 // Skip over templated conversion functions; they aren't considered.
John McCalld14a8642009-11-21 08:51:07 +0000898 if (isa<FunctionTemplateDecl>(*I))
Douglas Gregor0fea62d2009-09-09 23:39:55 +0000899 continue;
900
John McCalld14a8642009-11-21 08:51:07 +0000901 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*I);
Douglas Gregor0fea62d2009-09-09 23:39:55 +0000902
903 QualType ConvType = Conv->getConversionType().getNonReferenceType();
904 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
905 if (ConvPtrType->getPointeeType()->isObjectType())
Fariborz Jahanianadcea102009-09-15 22:15:23 +0000906 ObjectPtrConversions.push_back(Conv);
Douglas Gregor0fea62d2009-09-09 23:39:55 +0000907 }
Fariborz Jahanianadcea102009-09-15 22:15:23 +0000908 if (ObjectPtrConversions.size() == 1) {
909 // We have a single conversion to a pointer-to-object type. Perform
910 // that conversion.
911 Operand.release();
912 if (!PerformImplicitConversion(Ex,
913 ObjectPtrConversions.front()->getConversionType(),
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +0000914 AA_Converting)) {
Fariborz Jahanianadcea102009-09-15 22:15:23 +0000915 Operand = Owned(Ex);
916 Type = Ex->getType();
917 }
918 }
919 else if (ObjectPtrConversions.size() > 1) {
920 Diag(StartLoc, diag::err_ambiguous_delete_operand)
921 << Type << Ex->getSourceRange();
922 for (unsigned i= 0; i < ObjectPtrConversions.size(); i++) {
923 CXXConversionDecl *Conv = ObjectPtrConversions[i];
John McCallfd0b2f82010-01-06 09:43:14 +0000924 NoteOverloadCandidate(Conv);
Fariborz Jahanianadcea102009-09-15 22:15:23 +0000925 }
926 return ExprError();
Douglas Gregor0fea62d2009-09-09 23:39:55 +0000927 }
Sebastian Redl8d2ccae2009-02-26 14:39:58 +0000928 }
929
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000930 if (!Type->isPointerType())
931 return ExprError(Diag(StartLoc, diag::err_delete_operand)
932 << Type << Ex->getSourceRange());
Sebastian Redl8d2ccae2009-02-26 14:39:58 +0000933
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000934 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Douglas Gregorc9a1a3b2009-03-24 20:13:58 +0000935 if (Pointee->isFunctionType() || Pointee->isVoidType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000936 return ExprError(Diag(StartLoc, diag::err_delete_operand)
937 << Type << Ex->getSourceRange());
Douglas Gregorc9a1a3b2009-03-24 20:13:58 +0000938 else if (!Pointee->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +0000939 RequireCompleteType(StartLoc, Pointee,
Anders Carlssond624e162009-08-26 23:45:07 +0000940 PDiag(diag::warn_delete_incomplete)
941 << Ex->getSourceRange()))
Douglas Gregorc9a1a3b2009-03-24 20:13:58 +0000942 return ExprError();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +0000943
Douglas Gregor98496dc2009-09-29 21:38:53 +0000944 // C++ [expr.delete]p2:
945 // [Note: a pointer to a const type can be the operand of a
946 // delete-expression; it is not necessary to cast away the constness
947 // (5.2.11) of the pointer expression before it is used as the operand
948 // of the delete-expression. ]
949 ImpCastExprToType(Ex, Context.getPointerType(Context.VoidTy),
950 CastExpr::CK_NoOp);
951
952 // Update the operand.
953 Operand.take();
954 Operand = ExprArg(*this, Ex);
955
Anders Carlssona471db02009-08-16 20:29:29 +0000956 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
957 ArrayForm ? OO_Array_Delete : OO_Delete);
958
Anders Carlssone1d34ba02009-11-15 18:45:20 +0000959 if (const RecordType *RT = Pointee->getAs<RecordType>()) {
960 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
961
962 if (!UseGlobal &&
963 FindDeallocationFunction(StartLoc, RD, DeleteName, OperatorDelete))
Anders Carlsson654e5c72009-11-14 03:17:38 +0000964 return ExprError();
Anders Carlsson654e5c72009-11-14 03:17:38 +0000965
Anders Carlssone1d34ba02009-11-15 18:45:20 +0000966 if (!RD->hasTrivialDestructor())
967 if (const CXXDestructorDecl *Dtor = RD->getDestructor(Context))
Mike Stump11289f42009-09-09 15:08:12 +0000968 MarkDeclarationReferenced(StartLoc,
Fariborz Jahanian37d06562009-09-03 23:18:17 +0000969 const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssona471db02009-08-16 20:29:29 +0000970 }
Anders Carlssone1d34ba02009-11-15 18:45:20 +0000971
Anders Carlssona471db02009-08-16 20:29:29 +0000972 if (!OperatorDelete) {
Anders Carlssone1d34ba02009-11-15 18:45:20 +0000973 // Look for a global declaration.
Anders Carlssona471db02009-08-16 20:29:29 +0000974 DeclareGlobalNewDelete();
975 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000976 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
Douglas Gregorbb3e12f2009-09-29 18:16:17 +0000977 &Ex, 1, TUDecl, /*AllowMissing=*/false,
Anders Carlssona471db02009-08-16 20:29:29 +0000978 OperatorDelete))
979 return ExprError();
980 }
Mike Stump11289f42009-09-09 15:08:12 +0000981
Sebastian Redl8d2ccae2009-02-26 14:39:58 +0000982 // FIXME: Check access and ambiguity of operator delete and destructor.
Sebastian Redlbd150f42008-11-21 19:14:01 +0000983 }
984
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000985 Operand.release();
986 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
Anders Carlssona471db02009-08-16 20:29:29 +0000987 OperatorDelete, Ex, StartLoc));
Sebastian Redlbd150f42008-11-21 19:14:01 +0000988}
989
Douglas Gregor633caca2009-11-23 23:44:04 +0000990/// \brief Check the use of the given variable as a C++ condition in an if,
991/// while, do-while, or switch statement.
992Action::OwningExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar) {
993 QualType T = ConditionVar->getType();
994
995 // C++ [stmt.select]p2:
996 // The declarator shall not specify a function or an array.
997 if (T->isFunctionType())
998 return ExprError(Diag(ConditionVar->getLocation(),
999 diag::err_invalid_use_of_function_type)
1000 << ConditionVar->getSourceRange());
1001 else if (T->isArrayType())
1002 return ExprError(Diag(ConditionVar->getLocation(),
1003 diag::err_invalid_use_of_array_type)
1004 << ConditionVar->getSourceRange());
Douglas Gregor0156d1c2009-11-24 16:07:02 +00001005
Douglas Gregor633caca2009-11-23 23:44:04 +00001006 return Owned(DeclRefExpr::Create(Context, 0, SourceRange(), ConditionVar,
1007 ConditionVar->getLocation(),
1008 ConditionVar->getType().getNonReferenceType()));
1009}
1010
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001011/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
1012bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
1013 // C++ 6.4p4:
1014 // The value of a condition that is an initialized declaration in a statement
1015 // other than a switch statement is the value of the declared variable
1016 // implicitly converted to type bool. If that conversion is ill-formed, the
1017 // program is ill-formed.
1018 // The value of a condition that is an expression is the value of the
1019 // expression, implicitly converted to bool.
1020 //
Douglas Gregor5fb53972009-01-14 15:45:31 +00001021 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001022}
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001023
1024/// Helper function to determine whether this is the (deprecated) C++
1025/// conversion from a string literal to a pointer to non-const char or
1026/// non-const wchar_t (for narrow and wide string literals,
1027/// respectively).
Mike Stump11289f42009-09-09 15:08:12 +00001028bool
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001029Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
1030 // Look inside the implicit cast, if it exists.
1031 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
1032 From = Cast->getSubExpr();
1033
1034 // A string literal (2.13.4) that is not a wide string literal can
1035 // be converted to an rvalue of type "pointer to char"; a wide
1036 // string literal can be converted to an rvalue of type "pointer
1037 // to wchar_t" (C++ 4.2p2).
1038 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From))
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001039 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump11289f42009-09-09 15:08:12 +00001040 if (const BuiltinType *ToPointeeType
John McCall9dd450b2009-09-21 23:43:11 +00001041 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001042 // This conversion is considered only when there is an
1043 // explicit appropriate pointer target type (C++ 4.2p2).
John McCall8ccfcb52009-09-24 19:53:00 +00001044 if (!ToPtrType->getPointeeType().hasQualifiers() &&
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001045 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
1046 (!StrLit->isWide() &&
1047 (ToPointeeType->getKind() == BuiltinType::Char_U ||
1048 ToPointeeType->getKind() == BuiltinType::Char_S))))
1049 return true;
1050 }
1051
1052 return false;
1053}
Douglas Gregor39c16d42008-10-24 04:54:22 +00001054
1055/// PerformImplicitConversion - Perform an implicit conversion of the
1056/// expression From to the type ToType. Returns true if there was an
1057/// error, false otherwise. The expression From is replaced with the
Douglas Gregor47d3f272008-12-19 17:40:08 +00001058/// converted expression. Flavor is the kind of conversion we're
Douglas Gregor5fb53972009-01-14 15:45:31 +00001059/// performing, used in the error message. If @p AllowExplicit,
Sebastian Redl42e92c42009-04-12 17:16:29 +00001060/// explicit user-defined conversions are permitted. @p Elidable should be true
1061/// when called for copies which may be elided (C++ 12.8p15). C++0x overload
1062/// resolution works differently in that case.
1063bool
Douglas Gregor47d3f272008-12-19 17:40:08 +00001064Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001065 AssignmentAction Action, bool AllowExplicit,
Mike Stump11289f42009-09-09 15:08:12 +00001066 bool Elidable) {
Sebastian Redl42e92c42009-04-12 17:16:29 +00001067 ImplicitConversionSequence ICS;
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001068 return PerformImplicitConversion(From, ToType, Action, AllowExplicit,
Fariborz Jahanianaf0262d2009-09-23 20:55:32 +00001069 Elidable, ICS);
1070}
1071
1072bool
1073Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001074 AssignmentAction Action, bool AllowExplicit,
Fariborz Jahanianaf0262d2009-09-23 20:55:32 +00001075 bool Elidable,
1076 ImplicitConversionSequence& ICS) {
John McCall0d1da222010-01-12 00:44:57 +00001077 ICS.setBad();
John McCall6a61b522010-01-13 09:16:55 +00001078 ICS.Bad.init(BadConversionSequence::no_conversion, From, ToType);
Sebastian Redl42e92c42009-04-12 17:16:29 +00001079 if (Elidable && getLangOptions().CPlusPlus0x) {
Mike Stump11289f42009-09-09 15:08:12 +00001080 ICS = TryImplicitConversion(From, ToType,
Anders Carlssonef4c7212009-08-27 17:24:15 +00001081 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00001082 AllowExplicit,
Anders Carlsson228eea32009-08-28 15:33:32 +00001083 /*ForceRValue=*/true,
1084 /*InOverloadResolution=*/false);
Sebastian Redl42e92c42009-04-12 17:16:29 +00001085 }
John McCall0d1da222010-01-12 00:44:57 +00001086 if (ICS.isBad()) {
Mike Stump11289f42009-09-09 15:08:12 +00001087 ICS = TryImplicitConversion(From, ToType,
Anders Carlssonef4c7212009-08-27 17:24:15 +00001088 /*SuppressUserConversions=*/false,
1089 AllowExplicit,
Anders Carlsson228eea32009-08-28 15:33:32 +00001090 /*ForceRValue=*/false,
1091 /*InOverloadResolution=*/false);
Sebastian Redl42e92c42009-04-12 17:16:29 +00001092 }
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001093 return PerformImplicitConversion(From, ToType, ICS, Action);
Douglas Gregor5fb53972009-01-14 15:45:31 +00001094}
1095
1096/// PerformImplicitConversion - Perform an implicit conversion of the
1097/// expression From to the type ToType using the pre-computed implicit
1098/// conversion sequence ICS. Returns true if there was an error, false
1099/// otherwise. The expression From is replaced with the converted
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001100/// expression. Action is the kind of conversion we're performing,
Douglas Gregor5fb53972009-01-14 15:45:31 +00001101/// used in the error message.
1102bool
1103Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
1104 const ImplicitConversionSequence &ICS,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001105 AssignmentAction Action, bool IgnoreBaseAccess) {
John McCall0d1da222010-01-12 00:44:57 +00001106 switch (ICS.getKind()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001107 case ImplicitConversionSequence::StandardConversion:
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001108 if (PerformImplicitConversion(From, ToType, ICS.Standard, Action,
Sebastian Redl7c353682009-11-14 21:15:49 +00001109 IgnoreBaseAccess))
Douglas Gregor39c16d42008-10-24 04:54:22 +00001110 return true;
1111 break;
1112
Anders Carlsson110b07b2009-09-15 06:28:28 +00001113 case ImplicitConversionSequence::UserDefinedConversion: {
1114
Fariborz Jahanian2fee79a2009-08-28 22:04:50 +00001115 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
1116 CastExpr::CastKind CastKind = CastExpr::CK_Unknown;
Anders Carlsson110b07b2009-09-15 06:28:28 +00001117 QualType BeforeToType;
1118 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
Fariborz Jahanian2fee79a2009-08-28 22:04:50 +00001119 CastKind = CastExpr::CK_UserDefinedConversion;
Anders Carlsson110b07b2009-09-15 06:28:28 +00001120
1121 // If the user-defined conversion is specified by a conversion function,
1122 // the initial standard conversion sequence converts the source type to
1123 // the implicit object parameter of the conversion function.
1124 BeforeToType = Context.getTagDeclType(Conv->getParent());
1125 } else if (const CXXConstructorDecl *Ctor =
1126 dyn_cast<CXXConstructorDecl>(FD)) {
Anders Carlssone9766d52009-09-09 21:33:21 +00001127 CastKind = CastExpr::CK_ConstructorConversion;
Fariborz Jahanian55824512009-11-06 00:23:08 +00001128 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregor3153da72009-11-20 02:31:03 +00001129 if (!ICS.UserDefined.EllipsisConversion) {
Fariborz Jahanian55824512009-11-06 00:23:08 +00001130 // If the user-defined conversion is specified by a constructor, the
1131 // initial standard conversion sequence converts the source type to the
1132 // type required by the argument of the constructor
Douglas Gregor3153da72009-11-20 02:31:03 +00001133 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
1134 }
Anders Carlsson110b07b2009-09-15 06:28:28 +00001135 }
Anders Carlssone9766d52009-09-09 21:33:21 +00001136 else
1137 assert(0 && "Unknown conversion function kind!");
Fariborz Jahanian55824512009-11-06 00:23:08 +00001138 // Whatch out for elipsis conversion.
Fariborz Jahanianeec642f2009-11-06 00:55:14 +00001139 if (!ICS.UserDefined.EllipsisConversion) {
Fariborz Jahanian55824512009-11-06 00:23:08 +00001140 if (PerformImplicitConversion(From, BeforeToType,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001141 ICS.UserDefined.Before, AA_Converting,
Sebastian Redl7c353682009-11-14 21:15:49 +00001142 IgnoreBaseAccess))
Fariborz Jahanian55824512009-11-06 00:23:08 +00001143 return true;
1144 }
Anders Carlsson110b07b2009-09-15 06:28:28 +00001145
Anders Carlssone9766d52009-09-09 21:33:21 +00001146 OwningExprResult CastArg
1147 = BuildCXXCastArgument(From->getLocStart(),
1148 ToType.getNonReferenceType(),
1149 CastKind, cast<CXXMethodDecl>(FD),
1150 Owned(From));
1151
1152 if (CastArg.isInvalid())
1153 return true;
Eli Friedmane96f1d32009-11-27 04:41:50 +00001154
1155 From = CastArg.takeAs<Expr>();
1156
Eli Friedmane96f1d32009-11-27 04:41:50 +00001157 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001158 AA_Converting, IgnoreBaseAccess);
Fariborz Jahanianda21efb2009-10-16 19:20:59 +00001159 }
John McCall0d1da222010-01-12 00:44:57 +00001160
1161 case ImplicitConversionSequence::AmbiguousConversion:
1162 DiagnoseAmbiguousConversion(ICS, From->getExprLoc(),
1163 PDiag(diag::err_typecheck_ambiguous_condition)
1164 << From->getSourceRange());
1165 return true;
Fariborz Jahanianda21efb2009-10-16 19:20:59 +00001166
Douglas Gregor39c16d42008-10-24 04:54:22 +00001167 case ImplicitConversionSequence::EllipsisConversion:
1168 assert(false && "Cannot perform an ellipsis conversion");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001169 return false;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001170
1171 case ImplicitConversionSequence::BadConversion:
1172 return true;
1173 }
1174
1175 // Everything went well.
1176 return false;
1177}
1178
1179/// PerformImplicitConversion - Perform an implicit conversion of the
1180/// expression From to the type ToType by following the standard
1181/// conversion sequence SCS. Returns true if there was an error, false
1182/// otherwise. The expression From is replaced with the converted
Douglas Gregor47d3f272008-12-19 17:40:08 +00001183/// expression. Flavor is the context in which we're performing this
1184/// conversion, for use in error messages.
Mike Stump11289f42009-09-09 15:08:12 +00001185bool
Douglas Gregor39c16d42008-10-24 04:54:22 +00001186Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor47d3f272008-12-19 17:40:08 +00001187 const StandardConversionSequence& SCS,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001188 AssignmentAction Action, bool IgnoreBaseAccess) {
Mike Stump87c57ac2009-05-16 07:39:55 +00001189 // Overall FIXME: we are recomputing too many types here and doing far too
1190 // much extra work. What this means is that we need to keep track of more
1191 // information that is computed when we try the implicit conversion initially,
1192 // so that we don't need to recompute anything here.
Douglas Gregor39c16d42008-10-24 04:54:22 +00001193 QualType FromType = From->getType();
1194
Douglas Gregor2fe98832008-11-03 19:09:14 +00001195 if (SCS.CopyConstructor) {
Anders Carlsson549c5bd2009-05-19 04:45:15 +00001196 // FIXME: When can ToType be a reference type?
1197 assert(!ToType->isReferenceType());
Fariborz Jahanian49850df2009-09-25 18:59:21 +00001198 if (SCS.Second == ICK_Derived_To_Base) {
1199 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1200 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
1201 MultiExprArg(*this, (void **)&From, 1),
1202 /*FIXME:ConstructLoc*/SourceLocation(),
1203 ConstructorArgs))
1204 return true;
1205 OwningExprResult FromResult =
1206 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1207 ToType, SCS.CopyConstructor,
1208 move_arg(ConstructorArgs));
1209 if (FromResult.isInvalid())
1210 return true;
1211 From = FromResult.takeAs<Expr>();
1212 return false;
1213 }
Mike Stump11289f42009-09-09 15:08:12 +00001214 OwningExprResult FromResult =
1215 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1216 ToType, SCS.CopyConstructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00001217 MultiExprArg(*this, (void**)&From, 1));
Mike Stump11289f42009-09-09 15:08:12 +00001218
Anders Carlsson6eb55572009-08-25 05:12:04 +00001219 if (FromResult.isInvalid())
1220 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001221
Anders Carlsson6eb55572009-08-25 05:12:04 +00001222 From = FromResult.takeAs<Expr>();
Douglas Gregor2fe98832008-11-03 19:09:14 +00001223 return false;
1224 }
1225
Douglas Gregor39c16d42008-10-24 04:54:22 +00001226 // Perform the first implicit conversion.
1227 switch (SCS.First) {
1228 case ICK_Identity:
1229 case ICK_Lvalue_To_Rvalue:
1230 // Nothing to do.
1231 break;
1232
1233 case ICK_Array_To_Pointer:
Douglas Gregor171c45a2009-02-18 21:56:37 +00001234 FromType = Context.getArrayDecayedType(FromType);
Anders Carlsson2c101b32009-08-08 21:04:35 +00001235 ImpCastExprToType(From, FromType, CastExpr::CK_ArrayToPointerDecay);
Douglas Gregor171c45a2009-02-18 21:56:37 +00001236 break;
1237
1238 case ICK_Function_To_Pointer:
Douglas Gregor1baf54e2009-03-13 18:40:31 +00001239 if (Context.getCanonicalType(FromType) == Context.OverloadTy) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00001240 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, true);
1241 if (!Fn)
1242 return true;
1243
Douglas Gregor171c45a2009-02-18 21:56:37 +00001244 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
1245 return true;
1246
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00001247 From = FixOverloadedFunctionReference(From, Fn);
Douglas Gregorcd695e52008-11-10 20:40:00 +00001248 FromType = From->getType();
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00001249
Sebastian Redlfef1c0d2009-10-17 20:50:27 +00001250 // If there's already an address-of operator in the expression, we have
1251 // the right type already, and the code below would just introduce an
1252 // invalid additional pointer level.
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00001253 if (FromType->isPointerType() || FromType->isMemberFunctionPointerType())
Sebastian Redlfef1c0d2009-10-17 20:50:27 +00001254 break;
Douglas Gregorcd695e52008-11-10 20:40:00 +00001255 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00001256 FromType = Context.getPointerType(FromType);
Anders Carlsson6904f642009-09-01 20:37:18 +00001257 ImpCastExprToType(From, FromType, CastExpr::CK_FunctionToPointerDecay);
Douglas Gregor39c16d42008-10-24 04:54:22 +00001258 break;
1259
1260 default:
1261 assert(false && "Improper first standard conversion");
1262 break;
1263 }
1264
1265 // Perform the second implicit conversion
1266 switch (SCS.Second) {
1267 case ICK_Identity:
Sebastian Redl5d431642009-10-10 12:04:10 +00001268 // If both sides are functions (or pointers/references to them), there could
1269 // be incompatible exception declarations.
1270 if (CheckExceptionSpecCompatibility(From, ToType))
1271 return true;
1272 // Nothing else to do.
Douglas Gregor39c16d42008-10-24 04:54:22 +00001273 break;
1274
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001275 case ICK_NoReturn_Adjustment:
1276 // If both sides are functions (or pointers/references to them), there could
1277 // be incompatible exception declarations.
1278 if (CheckExceptionSpecCompatibility(From, ToType))
1279 return true;
1280
1281 ImpCastExprToType(From, Context.getNoReturnType(From->getType(), false),
1282 CastExpr::CK_NoOp);
1283 break;
1284
Douglas Gregor39c16d42008-10-24 04:54:22 +00001285 case ICK_Integral_Promotion:
Douglas Gregor39c16d42008-10-24 04:54:22 +00001286 case ICK_Integral_Conversion:
Eli Friedman06ed2a52009-10-20 08:27:19 +00001287 ImpCastExprToType(From, ToType, CastExpr::CK_IntegralCast);
1288 break;
1289
1290 case ICK_Floating_Promotion:
Douglas Gregor39c16d42008-10-24 04:54:22 +00001291 case ICK_Floating_Conversion:
Eli Friedman06ed2a52009-10-20 08:27:19 +00001292 ImpCastExprToType(From, ToType, CastExpr::CK_FloatingCast);
1293 break;
1294
1295 case ICK_Complex_Promotion:
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001296 case ICK_Complex_Conversion:
Eli Friedman06ed2a52009-10-20 08:27:19 +00001297 ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1298 break;
1299
Douglas Gregor39c16d42008-10-24 04:54:22 +00001300 case ICK_Floating_Integral:
Eli Friedman06ed2a52009-10-20 08:27:19 +00001301 if (ToType->isFloatingType())
1302 ImpCastExprToType(From, ToType, CastExpr::CK_IntegralToFloating);
1303 else
1304 ImpCastExprToType(From, ToType, CastExpr::CK_FloatingToIntegral);
1305 break;
1306
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001307 case ICK_Complex_Real:
Eli Friedman06ed2a52009-10-20 08:27:19 +00001308 ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1309 break;
1310
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001311 case ICK_Compatible_Conversion:
Eli Friedman06ed2a52009-10-20 08:27:19 +00001312 ImpCastExprToType(From, ToType, CastExpr::CK_NoOp);
Douglas Gregor39c16d42008-10-24 04:54:22 +00001313 break;
1314
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001315 case ICK_Pointer_Conversion: {
Douglas Gregor47d3f272008-12-19 17:40:08 +00001316 if (SCS.IncompatibleObjC) {
1317 // Diagnose incompatible Objective-C conversions
Mike Stump11289f42009-09-09 15:08:12 +00001318 Diag(From->getSourceRange().getBegin(),
Douglas Gregor47d3f272008-12-19 17:40:08 +00001319 diag::ext_typecheck_convert_incompatible_pointer)
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001320 << From->getType() << ToType << Action
Douglas Gregor47d3f272008-12-19 17:40:08 +00001321 << From->getSourceRange();
1322 }
1323
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001324
1325 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Sebastian Redl7c353682009-11-14 21:15:49 +00001326 if (CheckPointerConversion(From, ToType, Kind, IgnoreBaseAccess))
Douglas Gregor39c16d42008-10-24 04:54:22 +00001327 return true;
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001328 ImpCastExprToType(From, ToType, Kind);
Douglas Gregor39c16d42008-10-24 04:54:22 +00001329 break;
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001330 }
1331
1332 case ICK_Pointer_Member: {
1333 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Sebastian Redl7c353682009-11-14 21:15:49 +00001334 if (CheckMemberPointerConversion(From, ToType, Kind, IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001335 return true;
Sebastian Redl5d431642009-10-10 12:04:10 +00001336 if (CheckExceptionSpecCompatibility(From, ToType))
1337 return true;
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001338 ImpCastExprToType(From, ToType, Kind);
1339 break;
1340 }
Anders Carlsson7fa434c2009-11-23 20:04:44 +00001341 case ICK_Boolean_Conversion: {
1342 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
1343 if (FromType->isMemberPointerType())
1344 Kind = CastExpr::CK_MemberPointerToBoolean;
1345
1346 ImpCastExprToType(From, Context.BoolTy, Kind);
Douglas Gregor39c16d42008-10-24 04:54:22 +00001347 break;
Anders Carlsson7fa434c2009-11-23 20:04:44 +00001348 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00001349
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00001350 case ICK_Derived_To_Base:
1351 if (CheckDerivedToBaseConversion(From->getType(),
1352 ToType.getNonReferenceType(),
1353 From->getLocStart(),
Sebastian Redl7c353682009-11-14 21:15:49 +00001354 From->getSourceRange(),
1355 IgnoreBaseAccess))
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00001356 return true;
1357 ImpCastExprToType(From, ToType.getNonReferenceType(),
1358 CastExpr::CK_DerivedToBase);
1359 break;
1360
Douglas Gregor39c16d42008-10-24 04:54:22 +00001361 default:
1362 assert(false && "Improper second standard conversion");
1363 break;
1364 }
1365
1366 switch (SCS.Third) {
1367 case ICK_Identity:
1368 // Nothing to do.
1369 break;
1370
1371 case ICK_Qualification:
Mike Stump87c57ac2009-05-16 07:39:55 +00001372 // FIXME: Not sure about lvalue vs rvalue here in the presence of rvalue
1373 // references.
Mike Stump11289f42009-09-09 15:08:12 +00001374 ImpCastExprToType(From, ToType.getNonReferenceType(),
Eli Friedman06ed2a52009-10-20 08:27:19 +00001375 CastExpr::CK_NoOp,
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001376 ToType->isLValueReferenceType());
Douglas Gregor39c16d42008-10-24 04:54:22 +00001377 break;
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00001378
Douglas Gregor39c16d42008-10-24 04:54:22 +00001379 default:
1380 assert(false && "Improper second standard conversion");
1381 break;
1382 }
1383
1384 return false;
1385}
1386
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001387Sema::OwningExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
1388 SourceLocation KWLoc,
1389 SourceLocation LParen,
1390 TypeTy *Ty,
1391 SourceLocation RParen) {
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00001392 QualType T = GetTypeFromParser(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00001393
Anders Carlsson1f9648d2009-07-07 19:06:02 +00001394 // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
1395 // all traits except __is_class, __is_enum and __is_union require a the type
1396 // to be complete.
1397 if (OTT != UTT_IsClass && OTT != UTT_IsEnum && OTT != UTT_IsUnion) {
Mike Stump11289f42009-09-09 15:08:12 +00001398 if (RequireCompleteType(KWLoc, T,
Anders Carlsson029fc692009-08-26 22:59:12 +00001399 diag::err_incomplete_type_used_in_type_trait_expr))
Anders Carlsson1f9648d2009-07-07 19:06:02 +00001400 return ExprError();
1401 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001402
1403 // There is no point in eagerly computing the value. The traits are designed
1404 // to be used from type trait templates, so Ty will be a template parameter
1405 // 99% of the time.
Anders Carlsson1f9648d2009-07-07 19:06:02 +00001406 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT, T,
1407 RParen, Context.BoolTy));
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001408}
Sebastian Redl5822f082009-02-07 20:10:22 +00001409
1410QualType Sema::CheckPointerToMemberOperands(
Mike Stump11289f42009-09-09 15:08:12 +00001411 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect) {
Sebastian Redl5822f082009-02-07 20:10:22 +00001412 const char *OpSpelling = isIndirect ? "->*" : ".*";
1413 // C++ 5.5p2
1414 // The binary operator .* [p3: ->*] binds its second operand, which shall
1415 // be of type "pointer to member of T" (where T is a completely-defined
1416 // class type) [...]
1417 QualType RType = rex->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001418 const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
Douglas Gregorac1fb652009-03-24 19:52:54 +00001419 if (!MemPtr) {
Sebastian Redl5822f082009-02-07 20:10:22 +00001420 Diag(Loc, diag::err_bad_memptr_rhs)
1421 << OpSpelling << RType << rex->getSourceRange();
1422 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00001423 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00001424
Sebastian Redl5822f082009-02-07 20:10:22 +00001425 QualType Class(MemPtr->getClass(), 0);
1426
1427 // C++ 5.5p2
1428 // [...] to its first operand, which shall be of class T or of a class of
1429 // which T is an unambiguous and accessible base class. [p3: a pointer to
1430 // such a class]
1431 QualType LType = lex->getType();
1432 if (isIndirect) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001433 if (const PointerType *Ptr = LType->getAs<PointerType>())
Sebastian Redl5822f082009-02-07 20:10:22 +00001434 LType = Ptr->getPointeeType().getNonReferenceType();
1435 else {
1436 Diag(Loc, diag::err_bad_memptr_lhs)
Fariborz Jahanian59f64202009-10-26 20:45:27 +00001437 << OpSpelling << 1 << LType
1438 << CodeModificationHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl5822f082009-02-07 20:10:22 +00001439 return QualType();
1440 }
1441 }
1442
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001443 if (!Context.hasSameUnqualifiedType(Class, LType)) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001444 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1445 /*DetectVirtual=*/false);
Mike Stump87c57ac2009-05-16 07:39:55 +00001446 // FIXME: Would it be useful to print full ambiguity paths, or is that
1447 // overkill?
Sebastian Redl5822f082009-02-07 20:10:22 +00001448 if (!IsDerivedFrom(LType, Class, Paths) ||
1449 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
1450 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Eli Friedman1fcf66b2010-01-16 00:00:48 +00001451 << (int)isIndirect << lex->getType();
Sebastian Redl5822f082009-02-07 20:10:22 +00001452 return QualType();
1453 }
Eli Friedman1fcf66b2010-01-16 00:00:48 +00001454 // Cast LHS to type of use.
1455 QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
1456 bool isLValue = !isIndirect && lex->isLvalue(Context) == Expr::LV_Valid;
1457 ImpCastExprToType(lex, UseType, CastExpr::CK_DerivedToBase, isLValue);
Sebastian Redl5822f082009-02-07 20:10:22 +00001458 }
1459
Fariborz Jahanianfff3fb22009-11-18 22:16:17 +00001460 if (isa<CXXZeroInitValueExpr>(rex->IgnoreParens())) {
Fariborz Jahanian1bc0f9a2009-11-18 21:54:48 +00001461 // Diagnose use of pointer-to-member type which when used as
1462 // the functional cast in a pointer-to-member expression.
1463 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
1464 return QualType();
1465 }
Sebastian Redl5822f082009-02-07 20:10:22 +00001466 // C++ 5.5p2
1467 // The result is an object or a function of the type specified by the
1468 // second operand.
1469 // The cv qualifiers are the union of those in the pointer and the left side,
1470 // in accordance with 5.5p5 and 5.2.5.
1471 // FIXME: This returns a dereferenced member function pointer as a normal
1472 // function type. However, the only operation valid on such functions is
Mike Stump87c57ac2009-05-16 07:39:55 +00001473 // calling them. There's also a GCC extension to get a function pointer to the
1474 // thing, which is another complication, because this type - unlike the type
1475 // that is the result of this expression - takes the class as the first
Sebastian Redl5822f082009-02-07 20:10:22 +00001476 // argument.
1477 // We probably need a "MemberFunctionClosureType" or something like that.
1478 QualType Result = MemPtr->getPointeeType();
John McCall8ccfcb52009-09-24 19:53:00 +00001479 Result = Context.getCVRQualifiedType(Result, LType.getCVRQualifiers());
Sebastian Redl5822f082009-02-07 20:10:22 +00001480 return Result;
1481}
Sebastian Redl1a99f442009-04-16 17:51:27 +00001482
1483/// \brief Get the target type of a standard or user-defined conversion.
1484static QualType TargetType(const ImplicitConversionSequence &ICS) {
John McCall0d1da222010-01-12 00:44:57 +00001485 switch (ICS.getKind()) {
1486 case ImplicitConversionSequence::StandardConversion:
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001487 return ICS.Standard.getToType(2);
John McCall0d1da222010-01-12 00:44:57 +00001488 case ImplicitConversionSequence::UserDefinedConversion:
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001489 return ICS.UserDefined.After.getToType(2);
John McCall0d1da222010-01-12 00:44:57 +00001490 case ImplicitConversionSequence::AmbiguousConversion:
1491 return ICS.Ambiguous.getToType();
1492 case ImplicitConversionSequence::EllipsisConversion:
1493 case ImplicitConversionSequence::BadConversion:
1494 llvm_unreachable("function not valid for ellipsis or bad conversions");
1495 }
1496 return QualType(); // silence warnings
Sebastian Redl1a99f442009-04-16 17:51:27 +00001497}
1498
1499/// \brief Try to convert a type to another according to C++0x 5.16p3.
1500///
1501/// This is part of the parameter validation for the ? operator. If either
1502/// value operand is a class type, the two operands are attempted to be
1503/// converted to each other. This function does the conversion in one direction.
1504/// It emits a diagnostic and returns true only if it finds an ambiguous
1505/// conversion.
1506static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
1507 SourceLocation QuestionLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001508 ImplicitConversionSequence &ICS) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00001509 // C++0x 5.16p3
1510 // The process for determining whether an operand expression E1 of type T1
1511 // can be converted to match an operand expression E2 of type T2 is defined
1512 // as follows:
1513 // -- If E2 is an lvalue:
1514 if (To->isLvalue(Self.Context) == Expr::LV_Valid) {
1515 // E1 can be converted to match E2 if E1 can be implicitly converted to
1516 // type "lvalue reference to T2", subject to the constraint that in the
1517 // conversion the reference must bind directly to E1.
1518 if (!Self.CheckReferenceInit(From,
1519 Self.Context.getLValueReferenceType(To->getType()),
Douglas Gregorc809cc22009-09-23 23:04:10 +00001520 To->getLocStart(),
Anders Carlsson271e3a42009-08-27 17:30:43 +00001521 /*SuppressUserConversions=*/false,
1522 /*AllowExplicit=*/false,
1523 /*ForceRValue=*/false,
1524 &ICS))
Sebastian Redl1a99f442009-04-16 17:51:27 +00001525 {
John McCall0d1da222010-01-12 00:44:57 +00001526 assert((ICS.isStandard() || ICS.isUserDefined()) &&
Sebastian Redl1a99f442009-04-16 17:51:27 +00001527 "expected a definite conversion");
1528 bool DirectBinding =
John McCall0d1da222010-01-12 00:44:57 +00001529 ICS.isStandard() ? ICS.Standard.DirectBinding
1530 : ICS.UserDefined.After.DirectBinding;
Sebastian Redl1a99f442009-04-16 17:51:27 +00001531 if (DirectBinding)
1532 return false;
1533 }
1534 }
John McCall0d1da222010-01-12 00:44:57 +00001535 ICS.setBad();
Sebastian Redl1a99f442009-04-16 17:51:27 +00001536 // -- If E2 is an rvalue, or if the conversion above cannot be done:
1537 // -- if E1 and E2 have class type, and the underlying class types are
1538 // the same or one is a base class of the other:
1539 QualType FTy = From->getType();
1540 QualType TTy = To->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001541 const RecordType *FRec = FTy->getAs<RecordType>();
1542 const RecordType *TRec = TTy->getAs<RecordType>();
Sebastian Redl1a99f442009-04-16 17:51:27 +00001543 bool FDerivedFromT = FRec && TRec && Self.IsDerivedFrom(FTy, TTy);
1544 if (FRec && TRec && (FRec == TRec ||
1545 FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
1546 // E1 can be converted to match E2 if the class of T2 is the
1547 // same type as, or a base class of, the class of T1, and
1548 // [cv2 > cv1].
1549 if ((FRec == TRec || FDerivedFromT) && TTy.isAtLeastAsQualifiedAs(FTy)) {
1550 // Could still fail if there's no copy constructor.
1551 // FIXME: Is this a hard error then, or just a conversion failure? The
1552 // standard doesn't say.
Mike Stump11289f42009-09-09 15:08:12 +00001553 ICS = Self.TryCopyInitialization(From, TTy,
Anders Carlsson03068aa2009-08-27 17:18:13 +00001554 /*SuppressUserConversions=*/false,
Anders Carlsson20d13322009-08-27 17:37:39 +00001555 /*ForceRValue=*/false,
1556 /*InOverloadResolution=*/false);
Sebastian Redl1a99f442009-04-16 17:51:27 +00001557 }
1558 } else {
1559 // -- Otherwise: E1 can be converted to match E2 if E1 can be
1560 // implicitly converted to the type that expression E2 would have
1561 // if E2 were converted to an rvalue.
1562 // First find the decayed type.
1563 if (TTy->isFunctionType())
1564 TTy = Self.Context.getPointerType(TTy);
Mike Stump11289f42009-09-09 15:08:12 +00001565 else if (TTy->isArrayType())
Sebastian Redl1a99f442009-04-16 17:51:27 +00001566 TTy = Self.Context.getArrayDecayedType(TTy);
1567
1568 // Now try the implicit conversion.
1569 // FIXME: This doesn't detect ambiguities.
Anders Carlssonef4c7212009-08-27 17:24:15 +00001570 ICS = Self.TryImplicitConversion(From, TTy,
1571 /*SuppressUserConversions=*/false,
1572 /*AllowExplicit=*/false,
Anders Carlsson228eea32009-08-28 15:33:32 +00001573 /*ForceRValue=*/false,
1574 /*InOverloadResolution=*/false);
Sebastian Redl1a99f442009-04-16 17:51:27 +00001575 }
1576 return false;
1577}
1578
1579/// \brief Try to find a common type for two according to C++0x 5.16p5.
1580///
1581/// This is part of the parameter validation for the ? operator. If either
1582/// value operand is a class type, overload resolution is used to find a
1583/// conversion to a common type.
1584static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
1585 SourceLocation Loc) {
1586 Expr *Args[2] = { LHS, RHS };
1587 OverloadCandidateSet CandidateSet;
Douglas Gregorc02cfe22009-10-21 23:19:44 +00001588 Self.AddBuiltinOperatorCandidates(OO_Conditional, Loc, Args, 2, CandidateSet);
Sebastian Redl1a99f442009-04-16 17:51:27 +00001589
1590 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00001591 switch (Self.BestViableFunction(CandidateSet, Loc, Best)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001592 case OR_Success:
Sebastian Redl1a99f442009-04-16 17:51:27 +00001593 // We found a match. Perform the conversions on the arguments and move on.
1594 if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001595 Best->Conversions[0], Sema::AA_Converting) ||
Sebastian Redl1a99f442009-04-16 17:51:27 +00001596 Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001597 Best->Conversions[1], Sema::AA_Converting))
Sebastian Redl1a99f442009-04-16 17:51:27 +00001598 break;
1599 return false;
1600
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001601 case OR_No_Viable_Function:
Sebastian Redl1a99f442009-04-16 17:51:27 +00001602 Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
1603 << LHS->getType() << RHS->getType()
1604 << LHS->getSourceRange() << RHS->getSourceRange();
1605 return true;
1606
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001607 case OR_Ambiguous:
Sebastian Redl1a99f442009-04-16 17:51:27 +00001608 Self.Diag(Loc, diag::err_conditional_ambiguous_ovl)
1609 << LHS->getType() << RHS->getType()
1610 << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stump87c57ac2009-05-16 07:39:55 +00001611 // FIXME: Print the possible common types by printing the return types of
1612 // the viable candidates.
Sebastian Redl1a99f442009-04-16 17:51:27 +00001613 break;
1614
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001615 case OR_Deleted:
Sebastian Redl1a99f442009-04-16 17:51:27 +00001616 assert(false && "Conditional operator has only built-in overloads");
1617 break;
1618 }
1619 return true;
1620}
1621
Sebastian Redl5775af1a2009-04-17 16:30:52 +00001622/// \brief Perform an "extended" implicit conversion as returned by
1623/// TryClassUnification.
1624///
1625/// TryClassUnification generates ICSs that include reference bindings.
1626/// PerformImplicitConversion is not suitable for this; it chokes if the
1627/// second part of a standard conversion is ICK_DerivedToBase. This function
1628/// handles the reference binding specially.
1629static bool ConvertForConditional(Sema &Self, Expr *&E,
Mike Stump11289f42009-09-09 15:08:12 +00001630 const ImplicitConversionSequence &ICS) {
John McCall0d1da222010-01-12 00:44:57 +00001631 if (ICS.isStandard() && ICS.Standard.ReferenceBinding) {
Sebastian Redl5775af1a2009-04-17 16:30:52 +00001632 assert(ICS.Standard.DirectBinding &&
1633 "TryClassUnification should never generate indirect ref bindings");
Sebastian Redlf79d3972009-04-26 11:21:02 +00001634 // FIXME: CheckReferenceInit should be able to reuse the ICS instead of
1635 // redoing all the work.
1636 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
Anders Carlsson271e3a42009-08-27 17:30:43 +00001637 TargetType(ICS)),
Douglas Gregorc809cc22009-09-23 23:04:10 +00001638 /*FIXME:*/E->getLocStart(),
Anders Carlsson271e3a42009-08-27 17:30:43 +00001639 /*SuppressUserConversions=*/false,
1640 /*AllowExplicit=*/false,
1641 /*ForceRValue=*/false);
Sebastian Redl5775af1a2009-04-17 16:30:52 +00001642 }
John McCall0d1da222010-01-12 00:44:57 +00001643 if (ICS.isUserDefined() && ICS.UserDefined.After.ReferenceBinding) {
Sebastian Redl5775af1a2009-04-17 16:30:52 +00001644 assert(ICS.UserDefined.After.DirectBinding &&
1645 "TryClassUnification should never generate indirect ref bindings");
Sebastian Redlf79d3972009-04-26 11:21:02 +00001646 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
Anders Carlsson271e3a42009-08-27 17:30:43 +00001647 TargetType(ICS)),
Douglas Gregorc809cc22009-09-23 23:04:10 +00001648 /*FIXME:*/E->getLocStart(),
Anders Carlsson271e3a42009-08-27 17:30:43 +00001649 /*SuppressUserConversions=*/false,
1650 /*AllowExplicit=*/false,
1651 /*ForceRValue=*/false);
Sebastian Redl5775af1a2009-04-17 16:30:52 +00001652 }
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001653 if (Self.PerformImplicitConversion(E, TargetType(ICS), ICS, Sema::AA_Converting))
Sebastian Redl5775af1a2009-04-17 16:30:52 +00001654 return true;
1655 return false;
1656}
1657
Sebastian Redl1a99f442009-04-16 17:51:27 +00001658/// \brief Check the operands of ?: under C++ semantics.
1659///
1660/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
1661/// extension. In this case, LHS == Cond. (But they're not aliases.)
1662QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
1663 SourceLocation QuestionLoc) {
Mike Stump87c57ac2009-05-16 07:39:55 +00001664 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
1665 // interface pointers.
Sebastian Redl1a99f442009-04-16 17:51:27 +00001666
1667 // C++0x 5.16p1
1668 // The first expression is contextually converted to bool.
1669 if (!Cond->isTypeDependent()) {
1670 if (CheckCXXBooleanCondition(Cond))
1671 return QualType();
1672 }
1673
1674 // Either of the arguments dependent?
1675 if (LHS->isTypeDependent() || RHS->isTypeDependent())
1676 return Context.DependentTy;
1677
John McCall1fa36b72009-11-05 09:23:39 +00001678 CheckSignCompare(LHS, RHS, QuestionLoc, diag::warn_mixed_sign_conditional);
1679
Sebastian Redl1a99f442009-04-16 17:51:27 +00001680 // C++0x 5.16p2
1681 // If either the second or the third operand has type (cv) void, ...
1682 QualType LTy = LHS->getType();
1683 QualType RTy = RHS->getType();
1684 bool LVoid = LTy->isVoidType();
1685 bool RVoid = RTy->isVoidType();
1686 if (LVoid || RVoid) {
1687 // ... then the [l2r] conversions are performed on the second and third
1688 // operands ...
Douglas Gregorb92a1562010-02-03 00:27:59 +00001689 DefaultFunctionArrayLvalueConversion(LHS);
1690 DefaultFunctionArrayLvalueConversion(RHS);
Sebastian Redl1a99f442009-04-16 17:51:27 +00001691 LTy = LHS->getType();
1692 RTy = RHS->getType();
1693
1694 // ... and one of the following shall hold:
1695 // -- The second or the third operand (but not both) is a throw-
1696 // expression; the result is of the type of the other and is an rvalue.
1697 bool LThrow = isa<CXXThrowExpr>(LHS);
1698 bool RThrow = isa<CXXThrowExpr>(RHS);
1699 if (LThrow && !RThrow)
1700 return RTy;
1701 if (RThrow && !LThrow)
1702 return LTy;
1703
1704 // -- Both the second and third operands have type void; the result is of
1705 // type void and is an rvalue.
1706 if (LVoid && RVoid)
1707 return Context.VoidTy;
1708
1709 // Neither holds, error.
1710 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
1711 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
1712 << LHS->getSourceRange() << RHS->getSourceRange();
1713 return QualType();
1714 }
1715
1716 // Neither is void.
1717
1718 // C++0x 5.16p3
1719 // Otherwise, if the second and third operand have different types, and
1720 // either has (cv) class type, and attempt is made to convert each of those
1721 // operands to the other.
1722 if (Context.getCanonicalType(LTy) != Context.getCanonicalType(RTy) &&
1723 (LTy->isRecordType() || RTy->isRecordType())) {
1724 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
1725 // These return true if a single direction is already ambiguous.
1726 if (TryClassUnification(*this, LHS, RHS, QuestionLoc, ICSLeftToRight))
1727 return QualType();
1728 if (TryClassUnification(*this, RHS, LHS, QuestionLoc, ICSRightToLeft))
1729 return QualType();
1730
John McCall0d1da222010-01-12 00:44:57 +00001731 bool HaveL2R = !ICSLeftToRight.isBad();
1732 bool HaveR2L = !ICSRightToLeft.isBad();
Sebastian Redl1a99f442009-04-16 17:51:27 +00001733 // If both can be converted, [...] the program is ill-formed.
1734 if (HaveL2R && HaveR2L) {
1735 Diag(QuestionLoc, diag::err_conditional_ambiguous)
1736 << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
1737 return QualType();
1738 }
1739
1740 // If exactly one conversion is possible, that conversion is applied to
1741 // the chosen operand and the converted operands are used in place of the
1742 // original operands for the remainder of this section.
1743 if (HaveL2R) {
Sebastian Redl5775af1a2009-04-17 16:30:52 +00001744 if (ConvertForConditional(*this, LHS, ICSLeftToRight))
Sebastian Redl1a99f442009-04-16 17:51:27 +00001745 return QualType();
1746 LTy = LHS->getType();
1747 } else if (HaveR2L) {
Sebastian Redl5775af1a2009-04-17 16:30:52 +00001748 if (ConvertForConditional(*this, RHS, ICSRightToLeft))
Sebastian Redl1a99f442009-04-16 17:51:27 +00001749 return QualType();
1750 RTy = RHS->getType();
1751 }
1752 }
1753
1754 // C++0x 5.16p4
1755 // If the second and third operands are lvalues and have the same type,
1756 // the result is of that type [...]
1757 bool Same = Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy);
1758 if (Same && LHS->isLvalue(Context) == Expr::LV_Valid &&
1759 RHS->isLvalue(Context) == Expr::LV_Valid)
1760 return LTy;
1761
1762 // C++0x 5.16p5
1763 // Otherwise, the result is an rvalue. If the second and third operands
1764 // do not have the same type, and either has (cv) class type, ...
1765 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
1766 // ... overload resolution is used to determine the conversions (if any)
1767 // to be applied to the operands. If the overload resolution fails, the
1768 // program is ill-formed.
1769 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
1770 return QualType();
1771 }
1772
1773 // C++0x 5.16p6
1774 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
1775 // conversions are performed on the second and third operands.
Douglas Gregorb92a1562010-02-03 00:27:59 +00001776 DefaultFunctionArrayLvalueConversion(LHS);
1777 DefaultFunctionArrayLvalueConversion(RHS);
Sebastian Redl1a99f442009-04-16 17:51:27 +00001778 LTy = LHS->getType();
1779 RTy = RHS->getType();
1780
1781 // After those conversions, one of the following shall hold:
1782 // -- The second and third operands have the same type; the result
1783 // is of that type.
1784 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy))
1785 return LTy;
1786
1787 // -- The second and third operands have arithmetic or enumeration type;
1788 // the usual arithmetic conversions are performed to bring them to a
1789 // common type, and the result is of that type.
1790 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
1791 UsualArithmeticConversions(LHS, RHS);
1792 return LHS->getType();
1793 }
1794
1795 // -- The second and third operands have pointer type, or one has pointer
1796 // type and the other is a null pointer constant; pointer conversions
1797 // and qualification conversions are performed to bring them to their
1798 // composite pointer type. The result is of the composite pointer type.
Eli Friedman81390df2010-01-02 22:56:07 +00001799 // -- The second and third operands have pointer to member type, or one has
1800 // pointer to member type and the other is a null pointer constant;
1801 // pointer to member conversions and qualification conversions are
1802 // performed to bring them to a common type, whose cv-qualification
1803 // shall match the cv-qualification of either the second or the third
1804 // operand. The result is of the common type.
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00001805 QualType Composite = FindCompositePointerType(LHS, RHS);
1806 if (!Composite.isNull())
1807 return Composite;
Fariborz Jahanian798d2bd2009-12-10 20:46:08 +00001808
1809 // Similarly, attempt to find composite type of twp objective-c pointers.
1810 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
1811 if (!Composite.isNull())
1812 return Composite;
Sebastian Redl1a99f442009-04-16 17:51:27 +00001813
Sebastian Redl1a99f442009-04-16 17:51:27 +00001814 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
1815 << LHS->getType() << RHS->getType()
1816 << LHS->getSourceRange() << RHS->getSourceRange();
1817 return QualType();
1818}
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00001819
1820/// \brief Find a merged pointer type and convert the two expressions to it.
1821///
Douglas Gregorb00b10e2009-08-24 17:42:35 +00001822/// This finds the composite pointer type (or member pointer type) for @p E1
1823/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
1824/// type and returns it.
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00001825/// It does not emit diagnostics.
1826QualType Sema::FindCompositePointerType(Expr *&E1, Expr *&E2) {
1827 assert(getLangOptions().CPlusPlus && "This function assumes C++");
1828 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump11289f42009-09-09 15:08:12 +00001829
Fariborz Jahanian33e148f2009-12-08 20:04:24 +00001830 if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
1831 !T2->isAnyPointerType() && !T2->isMemberPointerType())
Douglas Gregorb00b10e2009-08-24 17:42:35 +00001832 return QualType();
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00001833
1834 // C++0x 5.9p2
1835 // Pointer conversions and qualification conversions are performed on
1836 // pointer operands to bring them to their composite pointer type. If
1837 // one operand is a null pointer constant, the composite pointer type is
1838 // the type of the other operand.
Douglas Gregor56751b52009-09-25 04:25:58 +00001839 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00001840 if (T2->isMemberPointerType())
1841 ImpCastExprToType(E1, T2, CastExpr::CK_NullToMemberPointer);
1842 else
1843 ImpCastExprToType(E1, T2, CastExpr::CK_IntegralToPointer);
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00001844 return T2;
1845 }
Douglas Gregor56751b52009-09-25 04:25:58 +00001846 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00001847 if (T1->isMemberPointerType())
1848 ImpCastExprToType(E2, T1, CastExpr::CK_NullToMemberPointer);
1849 else
1850 ImpCastExprToType(E2, T1, CastExpr::CK_IntegralToPointer);
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00001851 return T1;
1852 }
Mike Stump11289f42009-09-09 15:08:12 +00001853
Douglas Gregorb00b10e2009-08-24 17:42:35 +00001854 // Now both have to be pointers or member pointers.
Sebastian Redl658262f2009-11-16 21:03:45 +00001855 if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
1856 (!T2->isPointerType() && !T2->isMemberPointerType()))
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00001857 return QualType();
1858
1859 // Otherwise, of one of the operands has type "pointer to cv1 void," then
1860 // the other has type "pointer to cv2 T" and the composite pointer type is
1861 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
1862 // Otherwise, the composite pointer type is a pointer type similar to the
1863 // type of one of the operands, with a cv-qualification signature that is
1864 // the union of the cv-qualification signatures of the operand types.
1865 // In practice, the first part here is redundant; it's subsumed by the second.
1866 // What we do here is, we build the two possible composite types, and try the
1867 // conversions in both directions. If only one works, or if the two composite
1868 // types are the same, we have succeeded.
John McCall8ccfcb52009-09-24 19:53:00 +00001869 // FIXME: extended qualifiers?
Sebastian Redl658262f2009-11-16 21:03:45 +00001870 typedef llvm::SmallVector<unsigned, 4> QualifierVector;
1871 QualifierVector QualifierUnion;
1872 typedef llvm::SmallVector<std::pair<const Type *, const Type *>, 4>
1873 ContainingClassVector;
1874 ContainingClassVector MemberOfClass;
1875 QualType Composite1 = Context.getCanonicalType(T1),
1876 Composite2 = Context.getCanonicalType(T2);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00001877 do {
1878 const PointerType *Ptr1, *Ptr2;
1879 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
1880 (Ptr2 = Composite2->getAs<PointerType>())) {
1881 Composite1 = Ptr1->getPointeeType();
1882 Composite2 = Ptr2->getPointeeType();
1883 QualifierUnion.push_back(
1884 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
1885 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
1886 continue;
1887 }
Mike Stump11289f42009-09-09 15:08:12 +00001888
Douglas Gregorb00b10e2009-08-24 17:42:35 +00001889 const MemberPointerType *MemPtr1, *MemPtr2;
1890 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
1891 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
1892 Composite1 = MemPtr1->getPointeeType();
1893 Composite2 = MemPtr2->getPointeeType();
1894 QualifierUnion.push_back(
1895 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
1896 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
1897 MemPtr2->getClass()));
1898 continue;
1899 }
Mike Stump11289f42009-09-09 15:08:12 +00001900
Douglas Gregorb00b10e2009-08-24 17:42:35 +00001901 // FIXME: block pointer types?
Mike Stump11289f42009-09-09 15:08:12 +00001902
Douglas Gregorb00b10e2009-08-24 17:42:35 +00001903 // Cannot unwrap any more types.
1904 break;
1905 } while (true);
Mike Stump11289f42009-09-09 15:08:12 +00001906
Douglas Gregorb00b10e2009-08-24 17:42:35 +00001907 // Rewrap the composites as pointers or member pointers with the union CVRs.
Sebastian Redl658262f2009-11-16 21:03:45 +00001908 ContainingClassVector::reverse_iterator MOC
1909 = MemberOfClass.rbegin();
1910 for (QualifierVector::reverse_iterator
1911 I = QualifierUnion.rbegin(),
1912 E = QualifierUnion.rend();
Douglas Gregorb00b10e2009-08-24 17:42:35 +00001913 I != E; (void)++I, ++MOC) {
John McCall8ccfcb52009-09-24 19:53:00 +00001914 Qualifiers Quals = Qualifiers::fromCVRMask(*I);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00001915 if (MOC->first && MOC->second) {
1916 // Rebuild member pointer type
John McCall8ccfcb52009-09-24 19:53:00 +00001917 Composite1 = Context.getMemberPointerType(
1918 Context.getQualifiedType(Composite1, Quals),
1919 MOC->first);
1920 Composite2 = Context.getMemberPointerType(
1921 Context.getQualifiedType(Composite2, Quals),
1922 MOC->second);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00001923 } else {
1924 // Rebuild pointer type
John McCall8ccfcb52009-09-24 19:53:00 +00001925 Composite1
1926 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
1927 Composite2
1928 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregorb00b10e2009-08-24 17:42:35 +00001929 }
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00001930 }
1931
Mike Stump11289f42009-09-09 15:08:12 +00001932 ImplicitConversionSequence E1ToC1 =
Anders Carlssonef4c7212009-08-27 17:24:15 +00001933 TryImplicitConversion(E1, Composite1,
1934 /*SuppressUserConversions=*/false,
1935 /*AllowExplicit=*/false,
Anders Carlsson228eea32009-08-28 15:33:32 +00001936 /*ForceRValue=*/false,
1937 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00001938 ImplicitConversionSequence E2ToC1 =
Anders Carlssonef4c7212009-08-27 17:24:15 +00001939 TryImplicitConversion(E2, Composite1,
1940 /*SuppressUserConversions=*/false,
1941 /*AllowExplicit=*/false,
Anders Carlsson228eea32009-08-28 15:33:32 +00001942 /*ForceRValue=*/false,
1943 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00001944
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00001945 ImplicitConversionSequence E1ToC2, E2ToC2;
John McCall0d1da222010-01-12 00:44:57 +00001946 E1ToC2.setBad();
John McCall6a61b522010-01-13 09:16:55 +00001947 E2ToC2.setBad();
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00001948 if (Context.getCanonicalType(Composite1) !=
1949 Context.getCanonicalType(Composite2)) {
Anders Carlssonef4c7212009-08-27 17:24:15 +00001950 E1ToC2 = TryImplicitConversion(E1, Composite2,
1951 /*SuppressUserConversions=*/false,
1952 /*AllowExplicit=*/false,
Anders Carlsson228eea32009-08-28 15:33:32 +00001953 /*ForceRValue=*/false,
1954 /*InOverloadResolution=*/false);
Anders Carlssonef4c7212009-08-27 17:24:15 +00001955 E2ToC2 = TryImplicitConversion(E2, Composite2,
1956 /*SuppressUserConversions=*/false,
1957 /*AllowExplicit=*/false,
Anders Carlsson228eea32009-08-28 15:33:32 +00001958 /*ForceRValue=*/false,
1959 /*InOverloadResolution=*/false);
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00001960 }
1961
John McCall0d1da222010-01-12 00:44:57 +00001962 bool ToC1Viable = !E1ToC1.isBad() && !E2ToC1.isBad();
1963 bool ToC2Viable = !E1ToC2.isBad() && !E2ToC2.isBad();
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00001964 if (ToC1Viable && !ToC2Viable) {
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001965 if (!PerformImplicitConversion(E1, Composite1, E1ToC1, Sema::AA_Converting) &&
1966 !PerformImplicitConversion(E2, Composite1, E2ToC1, Sema::AA_Converting))
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00001967 return Composite1;
1968 }
1969 if (ToC2Viable && !ToC1Viable) {
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001970 if (!PerformImplicitConversion(E1, Composite2, E1ToC2, Sema::AA_Converting) &&
1971 !PerformImplicitConversion(E2, Composite2, E2ToC2, Sema::AA_Converting))
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00001972 return Composite2;
1973 }
1974 return QualType();
1975}
Anders Carlsson85a307d2009-05-17 18:41:29 +00001976
Anders Carlsson2d4cada2009-05-30 20:36:53 +00001977Sema::OwningExprResult Sema::MaybeBindToTemporary(Expr *E) {
Anders Carlssonf86a8d12009-08-15 23:41:35 +00001978 if (!Context.getLangOptions().CPlusPlus)
1979 return Owned(E);
Mike Stump11289f42009-09-09 15:08:12 +00001980
Douglas Gregor363b1512009-12-24 18:51:59 +00001981 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
1982
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001983 const RecordType *RT = E->getType()->getAs<RecordType>();
Anders Carlsson2d4cada2009-05-30 20:36:53 +00001984 if (!RT)
1985 return Owned(E);
Mike Stump11289f42009-09-09 15:08:12 +00001986
John McCall67da35c2010-02-04 22:26:26 +00001987 // If this is the result of a call expression, our source might
1988 // actually be a reference, in which case we shouldn't bind.
Anders Carlssonaedb46f2009-09-14 01:30:44 +00001989 if (CallExpr *CE = dyn_cast<CallExpr>(E)) {
1990 QualType Ty = CE->getCallee()->getType();
1991 if (const PointerType *PT = Ty->getAs<PointerType>())
1992 Ty = PT->getPointeeType();
1993
John McCall9dd450b2009-09-21 23:43:11 +00001994 const FunctionType *FTy = Ty->getAs<FunctionType>();
Anders Carlssonaedb46f2009-09-14 01:30:44 +00001995 if (FTy->getResultType()->isReferenceType())
1996 return Owned(E);
1997 }
John McCall67da35c2010-02-04 22:26:26 +00001998
1999 // That should be enough to guarantee that this type is complete.
2000 // If it has a trivial destructor, we can avoid the extra copy.
2001 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2002 if (RD->hasTrivialDestructor())
2003 return Owned(E);
2004
Mike Stump11289f42009-09-09 15:08:12 +00002005 CXXTemporary *Temp = CXXTemporary::Create(Context,
Anders Carlsson2d4cada2009-05-30 20:36:53 +00002006 RD->getDestructor(Context));
Anders Carlssonc78576e2009-05-30 21:21:49 +00002007 ExprTemporaries.push_back(Temp);
Fariborz Jahanian67828442009-08-03 19:13:25 +00002008 if (CXXDestructorDecl *Destructor =
2009 const_cast<CXXDestructorDecl*>(RD->getDestructor(Context)))
2010 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
Anders Carlsson2d4cada2009-05-30 20:36:53 +00002011 // FIXME: Add the temporary to the temporaries vector.
2012 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
2013}
2014
Anders Carlsson6e997b22009-12-15 20:51:39 +00002015Expr *Sema::MaybeCreateCXXExprWithTemporaries(Expr *SubExpr) {
Anders Carlssonb3d05d62009-06-05 15:38:08 +00002016 assert(SubExpr && "sub expression can't be null!");
Mike Stump11289f42009-09-09 15:08:12 +00002017
Douglas Gregor580cd4a2009-12-03 17:10:37 +00002018 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
2019 assert(ExprTemporaries.size() >= FirstTemporary);
2020 if (ExprTemporaries.size() == FirstTemporary)
Anders Carlssonb3d05d62009-06-05 15:38:08 +00002021 return SubExpr;
Mike Stump11289f42009-09-09 15:08:12 +00002022
Anders Carlssonb3d05d62009-06-05 15:38:08 +00002023 Expr *E = CXXExprWithTemporaries::Create(Context, SubExpr,
Douglas Gregor580cd4a2009-12-03 17:10:37 +00002024 &ExprTemporaries[FirstTemporary],
Anders Carlsson6e997b22009-12-15 20:51:39 +00002025 ExprTemporaries.size() - FirstTemporary);
Douglas Gregor580cd4a2009-12-03 17:10:37 +00002026 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
2027 ExprTemporaries.end());
Mike Stump11289f42009-09-09 15:08:12 +00002028
Anders Carlssonb3d05d62009-06-05 15:38:08 +00002029 return E;
2030}
2031
Douglas Gregorb6ea6082009-12-22 22:17:25 +00002032Sema::OwningExprResult
2033Sema::MaybeCreateCXXExprWithTemporaries(OwningExprResult SubExpr) {
2034 if (SubExpr.isInvalid())
2035 return ExprError();
2036
2037 return Owned(MaybeCreateCXXExprWithTemporaries(SubExpr.takeAs<Expr>()));
2038}
2039
Anders Carlssonafb2dad2009-12-16 02:09:40 +00002040FullExpr Sema::CreateFullExpr(Expr *SubExpr) {
2041 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
2042 assert(ExprTemporaries.size() >= FirstTemporary);
2043
2044 unsigned NumTemporaries = ExprTemporaries.size() - FirstTemporary;
2045 CXXTemporary **Temporaries =
2046 NumTemporaries == 0 ? 0 : &ExprTemporaries[FirstTemporary];
2047
2048 FullExpr E = FullExpr::Create(Context, SubExpr, Temporaries, NumTemporaries);
2049
2050 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
2051 ExprTemporaries.end());
2052
2053 return E;
2054}
2055
Mike Stump11289f42009-09-09 15:08:12 +00002056Sema::OwningExprResult
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002057Sema::ActOnStartCXXMemberReference(Scope *S, ExprArg Base, SourceLocation OpLoc,
2058 tok::TokenKind OpKind, TypeTy *&ObjectType) {
2059 // Since this might be a postfix expression, get rid of ParenListExprs.
2060 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
Mike Stump11289f42009-09-09 15:08:12 +00002061
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002062 Expr *BaseExpr = (Expr*)Base.get();
2063 assert(BaseExpr && "no record expansion");
Mike Stump11289f42009-09-09 15:08:12 +00002064
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002065 QualType BaseType = BaseExpr->getType();
2066 if (BaseType->isDependentType()) {
Douglas Gregor41127182009-11-04 22:49:18 +00002067 // If we have a pointer to a dependent type and are using the -> operator,
2068 // the object type is the type that the pointer points to. We might still
2069 // have enough information about that type to do something useful.
2070 if (OpKind == tok::arrow)
2071 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
2072 BaseType = Ptr->getPointeeType();
2073
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002074 ObjectType = BaseType.getAsOpaquePtr();
2075 return move(Base);
2076 }
Mike Stump11289f42009-09-09 15:08:12 +00002077
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002078 // C++ [over.match.oper]p8:
Mike Stump11289f42009-09-09 15:08:12 +00002079 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002080 // returned, with the original second operand.
2081 if (OpKind == tok::arrow) {
John McCallc1538c02009-09-30 01:01:30 +00002082 // The set of types we've considered so far.
John McCallbd0465b2009-09-30 01:30:54 +00002083 llvm::SmallPtrSet<CanQualType,8> CTypes;
Fariborz Jahanianac3005c2009-09-30 17:46:20 +00002084 llvm::SmallVector<SourceLocation, 8> Locations;
John McCallbd0465b2009-09-30 01:30:54 +00002085 CTypes.insert(Context.getCanonicalType(BaseType));
John McCallc1538c02009-09-30 01:01:30 +00002086
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002087 while (BaseType->isRecordType()) {
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00002088 Base = BuildOverloadedArrowExpr(S, move(Base), OpLoc);
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002089 BaseExpr = (Expr*)Base.get();
2090 if (BaseExpr == NULL)
2091 return ExprError();
Fariborz Jahanianac3005c2009-09-30 17:46:20 +00002092 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(BaseExpr))
Anders Carlssonfbd2d492009-10-13 22:55:59 +00002093 Locations.push_back(OpCall->getDirectCallee()->getLocation());
John McCallc1538c02009-09-30 01:01:30 +00002094 BaseType = BaseExpr->getType();
2095 CanQualType CBaseType = Context.getCanonicalType(BaseType);
John McCallbd0465b2009-09-30 01:30:54 +00002096 if (!CTypes.insert(CBaseType)) {
Fariborz Jahanian10ce9582009-09-30 00:19:41 +00002097 Diag(OpLoc, diag::err_operator_arrow_circular);
Fariborz Jahanianac3005c2009-09-30 17:46:20 +00002098 for (unsigned i = 0; i < Locations.size(); i++)
2099 Diag(Locations[i], diag::note_declared_at);
Fariborz Jahanian10ce9582009-09-30 00:19:41 +00002100 return ExprError();
2101 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002102 }
Mike Stump11289f42009-09-09 15:08:12 +00002103
Douglas Gregore4f764f2009-11-20 19:58:21 +00002104 if (BaseType->isPointerType())
2105 BaseType = BaseType->getPointeeType();
2106 }
Mike Stump11289f42009-09-09 15:08:12 +00002107
2108 // We could end up with various non-record types here, such as extended
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002109 // vector types or Objective-C interfaces. Just return early and let
2110 // ActOnMemberReferenceExpr do the work.
Douglas Gregor2b6ca462009-09-03 21:38:09 +00002111 if (!BaseType->isRecordType()) {
2112 // C++ [basic.lookup.classref]p2:
2113 // [...] If the type of the object expression is of pointer to scalar
2114 // type, the unqualified-id is looked up in the context of the complete
2115 // postfix-expression.
2116 ObjectType = 0;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002117 return move(Base);
Douglas Gregor2b6ca462009-09-03 21:38:09 +00002118 }
Mike Stump11289f42009-09-09 15:08:12 +00002119
Douglas Gregor3fad6172009-11-17 05:17:33 +00002120 // The object type must be complete (or dependent).
2121 if (!BaseType->isDependentType() &&
2122 RequireCompleteType(OpLoc, BaseType,
2123 PDiag(diag::err_incomplete_member_access)))
2124 return ExprError();
2125
Douglas Gregor2b6ca462009-09-03 21:38:09 +00002126 // C++ [basic.lookup.classref]p2:
Mike Stump11289f42009-09-09 15:08:12 +00002127 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor3fad6172009-11-17 05:17:33 +00002128 // unqualified-id, and the type of the object expression is of a class
Douglas Gregor2b6ca462009-09-03 21:38:09 +00002129 // type C (or of pointer to a class type C), the unqualified-id is looked
2130 // up in the scope of class C. [...]
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002131 ObjectType = BaseType.getAsOpaquePtr();
Douglas Gregor3fad6172009-11-17 05:17:33 +00002132
Mike Stump11289f42009-09-09 15:08:12 +00002133 return move(Base);
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002134}
2135
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00002136CXXMemberCallExpr *Sema::BuildCXXMemberCallExpr(Expr *Exp,
2137 CXXMethodDecl *Method) {
Eli Friedmanf7195532009-12-09 04:53:56 +00002138 if (PerformObjectArgumentInitialization(Exp, Method))
2139 assert(0 && "Calling BuildCXXMemberCallExpr with invalid call?");
2140
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00002141 MemberExpr *ME =
2142 new (Context) MemberExpr(Exp, /*IsArrow=*/false, Method,
2143 SourceLocation(), Method->getType());
Eli Friedmanf7195532009-12-09 04:53:56 +00002144 QualType ResultType = Method->getResultType().getNonReferenceType();
Douglas Gregor27381f32009-11-23 12:27:39 +00002145 MarkDeclarationReferenced(Exp->getLocStart(), Method);
2146 CXXMemberCallExpr *CE =
2147 new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType,
2148 Exp->getLocEnd());
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00002149 return CE;
2150}
2151
Anders Carlssone9766d52009-09-09 21:33:21 +00002152Sema::OwningExprResult Sema::BuildCXXCastArgument(SourceLocation CastLoc,
2153 QualType Ty,
2154 CastExpr::CastKind Kind,
2155 CXXMethodDecl *Method,
2156 ExprArg Arg) {
2157 Expr *From = Arg.takeAs<Expr>();
2158
2159 switch (Kind) {
2160 default: assert(0 && "Unhandled cast kind!");
2161 case CastExpr::CK_ConstructorConversion: {
Douglas Gregor5d3507d2009-09-09 23:08:42 +00002162 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
2163
2164 if (CompleteConstructorCall(cast<CXXConstructorDecl>(Method),
2165 MultiExprArg(*this, (void **)&From, 1),
2166 CastLoc, ConstructorArgs))
2167 return ExprError();
Anders Carlsson8f741bf2009-10-18 21:20:14 +00002168
2169 OwningExprResult Result =
2170 BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
2171 move_arg(ConstructorArgs));
2172 if (Result.isInvalid())
2173 return ExprError();
2174
2175 return MaybeBindToTemporary(Result.takeAs<Expr>());
Anders Carlssone9766d52009-09-09 21:33:21 +00002176 }
2177
2178 case CastExpr::CK_UserDefinedConversion: {
Anders Carlsson6b2737d2009-09-15 07:42:44 +00002179 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
Eli Friedmanf7195532009-12-09 04:53:56 +00002180
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00002181 // Create an implicit call expr that calls it.
2182 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(From, Method);
Anders Carlsson8f741bf2009-10-18 21:20:14 +00002183 return MaybeBindToTemporary(CE);
Anders Carlssone9766d52009-09-09 21:33:21 +00002184 }
Anders Carlssone9766d52009-09-09 21:33:21 +00002185 }
2186}
2187
Anders Carlsson85a307d2009-05-17 18:41:29 +00002188Sema::OwningExprResult Sema::ActOnFinishFullExpr(ExprArg Arg) {
2189 Expr *FullExpr = Arg.takeAs<Expr>();
Anders Carlssonb3d05d62009-06-05 15:38:08 +00002190 if (FullExpr)
Anders Carlsson6e997b22009-12-15 20:51:39 +00002191 FullExpr = MaybeCreateCXXExprWithTemporaries(FullExpr);
Anders Carlsson7e3f0e42009-08-25 23:46:41 +00002192
Anders Carlsson85a307d2009-05-17 18:41:29 +00002193 return Owned(FullExpr);
2194}