blob: 9005566ee478fdf2169a64c873efb0f9feb84e81 [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
Sebastian Redl5822f082009-02-07 20:10:22 +000014#include "SemaInherit.h"
Chris Lattner29375652006-12-04 18:06:35 +000015#include "Sema.h"
Steve Naroffaac94152007-08-25 14:02:58 +000016#include "clang/AST/ASTContext.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000017#include "clang/AST/ExprCXX.h"
18#include "clang/Basic/PartialDiagnostic.h"
Sebastian Redlfaf68082008-12-03 20:26:15 +000019#include "clang/Basic/TargetInfo.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000020#include "clang/Lex/Preprocessor.h"
21#include "clang/Parse/DeclSpec.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000022#include "llvm/ADT/STLExtras.h"
Chris Lattner29375652006-12-04 18:06:35 +000023using namespace clang;
24
Douglas Gregor7911b372008-11-19 19:09:45 +000025/// ActOnCXXConversionFunctionExpr - Parse a C++ conversion function
Douglas Gregorae2fbad2008-11-17 20:34:05 +000026/// name (e.g., operator void const *) as an expression. This is
27/// very similar to ActOnIdentifierExpr, except that instead of
28/// providing an identifier the parser provides the type of the
29/// conversion function.
Sebastian Redlffbcf962009-01-18 18:53:16 +000030Sema::OwningExprResult
Douglas Gregor7911b372008-11-19 19:09:45 +000031Sema::ActOnCXXConversionFunctionExpr(Scope *S, SourceLocation OperatorLoc,
32 TypeTy *Ty, bool HasTrailingLParen,
Sebastian Redl3d3f75a2009-02-03 20:19:35 +000033 const CXXScopeSpec &SS,
34 bool isAddressOfOperand) {
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +000035 //FIXME: Preserve type source info.
36 QualType ConvType = GetTypeFromParser(Ty);
Douglas Gregor2211d342009-08-05 05:36:45 +000037 CanQualType ConvTypeCanon = Context.getCanonicalType(ConvType);
Mike Stump11289f42009-09-09 15:08:12 +000038 DeclarationName ConvName
Douglas Gregorae2fbad2008-11-17 20:34:05 +000039 = Context.DeclarationNames.getCXXConversionFunctionName(ConvTypeCanon);
Sebastian Redlffbcf962009-01-18 18:53:16 +000040 return ActOnDeclarationNameExpr(S, OperatorLoc, ConvName, HasTrailingLParen,
Douglas Gregorb8a9a412009-02-04 15:01:18 +000041 &SS, isAddressOfOperand);
Douglas Gregorae2fbad2008-11-17 20:34:05 +000042}
Sebastian Redlc4704762008-11-11 11:37:55 +000043
Douglas Gregor7911b372008-11-19 19:09:45 +000044/// ActOnCXXOperatorFunctionIdExpr - Parse a C++ overloaded operator
Douglas Gregor163c5852008-11-18 14:39:36 +000045/// name (e.g., @c operator+ ) as an expression. This is very
46/// similar to ActOnIdentifierExpr, except that instead of providing
47/// an identifier the parser provides the kind of overloaded
48/// operator that was parsed.
Sebastian Redlffbcf962009-01-18 18:53:16 +000049Sema::OwningExprResult
Douglas Gregor7911b372008-11-19 19:09:45 +000050Sema::ActOnCXXOperatorFunctionIdExpr(Scope *S, SourceLocation OperatorLoc,
51 OverloadedOperatorKind Op,
52 bool HasTrailingLParen,
Sebastian Redl3d3f75a2009-02-03 20:19:35 +000053 const CXXScopeSpec &SS,
54 bool isAddressOfOperand) {
Douglas Gregor163c5852008-11-18 14:39:36 +000055 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(Op);
Sebastian Redl3d3f75a2009-02-03 20:19:35 +000056 return ActOnDeclarationNameExpr(S, OperatorLoc, Name, HasTrailingLParen, &SS,
Douglas Gregorb8a9a412009-02-04 15:01:18 +000057 isAddressOfOperand);
Douglas Gregor163c5852008-11-18 14:39:36 +000058}
59
Sebastian Redlc4704762008-11-11 11:37:55 +000060/// ActOnCXXTypeidOfType - Parse typeid( type-id ).
Sebastian Redl6d4256c2009-03-15 17:47:39 +000061Action::OwningExprResult
Sebastian Redlc4704762008-11-11 11:37:55 +000062Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
63 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Douglas Gregored8f2882009-01-30 01:04:22 +000064 NamespaceDecl *StdNs = GetStdNamespace();
Chris Lattnerec7f7732008-11-20 05:51:55 +000065 if (!StdNs)
Sebastian Redl6d4256c2009-03-15 17:47:39 +000066 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +000067
68 if (isType)
69 // FIXME: Preserve type source info.
70 TyOrExpr = GetTypeFromParser(TyOrExpr).getAsOpaquePtr();
71
Chris Lattnerec7f7732008-11-20 05:51:55 +000072 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
Douglas Gregored8f2882009-01-30 01:04:22 +000073 Decl *TypeInfoDecl = LookupQualifiedName(StdNs, TypeInfoII, LookupTagName);
Sebastian Redlc4704762008-11-11 11:37:55 +000074 RecordDecl *TypeInfoRecordDecl = dyn_cast_or_null<RecordDecl>(TypeInfoDecl);
Chris Lattnerec7f7732008-11-20 05:51:55 +000075 if (!TypeInfoRecordDecl)
Sebastian Redl6d4256c2009-03-15 17:47:39 +000076 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Sebastian Redlc4704762008-11-11 11:37:55 +000077
78 QualType TypeInfoType = Context.getTypeDeclType(TypeInfoRecordDecl);
79
Douglas Gregor0b6a6242009-06-22 20:57:11 +000080 if (!isType) {
81 // C++0x [expr.typeid]p3:
Mike Stump11289f42009-09-09 15:08:12 +000082 // When typeid is applied to an expression other than an lvalue of a
83 // polymorphic class type [...] [the] expression is an unevaluated
Douglas Gregor0b6a6242009-06-22 20:57:11 +000084 // operand.
Mike Stump11289f42009-09-09 15:08:12 +000085
Douglas Gregor0b6a6242009-06-22 20:57:11 +000086 // FIXME: if the type of the expression is a class type, the class
87 // shall be completely defined.
88 bool isUnevaluatedOperand = true;
89 Expr *E = static_cast<Expr *>(TyOrExpr);
90 if (E && !E->isTypeDependent() && E->isLvalue(Context) == Expr::LV_Valid) {
91 QualType T = E->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +000092 if (const RecordType *RecordT = T->getAs<RecordType>()) {
Douglas Gregor0b6a6242009-06-22 20:57:11 +000093 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
94 if (RecordD->isPolymorphic())
95 isUnevaluatedOperand = false;
96 }
97 }
Mike Stump11289f42009-09-09 15:08:12 +000098
Douglas Gregor0b6a6242009-06-22 20:57:11 +000099 // If this is an unevaluated operand, clear out the set of declaration
100 // references we have been computing.
101 if (isUnevaluatedOperand)
102 PotentiallyReferencedDeclStack.back().clear();
103 }
Mike Stump11289f42009-09-09 15:08:12 +0000104
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000105 return Owned(new (Context) CXXTypeidExpr(isType, TyOrExpr,
106 TypeInfoType.withConst(),
107 SourceRange(OpLoc, RParenLoc)));
Sebastian Redlc4704762008-11-11 11:37:55 +0000108}
109
Steve Naroff66356bd2007-09-16 14:56:35 +0000110/// ActOnCXXBoolLiteral - Parse {true,false} literals.
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000111Action::OwningExprResult
Steve Naroff66356bd2007-09-16 14:56:35 +0000112Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor08d918a2008-10-24 15:36:09 +0000113 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Bill Wendlingbf313b02007-02-13 20:09:46 +0000114 "Unknown C++ Boolean value!");
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000115 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
116 Context.BoolTy, OpLoc));
Bill Wendling4073ed52007-02-13 01:51:42 +0000117}
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000118
Sebastian Redl576fd422009-05-10 18:38:11 +0000119/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
120Action::OwningExprResult
121Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
122 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
123}
124
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000125/// ActOnCXXThrow - Parse throw expressions.
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000126Action::OwningExprResult
127Sema::ActOnCXXThrow(SourceLocation OpLoc, ExprArg E) {
Sebastian Redl4de47b42009-04-27 20:27:31 +0000128 Expr *Ex = E.takeAs<Expr>();
129 if (Ex && !Ex->isTypeDependent() && CheckCXXThrowOperand(OpLoc, Ex))
130 return ExprError();
131 return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc));
132}
133
134/// CheckCXXThrowOperand - Validate the operand of a throw.
135bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *&E) {
136 // C++ [except.throw]p3:
137 // [...] adjusting the type from "array of T" or "function returning T"
138 // to "pointer to T" or "pointer to function returning T", [...]
139 DefaultFunctionArrayConversion(E);
140
141 // If the type of the exception would be an incomplete type or a pointer
142 // to an incomplete type other than (cv) void the program is ill-formed.
143 QualType Ty = E->getType();
144 int isPointer = 0;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000145 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl4de47b42009-04-27 20:27:31 +0000146 Ty = Ptr->getPointeeType();
147 isPointer = 1;
148 }
149 if (!isPointer || !Ty->isVoidType()) {
150 if (RequireCompleteType(ThrowLoc, Ty,
Anders Carlsson029fc692009-08-26 22:59:12 +0000151 PDiag(isPointer ? diag::err_throw_incomplete_ptr
152 : diag::err_throw_incomplete)
153 << E->getSourceRange()))
Sebastian Redl4de47b42009-04-27 20:27:31 +0000154 return true;
155 }
156
157 // FIXME: Construct a temporary here.
158 return false;
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000159}
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000160
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000161Action::OwningExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000162 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
163 /// is a non-lvalue expression whose value is the address of the object for
164 /// which the function is called.
165
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000166 if (!isa<FunctionDecl>(CurContext))
167 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000168
169 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext))
170 if (MD->isInstance())
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000171 return Owned(new (Context) CXXThisExpr(ThisLoc,
172 MD->getThisType(Context)));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000173
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000174 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000175}
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000176
177/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
178/// Can be interpreted either as function-style casting ("int(x)")
179/// or class type construction ("ClassType(x,y,z)")
180/// or creation of a value-initialized type ("int()").
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000181Action::OwningExprResult
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000182Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep,
183 SourceLocation LParenLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000184 MultiExprArg exprs,
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000185 SourceLocation *CommaLocs,
186 SourceLocation RParenLoc) {
187 assert(TypeRep && "Missing type!");
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000188 // FIXME: Preserve type source info.
189 QualType Ty = GetTypeFromParser(TypeRep);
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000190 unsigned NumExprs = exprs.size();
191 Expr **Exprs = (Expr**)exprs.get();
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000192 SourceLocation TyBeginLoc = TypeRange.getBegin();
193 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
194
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000195 if (Ty->isDependentType() ||
Douglas Gregor0950e412009-03-13 21:01:28 +0000196 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000197 exprs.release();
Mike Stump11289f42009-09-09 15:08:12 +0000198
199 return Owned(CXXUnresolvedConstructExpr::Create(Context,
200 TypeRange.getBegin(), Ty,
Douglas Gregorce934142009-05-20 18:46:25 +0000201 LParenLoc,
202 Exprs, NumExprs,
203 RParenLoc));
Douglas Gregor0950e412009-03-13 21:01:28 +0000204 }
205
Anders Carlsson55243162009-08-27 03:53:50 +0000206 if (Ty->isArrayType())
207 return ExprError(Diag(TyBeginLoc,
208 diag::err_value_init_for_array_type) << FullRange);
209 if (!Ty->isVoidType() &&
210 RequireCompleteType(TyBeginLoc, Ty,
211 PDiag(diag::err_invalid_incomplete_type_use)
212 << FullRange))
213 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +0000214
Anders Carlsson55243162009-08-27 03:53:50 +0000215 if (RequireNonAbstractType(TyBeginLoc, Ty,
216 diag::err_allocation_of_abstract_type))
217 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +0000218
219
Douglas Gregordd04d332009-01-16 18:33:17 +0000220 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000221 // If the expression list is a single expression, the type conversion
222 // expression is equivalent (in definedness, and if defined in meaning) to the
223 // corresponding cast expression.
224 //
225 if (NumExprs == 1) {
Anders Carlssonf10e4142009-08-07 22:21:05 +0000226 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Anders Carlssone9766d52009-09-09 21:33:21 +0000227 CXXMethodDecl *Method = 0;
228 if (CheckCastTypes(TypeRange, Ty, Exprs[0], Kind, Method,
229 /*FunctionalStyle=*/true))
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000230 return ExprError();
Anders Carlssone9766d52009-09-09 21:33:21 +0000231
232 exprs.release();
233 if (Method) {
234 OwningExprResult CastArg
235 = BuildCXXCastArgument(TypeRange.getBegin(), Ty.getNonReferenceType(),
236 Kind, Method, Owned(Exprs[0]));
237 if (CastArg.isInvalid())
238 return ExprError();
239
240 Exprs[0] = CastArg.takeAs<Expr>();
Fariborz Jahanian8b899e42009-08-28 15:11:24 +0000241 }
Anders Carlssone9766d52009-09-09 21:33:21 +0000242
243 return Owned(new (Context) CXXFunctionalCastExpr(Ty.getNonReferenceType(),
244 Ty, TyBeginLoc, Kind,
245 Exprs[0], RParenLoc));
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000246 }
247
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000248 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Douglas Gregordd04d332009-01-16 18:33:17 +0000249 CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000250
Mike Stump11289f42009-09-09 15:08:12 +0000251 if (NumExprs > 1 || !Record->hasTrivialConstructor() ||
Anders Carlsson574315a2009-08-27 05:08:22 +0000252 !Record->hasTrivialDestructor()) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +0000253 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
254
Douglas Gregordd04d332009-01-16 18:33:17 +0000255 CXXConstructorDecl *Constructor
Douglas Gregor5d3507d2009-09-09 23:08:42 +0000256 = PerformInitializationByConstructor(Ty, move(exprs),
Douglas Gregordd04d332009-01-16 18:33:17 +0000257 TypeRange.getBegin(),
258 SourceRange(TypeRange.getBegin(),
259 RParenLoc),
260 DeclarationName(),
Douglas Gregor5d3507d2009-09-09 23:08:42 +0000261 IK_Direct,
262 ConstructorArgs);
Douglas Gregordd04d332009-01-16 18:33:17 +0000263
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000264 if (!Constructor)
265 return ExprError();
266
Mike Stump11289f42009-09-09 15:08:12 +0000267 OwningExprResult Result =
268 BuildCXXTemporaryObjectExpr(Constructor, Ty, TyBeginLoc,
Douglas Gregor5d3507d2009-09-09 23:08:42 +0000269 move_arg(ConstructorArgs), RParenLoc);
Anders Carlsson574315a2009-08-27 05:08:22 +0000270 if (Result.isInvalid())
271 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +0000272
Anders Carlsson574315a2009-08-27 05:08:22 +0000273 return MaybeBindToTemporary(Result.takeAs<Expr>());
Douglas Gregordd04d332009-01-16 18:33:17 +0000274 }
275
276 // Fall through to value-initialize an object of class type that
277 // doesn't have a user-declared default constructor.
278 }
279
280 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000281 // If the expression list specifies more than a single value, the type shall
282 // be a class with a suitably declared constructor.
283 //
284 if (NumExprs > 1)
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000285 return ExprError(Diag(CommaLocs[0],
286 diag::err_builtin_func_cast_more_than_one_arg)
287 << FullRange);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000288
289 assert(NumExprs == 0 && "Expected 0 expressions");
290
Douglas Gregordd04d332009-01-16 18:33:17 +0000291 // C++ [expr.type.conv]p2:
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000292 // The expression T(), where T is a simple-type-specifier for a non-array
293 // complete object type or the (possibly cv-qualified) void type, creates an
294 // rvalue of the specified type, which is value-initialized.
295 //
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000296 exprs.release();
297 return Owned(new (Context) CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc));
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000298}
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +0000299
300
Sebastian Redlbd150f42008-11-21 19:14:01 +0000301/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
302/// @code new (memory) int[size][4] @endcode
303/// or
304/// @code ::new Foo(23, "hello") @endcode
305/// For the interpretation of this heap of arguments, consult the base version.
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000306Action::OwningExprResult
Sebastian Redlbd150f42008-11-21 19:14:01 +0000307Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000308 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
Sebastian Redlbd150f42008-11-21 19:14:01 +0000309 SourceLocation PlacementRParen, bool ParenTypeId,
Sebastian Redl351bb782008-12-02 14:43:59 +0000310 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000311 MultiExprArg ConstructorArgs,
Mike Stump11289f42009-09-09 15:08:12 +0000312 SourceLocation ConstructorRParen) {
Sebastian Redl351bb782008-12-02 14:43:59 +0000313 Expr *ArraySize = 0;
314 unsigned Skip = 0;
315 // If the specified type is an array, unwrap it and save the expression.
316 if (D.getNumTypeObjects() > 0 &&
317 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
318 DeclaratorChunk &Chunk = D.getTypeObject(0);
319 if (Chunk.Arr.hasStatic)
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000320 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
321 << D.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +0000322 if (!Chunk.Arr.NumElts)
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000323 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
324 << D.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +0000325 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
326 Skip = 1;
327 }
328
Douglas Gregor73341c42009-09-11 00:18:58 +0000329 // Every dimension shall be of constant size.
330 if (D.getNumTypeObjects() > 0 &&
331 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
332 for (unsigned I = 1, N = D.getNumTypeObjects(); I < N; ++I) {
333 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
334 break;
335
336 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
337 if (Expr *NumElts = (Expr *)Array.NumElts) {
338 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
339 !NumElts->isIntegerConstantExpr(Context)) {
340 Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst)
341 << NumElts->getSourceRange();
342 return ExprError();
343 }
344 }
345 }
346 }
347
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +0000348 //FIXME: Store DeclaratorInfo in CXXNew expression.
349 DeclaratorInfo *DInfo = 0;
350 QualType AllocType = GetTypeForDeclarator(D, /*Scope=*/0, &DInfo, Skip);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +0000351 if (D.isInvalidType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000352 return ExprError();
Sebastian Redlbd150f42008-11-21 19:14:01 +0000353
Mike Stump11289f42009-09-09 15:08:12 +0000354 return BuildCXXNew(StartLoc, UseGlobal,
Douglas Gregord0fefba2009-05-21 00:00:09 +0000355 PlacementLParen,
Mike Stump11289f42009-09-09 15:08:12 +0000356 move(PlacementArgs),
Douglas Gregord0fefba2009-05-21 00:00:09 +0000357 PlacementRParen,
358 ParenTypeId,
Mike Stump11289f42009-09-09 15:08:12 +0000359 AllocType,
Douglas Gregord0fefba2009-05-21 00:00:09 +0000360 D.getSourceRange().getBegin(),
361 D.getSourceRange(),
362 Owned(ArraySize),
363 ConstructorLParen,
364 move(ConstructorArgs),
365 ConstructorRParen);
366}
367
Mike Stump11289f42009-09-09 15:08:12 +0000368Sema::OwningExprResult
Douglas Gregord0fefba2009-05-21 00:00:09 +0000369Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
370 SourceLocation PlacementLParen,
371 MultiExprArg PlacementArgs,
372 SourceLocation PlacementRParen,
Mike Stump11289f42009-09-09 15:08:12 +0000373 bool ParenTypeId,
Douglas Gregord0fefba2009-05-21 00:00:09 +0000374 QualType AllocType,
375 SourceLocation TypeLoc,
376 SourceRange TypeRange,
377 ExprArg ArraySizeE,
378 SourceLocation ConstructorLParen,
379 MultiExprArg ConstructorArgs,
380 SourceLocation ConstructorRParen) {
381 if (CheckAllocatedType(AllocType, TypeLoc, TypeRange))
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000382 return ExprError();
Sebastian Redl351bb782008-12-02 14:43:59 +0000383
Douglas Gregord0fefba2009-05-21 00:00:09 +0000384 QualType ResultType = Context.getPointerType(AllocType);
Sebastian Redlbd150f42008-11-21 19:14:01 +0000385
386 // That every array dimension except the first is constant was already
387 // checked by the type check above.
Sebastian Redl351bb782008-12-02 14:43:59 +0000388
Sebastian Redlbd150f42008-11-21 19:14:01 +0000389 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
390 // or enumeration type with a non-negative value."
Douglas Gregord0fefba2009-05-21 00:00:09 +0000391 Expr *ArraySize = (Expr *)ArraySizeE.get();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +0000392 if (ArraySize && !ArraySize->isTypeDependent()) {
Sebastian Redl351bb782008-12-02 14:43:59 +0000393 QualType SizeType = ArraySize->getType();
394 if (!SizeType->isIntegralType() && !SizeType->isEnumeralType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000395 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
396 diag::err_array_size_not_integral)
397 << SizeType << ArraySize->getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +0000398 // Let's see if this is a constant < 0. If so, we reject it out of hand.
399 // We don't care about special rules, so we tell the machinery it's not
400 // evaluated - it gives us a result in more cases.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +0000401 if (!ArraySize->isValueDependent()) {
402 llvm::APSInt Value;
403 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
404 if (Value < llvm::APSInt(
405 llvm::APInt::getNullValue(Value.getBitWidth()), false))
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000406 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
407 diag::err_typecheck_negative_array_size)
408 << ArraySize->getSourceRange());
Sebastian Redl8d2ccae2009-02-26 14:39:58 +0000409 }
Sebastian Redl351bb782008-12-02 14:43:59 +0000410 }
411 }
Sebastian Redlbd150f42008-11-21 19:14:01 +0000412
Sebastian Redlbd150f42008-11-21 19:14:01 +0000413 FunctionDecl *OperatorNew = 0;
414 FunctionDecl *OperatorDelete = 0;
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000415 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
416 unsigned NumPlaceArgs = PlacementArgs.size();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +0000417 if (!AllocType->isDependentType() &&
418 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
419 FindAllocationFunctions(StartLoc,
Sebastian Redl1df2bbe2009-02-09 18:24:27 +0000420 SourceRange(PlacementLParen, PlacementRParen),
421 UseGlobal, AllocType, ArraySize, PlaceArgs,
422 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000423 return ExprError();
Sebastian Redlbd150f42008-11-21 19:14:01 +0000424
425 bool Init = ConstructorLParen.isValid();
426 // --- Choosing a constructor ---
427 // C++ 5.3.4p15
428 // 1) If T is a POD and there's no initializer (ConstructorLParen is invalid)
429 // the object is not initialized. If the object, or any part of it, is
430 // const-qualified, it's an error.
431 // 2) If T is a POD and there's an empty initializer, the object is value-
432 // initialized.
433 // 3) If T is a POD and there's one initializer argument, the object is copy-
434 // constructed.
435 // 4) If T is a POD and there's more initializer arguments, it's an error.
436 // 5) If T is not a POD, the initializer arguments are used as constructor
437 // arguments.
438 //
439 // Or by the C++0x formulation:
440 // 1) If there's no initializer, the object is default-initialized according
441 // to C++0x rules.
442 // 2) Otherwise, the object is direct-initialized.
443 CXXConstructorDecl *Constructor = 0;
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000444 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
Sebastian Redlfb23ddf2009-05-07 16:14:23 +0000445 const RecordType *RT;
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000446 unsigned NumConsArgs = ConstructorArgs.size();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +0000447 if (AllocType->isDependentType()) {
448 // Skip all the checks.
Mike Stump12b8ce12009-08-04 21:02:39 +0000449 } else if ((RT = AllocType->getAs<RecordType>()) &&
450 !AllocType->isAggregateType()) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +0000451 ASTOwningVector<&ActionBase::DeleteExpr> ConvertedConstructorArgs(*this);
452
Sebastian Redlbd150f42008-11-21 19:14:01 +0000453 Constructor = PerformInitializationByConstructor(
Douglas Gregor5d3507d2009-09-09 23:08:42 +0000454 AllocType, move(ConstructorArgs),
Douglas Gregord0fefba2009-05-21 00:00:09 +0000455 TypeLoc,
456 SourceRange(TypeLoc, ConstructorRParen),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000457 RT->getDecl()->getDeclName(),
Douglas Gregor5d3507d2009-09-09 23:08:42 +0000458 NumConsArgs != 0 ? IK_Direct : IK_Default,
459 ConvertedConstructorArgs);
Sebastian Redlbd150f42008-11-21 19:14:01 +0000460 if (!Constructor)
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000461 return ExprError();
Douglas Gregor5d3507d2009-09-09 23:08:42 +0000462
463 // Take the converted constructor arguments and use them for the new
464 // expression.
465 NumConsArgs = ConvertedConstructorArgs.size();
466 ConsArgs = (Expr **)ConvertedConstructorArgs.take();
Sebastian Redlbd150f42008-11-21 19:14:01 +0000467 } else {
468 if (!Init) {
469 // FIXME: Check that no subpart is const.
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000470 if (AllocType.isConstQualified())
471 return ExprError(Diag(StartLoc, diag::err_new_uninitialized_const)
Douglas Gregord0fefba2009-05-21 00:00:09 +0000472 << TypeRange);
Sebastian Redlbd150f42008-11-21 19:14:01 +0000473 } else if (NumConsArgs == 0) {
474 // Object is value-initialized. Do nothing.
475 } else if (NumConsArgs == 1) {
476 // Object is direct-initialized.
Sebastian Redlfb23ddf2009-05-07 16:14:23 +0000477 // FIXME: What DeclarationName do we pass in here?
Sebastian Redl351bb782008-12-02 14:43:59 +0000478 if (CheckInitializerTypes(ConsArgs[0], AllocType, StartLoc,
Douglas Gregor5fb53972009-01-14 15:45:31 +0000479 DeclarationName() /*AllocType.getAsString()*/,
480 /*DirectInit=*/true))
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000481 return ExprError();
Sebastian Redlbd150f42008-11-21 19:14:01 +0000482 } else {
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000483 return ExprError(Diag(StartLoc,
484 diag::err_builtin_direct_init_more_than_one_arg)
485 << SourceRange(ConstructorLParen, ConstructorRParen));
Sebastian Redlbd150f42008-11-21 19:14:01 +0000486 }
487 }
488
489 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
490
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000491 PlacementArgs.release();
492 ConstructorArgs.release();
Douglas Gregord0fefba2009-05-21 00:00:09 +0000493 ArraySizeE.release();
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000494 return Owned(new (Context) CXXNewExpr(UseGlobal, OperatorNew, PlaceArgs,
Ted Kremenek5a201952009-02-07 01:47:29 +0000495 NumPlaceArgs, ParenTypeId, ArraySize, Constructor, Init,
Sebastian Redlbd150f42008-11-21 19:14:01 +0000496 ConsArgs, NumConsArgs, OperatorDelete, ResultType,
Mike Stump11289f42009-09-09 15:08:12 +0000497 StartLoc, Init ? ConstructorRParen : SourceLocation()));
Sebastian Redlbd150f42008-11-21 19:14:01 +0000498}
499
500/// CheckAllocatedType - Checks that a type is suitable as the allocated type
501/// in a new-expression.
502/// dimension off and stores the size expression in ArraySize.
Douglas Gregord0fefba2009-05-21 00:00:09 +0000503bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +0000504 SourceRange R) {
Sebastian Redlbd150f42008-11-21 19:14:01 +0000505 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
506 // abstract class type or array thereof.
Douglas Gregorac1fb652009-03-24 19:52:54 +0000507 if (AllocType->isFunctionType())
Douglas Gregord0fefba2009-05-21 00:00:09 +0000508 return Diag(Loc, diag::err_bad_new_type)
509 << AllocType << 0 << R;
Douglas Gregorac1fb652009-03-24 19:52:54 +0000510 else if (AllocType->isReferenceType())
Douglas Gregord0fefba2009-05-21 00:00:09 +0000511 return Diag(Loc, diag::err_bad_new_type)
512 << AllocType << 1 << R;
Douglas Gregorac1fb652009-03-24 19:52:54 +0000513 else if (!AllocType->isDependentType() &&
Douglas Gregord0fefba2009-05-21 00:00:09 +0000514 RequireCompleteType(Loc, AllocType,
Anders Carlssond624e162009-08-26 23:45:07 +0000515 PDiag(diag::err_new_incomplete_type)
516 << R))
Sebastian Redlbd150f42008-11-21 19:14:01 +0000517 return true;
Douglas Gregord0fefba2009-05-21 00:00:09 +0000518 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregorac1fb652009-03-24 19:52:54 +0000519 diag::err_allocation_of_abstract_type))
520 return true;
Sebastian Redlbd150f42008-11-21 19:14:01 +0000521
Sebastian Redlbd150f42008-11-21 19:14:01 +0000522 return false;
523}
524
Sebastian Redlfaf68082008-12-03 20:26:15 +0000525/// FindAllocationFunctions - Finds the overloads of operator new and delete
526/// that are appropriate for the allocation.
Sebastian Redl1df2bbe2009-02-09 18:24:27 +0000527bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
528 bool UseGlobal, QualType AllocType,
529 bool IsArray, Expr **PlaceArgs,
530 unsigned NumPlaceArgs,
Sebastian Redlfaf68082008-12-03 20:26:15 +0000531 FunctionDecl *&OperatorNew,
Mike Stump11289f42009-09-09 15:08:12 +0000532 FunctionDecl *&OperatorDelete) {
Sebastian Redlfaf68082008-12-03 20:26:15 +0000533 // --- Choosing an allocation function ---
534 // C++ 5.3.4p8 - 14 & 18
535 // 1) If UseGlobal is true, only look in the global scope. Else, also look
536 // in the scope of the allocated class.
537 // 2) If an array size is given, look for operator new[], else look for
538 // operator new.
539 // 3) The first argument is always size_t. Append the arguments from the
540 // placement form.
541 // FIXME: Also find the appropriate delete operator.
542
543 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
544 // We don't care about the actual value of this argument.
545 // FIXME: Should the Sema create the expression and embed it in the syntax
546 // tree? Or should the consumer just recalculate the value?
Anders Carlssona471db02009-08-16 20:29:29 +0000547 IntegerLiteral Size(llvm::APInt::getNullValue(
548 Context.Target.getPointerWidth(0)),
549 Context.getSizeType(),
550 SourceLocation());
551 AllocArgs[0] = &Size;
Sebastian Redlfaf68082008-12-03 20:26:15 +0000552 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
553
554 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
555 IsArray ? OO_Array_New : OO_New);
556 if (AllocType->isRecordType() && !UseGlobal) {
Mike Stump11289f42009-09-09 15:08:12 +0000557 CXXRecordDecl *Record
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000558 = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl());
Sebastian Redl33a31012008-12-04 22:20:51 +0000559 // FIXME: We fail to find inherited overloads.
Sebastian Redl1df2bbe2009-02-09 18:24:27 +0000560 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl33a31012008-12-04 22:20:51 +0000561 AllocArgs.size(), Record, /*AllowMissing=*/true,
562 OperatorNew))
Sebastian Redlfaf68082008-12-03 20:26:15 +0000563 return true;
Sebastian Redlfaf68082008-12-03 20:26:15 +0000564 }
565 if (!OperatorNew) {
566 // Didn't find a member overload. Look for a global one.
567 DeclareGlobalNewDelete();
Sebastian Redl33a31012008-12-04 22:20:51 +0000568 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl1df2bbe2009-02-09 18:24:27 +0000569 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl33a31012008-12-04 22:20:51 +0000570 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
571 OperatorNew))
Sebastian Redlfaf68082008-12-03 20:26:15 +0000572 return true;
Sebastian Redlfaf68082008-12-03 20:26:15 +0000573 }
574
Anders Carlsson6f9dabf2009-05-31 20:26:12 +0000575 // FindAllocationOverload can change the passed in arguments, so we need to
576 // copy them back.
577 if (NumPlaceArgs > 0)
578 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
Mike Stump11289f42009-09-09 15:08:12 +0000579
Sebastian Redlfaf68082008-12-03 20:26:15 +0000580 return false;
581}
582
Sebastian Redl33a31012008-12-04 22:20:51 +0000583/// FindAllocationOverload - Find an fitting overload for the allocation
584/// function in the specified scope.
Sebastian Redl1df2bbe2009-02-09 18:24:27 +0000585bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
586 DeclarationName Name, Expr** Args,
587 unsigned NumArgs, DeclContext *Ctx,
Mike Stump11289f42009-09-09 15:08:12 +0000588 bool AllowMissing, FunctionDecl *&Operator) {
Douglas Gregor55297ac2008-12-23 00:26:44 +0000589 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000590 llvm::tie(Alloc, AllocEnd) = Ctx->lookup(Name);
Douglas Gregor55297ac2008-12-23 00:26:44 +0000591 if (Alloc == AllocEnd) {
Sebastian Redl33a31012008-12-04 22:20:51 +0000592 if (AllowMissing)
593 return false;
Sebastian Redl33a31012008-12-04 22:20:51 +0000594 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner45d9d602009-02-17 07:29:20 +0000595 << Name << Range;
Sebastian Redl33a31012008-12-04 22:20:51 +0000596 }
597
598 OverloadCandidateSet Candidates;
Douglas Gregor55297ac2008-12-23 00:26:44 +0000599 for (; Alloc != AllocEnd; ++Alloc) {
600 // Even member operator new/delete are implicitly treated as
601 // static, so don't use AddMemberCandidate.
602 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>(*Alloc))
603 AddOverloadCandidate(Fn, Args, NumArgs, Candidates,
604 /*SuppressUserConversions=*/false);
Sebastian Redl33a31012008-12-04 22:20:51 +0000605 }
606
607 // Do the resolution.
608 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +0000609 switch(BestViableFunction(Candidates, StartLoc, Best)) {
Sebastian Redl33a31012008-12-04 22:20:51 +0000610 case OR_Success: {
611 // Got one!
612 FunctionDecl *FnDecl = Best->Function;
613 // The first argument is size_t, and the first parameter must be size_t,
614 // too. This is checked on declaration and can be assumed. (It can't be
615 // asserted on, though, since invalid decls are left in there.)
616 for (unsigned i = 1; i < NumArgs; ++i) {
617 // FIXME: Passing word to diagnostic.
Anders Carlsson24187122009-05-31 19:49:47 +0000618 if (PerformCopyInitialization(Args[i],
Sebastian Redl33a31012008-12-04 22:20:51 +0000619 FnDecl->getParamDecl(i)->getType(),
620 "passing"))
621 return true;
622 }
623 Operator = FnDecl;
624 return false;
625 }
626
627 case OR_No_Viable_Function:
Sebastian Redl33a31012008-12-04 22:20:51 +0000628 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner45d9d602009-02-17 07:29:20 +0000629 << Name << Range;
Sebastian Redl33a31012008-12-04 22:20:51 +0000630 PrintOverloadCandidates(Candidates, /*OnlyViable=*/false);
631 return true;
632
633 case OR_Ambiguous:
Sebastian Redl33a31012008-12-04 22:20:51 +0000634 Diag(StartLoc, diag::err_ovl_ambiguous_call)
Sebastian Redl1df2bbe2009-02-09 18:24:27 +0000635 << Name << Range;
Sebastian Redl33a31012008-12-04 22:20:51 +0000636 PrintOverloadCandidates(Candidates, /*OnlyViable=*/true);
637 return true;
Douglas Gregor171c45a2009-02-18 21:56:37 +0000638
639 case OR_Deleted:
640 Diag(StartLoc, diag::err_ovl_deleted_call)
641 << Best->Function->isDeleted()
642 << Name << Range;
643 PrintOverloadCandidates(Candidates, /*OnlyViable=*/true);
644 return true;
Sebastian Redl33a31012008-12-04 22:20:51 +0000645 }
646 assert(false && "Unreachable, bad result from BestViableFunction");
647 return true;
648}
649
650
Sebastian Redlfaf68082008-12-03 20:26:15 +0000651/// DeclareGlobalNewDelete - Declare the global forms of operator new and
652/// delete. These are:
653/// @code
654/// void* operator new(std::size_t) throw(std::bad_alloc);
655/// void* operator new[](std::size_t) throw(std::bad_alloc);
656/// void operator delete(void *) throw();
657/// void operator delete[](void *) throw();
658/// @endcode
659/// Note that the placement and nothrow forms of new are *not* implicitly
660/// declared. Their use requires including \<new\>.
Mike Stump11289f42009-09-09 15:08:12 +0000661void Sema::DeclareGlobalNewDelete() {
Sebastian Redlfaf68082008-12-03 20:26:15 +0000662 if (GlobalNewDeleteDeclared)
663 return;
664 GlobalNewDeleteDeclared = true;
665
666 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
667 QualType SizeT = Context.getSizeType();
668
669 // FIXME: Exception specifications are not added.
670 DeclareGlobalAllocationFunction(
671 Context.DeclarationNames.getCXXOperatorName(OO_New),
672 VoidPtr, SizeT);
673 DeclareGlobalAllocationFunction(
674 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
675 VoidPtr, SizeT);
676 DeclareGlobalAllocationFunction(
677 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
678 Context.VoidTy, VoidPtr);
679 DeclareGlobalAllocationFunction(
680 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
681 Context.VoidTy, VoidPtr);
682}
683
684/// DeclareGlobalAllocationFunction - Declares a single implicit global
685/// allocation function if it doesn't already exist.
686void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Mike Stump11289f42009-09-09 15:08:12 +0000687 QualType Return, QualType Argument) {
Sebastian Redlfaf68082008-12-03 20:26:15 +0000688 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
689
690 // Check if this function is already declared.
Douglas Gregor8b9ccca2008-12-23 21:05:05 +0000691 {
Douglas Gregor17eb26b2008-12-23 22:05:29 +0000692 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000693 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor8b9ccca2008-12-23 21:05:05 +0000694 Alloc != AllocEnd; ++Alloc) {
695 // FIXME: Do we need to check for default arguments here?
696 FunctionDecl *Func = cast<FunctionDecl>(*Alloc);
697 if (Func->getNumParams() == 1 &&
Ted Kremenek5a201952009-02-07 01:47:29 +0000698 Context.getCanonicalType(Func->getParamDecl(0)->getType())==Argument)
Sebastian Redlfaf68082008-12-03 20:26:15 +0000699 return;
Sebastian Redlfaf68082008-12-03 20:26:15 +0000700 }
701 }
702
703 QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0);
704 FunctionDecl *Alloc =
705 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +0000706 FnType, /*DInfo=*/0, FunctionDecl::None, false, true);
Sebastian Redlfaf68082008-12-03 20:26:15 +0000707 Alloc->setImplicit();
708 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +0000709 0, Argument, /*DInfo=*/0,
710 VarDecl::None, 0);
Ted Kremenek4ba36fc2009-01-14 00:42:25 +0000711 Alloc->setParams(Context, &Param, 1);
Sebastian Redlfaf68082008-12-03 20:26:15 +0000712
Douglas Gregor8b9ccca2008-12-23 21:05:05 +0000713 // FIXME: Also add this declaration to the IdentifierResolver, but
714 // make sure it is at the end of the chain to coincide with the
715 // global scope.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000716 ((DeclContext *)TUScope->getEntity())->addDecl(Alloc);
Sebastian Redlfaf68082008-12-03 20:26:15 +0000717}
718
Sebastian Redlbd150f42008-11-21 19:14:01 +0000719/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
720/// @code ::delete ptr; @endcode
721/// or
722/// @code delete [] ptr; @endcode
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000723Action::OwningExprResult
Sebastian Redlbd150f42008-11-21 19:14:01 +0000724Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
Mike Stump11289f42009-09-09 15:08:12 +0000725 bool ArrayForm, ExprArg Operand) {
Douglas Gregor0fea62d2009-09-09 23:39:55 +0000726 // C++ [expr.delete]p1:
727 // The operand shall have a pointer type, or a class type having a single
728 // conversion function to a pointer type. The result has type void.
729 //
Sebastian Redlbd150f42008-11-21 19:14:01 +0000730 // DR599 amends "pointer type" to "pointer to object type" in both cases.
731
Anders Carlssona471db02009-08-16 20:29:29 +0000732 FunctionDecl *OperatorDelete = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000733
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000734 Expr *Ex = (Expr *)Operand.get();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +0000735 if (!Ex->isTypeDependent()) {
736 QualType Type = Ex->getType();
Sebastian Redlbd150f42008-11-21 19:14:01 +0000737
Douglas Gregor0fea62d2009-09-09 23:39:55 +0000738 if (const RecordType *Record = Type->getAs<RecordType>()) {
Fariborz Jahanianc34c1792009-09-15 17:21:47 +0000739 OverloadCandidateSet CandidateSet;
Douglas Gregor0fea62d2009-09-09 23:39:55 +0000740 llvm::SmallVector<CXXConversionDecl *, 4> ObjectPtrConversions;
Fariborz Jahanianb54ccb22009-09-11 21:44:33 +0000741 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
742 OverloadedFunctionDecl *Conversions =
Fariborz Jahanianb394f502009-09-12 18:26:03 +0000743 RD->getVisibleConversionFunctions();
Douglas Gregor0fea62d2009-09-09 23:39:55 +0000744
Douglas Gregor0fea62d2009-09-09 23:39:55 +0000745 for (OverloadedFunctionDecl::function_iterator
746 Func = Conversions->function_begin(),
747 FuncEnd = Conversions->function_end();
748 Func != FuncEnd; ++Func) {
749 // Skip over templated conversion functions; they aren't considered.
750 if (isa<FunctionTemplateDecl>(*Func))
751 continue;
752
753 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
754
755 QualType ConvType = Conv->getConversionType().getNonReferenceType();
756 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
757 if (ConvPtrType->getPointeeType()->isObjectType())
Fariborz Jahanianc34c1792009-09-15 17:21:47 +0000758 AddConversionCandidate(Conv, Ex, ConvType, CandidateSet);
Douglas Gregor0fea62d2009-09-09 23:39:55 +0000759 }
Fariborz Jahanianc34c1792009-09-15 17:21:47 +0000760 OverloadCandidateSet::iterator Best;
761 switch (BestViableFunction(CandidateSet, Ex->getLocStart(), Best)) {
762 case OR_Success:
763 {
764 Operand.release();
765 CXXConversionDecl *Conversion
766 = cast<CXXConversionDecl>(Best->Function);
767 if (PerformImplicitConversion(Ex,
768 Conversion->getConversionType(),
769 "converting"))
770 return ExprError();
771
772 Operand = Owned(Ex);
773 Type = Ex->getType();
774 break;
775 }
776 case OR_No_Viable_Function:
777 case OR_Deleted:
778 break; // Will issue error below.
779 case OR_Ambiguous:
780 Diag(StartLoc, diag::err_ambiguous_delete_operand)
781 << Type << Ex->getSourceRange();
782 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregor0fea62d2009-09-09 23:39:55 +0000783 return ExprError();
Douglas Gregor0fea62d2009-09-09 23:39:55 +0000784 }
Sebastian Redl8d2ccae2009-02-26 14:39:58 +0000785 }
786
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000787 if (!Type->isPointerType())
788 return ExprError(Diag(StartLoc, diag::err_delete_operand)
789 << Type << Ex->getSourceRange());
Sebastian Redl8d2ccae2009-02-26 14:39:58 +0000790
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000791 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Douglas Gregorc9a1a3b2009-03-24 20:13:58 +0000792 if (Pointee->isFunctionType() || Pointee->isVoidType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000793 return ExprError(Diag(StartLoc, diag::err_delete_operand)
794 << Type << Ex->getSourceRange());
Douglas Gregorc9a1a3b2009-03-24 20:13:58 +0000795 else if (!Pointee->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +0000796 RequireCompleteType(StartLoc, Pointee,
Anders Carlssond624e162009-08-26 23:45:07 +0000797 PDiag(diag::warn_delete_incomplete)
798 << Ex->getSourceRange()))
Douglas Gregorc9a1a3b2009-03-24 20:13:58 +0000799 return ExprError();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +0000800
Mike Stump11289f42009-09-09 15:08:12 +0000801 // FIXME: This should be shared with the code for finding the delete
Anders Carlssona471db02009-08-16 20:29:29 +0000802 // operator in ActOnCXXNew.
803 IntegerLiteral Size(llvm::APInt::getNullValue(
804 Context.Target.getPointerWidth(0)),
805 Context.getSizeType(),
806 SourceLocation());
807 ImplicitCastExpr Cast(Context.getPointerType(Context.VoidTy),
808 CastExpr::CK_Unknown, &Size, false);
809 Expr *DeleteArg = &Cast;
Mike Stump11289f42009-09-09 15:08:12 +0000810
Anders Carlssona471db02009-08-16 20:29:29 +0000811 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
812 ArrayForm ? OO_Array_Delete : OO_Delete);
813
814 if (Pointee->isRecordType() && !UseGlobal) {
Mike Stump11289f42009-09-09 15:08:12 +0000815 CXXRecordDecl *Record
Anders Carlssona471db02009-08-16 20:29:29 +0000816 = cast<CXXRecordDecl>(Pointee->getAs<RecordType>()->getDecl());
817 // FIXME: We fail to find inherited overloads.
818 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
819 &DeleteArg, 1, Record, /*AllowMissing=*/true,
820 OperatorDelete))
821 return ExprError();
Fariborz Jahanian37d06562009-09-03 23:18:17 +0000822 if (!Record->hasTrivialDestructor())
823 if (const CXXDestructorDecl *Dtor = Record->getDestructor(Context))
Mike Stump11289f42009-09-09 15:08:12 +0000824 MarkDeclarationReferenced(StartLoc,
Fariborz Jahanian37d06562009-09-03 23:18:17 +0000825 const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssona471db02009-08-16 20:29:29 +0000826 }
Mike Stump11289f42009-09-09 15:08:12 +0000827
Anders Carlssona471db02009-08-16 20:29:29 +0000828 if (!OperatorDelete) {
829 // Didn't find a member overload. Look for a global one.
830 DeclareGlobalNewDelete();
831 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000832 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
Anders Carlssona471db02009-08-16 20:29:29 +0000833 &DeleteArg, 1, TUDecl, /*AllowMissing=*/false,
834 OperatorDelete))
835 return ExprError();
836 }
Mike Stump11289f42009-09-09 15:08:12 +0000837
Sebastian Redl8d2ccae2009-02-26 14:39:58 +0000838 // FIXME: Check access and ambiguity of operator delete and destructor.
Sebastian Redlbd150f42008-11-21 19:14:01 +0000839 }
840
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000841 Operand.release();
842 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
Anders Carlssona471db02009-08-16 20:29:29 +0000843 OperatorDelete, Ex, StartLoc));
Sebastian Redlbd150f42008-11-21 19:14:01 +0000844}
845
846
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +0000847/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
848/// C++ if/switch/while/for statement.
849/// e.g: "if (int x = f()) {...}"
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000850Action::OwningExprResult
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +0000851Sema::ActOnCXXConditionDeclarationExpr(Scope *S, SourceLocation StartLoc,
852 Declarator &D,
853 SourceLocation EqualLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000854 ExprArg AssignExprVal) {
855 assert(AssignExprVal.get() && "Null assignment expression");
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +0000856
857 // C++ 6.4p2:
858 // The declarator shall not specify a function or an array.
859 // The type-specifier-seq shall not contain typedef and shall not declare a
860 // new class or enumeration.
861
862 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
863 "Parser allowed 'typedef' as storage class of condition decl.");
864
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +0000865 // FIXME: Store DeclaratorInfo in the expression.
866 DeclaratorInfo *DInfo = 0;
Argyrios Kyrtzidisae438f82009-08-11 05:20:41 +0000867 TagDecl *OwnedTag = 0;
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +0000868 QualType Ty = GetTypeForDeclarator(D, S, &DInfo, /*Skip=*/0, &OwnedTag);
Mike Stump11289f42009-09-09 15:08:12 +0000869
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +0000870 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
871 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
872 // would be created and CXXConditionDeclExpr wants a VarDecl.
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000873 return ExprError(Diag(StartLoc, diag::err_invalid_use_of_function_type)
874 << SourceRange(StartLoc, EqualLoc));
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +0000875 } else if (Ty->isArrayType()) { // ...or an array.
Chris Lattnerf490e152008-11-19 05:27:50 +0000876 Diag(StartLoc, diag::err_invalid_use_of_array_type)
877 << SourceRange(StartLoc, EqualLoc);
Argyrios Kyrtzidisae438f82009-08-11 05:20:41 +0000878 } else if (OwnedTag && OwnedTag->isDefinition()) {
879 // The type-specifier-seq shall not declare a new class or enumeration.
880 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +0000881 }
882
Douglas Gregor4a75be22009-06-23 21:43:56 +0000883 DeclPtrTy Dcl = ActOnDeclarator(S, D);
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +0000884 if (!Dcl)
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000885 return ExprError();
Anders Carlsson5e9444f2009-05-30 21:37:25 +0000886 AddInitializerToDecl(Dcl, move(AssignExprVal), /*DirectInit=*/false);
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +0000887
Douglas Gregor85970ca2008-12-10 23:01:14 +0000888 // Mark this variable as one that is declared within a conditional.
Chris Lattner83f095c2009-03-28 19:18:32 +0000889 // We know that the decl had to be a VarDecl because that is the only type of
890 // decl that can be assigned and the grammar requires an '='.
891 VarDecl *VD = cast<VarDecl>(Dcl.getAs<Decl>());
892 VD->setDeclaredInCondition(true);
893 return Owned(new (Context) CXXConditionDeclExpr(StartLoc, EqualLoc, VD));
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +0000894}
895
896/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
897bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
898 // C++ 6.4p4:
899 // The value of a condition that is an initialized declaration in a statement
900 // other than a switch statement is the value of the declared variable
901 // implicitly converted to type bool. If that conversion is ill-formed, the
902 // program is ill-formed.
903 // The value of a condition that is an expression is the value of the
904 // expression, implicitly converted to bool.
905 //
Douglas Gregor5fb53972009-01-14 15:45:31 +0000906 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +0000907}
Douglas Gregoraa1e21d2008-09-12 00:47:35 +0000908
909/// Helper function to determine whether this is the (deprecated) C++
910/// conversion from a string literal to a pointer to non-const char or
911/// non-const wchar_t (for narrow and wide string literals,
912/// respectively).
Mike Stump11289f42009-09-09 15:08:12 +0000913bool
Douglas Gregoraa1e21d2008-09-12 00:47:35 +0000914Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
915 // Look inside the implicit cast, if it exists.
916 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
917 From = Cast->getSubExpr();
918
919 // A string literal (2.13.4) that is not a wide string literal can
920 // be converted to an rvalue of type "pointer to char"; a wide
921 // string literal can be converted to an rvalue of type "pointer
922 // to wchar_t" (C++ 4.2p2).
923 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From))
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000924 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump11289f42009-09-09 15:08:12 +0000925 if (const BuiltinType *ToPointeeType
Douglas Gregoraa1e21d2008-09-12 00:47:35 +0000926 = ToPtrType->getPointeeType()->getAsBuiltinType()) {
927 // This conversion is considered only when there is an
928 // explicit appropriate pointer target type (C++ 4.2p2).
929 if (ToPtrType->getPointeeType().getCVRQualifiers() == 0 &&
930 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
931 (!StrLit->isWide() &&
932 (ToPointeeType->getKind() == BuiltinType::Char_U ||
933 ToPointeeType->getKind() == BuiltinType::Char_S))))
934 return true;
935 }
936
937 return false;
938}
Douglas Gregor39c16d42008-10-24 04:54:22 +0000939
940/// PerformImplicitConversion - Perform an implicit conversion of the
941/// expression From to the type ToType. Returns true if there was an
942/// error, false otherwise. The expression From is replaced with the
Douglas Gregor47d3f272008-12-19 17:40:08 +0000943/// converted expression. Flavor is the kind of conversion we're
Douglas Gregor5fb53972009-01-14 15:45:31 +0000944/// performing, used in the error message. If @p AllowExplicit,
Sebastian Redl42e92c42009-04-12 17:16:29 +0000945/// explicit user-defined conversions are permitted. @p Elidable should be true
946/// when called for copies which may be elided (C++ 12.8p15). C++0x overload
947/// resolution works differently in that case.
948bool
Douglas Gregor47d3f272008-12-19 17:40:08 +0000949Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Sebastian Redl42e92c42009-04-12 17:16:29 +0000950 const char *Flavor, bool AllowExplicit,
Mike Stump11289f42009-09-09 15:08:12 +0000951 bool Elidable) {
Sebastian Redl42e92c42009-04-12 17:16:29 +0000952 ImplicitConversionSequence ICS;
953 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
954 if (Elidable && getLangOptions().CPlusPlus0x) {
Mike Stump11289f42009-09-09 15:08:12 +0000955 ICS = TryImplicitConversion(From, ToType,
Anders Carlssonef4c7212009-08-27 17:24:15 +0000956 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +0000957 AllowExplicit,
Anders Carlsson228eea32009-08-28 15:33:32 +0000958 /*ForceRValue=*/true,
959 /*InOverloadResolution=*/false);
Sebastian Redl42e92c42009-04-12 17:16:29 +0000960 }
961 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion) {
Mike Stump11289f42009-09-09 15:08:12 +0000962 ICS = TryImplicitConversion(From, ToType,
Anders Carlssonef4c7212009-08-27 17:24:15 +0000963 /*SuppressUserConversions=*/false,
964 AllowExplicit,
Anders Carlsson228eea32009-08-28 15:33:32 +0000965 /*ForceRValue=*/false,
966 /*InOverloadResolution=*/false);
Sebastian Redl42e92c42009-04-12 17:16:29 +0000967 }
Douglas Gregor5fb53972009-01-14 15:45:31 +0000968 return PerformImplicitConversion(From, ToType, ICS, Flavor);
969}
970
971/// PerformImplicitConversion - Perform an implicit conversion of the
972/// expression From to the type ToType using the pre-computed implicit
973/// conversion sequence ICS. Returns true if there was an error, false
974/// otherwise. The expression From is replaced with the converted
975/// expression. Flavor is the kind of conversion we're performing,
976/// used in the error message.
977bool
978Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
979 const ImplicitConversionSequence &ICS,
980 const char* Flavor) {
Douglas Gregor39c16d42008-10-24 04:54:22 +0000981 switch (ICS.ConversionKind) {
982 case ImplicitConversionSequence::StandardConversion:
Douglas Gregor47d3f272008-12-19 17:40:08 +0000983 if (PerformImplicitConversion(From, ToType, ICS.Standard, Flavor))
Douglas Gregor39c16d42008-10-24 04:54:22 +0000984 return true;
985 break;
986
Anders Carlsson110b07b2009-09-15 06:28:28 +0000987 case ImplicitConversionSequence::UserDefinedConversion: {
988
Fariborz Jahanian2fee79a2009-08-28 22:04:50 +0000989 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
990 CastExpr::CastKind CastKind = CastExpr::CK_Unknown;
Anders Carlsson110b07b2009-09-15 06:28:28 +0000991 QualType BeforeToType;
992 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
Fariborz Jahanian2fee79a2009-08-28 22:04:50 +0000993 CastKind = CastExpr::CK_UserDefinedConversion;
Anders Carlsson110b07b2009-09-15 06:28:28 +0000994
995 // If the user-defined conversion is specified by a conversion function,
996 // the initial standard conversion sequence converts the source type to
997 // the implicit object parameter of the conversion function.
998 BeforeToType = Context.getTagDeclType(Conv->getParent());
999 } else if (const CXXConstructorDecl *Ctor =
1000 dyn_cast<CXXConstructorDecl>(FD)) {
Anders Carlssone9766d52009-09-09 21:33:21 +00001001 CastKind = CastExpr::CK_ConstructorConversion;
Anders Carlsson110b07b2009-09-15 06:28:28 +00001002
1003 // If the user-defined conversion is specified by a constructor, the
1004 // initial standard conversion sequence converts the source type to the
1005 // type required by the argument of the constructor
1006 BeforeToType = Ctor->getParamDecl(0)->getType();
1007 }
Anders Carlssone9766d52009-09-09 21:33:21 +00001008 else
1009 assert(0 && "Unknown conversion function kind!");
1010
Anders Carlsson110b07b2009-09-15 06:28:28 +00001011 if (PerformImplicitConversion(From, BeforeToType,
1012 ICS.UserDefined.Before, "converting"))
1013 return true;
1014
Anders Carlssone9766d52009-09-09 21:33:21 +00001015 OwningExprResult CastArg
1016 = BuildCXXCastArgument(From->getLocStart(),
1017 ToType.getNonReferenceType(),
1018 CastKind, cast<CXXMethodDecl>(FD),
1019 Owned(From));
1020
1021 if (CastArg.isInvalid())
1022 return true;
1023
Anders Carlsson611da282009-09-15 05:49:31 +00001024 From = new (Context) ImplicitCastExpr(ToType.getNonReferenceType(),
1025 CastKind, CastArg.takeAs<Expr>(),
1026 ToType->isLValueReferenceType());
Fariborz Jahanian2fee79a2009-08-28 22:04:50 +00001027 return false;
1028 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00001029
1030 case ImplicitConversionSequence::EllipsisConversion:
1031 assert(false && "Cannot perform an ellipsis conversion");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001032 return false;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001033
1034 case ImplicitConversionSequence::BadConversion:
1035 return true;
1036 }
1037
1038 // Everything went well.
1039 return false;
1040}
1041
1042/// PerformImplicitConversion - Perform an implicit conversion of the
1043/// expression From to the type ToType by following the standard
1044/// conversion sequence SCS. Returns true if there was an error, false
1045/// otherwise. The expression From is replaced with the converted
Douglas Gregor47d3f272008-12-19 17:40:08 +00001046/// expression. Flavor is the context in which we're performing this
1047/// conversion, for use in error messages.
Mike Stump11289f42009-09-09 15:08:12 +00001048bool
Douglas Gregor39c16d42008-10-24 04:54:22 +00001049Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor47d3f272008-12-19 17:40:08 +00001050 const StandardConversionSequence& SCS,
Douglas Gregor5fb53972009-01-14 15:45:31 +00001051 const char *Flavor) {
Mike Stump87c57ac2009-05-16 07:39:55 +00001052 // Overall FIXME: we are recomputing too many types here and doing far too
1053 // much extra work. What this means is that we need to keep track of more
1054 // information that is computed when we try the implicit conversion initially,
1055 // so that we don't need to recompute anything here.
Douglas Gregor39c16d42008-10-24 04:54:22 +00001056 QualType FromType = From->getType();
1057
Douglas Gregor2fe98832008-11-03 19:09:14 +00001058 if (SCS.CopyConstructor) {
Anders Carlsson549c5bd2009-05-19 04:45:15 +00001059 // FIXME: When can ToType be a reference type?
1060 assert(!ToType->isReferenceType());
Mike Stump11289f42009-09-09 15:08:12 +00001061
1062 OwningExprResult FromResult =
1063 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1064 ToType, SCS.CopyConstructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00001065 MultiExprArg(*this, (void**)&From, 1));
Mike Stump11289f42009-09-09 15:08:12 +00001066
Anders Carlsson6eb55572009-08-25 05:12:04 +00001067 if (FromResult.isInvalid())
1068 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001069
Anders Carlsson6eb55572009-08-25 05:12:04 +00001070 From = FromResult.takeAs<Expr>();
Douglas Gregor2fe98832008-11-03 19:09:14 +00001071 return false;
1072 }
1073
Douglas Gregor39c16d42008-10-24 04:54:22 +00001074 // Perform the first implicit conversion.
1075 switch (SCS.First) {
1076 case ICK_Identity:
1077 case ICK_Lvalue_To_Rvalue:
1078 // Nothing to do.
1079 break;
1080
1081 case ICK_Array_To_Pointer:
Douglas Gregor171c45a2009-02-18 21:56:37 +00001082 FromType = Context.getArrayDecayedType(FromType);
Anders Carlsson2c101b32009-08-08 21:04:35 +00001083 ImpCastExprToType(From, FromType, CastExpr::CK_ArrayToPointerDecay);
Douglas Gregor171c45a2009-02-18 21:56:37 +00001084 break;
1085
1086 case ICK_Function_To_Pointer:
Douglas Gregor1baf54e2009-03-13 18:40:31 +00001087 if (Context.getCanonicalType(FromType) == Context.OverloadTy) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00001088 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, true);
1089 if (!Fn)
1090 return true;
1091
Douglas Gregor171c45a2009-02-18 21:56:37 +00001092 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
1093 return true;
1094
Douglas Gregorcd695e52008-11-10 20:40:00 +00001095 FixOverloadedFunctionReference(From, Fn);
1096 FromType = From->getType();
Douglas Gregorcd695e52008-11-10 20:40:00 +00001097 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00001098 FromType = Context.getPointerType(FromType);
Anders Carlsson6904f642009-09-01 20:37:18 +00001099 ImpCastExprToType(From, FromType, CastExpr::CK_FunctionToPointerDecay);
Douglas Gregor39c16d42008-10-24 04:54:22 +00001100 break;
1101
1102 default:
1103 assert(false && "Improper first standard conversion");
1104 break;
1105 }
1106
1107 // Perform the second implicit conversion
1108 switch (SCS.Second) {
1109 case ICK_Identity:
1110 // Nothing to do.
1111 break;
1112
1113 case ICK_Integral_Promotion:
1114 case ICK_Floating_Promotion:
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001115 case ICK_Complex_Promotion:
Douglas Gregor39c16d42008-10-24 04:54:22 +00001116 case ICK_Integral_Conversion:
1117 case ICK_Floating_Conversion:
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001118 case ICK_Complex_Conversion:
Douglas Gregor39c16d42008-10-24 04:54:22 +00001119 case ICK_Floating_Integral:
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001120 case ICK_Complex_Real:
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001121 case ICK_Compatible_Conversion:
1122 // FIXME: Go deeper to get the unqualified type!
Douglas Gregor39c16d42008-10-24 04:54:22 +00001123 FromType = ToType.getUnqualifiedType();
1124 ImpCastExprToType(From, FromType);
1125 break;
1126
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001127 case ICK_Pointer_Conversion: {
Douglas Gregor47d3f272008-12-19 17:40:08 +00001128 if (SCS.IncompatibleObjC) {
1129 // Diagnose incompatible Objective-C conversions
Mike Stump11289f42009-09-09 15:08:12 +00001130 Diag(From->getSourceRange().getBegin(),
Douglas Gregor47d3f272008-12-19 17:40:08 +00001131 diag::ext_typecheck_convert_incompatible_pointer)
1132 << From->getType() << ToType << Flavor
1133 << From->getSourceRange();
1134 }
1135
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001136
1137 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
1138 if (CheckPointerConversion(From, ToType, Kind))
Douglas Gregor39c16d42008-10-24 04:54:22 +00001139 return true;
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001140 ImpCastExprToType(From, ToType, Kind);
Douglas Gregor39c16d42008-10-24 04:54:22 +00001141 break;
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001142 }
1143
1144 case ICK_Pointer_Member: {
1145 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
1146 if (CheckMemberPointerConversion(From, ToType, Kind))
1147 return true;
1148 ImpCastExprToType(From, ToType, Kind);
1149 break;
1150 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00001151 case ICK_Boolean_Conversion:
1152 FromType = Context.BoolTy;
1153 ImpCastExprToType(From, FromType);
1154 break;
1155
1156 default:
1157 assert(false && "Improper second standard conversion");
1158 break;
1159 }
1160
1161 switch (SCS.Third) {
1162 case ICK_Identity:
1163 // Nothing to do.
1164 break;
1165
1166 case ICK_Qualification:
Mike Stump87c57ac2009-05-16 07:39:55 +00001167 // FIXME: Not sure about lvalue vs rvalue here in the presence of rvalue
1168 // references.
Mike Stump11289f42009-09-09 15:08:12 +00001169 ImpCastExprToType(From, ToType.getNonReferenceType(),
Anders Carlssona076d142009-07-31 01:23:52 +00001170 CastExpr::CK_Unknown,
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001171 ToType->isLValueReferenceType());
Douglas Gregor39c16d42008-10-24 04:54:22 +00001172 break;
1173
1174 default:
1175 assert(false && "Improper second standard conversion");
1176 break;
1177 }
1178
1179 return false;
1180}
1181
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001182Sema::OwningExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
1183 SourceLocation KWLoc,
1184 SourceLocation LParen,
1185 TypeTy *Ty,
1186 SourceLocation RParen) {
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00001187 QualType T = GetTypeFromParser(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00001188
Anders Carlsson1f9648d2009-07-07 19:06:02 +00001189 // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
1190 // all traits except __is_class, __is_enum and __is_union require a the type
1191 // to be complete.
1192 if (OTT != UTT_IsClass && OTT != UTT_IsEnum && OTT != UTT_IsUnion) {
Mike Stump11289f42009-09-09 15:08:12 +00001193 if (RequireCompleteType(KWLoc, T,
Anders Carlsson029fc692009-08-26 22:59:12 +00001194 diag::err_incomplete_type_used_in_type_trait_expr))
Anders Carlsson1f9648d2009-07-07 19:06:02 +00001195 return ExprError();
1196 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001197
1198 // There is no point in eagerly computing the value. The traits are designed
1199 // to be used from type trait templates, so Ty will be a template parameter
1200 // 99% of the time.
Anders Carlsson1f9648d2009-07-07 19:06:02 +00001201 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT, T,
1202 RParen, Context.BoolTy));
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001203}
Sebastian Redl5822f082009-02-07 20:10:22 +00001204
1205QualType Sema::CheckPointerToMemberOperands(
Mike Stump11289f42009-09-09 15:08:12 +00001206 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect) {
Sebastian Redl5822f082009-02-07 20:10:22 +00001207 const char *OpSpelling = isIndirect ? "->*" : ".*";
1208 // C++ 5.5p2
1209 // The binary operator .* [p3: ->*] binds its second operand, which shall
1210 // be of type "pointer to member of T" (where T is a completely-defined
1211 // class type) [...]
1212 QualType RType = rex->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001213 const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
Douglas Gregorac1fb652009-03-24 19:52:54 +00001214 if (!MemPtr) {
Sebastian Redl5822f082009-02-07 20:10:22 +00001215 Diag(Loc, diag::err_bad_memptr_rhs)
1216 << OpSpelling << RType << rex->getSourceRange();
1217 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00001218 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00001219
Sebastian Redl5822f082009-02-07 20:10:22 +00001220 QualType Class(MemPtr->getClass(), 0);
1221
1222 // C++ 5.5p2
1223 // [...] to its first operand, which shall be of class T or of a class of
1224 // which T is an unambiguous and accessible base class. [p3: a pointer to
1225 // such a class]
1226 QualType LType = lex->getType();
1227 if (isIndirect) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001228 if (const PointerType *Ptr = LType->getAs<PointerType>())
Sebastian Redl5822f082009-02-07 20:10:22 +00001229 LType = Ptr->getPointeeType().getNonReferenceType();
1230 else {
1231 Diag(Loc, diag::err_bad_memptr_lhs)
1232 << OpSpelling << 1 << LType << lex->getSourceRange();
1233 return QualType();
1234 }
1235 }
1236
1237 if (Context.getCanonicalType(Class).getUnqualifiedType() !=
1238 Context.getCanonicalType(LType).getUnqualifiedType()) {
1239 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1240 /*DetectVirtual=*/false);
Mike Stump87c57ac2009-05-16 07:39:55 +00001241 // FIXME: Would it be useful to print full ambiguity paths, or is that
1242 // overkill?
Sebastian Redl5822f082009-02-07 20:10:22 +00001243 if (!IsDerivedFrom(LType, Class, Paths) ||
1244 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
1245 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
1246 << (int)isIndirect << lex->getType() << lex->getSourceRange();
1247 return QualType();
1248 }
1249 }
1250
1251 // C++ 5.5p2
1252 // The result is an object or a function of the type specified by the
1253 // second operand.
1254 // The cv qualifiers are the union of those in the pointer and the left side,
1255 // in accordance with 5.5p5 and 5.2.5.
1256 // FIXME: This returns a dereferenced member function pointer as a normal
1257 // function type. However, the only operation valid on such functions is
Mike Stump87c57ac2009-05-16 07:39:55 +00001258 // calling them. There's also a GCC extension to get a function pointer to the
1259 // thing, which is another complication, because this type - unlike the type
1260 // that is the result of this expression - takes the class as the first
Sebastian Redl5822f082009-02-07 20:10:22 +00001261 // argument.
1262 // We probably need a "MemberFunctionClosureType" or something like that.
1263 QualType Result = MemPtr->getPointeeType();
1264 if (LType.isConstQualified())
1265 Result.addConst();
1266 if (LType.isVolatileQualified())
1267 Result.addVolatile();
1268 return Result;
1269}
Sebastian Redl1a99f442009-04-16 17:51:27 +00001270
1271/// \brief Get the target type of a standard or user-defined conversion.
1272static QualType TargetType(const ImplicitConversionSequence &ICS) {
1273 assert((ICS.ConversionKind ==
1274 ImplicitConversionSequence::StandardConversion ||
1275 ICS.ConversionKind ==
1276 ImplicitConversionSequence::UserDefinedConversion) &&
1277 "function only valid for standard or user-defined conversions");
1278 if (ICS.ConversionKind == ImplicitConversionSequence::StandardConversion)
1279 return QualType::getFromOpaquePtr(ICS.Standard.ToTypePtr);
1280 return QualType::getFromOpaquePtr(ICS.UserDefined.After.ToTypePtr);
1281}
1282
1283/// \brief Try to convert a type to another according to C++0x 5.16p3.
1284///
1285/// This is part of the parameter validation for the ? operator. If either
1286/// value operand is a class type, the two operands are attempted to be
1287/// converted to each other. This function does the conversion in one direction.
1288/// It emits a diagnostic and returns true only if it finds an ambiguous
1289/// conversion.
1290static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
1291 SourceLocation QuestionLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001292 ImplicitConversionSequence &ICS) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00001293 // C++0x 5.16p3
1294 // The process for determining whether an operand expression E1 of type T1
1295 // can be converted to match an operand expression E2 of type T2 is defined
1296 // as follows:
1297 // -- If E2 is an lvalue:
1298 if (To->isLvalue(Self.Context) == Expr::LV_Valid) {
1299 // E1 can be converted to match E2 if E1 can be implicitly converted to
1300 // type "lvalue reference to T2", subject to the constraint that in the
1301 // conversion the reference must bind directly to E1.
1302 if (!Self.CheckReferenceInit(From,
1303 Self.Context.getLValueReferenceType(To->getType()),
Anders Carlsson271e3a42009-08-27 17:30:43 +00001304 /*SuppressUserConversions=*/false,
1305 /*AllowExplicit=*/false,
1306 /*ForceRValue=*/false,
1307 &ICS))
Sebastian Redl1a99f442009-04-16 17:51:27 +00001308 {
1309 assert((ICS.ConversionKind ==
1310 ImplicitConversionSequence::StandardConversion ||
1311 ICS.ConversionKind ==
1312 ImplicitConversionSequence::UserDefinedConversion) &&
1313 "expected a definite conversion");
1314 bool DirectBinding =
1315 ICS.ConversionKind == ImplicitConversionSequence::StandardConversion ?
1316 ICS.Standard.DirectBinding : ICS.UserDefined.After.DirectBinding;
1317 if (DirectBinding)
1318 return false;
1319 }
1320 }
1321 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1322 // -- If E2 is an rvalue, or if the conversion above cannot be done:
1323 // -- if E1 and E2 have class type, and the underlying class types are
1324 // the same or one is a base class of the other:
1325 QualType FTy = From->getType();
1326 QualType TTy = To->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001327 const RecordType *FRec = FTy->getAs<RecordType>();
1328 const RecordType *TRec = TTy->getAs<RecordType>();
Sebastian Redl1a99f442009-04-16 17:51:27 +00001329 bool FDerivedFromT = FRec && TRec && Self.IsDerivedFrom(FTy, TTy);
1330 if (FRec && TRec && (FRec == TRec ||
1331 FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
1332 // E1 can be converted to match E2 if the class of T2 is the
1333 // same type as, or a base class of, the class of T1, and
1334 // [cv2 > cv1].
1335 if ((FRec == TRec || FDerivedFromT) && TTy.isAtLeastAsQualifiedAs(FTy)) {
1336 // Could still fail if there's no copy constructor.
1337 // FIXME: Is this a hard error then, or just a conversion failure? The
1338 // standard doesn't say.
Mike Stump11289f42009-09-09 15:08:12 +00001339 ICS = Self.TryCopyInitialization(From, TTy,
Anders Carlsson03068aa2009-08-27 17:18:13 +00001340 /*SuppressUserConversions=*/false,
Anders Carlsson20d13322009-08-27 17:37:39 +00001341 /*ForceRValue=*/false,
1342 /*InOverloadResolution=*/false);
Sebastian Redl1a99f442009-04-16 17:51:27 +00001343 }
1344 } else {
1345 // -- Otherwise: E1 can be converted to match E2 if E1 can be
1346 // implicitly converted to the type that expression E2 would have
1347 // if E2 were converted to an rvalue.
1348 // First find the decayed type.
1349 if (TTy->isFunctionType())
1350 TTy = Self.Context.getPointerType(TTy);
Mike Stump11289f42009-09-09 15:08:12 +00001351 else if (TTy->isArrayType())
Sebastian Redl1a99f442009-04-16 17:51:27 +00001352 TTy = Self.Context.getArrayDecayedType(TTy);
1353
1354 // Now try the implicit conversion.
1355 // FIXME: This doesn't detect ambiguities.
Anders Carlssonef4c7212009-08-27 17:24:15 +00001356 ICS = Self.TryImplicitConversion(From, TTy,
1357 /*SuppressUserConversions=*/false,
1358 /*AllowExplicit=*/false,
Anders Carlsson228eea32009-08-28 15:33:32 +00001359 /*ForceRValue=*/false,
1360 /*InOverloadResolution=*/false);
Sebastian Redl1a99f442009-04-16 17:51:27 +00001361 }
1362 return false;
1363}
1364
1365/// \brief Try to find a common type for two according to C++0x 5.16p5.
1366///
1367/// This is part of the parameter validation for the ? operator. If either
1368/// value operand is a class type, overload resolution is used to find a
1369/// conversion to a common type.
1370static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
1371 SourceLocation Loc) {
1372 Expr *Args[2] = { LHS, RHS };
1373 OverloadCandidateSet CandidateSet;
1374 Self.AddBuiltinOperatorCandidates(OO_Conditional, Args, 2, CandidateSet);
1375
1376 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00001377 switch (Self.BestViableFunction(CandidateSet, Loc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00001378 case Sema::OR_Success:
1379 // We found a match. Perform the conversions on the arguments and move on.
1380 if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
1381 Best->Conversions[0], "converting") ||
1382 Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
1383 Best->Conversions[1], "converting"))
1384 break;
1385 return false;
1386
1387 case Sema::OR_No_Viable_Function:
1388 Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
1389 << LHS->getType() << RHS->getType()
1390 << LHS->getSourceRange() << RHS->getSourceRange();
1391 return true;
1392
1393 case Sema::OR_Ambiguous:
1394 Self.Diag(Loc, diag::err_conditional_ambiguous_ovl)
1395 << LHS->getType() << RHS->getType()
1396 << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stump87c57ac2009-05-16 07:39:55 +00001397 // FIXME: Print the possible common types by printing the return types of
1398 // the viable candidates.
Sebastian Redl1a99f442009-04-16 17:51:27 +00001399 break;
1400
1401 case Sema::OR_Deleted:
1402 assert(false && "Conditional operator has only built-in overloads");
1403 break;
1404 }
1405 return true;
1406}
1407
Sebastian Redl5775af1a2009-04-17 16:30:52 +00001408/// \brief Perform an "extended" implicit conversion as returned by
1409/// TryClassUnification.
1410///
1411/// TryClassUnification generates ICSs that include reference bindings.
1412/// PerformImplicitConversion is not suitable for this; it chokes if the
1413/// second part of a standard conversion is ICK_DerivedToBase. This function
1414/// handles the reference binding specially.
1415static bool ConvertForConditional(Sema &Self, Expr *&E,
Mike Stump11289f42009-09-09 15:08:12 +00001416 const ImplicitConversionSequence &ICS) {
Sebastian Redl5775af1a2009-04-17 16:30:52 +00001417 if (ICS.ConversionKind == ImplicitConversionSequence::StandardConversion &&
1418 ICS.Standard.ReferenceBinding) {
1419 assert(ICS.Standard.DirectBinding &&
1420 "TryClassUnification should never generate indirect ref bindings");
Sebastian Redlf79d3972009-04-26 11:21:02 +00001421 // FIXME: CheckReferenceInit should be able to reuse the ICS instead of
1422 // redoing all the work.
1423 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
Anders Carlsson271e3a42009-08-27 17:30:43 +00001424 TargetType(ICS)),
1425 /*SuppressUserConversions=*/false,
1426 /*AllowExplicit=*/false,
1427 /*ForceRValue=*/false);
Sebastian Redl5775af1a2009-04-17 16:30:52 +00001428 }
1429 if (ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion &&
1430 ICS.UserDefined.After.ReferenceBinding) {
1431 assert(ICS.UserDefined.After.DirectBinding &&
1432 "TryClassUnification should never generate indirect ref bindings");
Sebastian Redlf79d3972009-04-26 11:21:02 +00001433 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
Anders Carlsson271e3a42009-08-27 17:30:43 +00001434 TargetType(ICS)),
1435 /*SuppressUserConversions=*/false,
1436 /*AllowExplicit=*/false,
1437 /*ForceRValue=*/false);
Sebastian Redl5775af1a2009-04-17 16:30:52 +00001438 }
1439 if (Self.PerformImplicitConversion(E, TargetType(ICS), ICS, "converting"))
1440 return true;
1441 return false;
1442}
1443
Sebastian Redl1a99f442009-04-16 17:51:27 +00001444/// \brief Check the operands of ?: under C++ semantics.
1445///
1446/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
1447/// extension. In this case, LHS == Cond. (But they're not aliases.)
1448QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
1449 SourceLocation QuestionLoc) {
Mike Stump87c57ac2009-05-16 07:39:55 +00001450 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
1451 // interface pointers.
Sebastian Redl1a99f442009-04-16 17:51:27 +00001452
1453 // C++0x 5.16p1
1454 // The first expression is contextually converted to bool.
1455 if (!Cond->isTypeDependent()) {
1456 if (CheckCXXBooleanCondition(Cond))
1457 return QualType();
1458 }
1459
1460 // Either of the arguments dependent?
1461 if (LHS->isTypeDependent() || RHS->isTypeDependent())
1462 return Context.DependentTy;
1463
1464 // C++0x 5.16p2
1465 // If either the second or the third operand has type (cv) void, ...
1466 QualType LTy = LHS->getType();
1467 QualType RTy = RHS->getType();
1468 bool LVoid = LTy->isVoidType();
1469 bool RVoid = RTy->isVoidType();
1470 if (LVoid || RVoid) {
1471 // ... then the [l2r] conversions are performed on the second and third
1472 // operands ...
1473 DefaultFunctionArrayConversion(LHS);
1474 DefaultFunctionArrayConversion(RHS);
1475 LTy = LHS->getType();
1476 RTy = RHS->getType();
1477
1478 // ... and one of the following shall hold:
1479 // -- The second or the third operand (but not both) is a throw-
1480 // expression; the result is of the type of the other and is an rvalue.
1481 bool LThrow = isa<CXXThrowExpr>(LHS);
1482 bool RThrow = isa<CXXThrowExpr>(RHS);
1483 if (LThrow && !RThrow)
1484 return RTy;
1485 if (RThrow && !LThrow)
1486 return LTy;
1487
1488 // -- Both the second and third operands have type void; the result is of
1489 // type void and is an rvalue.
1490 if (LVoid && RVoid)
1491 return Context.VoidTy;
1492
1493 // Neither holds, error.
1494 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
1495 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
1496 << LHS->getSourceRange() << RHS->getSourceRange();
1497 return QualType();
1498 }
1499
1500 // Neither is void.
1501
1502 // C++0x 5.16p3
1503 // Otherwise, if the second and third operand have different types, and
1504 // either has (cv) class type, and attempt is made to convert each of those
1505 // operands to the other.
1506 if (Context.getCanonicalType(LTy) != Context.getCanonicalType(RTy) &&
1507 (LTy->isRecordType() || RTy->isRecordType())) {
1508 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
1509 // These return true if a single direction is already ambiguous.
1510 if (TryClassUnification(*this, LHS, RHS, QuestionLoc, ICSLeftToRight))
1511 return QualType();
1512 if (TryClassUnification(*this, RHS, LHS, QuestionLoc, ICSRightToLeft))
1513 return QualType();
1514
1515 bool HaveL2R = ICSLeftToRight.ConversionKind !=
1516 ImplicitConversionSequence::BadConversion;
1517 bool HaveR2L = ICSRightToLeft.ConversionKind !=
1518 ImplicitConversionSequence::BadConversion;
1519 // If both can be converted, [...] the program is ill-formed.
1520 if (HaveL2R && HaveR2L) {
1521 Diag(QuestionLoc, diag::err_conditional_ambiguous)
1522 << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
1523 return QualType();
1524 }
1525
1526 // If exactly one conversion is possible, that conversion is applied to
1527 // the chosen operand and the converted operands are used in place of the
1528 // original operands for the remainder of this section.
1529 if (HaveL2R) {
Sebastian Redl5775af1a2009-04-17 16:30:52 +00001530 if (ConvertForConditional(*this, LHS, ICSLeftToRight))
Sebastian Redl1a99f442009-04-16 17:51:27 +00001531 return QualType();
1532 LTy = LHS->getType();
1533 } else if (HaveR2L) {
Sebastian Redl5775af1a2009-04-17 16:30:52 +00001534 if (ConvertForConditional(*this, RHS, ICSRightToLeft))
Sebastian Redl1a99f442009-04-16 17:51:27 +00001535 return QualType();
1536 RTy = RHS->getType();
1537 }
1538 }
1539
1540 // C++0x 5.16p4
1541 // If the second and third operands are lvalues and have the same type,
1542 // the result is of that type [...]
1543 bool Same = Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy);
1544 if (Same && LHS->isLvalue(Context) == Expr::LV_Valid &&
1545 RHS->isLvalue(Context) == Expr::LV_Valid)
1546 return LTy;
1547
1548 // C++0x 5.16p5
1549 // Otherwise, the result is an rvalue. If the second and third operands
1550 // do not have the same type, and either has (cv) class type, ...
1551 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
1552 // ... overload resolution is used to determine the conversions (if any)
1553 // to be applied to the operands. If the overload resolution fails, the
1554 // program is ill-formed.
1555 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
1556 return QualType();
1557 }
1558
1559 // C++0x 5.16p6
1560 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
1561 // conversions are performed on the second and third operands.
1562 DefaultFunctionArrayConversion(LHS);
1563 DefaultFunctionArrayConversion(RHS);
1564 LTy = LHS->getType();
1565 RTy = RHS->getType();
1566
1567 // After those conversions, one of the following shall hold:
1568 // -- The second and third operands have the same type; the result
1569 // is of that type.
1570 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy))
1571 return LTy;
1572
1573 // -- The second and third operands have arithmetic or enumeration type;
1574 // the usual arithmetic conversions are performed to bring them to a
1575 // common type, and the result is of that type.
1576 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
1577 UsualArithmeticConversions(LHS, RHS);
1578 return LHS->getType();
1579 }
1580
1581 // -- The second and third operands have pointer type, or one has pointer
1582 // type and the other is a null pointer constant; pointer conversions
1583 // and qualification conversions are performed to bring them to their
1584 // composite pointer type. The result is of the composite pointer type.
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00001585 QualType Composite = FindCompositePointerType(LHS, RHS);
1586 if (!Composite.isNull())
1587 return Composite;
Sebastian Redl1a99f442009-04-16 17:51:27 +00001588
Sebastian Redl0753c6f2009-04-19 21:15:26 +00001589 // Fourth bullet is same for pointers-to-member. However, the possible
1590 // conversions are far more limited: we have null-to-pointer, upcast of
1591 // containing class, and second-level cv-ness.
1592 // cv-ness is not a union, but must match one of the two operands. (Which,
1593 // frankly, is stupid.)
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001594 const MemberPointerType *LMemPtr = LTy->getAs<MemberPointerType>();
1595 const MemberPointerType *RMemPtr = RTy->getAs<MemberPointerType>();
Sebastian Redl0753c6f2009-04-19 21:15:26 +00001596 if (LMemPtr && RHS->isNullPointerConstant(Context)) {
1597 ImpCastExprToType(RHS, LTy);
1598 return LTy;
1599 }
1600 if (RMemPtr && LHS->isNullPointerConstant(Context)) {
1601 ImpCastExprToType(LHS, RTy);
1602 return RTy;
1603 }
1604 if (LMemPtr && RMemPtr) {
1605 QualType LPointee = LMemPtr->getPointeeType();
1606 QualType RPointee = RMemPtr->getPointeeType();
1607 // First, we check that the unqualified pointee type is the same. If it's
1608 // not, there's no conversion that will unify the two pointers.
1609 if (Context.getCanonicalType(LPointee).getUnqualifiedType() ==
1610 Context.getCanonicalType(RPointee).getUnqualifiedType()) {
1611 // Second, we take the greater of the two cv qualifications. If neither
1612 // is greater than the other, the conversion is not possible.
1613 unsigned Q = LPointee.getCVRQualifiers() | RPointee.getCVRQualifiers();
1614 if (Q == LPointee.getCVRQualifiers() || Q == RPointee.getCVRQualifiers()){
1615 // Third, we check if either of the container classes is derived from
1616 // the other.
1617 QualType LContainer(LMemPtr->getClass(), 0);
1618 QualType RContainer(RMemPtr->getClass(), 0);
1619 QualType MoreDerived;
1620 if (Context.getCanonicalType(LContainer) ==
1621 Context.getCanonicalType(RContainer))
1622 MoreDerived = LContainer;
1623 else if (IsDerivedFrom(LContainer, RContainer))
1624 MoreDerived = LContainer;
1625 else if (IsDerivedFrom(RContainer, LContainer))
1626 MoreDerived = RContainer;
1627
1628 if (!MoreDerived.isNull()) {
1629 // The type 'Q Pointee (MoreDerived::*)' is the common type.
1630 // We don't use ImpCastExprToType here because this could still fail
1631 // for ambiguous or inaccessible conversions.
1632 QualType Common = Context.getMemberPointerType(
1633 LPointee.getQualifiedType(Q), MoreDerived.getTypePtr());
1634 if (PerformImplicitConversion(LHS, Common, "converting"))
1635 return QualType();
1636 if (PerformImplicitConversion(RHS, Common, "converting"))
1637 return QualType();
1638 return Common;
1639 }
1640 }
1641 }
1642 }
1643
Sebastian Redl1a99f442009-04-16 17:51:27 +00001644 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
1645 << LHS->getType() << RHS->getType()
1646 << LHS->getSourceRange() << RHS->getSourceRange();
1647 return QualType();
1648}
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00001649
1650/// \brief Find a merged pointer type and convert the two expressions to it.
1651///
Douglas Gregorb00b10e2009-08-24 17:42:35 +00001652/// This finds the composite pointer type (or member pointer type) for @p E1
1653/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
1654/// type and returns it.
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00001655/// It does not emit diagnostics.
1656QualType Sema::FindCompositePointerType(Expr *&E1, Expr *&E2) {
1657 assert(getLangOptions().CPlusPlus && "This function assumes C++");
1658 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump11289f42009-09-09 15:08:12 +00001659
Douglas Gregorb00b10e2009-08-24 17:42:35 +00001660 if (!T1->isPointerType() && !T1->isMemberPointerType() &&
1661 !T2->isPointerType() && !T2->isMemberPointerType())
1662 return QualType();
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00001663
Douglas Gregorb00b10e2009-08-24 17:42:35 +00001664 // FIXME: Do we need to work on the canonical types?
Mike Stump11289f42009-09-09 15:08:12 +00001665
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00001666 // C++0x 5.9p2
1667 // Pointer conversions and qualification conversions are performed on
1668 // pointer operands to bring them to their composite pointer type. If
1669 // one operand is a null pointer constant, the composite pointer type is
1670 // the type of the other operand.
1671 if (E1->isNullPointerConstant(Context)) {
1672 ImpCastExprToType(E1, T2);
1673 return T2;
1674 }
1675 if (E2->isNullPointerConstant(Context)) {
1676 ImpCastExprToType(E2, T1);
1677 return T1;
1678 }
Mike Stump11289f42009-09-09 15:08:12 +00001679
Douglas Gregorb00b10e2009-08-24 17:42:35 +00001680 // Now both have to be pointers or member pointers.
1681 if (!T1->isPointerType() && !T1->isMemberPointerType() &&
1682 !T2->isPointerType() && !T2->isMemberPointerType())
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00001683 return QualType();
1684
1685 // Otherwise, of one of the operands has type "pointer to cv1 void," then
1686 // the other has type "pointer to cv2 T" and the composite pointer type is
1687 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
1688 // Otherwise, the composite pointer type is a pointer type similar to the
1689 // type of one of the operands, with a cv-qualification signature that is
1690 // the union of the cv-qualification signatures of the operand types.
1691 // In practice, the first part here is redundant; it's subsumed by the second.
1692 // What we do here is, we build the two possible composite types, and try the
1693 // conversions in both directions. If only one works, or if the two composite
1694 // types are the same, we have succeeded.
1695 llvm::SmallVector<unsigned, 4> QualifierUnion;
Douglas Gregorb00b10e2009-08-24 17:42:35 +00001696 llvm::SmallVector<std::pair<const Type *, const Type *>, 4> MemberOfClass;
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00001697 QualType Composite1 = T1, Composite2 = T2;
Douglas Gregorb00b10e2009-08-24 17:42:35 +00001698 do {
1699 const PointerType *Ptr1, *Ptr2;
1700 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
1701 (Ptr2 = Composite2->getAs<PointerType>())) {
1702 Composite1 = Ptr1->getPointeeType();
1703 Composite2 = Ptr2->getPointeeType();
1704 QualifierUnion.push_back(
1705 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
1706 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
1707 continue;
1708 }
Mike Stump11289f42009-09-09 15:08:12 +00001709
Douglas Gregorb00b10e2009-08-24 17:42:35 +00001710 const MemberPointerType *MemPtr1, *MemPtr2;
1711 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
1712 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
1713 Composite1 = MemPtr1->getPointeeType();
1714 Composite2 = MemPtr2->getPointeeType();
1715 QualifierUnion.push_back(
1716 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
1717 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
1718 MemPtr2->getClass()));
1719 continue;
1720 }
Mike Stump11289f42009-09-09 15:08:12 +00001721
Douglas Gregorb00b10e2009-08-24 17:42:35 +00001722 // FIXME: block pointer types?
Mike Stump11289f42009-09-09 15:08:12 +00001723
Douglas Gregorb00b10e2009-08-24 17:42:35 +00001724 // Cannot unwrap any more types.
1725 break;
1726 } while (true);
Mike Stump11289f42009-09-09 15:08:12 +00001727
Douglas Gregorb00b10e2009-08-24 17:42:35 +00001728 // Rewrap the composites as pointers or member pointers with the union CVRs.
1729 llvm::SmallVector<std::pair<const Type *, const Type *>, 4>::iterator MOC
1730 = MemberOfClass.begin();
Mike Stump11289f42009-09-09 15:08:12 +00001731 for (llvm::SmallVector<unsigned, 4>::iterator
Douglas Gregorb00b10e2009-08-24 17:42:35 +00001732 I = QualifierUnion.begin(),
Mike Stump11289f42009-09-09 15:08:12 +00001733 E = QualifierUnion.end();
Douglas Gregorb00b10e2009-08-24 17:42:35 +00001734 I != E; (void)++I, ++MOC) {
1735 if (MOC->first && MOC->second) {
1736 // Rebuild member pointer type
1737 Composite1 = Context.getMemberPointerType(Composite1.getQualifiedType(*I),
1738 MOC->first);
1739 Composite2 = Context.getMemberPointerType(Composite2.getQualifiedType(*I),
1740 MOC->second);
1741 } else {
1742 // Rebuild pointer type
1743 Composite1 = Context.getPointerType(Composite1.getQualifiedType(*I));
1744 Composite2 = Context.getPointerType(Composite2.getQualifiedType(*I));
1745 }
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00001746 }
1747
Mike Stump11289f42009-09-09 15:08:12 +00001748 ImplicitConversionSequence E1ToC1 =
Anders Carlssonef4c7212009-08-27 17:24:15 +00001749 TryImplicitConversion(E1, Composite1,
1750 /*SuppressUserConversions=*/false,
1751 /*AllowExplicit=*/false,
Anders Carlsson228eea32009-08-28 15:33:32 +00001752 /*ForceRValue=*/false,
1753 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00001754 ImplicitConversionSequence E2ToC1 =
Anders Carlssonef4c7212009-08-27 17:24:15 +00001755 TryImplicitConversion(E2, Composite1,
1756 /*SuppressUserConversions=*/false,
1757 /*AllowExplicit=*/false,
Anders Carlsson228eea32009-08-28 15:33:32 +00001758 /*ForceRValue=*/false,
1759 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00001760
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00001761 ImplicitConversionSequence E1ToC2, E2ToC2;
1762 E1ToC2.ConversionKind = ImplicitConversionSequence::BadConversion;
1763 E2ToC2.ConversionKind = ImplicitConversionSequence::BadConversion;
1764 if (Context.getCanonicalType(Composite1) !=
1765 Context.getCanonicalType(Composite2)) {
Anders Carlssonef4c7212009-08-27 17:24:15 +00001766 E1ToC2 = TryImplicitConversion(E1, Composite2,
1767 /*SuppressUserConversions=*/false,
1768 /*AllowExplicit=*/false,
Anders Carlsson228eea32009-08-28 15:33:32 +00001769 /*ForceRValue=*/false,
1770 /*InOverloadResolution=*/false);
Anders Carlssonef4c7212009-08-27 17:24:15 +00001771 E2ToC2 = TryImplicitConversion(E2, Composite2,
1772 /*SuppressUserConversions=*/false,
1773 /*AllowExplicit=*/false,
Anders Carlsson228eea32009-08-28 15:33:32 +00001774 /*ForceRValue=*/false,
1775 /*InOverloadResolution=*/false);
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00001776 }
1777
1778 bool ToC1Viable = E1ToC1.ConversionKind !=
1779 ImplicitConversionSequence::BadConversion
1780 && E2ToC1.ConversionKind !=
1781 ImplicitConversionSequence::BadConversion;
1782 bool ToC2Viable = E1ToC2.ConversionKind !=
1783 ImplicitConversionSequence::BadConversion
1784 && E2ToC2.ConversionKind !=
1785 ImplicitConversionSequence::BadConversion;
1786 if (ToC1Viable && !ToC2Viable) {
1787 if (!PerformImplicitConversion(E1, Composite1, E1ToC1, "converting") &&
1788 !PerformImplicitConversion(E2, Composite1, E2ToC1, "converting"))
1789 return Composite1;
1790 }
1791 if (ToC2Viable && !ToC1Viable) {
1792 if (!PerformImplicitConversion(E1, Composite2, E1ToC2, "converting") &&
1793 !PerformImplicitConversion(E2, Composite2, E2ToC2, "converting"))
1794 return Composite2;
1795 }
1796 return QualType();
1797}
Anders Carlsson85a307d2009-05-17 18:41:29 +00001798
Anders Carlsson2d4cada2009-05-30 20:36:53 +00001799Sema::OwningExprResult Sema::MaybeBindToTemporary(Expr *E) {
Anders Carlssonf86a8d12009-08-15 23:41:35 +00001800 if (!Context.getLangOptions().CPlusPlus)
1801 return Owned(E);
Mike Stump11289f42009-09-09 15:08:12 +00001802
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001803 const RecordType *RT = E->getType()->getAs<RecordType>();
Anders Carlsson2d4cada2009-05-30 20:36:53 +00001804 if (!RT)
1805 return Owned(E);
Mike Stump11289f42009-09-09 15:08:12 +00001806
Anders Carlsson2d4cada2009-05-30 20:36:53 +00001807 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1808 if (RD->hasTrivialDestructor())
1809 return Owned(E);
Mike Stump11289f42009-09-09 15:08:12 +00001810
Anders Carlssonaedb46f2009-09-14 01:30:44 +00001811 if (CallExpr *CE = dyn_cast<CallExpr>(E)) {
1812 QualType Ty = CE->getCallee()->getType();
1813 if (const PointerType *PT = Ty->getAs<PointerType>())
1814 Ty = PT->getPointeeType();
1815
1816 const FunctionType *FTy = Ty->getAsFunctionType();
1817 if (FTy->getResultType()->isReferenceType())
1818 return Owned(E);
1819 }
Mike Stump11289f42009-09-09 15:08:12 +00001820 CXXTemporary *Temp = CXXTemporary::Create(Context,
Anders Carlsson2d4cada2009-05-30 20:36:53 +00001821 RD->getDestructor(Context));
Anders Carlssonc78576e2009-05-30 21:21:49 +00001822 ExprTemporaries.push_back(Temp);
Fariborz Jahanian67828442009-08-03 19:13:25 +00001823 if (CXXDestructorDecl *Destructor =
1824 const_cast<CXXDestructorDecl*>(RD->getDestructor(Context)))
1825 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
Anders Carlsson2d4cada2009-05-30 20:36:53 +00001826 // FIXME: Add the temporary to the temporaries vector.
1827 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
1828}
1829
Mike Stump11289f42009-09-09 15:08:12 +00001830Expr *Sema::MaybeCreateCXXExprWithTemporaries(Expr *SubExpr,
Anders Carlssona42ab8f2009-06-16 03:37:31 +00001831 bool ShouldDestroyTemps) {
Anders Carlssonb3d05d62009-06-05 15:38:08 +00001832 assert(SubExpr && "sub expression can't be null!");
Mike Stump11289f42009-09-09 15:08:12 +00001833
Anders Carlssonb3d05d62009-06-05 15:38:08 +00001834 if (ExprTemporaries.empty())
1835 return SubExpr;
Mike Stump11289f42009-09-09 15:08:12 +00001836
Anders Carlssonb3d05d62009-06-05 15:38:08 +00001837 Expr *E = CXXExprWithTemporaries::Create(Context, SubExpr,
Mike Stump11289f42009-09-09 15:08:12 +00001838 &ExprTemporaries[0],
Anders Carlssonb3d05d62009-06-05 15:38:08 +00001839 ExprTemporaries.size(),
Anders Carlssona42ab8f2009-06-16 03:37:31 +00001840 ShouldDestroyTemps);
Anders Carlssonb3d05d62009-06-05 15:38:08 +00001841 ExprTemporaries.clear();
Mike Stump11289f42009-09-09 15:08:12 +00001842
Anders Carlssonb3d05d62009-06-05 15:38:08 +00001843 return E;
1844}
1845
Mike Stump11289f42009-09-09 15:08:12 +00001846Sema::OwningExprResult
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001847Sema::ActOnStartCXXMemberReference(Scope *S, ExprArg Base, SourceLocation OpLoc,
1848 tok::TokenKind OpKind, TypeTy *&ObjectType) {
1849 // Since this might be a postfix expression, get rid of ParenListExprs.
1850 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
Mike Stump11289f42009-09-09 15:08:12 +00001851
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001852 Expr *BaseExpr = (Expr*)Base.get();
1853 assert(BaseExpr && "no record expansion");
Mike Stump11289f42009-09-09 15:08:12 +00001854
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001855 QualType BaseType = BaseExpr->getType();
1856 if (BaseType->isDependentType()) {
1857 // FIXME: member of the current instantiation
1858 ObjectType = BaseType.getAsOpaquePtr();
1859 return move(Base);
1860 }
Mike Stump11289f42009-09-09 15:08:12 +00001861
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001862 // C++ [over.match.oper]p8:
Mike Stump11289f42009-09-09 15:08:12 +00001863 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001864 // returned, with the original second operand.
1865 if (OpKind == tok::arrow) {
1866 while (BaseType->isRecordType()) {
1867 Base = BuildOverloadedArrowExpr(S, move(Base), BaseExpr->getExprLoc());
1868 BaseExpr = (Expr*)Base.get();
1869 if (BaseExpr == NULL)
1870 return ExprError();
1871 BaseType = BaseExpr->getType();
1872 }
1873 }
Mike Stump11289f42009-09-09 15:08:12 +00001874
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001875 if (BaseType->isPointerType())
1876 BaseType = BaseType->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00001877
1878 // We could end up with various non-record types here, such as extended
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001879 // vector types or Objective-C interfaces. Just return early and let
1880 // ActOnMemberReferenceExpr do the work.
Douglas Gregor2b6ca462009-09-03 21:38:09 +00001881 if (!BaseType->isRecordType()) {
1882 // C++ [basic.lookup.classref]p2:
1883 // [...] If the type of the object expression is of pointer to scalar
1884 // type, the unqualified-id is looked up in the context of the complete
1885 // postfix-expression.
1886 ObjectType = 0;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001887 return move(Base);
Douglas Gregor2b6ca462009-09-03 21:38:09 +00001888 }
Mike Stump11289f42009-09-09 15:08:12 +00001889
Douglas Gregor2b6ca462009-09-03 21:38:09 +00001890 // C++ [basic.lookup.classref]p2:
Mike Stump11289f42009-09-09 15:08:12 +00001891 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor2b6ca462009-09-03 21:38:09 +00001892 // unqualified-id, and the type of the object expres- sion is of a class
1893 // type C (or of pointer to a class type C), the unqualified-id is looked
1894 // up in the scope of class C. [...]
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001895 ObjectType = BaseType.getAsOpaquePtr();
Mike Stump11289f42009-09-09 15:08:12 +00001896 return move(Base);
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001897}
1898
Anders Carlsson7e3f0e42009-08-25 23:46:41 +00001899Sema::OwningExprResult
Anders Carlssone7b9d712009-08-26 17:36:19 +00001900Sema::ActOnDestructorReferenceExpr(Scope *S, ExprArg Base,
Anders Carlsson7e3f0e42009-08-25 23:46:41 +00001901 SourceLocation OpLoc,
1902 tok::TokenKind OpKind,
1903 SourceLocation ClassNameLoc,
1904 IdentifierInfo *ClassName,
Douglas Gregorbddb73fa12009-09-04 18:29:40 +00001905 const CXXScopeSpec &SS,
1906 bool HasTrailingLParen) {
1907 if (SS.isInvalid())
Anders Carlsson7e3f0e42009-08-25 23:46:41 +00001908 return ExprError();
Anders Carlssonc24fc292009-08-26 19:22:42 +00001909
Douglas Gregorad8a3362009-09-04 17:36:40 +00001910 QualType BaseType;
Douglas Gregorbddb73fa12009-09-04 18:29:40 +00001911 if (isUnknownSpecialization(SS))
1912 BaseType = Context.getTypenameType((NestedNameSpecifier *)SS.getScopeRep(),
Douglas Gregorad8a3362009-09-04 17:36:40 +00001913 ClassName);
1914 else {
Douglas Gregorbddb73fa12009-09-04 18:29:40 +00001915 TypeTy *BaseTy = getTypeName(*ClassName, ClassNameLoc, S, &SS);
Douglas Gregorad8a3362009-09-04 17:36:40 +00001916 if (!BaseTy) {
Mike Stump11289f42009-09-09 15:08:12 +00001917 Diag(ClassNameLoc, diag::err_ident_in_pseudo_dtor_not_a_type)
Douglas Gregorad8a3362009-09-04 17:36:40 +00001918 << ClassName;
1919 return ExprError();
1920 }
Mike Stump11289f42009-09-09 15:08:12 +00001921
Douglas Gregorad8a3362009-09-04 17:36:40 +00001922 BaseType = GetTypeFromParser(BaseTy);
Anders Carlssonc24fc292009-08-26 19:22:42 +00001923 }
Mike Stump11289f42009-09-09 15:08:12 +00001924
Anders Carlssonc24fc292009-08-26 19:22:42 +00001925 CanQualType CanBaseType = Context.getCanonicalType(BaseType);
Mike Stump11289f42009-09-09 15:08:12 +00001926 DeclarationName DtorName =
Anders Carlssonc24fc292009-08-26 19:22:42 +00001927 Context.DeclarationNames.getCXXDestructorName(CanBaseType);
1928
Douglas Gregorbddb73fa12009-09-04 18:29:40 +00001929 OwningExprResult Result
1930 = BuildMemberReferenceExpr(S, move(Base), OpLoc, OpKind, ClassNameLoc,
1931 DtorName, DeclPtrTy(), &SS);
1932 if (Result.isInvalid() || HasTrailingLParen)
1933 return move(Result);
Mike Stump11289f42009-09-09 15:08:12 +00001934
1935 // The only way a reference to a destructor can be used is to
Douglas Gregorbddb73fa12009-09-04 18:29:40 +00001936 // immediately call them. Since the next token is not a '(', produce a
1937 // diagnostic and build the call now.
1938 Expr *E = (Expr *)Result.get();
1939 SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(E->getLocEnd());
1940 Diag(E->getLocStart(), diag::err_dtor_expr_without_call)
1941 << isa<CXXPseudoDestructorExpr>(E)
1942 << CodeModificationHint::CreateInsertion(ExpectedLParenLoc, "()");
Mike Stump11289f42009-09-09 15:08:12 +00001943
1944 return ActOnCallExpr(0, move(Result), ExpectedLParenLoc,
Douglas Gregorbddb73fa12009-09-04 18:29:40 +00001945 MultiExprArg(*this, 0, 0), 0, ExpectedLParenLoc);
Anders Carlsson7e3f0e42009-08-25 23:46:41 +00001946}
1947
Douglas Gregor522fbc42009-08-31 19:52:13 +00001948Sema::OwningExprResult
1949Sema::ActOnOverloadedOperatorReferenceExpr(Scope *S, ExprArg Base,
1950 SourceLocation OpLoc,
1951 tok::TokenKind OpKind,
1952 SourceLocation ClassNameLoc,
1953 OverloadedOperatorKind OverOpKind,
1954 const CXXScopeSpec *SS) {
1955 if (SS && SS->isInvalid())
1956 return ExprError();
1957
1958 DeclarationName Name =
1959 Context.DeclarationNames.getCXXOperatorName(OverOpKind);
1960
1961 return BuildMemberReferenceExpr(S, move(Base), OpLoc, OpKind, ClassNameLoc,
1962 Name, DeclPtrTy(), SS);
1963}
1964
1965Sema::OwningExprResult
1966Sema::ActOnConversionOperatorReferenceExpr(Scope *S, ExprArg Base,
1967 SourceLocation OpLoc,
1968 tok::TokenKind OpKind,
1969 SourceLocation ClassNameLoc,
1970 TypeTy *Ty,
1971 const CXXScopeSpec *SS) {
1972 if (SS && SS->isInvalid())
1973 return ExprError();
1974
1975 //FIXME: Preserve type source info.
1976 QualType ConvType = GetTypeFromParser(Ty);
1977 CanQualType ConvTypeCanon = Context.getCanonicalType(ConvType);
1978 DeclarationName ConvName =
1979 Context.DeclarationNames.getCXXConversionFunctionName(ConvTypeCanon);
1980
1981 return BuildMemberReferenceExpr(S, move(Base), OpLoc, OpKind, ClassNameLoc,
1982 ConvName, DeclPtrTy(), SS);
1983}
1984
Anders Carlssone9766d52009-09-09 21:33:21 +00001985Sema::OwningExprResult Sema::BuildCXXCastArgument(SourceLocation CastLoc,
1986 QualType Ty,
1987 CastExpr::CastKind Kind,
1988 CXXMethodDecl *Method,
1989 ExprArg Arg) {
1990 Expr *From = Arg.takeAs<Expr>();
1991
1992 switch (Kind) {
1993 default: assert(0 && "Unhandled cast kind!");
1994 case CastExpr::CK_ConstructorConversion: {
Douglas Gregor5d3507d2009-09-09 23:08:42 +00001995 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1996
1997 if (CompleteConstructorCall(cast<CXXConstructorDecl>(Method),
1998 MultiExprArg(*this, (void **)&From, 1),
1999 CastLoc, ConstructorArgs))
2000 return ExprError();
2001
Anders Carlssone9766d52009-09-09 21:33:21 +00002002 return BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
Douglas Gregor5d3507d2009-09-09 23:08:42 +00002003 move_arg(ConstructorArgs));
Anders Carlssone9766d52009-09-09 21:33:21 +00002004 }
2005
2006 case CastExpr::CK_UserDefinedConversion: {
Anders Carlsson6b2737d2009-09-15 07:42:44 +00002007 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
2008
2009 // Cast to base if needed.
2010 if (PerformObjectArgumentInitialization(From, Method))
2011 return ExprError();
2012
Anders Carlssone9766d52009-09-09 21:33:21 +00002013 // Create an implicit member expr to refer to the conversion operator.
2014 MemberExpr *ME =
Anders Carlsson6b2737d2009-09-15 07:42:44 +00002015 new (Context) MemberExpr(From, /*IsArrow=*/false, Method,
Anders Carlssone9766d52009-09-09 21:33:21 +00002016 SourceLocation(), Method->getType());
2017
2018
2019 // And an implicit call expr that calls it.
2020 QualType ResultType = Method->getResultType().getNonReferenceType();
2021 CXXMemberCallExpr *CE =
2022 new (Context) CXXMemberCallExpr(Context, ME, 0, 0,
2023 ResultType,
2024 SourceLocation());
2025
2026 return Owned(CE);
2027 }
2028
2029 }
2030}
2031
Anders Carlsson85a307d2009-05-17 18:41:29 +00002032Sema::OwningExprResult Sema::ActOnFinishFullExpr(ExprArg Arg) {
2033 Expr *FullExpr = Arg.takeAs<Expr>();
Anders Carlssonb3d05d62009-06-05 15:38:08 +00002034 if (FullExpr)
Mike Stump11289f42009-09-09 15:08:12 +00002035 FullExpr = MaybeCreateCXXExprWithTemporaries(FullExpr,
Anders Carlssona42ab8f2009-06-16 03:37:31 +00002036 /*ShouldDestroyTemps=*/true);
Anders Carlsson85a307d2009-05-17 18:41:29 +00002037
Anders Carlsson7e3f0e42009-08-25 23:46:41 +00002038
Anders Carlsson85a307d2009-05-17 18:41:29 +00002039 return Owned(FullExpr);
2040}