blob: 3fcacfc9f325f0a115013b695ac814da50f7d0f5 [file] [log] [blame]
Chris Lattner29375652006-12-04 18:06:35 +00001//===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner29375652006-12-04 18:06:35 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Steve Naroffaac94152007-08-25 14:02:58 +000015#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000016#include "clang/AST/CXXInheritance.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
Sebastian Redlc4704762008-11-11 11:37:55 +000025/// ActOnCXXTypeidOfType - Parse typeid( type-id ).
Sebastian Redl6d4256c2009-03-15 17:47:39 +000026Action::OwningExprResult
Sebastian Redlc4704762008-11-11 11:37:55 +000027Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
28 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Douglas Gregor87f54062009-09-15 22:30:29 +000029 if (!StdNamespace)
Sebastian Redl6d4256c2009-03-15 17:47:39 +000030 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +000031
32 if (isType)
33 // FIXME: Preserve type source info.
34 TyOrExpr = GetTypeFromParser(TyOrExpr).getAsOpaquePtr();
35
Chris Lattnerec7f7732008-11-20 05:51:55 +000036 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
John McCall9f3059a2009-10-09 21:13:30 +000037 LookupResult R;
38 LookupQualifiedName(R, StdNamespace, TypeInfoII, LookupTagName);
39 Decl *TypeInfoDecl = R.getAsSingleDecl(Context);
Sebastian Redlc4704762008-11-11 11:37:55 +000040 RecordDecl *TypeInfoRecordDecl = dyn_cast_or_null<RecordDecl>(TypeInfoDecl);
Chris Lattnerec7f7732008-11-20 05:51:55 +000041 if (!TypeInfoRecordDecl)
Sebastian Redl6d4256c2009-03-15 17:47:39 +000042 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Sebastian Redlc4704762008-11-11 11:37:55 +000043
44 QualType TypeInfoType = Context.getTypeDeclType(TypeInfoRecordDecl);
45
Douglas Gregor0b6a6242009-06-22 20:57:11 +000046 if (!isType) {
47 // C++0x [expr.typeid]p3:
Mike Stump11289f42009-09-09 15:08:12 +000048 // When typeid is applied to an expression other than an lvalue of a
49 // polymorphic class type [...] [the] expression is an unevaluated
Douglas Gregor0b6a6242009-06-22 20:57:11 +000050 // operand.
Mike Stump11289f42009-09-09 15:08:12 +000051
Douglas Gregor0b6a6242009-06-22 20:57:11 +000052 // FIXME: if the type of the expression is a class type, the class
53 // shall be completely defined.
54 bool isUnevaluatedOperand = true;
55 Expr *E = static_cast<Expr *>(TyOrExpr);
56 if (E && !E->isTypeDependent() && E->isLvalue(Context) == Expr::LV_Valid) {
57 QualType T = E->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +000058 if (const RecordType *RecordT = T->getAs<RecordType>()) {
Douglas Gregor0b6a6242009-06-22 20:57:11 +000059 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
60 if (RecordD->isPolymorphic())
61 isUnevaluatedOperand = false;
62 }
63 }
Mike Stump11289f42009-09-09 15:08:12 +000064
Douglas Gregor0b6a6242009-06-22 20:57:11 +000065 // If this is an unevaluated operand, clear out the set of declaration
66 // references we have been computing.
67 if (isUnevaluatedOperand)
68 PotentiallyReferencedDeclStack.back().clear();
69 }
Mike Stump11289f42009-09-09 15:08:12 +000070
Sebastian Redl6d4256c2009-03-15 17:47:39 +000071 return Owned(new (Context) CXXTypeidExpr(isType, TyOrExpr,
72 TypeInfoType.withConst(),
73 SourceRange(OpLoc, RParenLoc)));
Sebastian Redlc4704762008-11-11 11:37:55 +000074}
75
Steve Naroff66356bd2007-09-16 14:56:35 +000076/// ActOnCXXBoolLiteral - Parse {true,false} literals.
Sebastian Redl6d4256c2009-03-15 17:47:39 +000077Action::OwningExprResult
Steve Naroff66356bd2007-09-16 14:56:35 +000078Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor08d918a2008-10-24 15:36:09 +000079 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Bill Wendlingbf313b02007-02-13 20:09:46 +000080 "Unknown C++ Boolean value!");
Sebastian Redl6d4256c2009-03-15 17:47:39 +000081 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
82 Context.BoolTy, OpLoc));
Bill Wendling4073ed52007-02-13 01:51:42 +000083}
Chris Lattnerb7e656b2008-02-26 00:51:44 +000084
Sebastian Redl576fd422009-05-10 18:38:11 +000085/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
86Action::OwningExprResult
87Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
88 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
89}
90
Chris Lattnerb7e656b2008-02-26 00:51:44 +000091/// ActOnCXXThrow - Parse throw expressions.
Sebastian Redl6d4256c2009-03-15 17:47:39 +000092Action::OwningExprResult
93Sema::ActOnCXXThrow(SourceLocation OpLoc, ExprArg E) {
Sebastian Redl4de47b42009-04-27 20:27:31 +000094 Expr *Ex = E.takeAs<Expr>();
95 if (Ex && !Ex->isTypeDependent() && CheckCXXThrowOperand(OpLoc, Ex))
96 return ExprError();
97 return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc));
98}
99
100/// CheckCXXThrowOperand - Validate the operand of a throw.
101bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *&E) {
102 // C++ [except.throw]p3:
103 // [...] adjusting the type from "array of T" or "function returning T"
104 // to "pointer to T" or "pointer to function returning T", [...]
105 DefaultFunctionArrayConversion(E);
106
107 // If the type of the exception would be an incomplete type or a pointer
108 // to an incomplete type other than (cv) void the program is ill-formed.
109 QualType Ty = E->getType();
110 int isPointer = 0;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000111 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl4de47b42009-04-27 20:27:31 +0000112 Ty = Ptr->getPointeeType();
113 isPointer = 1;
114 }
115 if (!isPointer || !Ty->isVoidType()) {
116 if (RequireCompleteType(ThrowLoc, Ty,
Anders Carlsson029fc692009-08-26 22:59:12 +0000117 PDiag(isPointer ? diag::err_throw_incomplete_ptr
118 : diag::err_throw_incomplete)
119 << E->getSourceRange()))
Sebastian Redl4de47b42009-04-27 20:27:31 +0000120 return true;
121 }
122
123 // FIXME: Construct a temporary here.
124 return false;
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000125}
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000126
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000127Action::OwningExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000128 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
129 /// is a non-lvalue expression whose value is the address of the object for
130 /// which the function is called.
131
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000132 if (!isa<FunctionDecl>(CurContext))
133 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000134
135 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext))
136 if (MD->isInstance())
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000137 return Owned(new (Context) CXXThisExpr(ThisLoc,
138 MD->getThisType(Context)));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000139
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000140 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000141}
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000142
143/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
144/// Can be interpreted either as function-style casting ("int(x)")
145/// or class type construction ("ClassType(x,y,z)")
146/// or creation of a value-initialized type ("int()").
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000147Action::OwningExprResult
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000148Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep,
149 SourceLocation LParenLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000150 MultiExprArg exprs,
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000151 SourceLocation *CommaLocs,
152 SourceLocation RParenLoc) {
153 assert(TypeRep && "Missing type!");
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000154 // FIXME: Preserve type source info.
155 QualType Ty = GetTypeFromParser(TypeRep);
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000156 unsigned NumExprs = exprs.size();
157 Expr **Exprs = (Expr**)exprs.get();
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000158 SourceLocation TyBeginLoc = TypeRange.getBegin();
159 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
160
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000161 if (Ty->isDependentType() ||
Douglas Gregor0950e412009-03-13 21:01:28 +0000162 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000163 exprs.release();
Mike Stump11289f42009-09-09 15:08:12 +0000164
165 return Owned(CXXUnresolvedConstructExpr::Create(Context,
166 TypeRange.getBegin(), Ty,
Douglas Gregorce934142009-05-20 18:46:25 +0000167 LParenLoc,
168 Exprs, NumExprs,
169 RParenLoc));
Douglas Gregor0950e412009-03-13 21:01:28 +0000170 }
171
Anders Carlsson55243162009-08-27 03:53:50 +0000172 if (Ty->isArrayType())
173 return ExprError(Diag(TyBeginLoc,
174 diag::err_value_init_for_array_type) << FullRange);
175 if (!Ty->isVoidType() &&
176 RequireCompleteType(TyBeginLoc, Ty,
177 PDiag(diag::err_invalid_incomplete_type_use)
178 << FullRange))
179 return ExprError();
Fariborz Jahanian9a14b842009-10-23 21:01:39 +0000180
Anders Carlsson55243162009-08-27 03:53:50 +0000181 if (RequireNonAbstractType(TyBeginLoc, Ty,
182 diag::err_allocation_of_abstract_type))
183 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +0000184
185
Douglas Gregordd04d332009-01-16 18:33:17 +0000186 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000187 // If the expression list is a single expression, the type conversion
188 // expression is equivalent (in definedness, and if defined in meaning) to the
189 // corresponding cast expression.
190 //
191 if (NumExprs == 1) {
Anders Carlssonf10e4142009-08-07 22:21:05 +0000192 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Anders Carlssone9766d52009-09-09 21:33:21 +0000193 CXXMethodDecl *Method = 0;
194 if (CheckCastTypes(TypeRange, Ty, Exprs[0], Kind, Method,
195 /*FunctionalStyle=*/true))
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000196 return ExprError();
Anders Carlssone9766d52009-09-09 21:33:21 +0000197
198 exprs.release();
199 if (Method) {
200 OwningExprResult CastArg
201 = BuildCXXCastArgument(TypeRange.getBegin(), Ty.getNonReferenceType(),
202 Kind, Method, Owned(Exprs[0]));
203 if (CastArg.isInvalid())
204 return ExprError();
205
206 Exprs[0] = CastArg.takeAs<Expr>();
Fariborz Jahanian8b899e42009-08-28 15:11:24 +0000207 }
Anders Carlssone9766d52009-09-09 21:33:21 +0000208
209 return Owned(new (Context) CXXFunctionalCastExpr(Ty.getNonReferenceType(),
210 Ty, TyBeginLoc, Kind,
211 Exprs[0], RParenLoc));
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000212 }
213
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000214 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Douglas Gregordd04d332009-01-16 18:33:17 +0000215 CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000216
Mike Stump11289f42009-09-09 15:08:12 +0000217 if (NumExprs > 1 || !Record->hasTrivialConstructor() ||
Anders Carlsson574315a2009-08-27 05:08:22 +0000218 !Record->hasTrivialDestructor()) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +0000219 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
220
Douglas Gregordd04d332009-01-16 18:33:17 +0000221 CXXConstructorDecl *Constructor
Douglas Gregor5d3507d2009-09-09 23:08:42 +0000222 = PerformInitializationByConstructor(Ty, move(exprs),
Douglas Gregordd04d332009-01-16 18:33:17 +0000223 TypeRange.getBegin(),
224 SourceRange(TypeRange.getBegin(),
225 RParenLoc),
226 DeclarationName(),
Douglas Gregor5d3507d2009-09-09 23:08:42 +0000227 IK_Direct,
228 ConstructorArgs);
Douglas Gregordd04d332009-01-16 18:33:17 +0000229
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000230 if (!Constructor)
231 return ExprError();
232
Mike Stump11289f42009-09-09 15:08:12 +0000233 OwningExprResult Result =
234 BuildCXXTemporaryObjectExpr(Constructor, Ty, TyBeginLoc,
Douglas Gregor5d3507d2009-09-09 23:08:42 +0000235 move_arg(ConstructorArgs), RParenLoc);
Anders Carlsson574315a2009-08-27 05:08:22 +0000236 if (Result.isInvalid())
237 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +0000238
Anders Carlsson574315a2009-08-27 05:08:22 +0000239 return MaybeBindToTemporary(Result.takeAs<Expr>());
Douglas Gregordd04d332009-01-16 18:33:17 +0000240 }
241
242 // Fall through to value-initialize an object of class type that
243 // doesn't have a user-declared default constructor.
244 }
245
246 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000247 // If the expression list specifies more than a single value, the type shall
248 // be a class with a suitably declared constructor.
249 //
250 if (NumExprs > 1)
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000251 return ExprError(Diag(CommaLocs[0],
252 diag::err_builtin_func_cast_more_than_one_arg)
253 << FullRange);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000254
255 assert(NumExprs == 0 && "Expected 0 expressions");
Douglas Gregordd04d332009-01-16 18:33:17 +0000256 // C++ [expr.type.conv]p2:
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000257 // The expression T(), where T is a simple-type-specifier for a non-array
258 // complete object type or the (possibly cv-qualified) void type, creates an
259 // rvalue of the specified type, which is value-initialized.
260 //
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000261 exprs.release();
262 return Owned(new (Context) CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc));
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000263}
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +0000264
265
Sebastian Redlbd150f42008-11-21 19:14:01 +0000266/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
267/// @code new (memory) int[size][4] @endcode
268/// or
269/// @code ::new Foo(23, "hello") @endcode
270/// For the interpretation of this heap of arguments, consult the base version.
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000271Action::OwningExprResult
Sebastian Redlbd150f42008-11-21 19:14:01 +0000272Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000273 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
Sebastian Redlbd150f42008-11-21 19:14:01 +0000274 SourceLocation PlacementRParen, bool ParenTypeId,
Sebastian Redl351bb782008-12-02 14:43:59 +0000275 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000276 MultiExprArg ConstructorArgs,
Mike Stump11289f42009-09-09 15:08:12 +0000277 SourceLocation ConstructorRParen) {
Sebastian Redl351bb782008-12-02 14:43:59 +0000278 Expr *ArraySize = 0;
Sebastian Redl351bb782008-12-02 14:43:59 +0000279 // If the specified type is an array, unwrap it and save the expression.
280 if (D.getNumTypeObjects() > 0 &&
281 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
282 DeclaratorChunk &Chunk = D.getTypeObject(0);
283 if (Chunk.Arr.hasStatic)
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000284 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
285 << D.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +0000286 if (!Chunk.Arr.NumElts)
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000287 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
288 << D.getSourceRange());
Sebastian Redld7b3d7d2009-10-25 21:45:37 +0000289
290 if (ParenTypeId) {
291 // Can't have dynamic array size when the type-id is in parentheses.
292 Expr *NumElts = (Expr *)Chunk.Arr.NumElts;
293 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
294 !NumElts->isIntegerConstantExpr(Context)) {
295 Diag(D.getTypeObject(0).Loc, diag::err_new_paren_array_nonconst)
296 << NumElts->getSourceRange();
297 return ExprError();
298 }
299 }
300
Sebastian Redl351bb782008-12-02 14:43:59 +0000301 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redld7b3d7d2009-10-25 21:45:37 +0000302 D.DropFirstTypeObject();
Sebastian Redl351bb782008-12-02 14:43:59 +0000303 }
304
Douglas Gregor73341c42009-09-11 00:18:58 +0000305 // Every dimension shall be of constant size.
Sebastian Redld7b3d7d2009-10-25 21:45:37 +0000306 if (ArraySize) {
307 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor73341c42009-09-11 00:18:58 +0000308 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
309 break;
310
311 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
312 if (Expr *NumElts = (Expr *)Array.NumElts) {
313 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
314 !NumElts->isIntegerConstantExpr(Context)) {
315 Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst)
316 << NumElts->getSourceRange();
317 return ExprError();
318 }
319 }
320 }
321 }
Sebastian Redld7b3d7d2009-10-25 21:45:37 +0000322
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +0000323 //FIXME: Store DeclaratorInfo in CXXNew expression.
324 DeclaratorInfo *DInfo = 0;
Sebastian Redld7b3d7d2009-10-25 21:45:37 +0000325 QualType AllocType = GetTypeForDeclarator(D, /*Scope=*/0, &DInfo);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +0000326 if (D.isInvalidType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000327 return ExprError();
Sebastian Redlbd150f42008-11-21 19:14:01 +0000328
Mike Stump11289f42009-09-09 15:08:12 +0000329 return BuildCXXNew(StartLoc, UseGlobal,
Douglas Gregord0fefba2009-05-21 00:00:09 +0000330 PlacementLParen,
Mike Stump11289f42009-09-09 15:08:12 +0000331 move(PlacementArgs),
Douglas Gregord0fefba2009-05-21 00:00:09 +0000332 PlacementRParen,
333 ParenTypeId,
Mike Stump11289f42009-09-09 15:08:12 +0000334 AllocType,
Douglas Gregord0fefba2009-05-21 00:00:09 +0000335 D.getSourceRange().getBegin(),
336 D.getSourceRange(),
337 Owned(ArraySize),
338 ConstructorLParen,
339 move(ConstructorArgs),
340 ConstructorRParen);
341}
342
Mike Stump11289f42009-09-09 15:08:12 +0000343Sema::OwningExprResult
Douglas Gregord0fefba2009-05-21 00:00:09 +0000344Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
345 SourceLocation PlacementLParen,
346 MultiExprArg PlacementArgs,
347 SourceLocation PlacementRParen,
Mike Stump11289f42009-09-09 15:08:12 +0000348 bool ParenTypeId,
Douglas Gregord0fefba2009-05-21 00:00:09 +0000349 QualType AllocType,
350 SourceLocation TypeLoc,
351 SourceRange TypeRange,
352 ExprArg ArraySizeE,
353 SourceLocation ConstructorLParen,
354 MultiExprArg ConstructorArgs,
355 SourceLocation ConstructorRParen) {
356 if (CheckAllocatedType(AllocType, TypeLoc, TypeRange))
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000357 return ExprError();
Sebastian Redl351bb782008-12-02 14:43:59 +0000358
Douglas Gregord0fefba2009-05-21 00:00:09 +0000359 QualType ResultType = Context.getPointerType(AllocType);
Sebastian Redlbd150f42008-11-21 19:14:01 +0000360
361 // That every array dimension except the first is constant was already
362 // checked by the type check above.
Sebastian Redl351bb782008-12-02 14:43:59 +0000363
Sebastian Redlbd150f42008-11-21 19:14:01 +0000364 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
365 // or enumeration type with a non-negative value."
Douglas Gregord0fefba2009-05-21 00:00:09 +0000366 Expr *ArraySize = (Expr *)ArraySizeE.get();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +0000367 if (ArraySize && !ArraySize->isTypeDependent()) {
Sebastian Redl351bb782008-12-02 14:43:59 +0000368 QualType SizeType = ArraySize->getType();
369 if (!SizeType->isIntegralType() && !SizeType->isEnumeralType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000370 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
371 diag::err_array_size_not_integral)
372 << SizeType << ArraySize->getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +0000373 // Let's see if this is a constant < 0. If so, we reject it out of hand.
374 // We don't care about special rules, so we tell the machinery it's not
375 // evaluated - it gives us a result in more cases.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +0000376 if (!ArraySize->isValueDependent()) {
377 llvm::APSInt Value;
378 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
379 if (Value < llvm::APSInt(
Anders Carlsson8ab20bb2009-09-23 00:37:25 +0000380 llvm::APInt::getNullValue(Value.getBitWidth()),
381 Value.isUnsigned()))
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000382 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
383 diag::err_typecheck_negative_array_size)
384 << ArraySize->getSourceRange());
Sebastian Redl8d2ccae2009-02-26 14:39:58 +0000385 }
Sebastian Redl351bb782008-12-02 14:43:59 +0000386 }
Anders Carlsson8ab20bb2009-09-23 00:37:25 +0000387
Eli Friedman06ed2a52009-10-20 08:27:19 +0000388 ImpCastExprToType(ArraySize, Context.getSizeType(),
389 CastExpr::CK_IntegralCast);
Sebastian Redl351bb782008-12-02 14:43:59 +0000390 }
Sebastian Redlbd150f42008-11-21 19:14:01 +0000391
Sebastian Redlbd150f42008-11-21 19:14:01 +0000392 FunctionDecl *OperatorNew = 0;
393 FunctionDecl *OperatorDelete = 0;
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000394 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
395 unsigned NumPlaceArgs = PlacementArgs.size();
Douglas Gregor4bbd1ac2009-10-17 21:40:42 +0000396
Sebastian Redl8d2ccae2009-02-26 14:39:58 +0000397 if (!AllocType->isDependentType() &&
398 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
399 FindAllocationFunctions(StartLoc,
Sebastian Redl1df2bbe2009-02-09 18:24:27 +0000400 SourceRange(PlacementLParen, PlacementRParen),
401 UseGlobal, AllocType, ArraySize, PlaceArgs,
402 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000403 return ExprError();
Sebastian Redlbd150f42008-11-21 19:14:01 +0000404
405 bool Init = ConstructorLParen.isValid();
406 // --- Choosing a constructor ---
407 // C++ 5.3.4p15
408 // 1) If T is a POD and there's no initializer (ConstructorLParen is invalid)
409 // the object is not initialized. If the object, or any part of it, is
410 // const-qualified, it's an error.
411 // 2) If T is a POD and there's an empty initializer, the object is value-
412 // initialized.
413 // 3) If T is a POD and there's one initializer argument, the object is copy-
414 // constructed.
415 // 4) If T is a POD and there's more initializer arguments, it's an error.
416 // 5) If T is not a POD, the initializer arguments are used as constructor
417 // arguments.
418 //
419 // Or by the C++0x formulation:
420 // 1) If there's no initializer, the object is default-initialized according
421 // to C++0x rules.
422 // 2) Otherwise, the object is direct-initialized.
423 CXXConstructorDecl *Constructor = 0;
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000424 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
Sebastian Redlfb23ddf2009-05-07 16:14:23 +0000425 const RecordType *RT;
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000426 unsigned NumConsArgs = ConstructorArgs.size();
Eli Friedmanfd8d4e12009-11-08 22:15:39 +0000427 ASTOwningVector<&ActionBase::DeleteExpr> ConvertedConstructorArgs(*this);
428
Douglas Gregor4bbd1ac2009-10-17 21:40:42 +0000429 if (AllocType->isDependentType() ||
430 Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +0000431 // Skip all the checks.
Mike Stump12b8ce12009-08-04 21:02:39 +0000432 } else if ((RT = AllocType->getAs<RecordType>()) &&
433 !AllocType->isAggregateType()) {
Sebastian Redlbd150f42008-11-21 19:14:01 +0000434 Constructor = PerformInitializationByConstructor(
Douglas Gregor5d3507d2009-09-09 23:08:42 +0000435 AllocType, move(ConstructorArgs),
Douglas Gregord0fefba2009-05-21 00:00:09 +0000436 TypeLoc,
437 SourceRange(TypeLoc, ConstructorRParen),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000438 RT->getDecl()->getDeclName(),
Douglas Gregor5d3507d2009-09-09 23:08:42 +0000439 NumConsArgs != 0 ? IK_Direct : IK_Default,
440 ConvertedConstructorArgs);
Sebastian Redlbd150f42008-11-21 19:14:01 +0000441 if (!Constructor)
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000442 return ExprError();
Douglas Gregor5d3507d2009-09-09 23:08:42 +0000443
444 // Take the converted constructor arguments and use them for the new
445 // expression.
446 NumConsArgs = ConvertedConstructorArgs.size();
447 ConsArgs = (Expr **)ConvertedConstructorArgs.take();
Sebastian Redlbd150f42008-11-21 19:14:01 +0000448 } else {
449 if (!Init) {
450 // FIXME: Check that no subpart is const.
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000451 if (AllocType.isConstQualified())
452 return ExprError(Diag(StartLoc, diag::err_new_uninitialized_const)
Douglas Gregord0fefba2009-05-21 00:00:09 +0000453 << TypeRange);
Sebastian Redlbd150f42008-11-21 19:14:01 +0000454 } else if (NumConsArgs == 0) {
Fariborz Jahanian7ad36162009-11-03 20:38:53 +0000455 // Object is value-initialized. Do nothing.
Sebastian Redlbd150f42008-11-21 19:14:01 +0000456 } else if (NumConsArgs == 1) {
457 // Object is direct-initialized.
Sebastian Redlfb23ddf2009-05-07 16:14:23 +0000458 // FIXME: What DeclarationName do we pass in here?
Sebastian Redl351bb782008-12-02 14:43:59 +0000459 if (CheckInitializerTypes(ConsArgs[0], AllocType, StartLoc,
Douglas Gregor5fb53972009-01-14 15:45:31 +0000460 DeclarationName() /*AllocType.getAsString()*/,
461 /*DirectInit=*/true))
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000462 return ExprError();
Sebastian Redlbd150f42008-11-21 19:14:01 +0000463 } else {
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000464 return ExprError(Diag(StartLoc,
465 diag::err_builtin_direct_init_more_than_one_arg)
466 << SourceRange(ConstructorLParen, ConstructorRParen));
Sebastian Redlbd150f42008-11-21 19:14:01 +0000467 }
468 }
469
470 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
Douglas Gregor4bbd1ac2009-10-17 21:40:42 +0000471
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000472 PlacementArgs.release();
473 ConstructorArgs.release();
Douglas Gregord0fefba2009-05-21 00:00:09 +0000474 ArraySizeE.release();
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000475 return Owned(new (Context) CXXNewExpr(UseGlobal, OperatorNew, PlaceArgs,
Ted Kremenek5a201952009-02-07 01:47:29 +0000476 NumPlaceArgs, ParenTypeId, ArraySize, Constructor, Init,
Sebastian Redlbd150f42008-11-21 19:14:01 +0000477 ConsArgs, NumConsArgs, OperatorDelete, ResultType,
Mike Stump11289f42009-09-09 15:08:12 +0000478 StartLoc, Init ? ConstructorRParen : SourceLocation()));
Sebastian Redlbd150f42008-11-21 19:14:01 +0000479}
480
481/// CheckAllocatedType - Checks that a type is suitable as the allocated type
482/// in a new-expression.
483/// dimension off and stores the size expression in ArraySize.
Douglas Gregord0fefba2009-05-21 00:00:09 +0000484bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +0000485 SourceRange R) {
Sebastian Redlbd150f42008-11-21 19:14:01 +0000486 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
487 // abstract class type or array thereof.
Douglas Gregorac1fb652009-03-24 19:52:54 +0000488 if (AllocType->isFunctionType())
Douglas Gregord0fefba2009-05-21 00:00:09 +0000489 return Diag(Loc, diag::err_bad_new_type)
490 << AllocType << 0 << R;
Douglas Gregorac1fb652009-03-24 19:52:54 +0000491 else if (AllocType->isReferenceType())
Douglas Gregord0fefba2009-05-21 00:00:09 +0000492 return Diag(Loc, diag::err_bad_new_type)
493 << AllocType << 1 << R;
Douglas Gregorac1fb652009-03-24 19:52:54 +0000494 else if (!AllocType->isDependentType() &&
Douglas Gregord0fefba2009-05-21 00:00:09 +0000495 RequireCompleteType(Loc, AllocType,
Anders Carlssond624e162009-08-26 23:45:07 +0000496 PDiag(diag::err_new_incomplete_type)
497 << R))
Sebastian Redlbd150f42008-11-21 19:14:01 +0000498 return true;
Douglas Gregord0fefba2009-05-21 00:00:09 +0000499 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregorac1fb652009-03-24 19:52:54 +0000500 diag::err_allocation_of_abstract_type))
501 return true;
Sebastian Redlbd150f42008-11-21 19:14:01 +0000502
Sebastian Redlbd150f42008-11-21 19:14:01 +0000503 return false;
504}
505
Sebastian Redlfaf68082008-12-03 20:26:15 +0000506/// FindAllocationFunctions - Finds the overloads of operator new and delete
507/// that are appropriate for the allocation.
Sebastian Redl1df2bbe2009-02-09 18:24:27 +0000508bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
509 bool UseGlobal, QualType AllocType,
510 bool IsArray, Expr **PlaceArgs,
511 unsigned NumPlaceArgs,
Sebastian Redlfaf68082008-12-03 20:26:15 +0000512 FunctionDecl *&OperatorNew,
Mike Stump11289f42009-09-09 15:08:12 +0000513 FunctionDecl *&OperatorDelete) {
Sebastian Redlfaf68082008-12-03 20:26:15 +0000514 // --- Choosing an allocation function ---
515 // C++ 5.3.4p8 - 14 & 18
516 // 1) If UseGlobal is true, only look in the global scope. Else, also look
517 // in the scope of the allocated class.
518 // 2) If an array size is given, look for operator new[], else look for
519 // operator new.
520 // 3) The first argument is always size_t. Append the arguments from the
521 // placement form.
522 // FIXME: Also find the appropriate delete operator.
523
524 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
525 // We don't care about the actual value of this argument.
526 // FIXME: Should the Sema create the expression and embed it in the syntax
527 // tree? Or should the consumer just recalculate the value?
Anders Carlssona471db02009-08-16 20:29:29 +0000528 IntegerLiteral Size(llvm::APInt::getNullValue(
529 Context.Target.getPointerWidth(0)),
530 Context.getSizeType(),
531 SourceLocation());
532 AllocArgs[0] = &Size;
Sebastian Redlfaf68082008-12-03 20:26:15 +0000533 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
534
535 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
536 IsArray ? OO_Array_New : OO_New);
537 if (AllocType->isRecordType() && !UseGlobal) {
Mike Stump11289f42009-09-09 15:08:12 +0000538 CXXRecordDecl *Record
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000539 = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl());
Sebastian Redl33a31012008-12-04 22:20:51 +0000540 // FIXME: We fail to find inherited overloads.
Sebastian Redl1df2bbe2009-02-09 18:24:27 +0000541 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl33a31012008-12-04 22:20:51 +0000542 AllocArgs.size(), Record, /*AllowMissing=*/true,
543 OperatorNew))
Sebastian Redlfaf68082008-12-03 20:26:15 +0000544 return true;
Sebastian Redlfaf68082008-12-03 20:26:15 +0000545 }
546 if (!OperatorNew) {
547 // Didn't find a member overload. Look for a global one.
548 DeclareGlobalNewDelete();
Sebastian Redl33a31012008-12-04 22:20:51 +0000549 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl1df2bbe2009-02-09 18:24:27 +0000550 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl33a31012008-12-04 22:20:51 +0000551 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
552 OperatorNew))
Sebastian Redlfaf68082008-12-03 20:26:15 +0000553 return true;
Sebastian Redlfaf68082008-12-03 20:26:15 +0000554 }
555
Anders Carlsson6f9dabf2009-05-31 20:26:12 +0000556 // FindAllocationOverload can change the passed in arguments, so we need to
557 // copy them back.
558 if (NumPlaceArgs > 0)
559 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
Mike Stump11289f42009-09-09 15:08:12 +0000560
Sebastian Redlfaf68082008-12-03 20:26:15 +0000561 return false;
562}
563
Sebastian Redl33a31012008-12-04 22:20:51 +0000564/// FindAllocationOverload - Find an fitting overload for the allocation
565/// function in the specified scope.
Sebastian Redl1df2bbe2009-02-09 18:24:27 +0000566bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
567 DeclarationName Name, Expr** Args,
568 unsigned NumArgs, DeclContext *Ctx,
Mike Stump11289f42009-09-09 15:08:12 +0000569 bool AllowMissing, FunctionDecl *&Operator) {
John McCall9f3059a2009-10-09 21:13:30 +0000570 LookupResult R;
571 LookupQualifiedName(R, Ctx, Name, LookupOrdinaryName);
572 if (R.empty()) {
Sebastian Redl33a31012008-12-04 22:20:51 +0000573 if (AllowMissing)
574 return false;
Sebastian Redl33a31012008-12-04 22:20:51 +0000575 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner45d9d602009-02-17 07:29:20 +0000576 << Name << Range;
Sebastian Redl33a31012008-12-04 22:20:51 +0000577 }
578
John McCall9f3059a2009-10-09 21:13:30 +0000579 // FIXME: handle ambiguity
580
Sebastian Redl33a31012008-12-04 22:20:51 +0000581 OverloadCandidateSet Candidates;
Douglas Gregor80a6cc52009-09-30 00:03:47 +0000582 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
583 Alloc != AllocEnd; ++Alloc) {
Douglas Gregor55297ac2008-12-23 00:26:44 +0000584 // Even member operator new/delete are implicitly treated as
585 // static, so don't use AddMemberCandidate.
Douglas Gregorbb3e12f2009-09-29 18:16:17 +0000586 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>(*Alloc)) {
Douglas Gregor55297ac2008-12-23 00:26:44 +0000587 AddOverloadCandidate(Fn, Args, NumArgs, Candidates,
588 /*SuppressUserConversions=*/false);
Douglas Gregorbb3e12f2009-09-29 18:16:17 +0000589 continue;
590 }
591
592 // FIXME: Handle function templates
Sebastian Redl33a31012008-12-04 22:20:51 +0000593 }
594
595 // Do the resolution.
596 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +0000597 switch(BestViableFunction(Candidates, StartLoc, Best)) {
Sebastian Redl33a31012008-12-04 22:20:51 +0000598 case OR_Success: {
599 // Got one!
600 FunctionDecl *FnDecl = Best->Function;
601 // The first argument is size_t, and the first parameter must be size_t,
602 // too. This is checked on declaration and can be assumed. (It can't be
603 // asserted on, though, since invalid decls are left in there.)
Douglas Gregorbb3e12f2009-09-29 18:16:17 +0000604 for (unsigned i = 0; i < NumArgs; ++i) {
Sebastian Redl33a31012008-12-04 22:20:51 +0000605 // FIXME: Passing word to diagnostic.
Anders Carlsson24187122009-05-31 19:49:47 +0000606 if (PerformCopyInitialization(Args[i],
Sebastian Redl33a31012008-12-04 22:20:51 +0000607 FnDecl->getParamDecl(i)->getType(),
608 "passing"))
609 return true;
610 }
611 Operator = FnDecl;
612 return false;
613 }
614
615 case OR_No_Viable_Function:
Sebastian Redl33a31012008-12-04 22:20:51 +0000616 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner45d9d602009-02-17 07:29:20 +0000617 << Name << Range;
Sebastian Redl33a31012008-12-04 22:20:51 +0000618 PrintOverloadCandidates(Candidates, /*OnlyViable=*/false);
619 return true;
620
621 case OR_Ambiguous:
Sebastian Redl33a31012008-12-04 22:20:51 +0000622 Diag(StartLoc, diag::err_ovl_ambiguous_call)
Sebastian Redl1df2bbe2009-02-09 18:24:27 +0000623 << Name << Range;
Sebastian Redl33a31012008-12-04 22:20:51 +0000624 PrintOverloadCandidates(Candidates, /*OnlyViable=*/true);
625 return true;
Douglas Gregor171c45a2009-02-18 21:56:37 +0000626
627 case OR_Deleted:
628 Diag(StartLoc, diag::err_ovl_deleted_call)
629 << Best->Function->isDeleted()
630 << Name << Range;
631 PrintOverloadCandidates(Candidates, /*OnlyViable=*/true);
632 return true;
Sebastian Redl33a31012008-12-04 22:20:51 +0000633 }
634 assert(false && "Unreachable, bad result from BestViableFunction");
635 return true;
636}
637
638
Sebastian Redlfaf68082008-12-03 20:26:15 +0000639/// DeclareGlobalNewDelete - Declare the global forms of operator new and
640/// delete. These are:
641/// @code
642/// void* operator new(std::size_t) throw(std::bad_alloc);
643/// void* operator new[](std::size_t) throw(std::bad_alloc);
644/// void operator delete(void *) throw();
645/// void operator delete[](void *) throw();
646/// @endcode
647/// Note that the placement and nothrow forms of new are *not* implicitly
648/// declared. Their use requires including \<new\>.
Mike Stump11289f42009-09-09 15:08:12 +0000649void Sema::DeclareGlobalNewDelete() {
Sebastian Redlfaf68082008-12-03 20:26:15 +0000650 if (GlobalNewDeleteDeclared)
651 return;
Douglas Gregor87f54062009-09-15 22:30:29 +0000652
653 // C++ [basic.std.dynamic]p2:
654 // [...] The following allocation and deallocation functions (18.4) are
655 // implicitly declared in global scope in each translation unit of a
656 // program
657 //
658 // void* operator new(std::size_t) throw(std::bad_alloc);
659 // void* operator new[](std::size_t) throw(std::bad_alloc);
660 // void operator delete(void*) throw();
661 // void operator delete[](void*) throw();
662 //
663 // These implicit declarations introduce only the function names operator
664 // new, operator new[], operator delete, operator delete[].
665 //
666 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
667 // "std" or "bad_alloc" as necessary to form the exception specification.
668 // However, we do not make these implicit declarations visible to name
669 // lookup.
670 if (!StdNamespace) {
671 // The "std" namespace has not yet been defined, so build one implicitly.
672 StdNamespace = NamespaceDecl::Create(Context,
673 Context.getTranslationUnitDecl(),
674 SourceLocation(),
675 &PP.getIdentifierTable().get("std"));
676 StdNamespace->setImplicit(true);
677 }
678
679 if (!StdBadAlloc) {
680 // The "std::bad_alloc" class has not yet been declared, so build it
681 // implicitly.
682 StdBadAlloc = CXXRecordDecl::Create(Context, TagDecl::TK_class,
683 StdNamespace,
684 SourceLocation(),
685 &PP.getIdentifierTable().get("bad_alloc"),
686 SourceLocation(), 0);
687 StdBadAlloc->setImplicit(true);
688 }
689
Sebastian Redlfaf68082008-12-03 20:26:15 +0000690 GlobalNewDeleteDeclared = true;
691
692 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
693 QualType SizeT = Context.getSizeType();
694
Sebastian Redlfaf68082008-12-03 20:26:15 +0000695 DeclareGlobalAllocationFunction(
696 Context.DeclarationNames.getCXXOperatorName(OO_New),
697 VoidPtr, SizeT);
698 DeclareGlobalAllocationFunction(
699 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
700 VoidPtr, SizeT);
701 DeclareGlobalAllocationFunction(
702 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
703 Context.VoidTy, VoidPtr);
704 DeclareGlobalAllocationFunction(
705 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
706 Context.VoidTy, VoidPtr);
707}
708
709/// DeclareGlobalAllocationFunction - Declares a single implicit global
710/// allocation function if it doesn't already exist.
711void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Mike Stump11289f42009-09-09 15:08:12 +0000712 QualType Return, QualType Argument) {
Sebastian Redlfaf68082008-12-03 20:26:15 +0000713 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
714
715 // Check if this function is already declared.
Douglas Gregor8b9ccca2008-12-23 21:05:05 +0000716 {
Douglas Gregor17eb26b2008-12-23 22:05:29 +0000717 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000718 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor8b9ccca2008-12-23 21:05:05 +0000719 Alloc != AllocEnd; ++Alloc) {
720 // FIXME: Do we need to check for default arguments here?
721 FunctionDecl *Func = cast<FunctionDecl>(*Alloc);
722 if (Func->getNumParams() == 1 &&
Ted Kremenek5a201952009-02-07 01:47:29 +0000723 Context.getCanonicalType(Func->getParamDecl(0)->getType())==Argument)
Sebastian Redlfaf68082008-12-03 20:26:15 +0000724 return;
Sebastian Redlfaf68082008-12-03 20:26:15 +0000725 }
726 }
727
Douglas Gregor87f54062009-09-15 22:30:29 +0000728 QualType BadAllocType;
729 bool HasBadAllocExceptionSpec
730 = (Name.getCXXOverloadedOperator() == OO_New ||
731 Name.getCXXOverloadedOperator() == OO_Array_New);
732 if (HasBadAllocExceptionSpec) {
733 assert(StdBadAlloc && "Must have std::bad_alloc declared");
734 BadAllocType = Context.getTypeDeclType(StdBadAlloc);
735 }
736
737 QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0,
738 true, false,
739 HasBadAllocExceptionSpec? 1 : 0,
740 &BadAllocType);
Sebastian Redlfaf68082008-12-03 20:26:15 +0000741 FunctionDecl *Alloc =
742 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +0000743 FnType, /*DInfo=*/0, FunctionDecl::None, false, true);
Sebastian Redlfaf68082008-12-03 20:26:15 +0000744 Alloc->setImplicit();
745 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +0000746 0, Argument, /*DInfo=*/0,
747 VarDecl::None, 0);
Ted Kremenek4ba36fc2009-01-14 00:42:25 +0000748 Alloc->setParams(Context, &Param, 1);
Sebastian Redlfaf68082008-12-03 20:26:15 +0000749
Douglas Gregor8b9ccca2008-12-23 21:05:05 +0000750 // FIXME: Also add this declaration to the IdentifierResolver, but
751 // make sure it is at the end of the chain to coincide with the
752 // global scope.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000753 ((DeclContext *)TUScope->getEntity())->addDecl(Alloc);
Sebastian Redlfaf68082008-12-03 20:26:15 +0000754}
755
Anders Carlssone1d34ba02009-11-15 18:45:20 +0000756bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
757 DeclarationName Name,
758 FunctionDecl* &Operator) {
759 LookupResult Found;
760 // Try to find operator delete/operator delete[] in class scope.
761 LookupQualifiedName(Found, RD, Name, LookupOrdinaryName);
762
763 if (Found.isAmbiguous()) {
764 DiagnoseAmbiguousLookup(Found, Name, StartLoc);
765 return true;
766 }
767
768 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
769 F != FEnd; ++F) {
770 if (CXXMethodDecl *Delete = dyn_cast<CXXMethodDecl>(*F))
771 if (Delete->isUsualDeallocationFunction()) {
772 Operator = Delete;
773 return false;
774 }
775 }
776
777 // We did find operator delete/operator delete[] declarations, but
778 // none of them were suitable.
779 if (!Found.empty()) {
780 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
781 << Name << RD;
782
783 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
784 F != FEnd; ++F) {
785 Diag((*F)->getLocation(),
786 diag::note_delete_member_function_declared_here)
787 << Name;
788 }
789
790 return true;
791 }
792
793 // Look for a global declaration.
794 DeclareGlobalNewDelete();
795 DeclContext *TUDecl = Context.getTranslationUnitDecl();
796
797 CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation());
798 Expr* DeallocArgs[1];
799 DeallocArgs[0] = &Null;
800 if (FindAllocationOverload(StartLoc, SourceRange(), Name,
801 DeallocArgs, 1, TUDecl, /*AllowMissing=*/false,
802 Operator))
803 return true;
804
805 assert(Operator && "Did not find a deallocation function!");
806 return false;
807}
808
Sebastian Redlbd150f42008-11-21 19:14:01 +0000809/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
810/// @code ::delete ptr; @endcode
811/// or
812/// @code delete [] ptr; @endcode
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000813Action::OwningExprResult
Sebastian Redlbd150f42008-11-21 19:14:01 +0000814Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
Mike Stump11289f42009-09-09 15:08:12 +0000815 bool ArrayForm, ExprArg Operand) {
Douglas Gregor0fea62d2009-09-09 23:39:55 +0000816 // C++ [expr.delete]p1:
817 // The operand shall have a pointer type, or a class type having a single
818 // conversion function to a pointer type. The result has type void.
819 //
Sebastian Redlbd150f42008-11-21 19:14:01 +0000820 // DR599 amends "pointer type" to "pointer to object type" in both cases.
821
Anders Carlssona471db02009-08-16 20:29:29 +0000822 FunctionDecl *OperatorDelete = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000823
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000824 Expr *Ex = (Expr *)Operand.get();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +0000825 if (!Ex->isTypeDependent()) {
826 QualType Type = Ex->getType();
Sebastian Redlbd150f42008-11-21 19:14:01 +0000827
Douglas Gregor0fea62d2009-09-09 23:39:55 +0000828 if (const RecordType *Record = Type->getAs<RecordType>()) {
Douglas Gregor0fea62d2009-09-09 23:39:55 +0000829 llvm::SmallVector<CXXConversionDecl *, 4> ObjectPtrConversions;
Fariborz Jahanianb54ccb22009-09-11 21:44:33 +0000830 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
831 OverloadedFunctionDecl *Conversions =
Fariborz Jahanianb394f502009-09-12 18:26:03 +0000832 RD->getVisibleConversionFunctions();
Douglas Gregor0fea62d2009-09-09 23:39:55 +0000833
Douglas Gregor0fea62d2009-09-09 23:39:55 +0000834 for (OverloadedFunctionDecl::function_iterator
835 Func = Conversions->function_begin(),
836 FuncEnd = Conversions->function_end();
837 Func != FuncEnd; ++Func) {
838 // Skip over templated conversion functions; they aren't considered.
839 if (isa<FunctionTemplateDecl>(*Func))
840 continue;
841
842 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
843
844 QualType ConvType = Conv->getConversionType().getNonReferenceType();
845 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
846 if (ConvPtrType->getPointeeType()->isObjectType())
Fariborz Jahanianadcea102009-09-15 22:15:23 +0000847 ObjectPtrConversions.push_back(Conv);
Douglas Gregor0fea62d2009-09-09 23:39:55 +0000848 }
Fariborz Jahanianadcea102009-09-15 22:15:23 +0000849 if (ObjectPtrConversions.size() == 1) {
850 // We have a single conversion to a pointer-to-object type. Perform
851 // that conversion.
852 Operand.release();
853 if (!PerformImplicitConversion(Ex,
854 ObjectPtrConversions.front()->getConversionType(),
855 "converting")) {
856 Operand = Owned(Ex);
857 Type = Ex->getType();
858 }
859 }
860 else if (ObjectPtrConversions.size() > 1) {
861 Diag(StartLoc, diag::err_ambiguous_delete_operand)
862 << Type << Ex->getSourceRange();
863 for (unsigned i= 0; i < ObjectPtrConversions.size(); i++) {
864 CXXConversionDecl *Conv = ObjectPtrConversions[i];
865 Diag(Conv->getLocation(), diag::err_ovl_candidate);
866 }
867 return ExprError();
Douglas Gregor0fea62d2009-09-09 23:39:55 +0000868 }
Sebastian Redl8d2ccae2009-02-26 14:39:58 +0000869 }
870
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000871 if (!Type->isPointerType())
872 return ExprError(Diag(StartLoc, diag::err_delete_operand)
873 << Type << Ex->getSourceRange());
Sebastian Redl8d2ccae2009-02-26 14:39:58 +0000874
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000875 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Douglas Gregorc9a1a3b2009-03-24 20:13:58 +0000876 if (Pointee->isFunctionType() || Pointee->isVoidType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000877 return ExprError(Diag(StartLoc, diag::err_delete_operand)
878 << Type << Ex->getSourceRange());
Douglas Gregorc9a1a3b2009-03-24 20:13:58 +0000879 else if (!Pointee->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +0000880 RequireCompleteType(StartLoc, Pointee,
Anders Carlssond624e162009-08-26 23:45:07 +0000881 PDiag(diag::warn_delete_incomplete)
882 << Ex->getSourceRange()))
Douglas Gregorc9a1a3b2009-03-24 20:13:58 +0000883 return ExprError();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +0000884
Douglas Gregor98496dc2009-09-29 21:38:53 +0000885 // C++ [expr.delete]p2:
886 // [Note: a pointer to a const type can be the operand of a
887 // delete-expression; it is not necessary to cast away the constness
888 // (5.2.11) of the pointer expression before it is used as the operand
889 // of the delete-expression. ]
890 ImpCastExprToType(Ex, Context.getPointerType(Context.VoidTy),
891 CastExpr::CK_NoOp);
892
893 // Update the operand.
894 Operand.take();
895 Operand = ExprArg(*this, Ex);
896
Anders Carlssona471db02009-08-16 20:29:29 +0000897 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
898 ArrayForm ? OO_Array_Delete : OO_Delete);
899
Anders Carlssone1d34ba02009-11-15 18:45:20 +0000900 if (const RecordType *RT = Pointee->getAs<RecordType>()) {
901 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
902
903 if (!UseGlobal &&
904 FindDeallocationFunction(StartLoc, RD, DeleteName, OperatorDelete))
Anders Carlsson654e5c72009-11-14 03:17:38 +0000905 return ExprError();
Anders Carlsson654e5c72009-11-14 03:17:38 +0000906
Anders Carlssone1d34ba02009-11-15 18:45:20 +0000907 if (!RD->hasTrivialDestructor())
908 if (const CXXDestructorDecl *Dtor = RD->getDestructor(Context))
Mike Stump11289f42009-09-09 15:08:12 +0000909 MarkDeclarationReferenced(StartLoc,
Fariborz Jahanian37d06562009-09-03 23:18:17 +0000910 const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssona471db02009-08-16 20:29:29 +0000911 }
Anders Carlssone1d34ba02009-11-15 18:45:20 +0000912
Anders Carlssona471db02009-08-16 20:29:29 +0000913 if (!OperatorDelete) {
Anders Carlssone1d34ba02009-11-15 18:45:20 +0000914 // Look for a global declaration.
Anders Carlssona471db02009-08-16 20:29:29 +0000915 DeclareGlobalNewDelete();
916 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000917 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
Douglas Gregorbb3e12f2009-09-29 18:16:17 +0000918 &Ex, 1, TUDecl, /*AllowMissing=*/false,
Anders Carlssona471db02009-08-16 20:29:29 +0000919 OperatorDelete))
920 return ExprError();
921 }
Mike Stump11289f42009-09-09 15:08:12 +0000922
Sebastian Redl8d2ccae2009-02-26 14:39:58 +0000923 // FIXME: Check access and ambiguity of operator delete and destructor.
Sebastian Redlbd150f42008-11-21 19:14:01 +0000924 }
925
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000926 Operand.release();
927 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
Anders Carlssona471db02009-08-16 20:29:29 +0000928 OperatorDelete, Ex, StartLoc));
Sebastian Redlbd150f42008-11-21 19:14:01 +0000929}
930
931
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +0000932/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
933/// C++ if/switch/while/for statement.
934/// e.g: "if (int x = f()) {...}"
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000935Action::OwningExprResult
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +0000936Sema::ActOnCXXConditionDeclarationExpr(Scope *S, SourceLocation StartLoc,
937 Declarator &D,
938 SourceLocation EqualLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000939 ExprArg AssignExprVal) {
940 assert(AssignExprVal.get() && "Null assignment expression");
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +0000941
942 // C++ 6.4p2:
943 // The declarator shall not specify a function or an array.
944 // The type-specifier-seq shall not contain typedef and shall not declare a
945 // new class or enumeration.
946
947 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
948 "Parser allowed 'typedef' as storage class of condition decl.");
949
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +0000950 // FIXME: Store DeclaratorInfo in the expression.
951 DeclaratorInfo *DInfo = 0;
Argyrios Kyrtzidisae438f82009-08-11 05:20:41 +0000952 TagDecl *OwnedTag = 0;
Sebastian Redld7b3d7d2009-10-25 21:45:37 +0000953 QualType Ty = GetTypeForDeclarator(D, S, &DInfo, &OwnedTag);
Mike Stump11289f42009-09-09 15:08:12 +0000954
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +0000955 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
956 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
957 // would be created and CXXConditionDeclExpr wants a VarDecl.
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000958 return ExprError(Diag(StartLoc, diag::err_invalid_use_of_function_type)
959 << SourceRange(StartLoc, EqualLoc));
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +0000960 } else if (Ty->isArrayType()) { // ...or an array.
Chris Lattnerf490e152008-11-19 05:27:50 +0000961 Diag(StartLoc, diag::err_invalid_use_of_array_type)
962 << SourceRange(StartLoc, EqualLoc);
Argyrios Kyrtzidisae438f82009-08-11 05:20:41 +0000963 } else if (OwnedTag && OwnedTag->isDefinition()) {
964 // The type-specifier-seq shall not declare a new class or enumeration.
965 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +0000966 }
967
Douglas Gregor4a75be22009-06-23 21:43:56 +0000968 DeclPtrTy Dcl = ActOnDeclarator(S, D);
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +0000969 if (!Dcl)
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000970 return ExprError();
Anders Carlsson5e9444f2009-05-30 21:37:25 +0000971 AddInitializerToDecl(Dcl, move(AssignExprVal), /*DirectInit=*/false);
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +0000972
Douglas Gregor85970ca2008-12-10 23:01:14 +0000973 // Mark this variable as one that is declared within a conditional.
Chris Lattner83f095c2009-03-28 19:18:32 +0000974 // We know that the decl had to be a VarDecl because that is the only type of
975 // decl that can be assigned and the grammar requires an '='.
976 VarDecl *VD = cast<VarDecl>(Dcl.getAs<Decl>());
977 VD->setDeclaredInCondition(true);
978 return Owned(new (Context) CXXConditionDeclExpr(StartLoc, EqualLoc, VD));
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +0000979}
980
981/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
982bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
983 // C++ 6.4p4:
984 // The value of a condition that is an initialized declaration in a statement
985 // other than a switch statement is the value of the declared variable
986 // implicitly converted to type bool. If that conversion is ill-formed, the
987 // program is ill-formed.
988 // The value of a condition that is an expression is the value of the
989 // expression, implicitly converted to bool.
990 //
Douglas Gregor5fb53972009-01-14 15:45:31 +0000991 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +0000992}
Douglas Gregoraa1e21d2008-09-12 00:47:35 +0000993
994/// Helper function to determine whether this is the (deprecated) C++
995/// conversion from a string literal to a pointer to non-const char or
996/// non-const wchar_t (for narrow and wide string literals,
997/// respectively).
Mike Stump11289f42009-09-09 15:08:12 +0000998bool
Douglas Gregoraa1e21d2008-09-12 00:47:35 +0000999Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
1000 // Look inside the implicit cast, if it exists.
1001 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
1002 From = Cast->getSubExpr();
1003
1004 // A string literal (2.13.4) that is not a wide string literal can
1005 // be converted to an rvalue of type "pointer to char"; a wide
1006 // string literal can be converted to an rvalue of type "pointer
1007 // to wchar_t" (C++ 4.2p2).
1008 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From))
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001009 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump11289f42009-09-09 15:08:12 +00001010 if (const BuiltinType *ToPointeeType
John McCall9dd450b2009-09-21 23:43:11 +00001011 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001012 // This conversion is considered only when there is an
1013 // explicit appropriate pointer target type (C++ 4.2p2).
John McCall8ccfcb52009-09-24 19:53:00 +00001014 if (!ToPtrType->getPointeeType().hasQualifiers() &&
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001015 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
1016 (!StrLit->isWide() &&
1017 (ToPointeeType->getKind() == BuiltinType::Char_U ||
1018 ToPointeeType->getKind() == BuiltinType::Char_S))))
1019 return true;
1020 }
1021
1022 return false;
1023}
Douglas Gregor39c16d42008-10-24 04:54:22 +00001024
1025/// PerformImplicitConversion - Perform an implicit conversion of the
1026/// expression From to the type ToType. Returns true if there was an
1027/// error, false otherwise. The expression From is replaced with the
Douglas Gregor47d3f272008-12-19 17:40:08 +00001028/// converted expression. Flavor is the kind of conversion we're
Douglas Gregor5fb53972009-01-14 15:45:31 +00001029/// performing, used in the error message. If @p AllowExplicit,
Sebastian Redl42e92c42009-04-12 17:16:29 +00001030/// explicit user-defined conversions are permitted. @p Elidable should be true
1031/// when called for copies which may be elided (C++ 12.8p15). C++0x overload
1032/// resolution works differently in that case.
1033bool
Douglas Gregor47d3f272008-12-19 17:40:08 +00001034Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Sebastian Redl42e92c42009-04-12 17:16:29 +00001035 const char *Flavor, bool AllowExplicit,
Mike Stump11289f42009-09-09 15:08:12 +00001036 bool Elidable) {
Sebastian Redl42e92c42009-04-12 17:16:29 +00001037 ImplicitConversionSequence ICS;
Fariborz Jahanianaf0262d2009-09-23 20:55:32 +00001038 return PerformImplicitConversion(From, ToType, Flavor, AllowExplicit,
1039 Elidable, ICS);
1040}
1041
1042bool
1043Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
1044 const char *Flavor, bool AllowExplicit,
1045 bool Elidable,
1046 ImplicitConversionSequence& ICS) {
Sebastian Redl42e92c42009-04-12 17:16:29 +00001047 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1048 if (Elidable && getLangOptions().CPlusPlus0x) {
Mike Stump11289f42009-09-09 15:08:12 +00001049 ICS = TryImplicitConversion(From, ToType,
Anders Carlssonef4c7212009-08-27 17:24:15 +00001050 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00001051 AllowExplicit,
Anders Carlsson228eea32009-08-28 15:33:32 +00001052 /*ForceRValue=*/true,
1053 /*InOverloadResolution=*/false);
Sebastian Redl42e92c42009-04-12 17:16:29 +00001054 }
1055 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion) {
Mike Stump11289f42009-09-09 15:08:12 +00001056 ICS = TryImplicitConversion(From, ToType,
Anders Carlssonef4c7212009-08-27 17:24:15 +00001057 /*SuppressUserConversions=*/false,
1058 AllowExplicit,
Anders Carlsson228eea32009-08-28 15:33:32 +00001059 /*ForceRValue=*/false,
1060 /*InOverloadResolution=*/false);
Sebastian Redl42e92c42009-04-12 17:16:29 +00001061 }
Douglas Gregor5fb53972009-01-14 15:45:31 +00001062 return PerformImplicitConversion(From, ToType, ICS, Flavor);
1063}
1064
Fariborz Jahanianda21efb2009-10-16 19:20:59 +00001065/// BuildCXXDerivedToBaseExpr - This routine generates the suitable AST
1066/// for the derived to base conversion of the expression 'From'. All
1067/// necessary information is passed in ICS.
1068bool
1069Sema::BuildCXXDerivedToBaseExpr(Expr *&From, CastExpr::CastKind CastKind,
1070 const ImplicitConversionSequence& ICS,
1071 const char *Flavor) {
1072 QualType BaseType =
1073 QualType::getFromOpaquePtr(ICS.UserDefined.After.ToTypePtr);
1074 // Must do additional defined to base conversion.
1075 QualType DerivedType =
1076 QualType::getFromOpaquePtr(ICS.UserDefined.After.FromTypePtr);
1077
1078 From = new (Context) ImplicitCastExpr(
1079 DerivedType.getNonReferenceType(),
1080 CastKind,
1081 From,
1082 DerivedType->isLValueReferenceType());
1083 From = new (Context) ImplicitCastExpr(BaseType.getNonReferenceType(),
1084 CastExpr::CK_DerivedToBase, From,
1085 BaseType->isLValueReferenceType());
1086 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1087 OwningExprResult FromResult =
1088 BuildCXXConstructExpr(
1089 ICS.UserDefined.After.CopyConstructor->getLocation(),
1090 BaseType,
1091 ICS.UserDefined.After.CopyConstructor,
1092 MultiExprArg(*this, (void **)&From, 1));
1093 if (FromResult.isInvalid())
1094 return true;
1095 From = FromResult.takeAs<Expr>();
1096 return false;
1097}
1098
Douglas Gregor5fb53972009-01-14 15:45:31 +00001099/// PerformImplicitConversion - Perform an implicit conversion of the
1100/// expression From to the type ToType using the pre-computed implicit
1101/// conversion sequence ICS. Returns true if there was an error, false
1102/// otherwise. The expression From is replaced with the converted
1103/// expression. Flavor is the kind of conversion we're performing,
1104/// used in the error message.
1105bool
1106Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
1107 const ImplicitConversionSequence &ICS,
Sebastian Redl7c353682009-11-14 21:15:49 +00001108 const char* Flavor, bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001109 switch (ICS.ConversionKind) {
1110 case ImplicitConversionSequence::StandardConversion:
Sebastian Redl7c353682009-11-14 21:15:49 +00001111 if (PerformImplicitConversion(From, ToType, ICS.Standard, Flavor,
1112 IgnoreBaseAccess))
Douglas Gregor39c16d42008-10-24 04:54:22 +00001113 return true;
1114 break;
1115
Anders Carlsson110b07b2009-09-15 06:28:28 +00001116 case ImplicitConversionSequence::UserDefinedConversion: {
1117
Fariborz Jahanian2fee79a2009-08-28 22:04:50 +00001118 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
1119 CastExpr::CastKind CastKind = CastExpr::CK_Unknown;
Anders Carlsson110b07b2009-09-15 06:28:28 +00001120 QualType BeforeToType;
1121 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
Fariborz Jahanian2fee79a2009-08-28 22:04:50 +00001122 CastKind = CastExpr::CK_UserDefinedConversion;
Anders Carlsson110b07b2009-09-15 06:28:28 +00001123
1124 // If the user-defined conversion is specified by a conversion function,
1125 // the initial standard conversion sequence converts the source type to
1126 // the implicit object parameter of the conversion function.
1127 BeforeToType = Context.getTagDeclType(Conv->getParent());
1128 } else if (const CXXConstructorDecl *Ctor =
1129 dyn_cast<CXXConstructorDecl>(FD)) {
Anders Carlssone9766d52009-09-09 21:33:21 +00001130 CastKind = CastExpr::CK_ConstructorConversion;
Fariborz Jahanian55824512009-11-06 00:23:08 +00001131 // Do no conversion if dealing with ... for the first conversion.
1132 if (!ICS.UserDefined.EllipsisConversion)
1133 // If the user-defined conversion is specified by a constructor, the
1134 // initial standard conversion sequence converts the source type to the
1135 // type required by the argument of the constructor
1136 BeforeToType = Ctor->getParamDecl(0)->getType();
Anders Carlsson110b07b2009-09-15 06:28:28 +00001137 }
Anders Carlssone9766d52009-09-09 21:33:21 +00001138 else
1139 assert(0 && "Unknown conversion function kind!");
Fariborz Jahanian55824512009-11-06 00:23:08 +00001140 // Whatch out for elipsis conversion.
Fariborz Jahanianeec642f2009-11-06 00:55:14 +00001141 if (!ICS.UserDefined.EllipsisConversion) {
Fariborz Jahanian55824512009-11-06 00:23:08 +00001142 if (PerformImplicitConversion(From, BeforeToType,
Sebastian Redl7c353682009-11-14 21:15:49 +00001143 ICS.UserDefined.Before, "converting",
1144 IgnoreBaseAccess))
Fariborz Jahanian55824512009-11-06 00:23:08 +00001145 return true;
1146 }
Anders Carlsson110b07b2009-09-15 06:28:28 +00001147
Anders Carlssone9766d52009-09-09 21:33:21 +00001148 OwningExprResult CastArg
1149 = BuildCXXCastArgument(From->getLocStart(),
1150 ToType.getNonReferenceType(),
1151 CastKind, cast<CXXMethodDecl>(FD),
1152 Owned(From));
1153
1154 if (CastArg.isInvalid())
1155 return true;
Fariborz Jahanianda21efb2009-10-16 19:20:59 +00001156
1157 if (ICS.UserDefined.After.Second == ICK_Derived_To_Base &&
1158 ICS.UserDefined.After.CopyConstructor) {
1159 From = CastArg.takeAs<Expr>();
1160 return BuildCXXDerivedToBaseExpr(From, CastKind, ICS, Flavor);
1161 }
Fariborz Jahanianc9af8fd2009-10-23 18:08:22 +00001162
1163 if (ICS.UserDefined.After.Second == ICK_Pointer_Member &&
1164 ToType.getNonReferenceType()->isMemberFunctionPointerType())
1165 CastKind = CastExpr::CK_BaseToDerivedMemberPointer;
Anders Carlssone9766d52009-09-09 21:33:21 +00001166
Anders Carlsson611da282009-09-15 05:49:31 +00001167 From = new (Context) ImplicitCastExpr(ToType.getNonReferenceType(),
Fariborz Jahanianda21efb2009-10-16 19:20:59 +00001168 CastKind, CastArg.takeAs<Expr>(),
Anders Carlsson611da282009-09-15 05:49:31 +00001169 ToType->isLValueReferenceType());
Fariborz Jahanian2fee79a2009-08-28 22:04:50 +00001170 return false;
Fariborz Jahanianda21efb2009-10-16 19:20:59 +00001171 }
1172
Douglas Gregor39c16d42008-10-24 04:54:22 +00001173 case ImplicitConversionSequence::EllipsisConversion:
1174 assert(false && "Cannot perform an ellipsis conversion");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001175 return false;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001176
1177 case ImplicitConversionSequence::BadConversion:
1178 return true;
1179 }
1180
1181 // Everything went well.
1182 return false;
1183}
1184
1185/// PerformImplicitConversion - Perform an implicit conversion of the
1186/// expression From to the type ToType by following the standard
1187/// conversion sequence SCS. Returns true if there was an error, false
1188/// otherwise. The expression From is replaced with the converted
Douglas Gregor47d3f272008-12-19 17:40:08 +00001189/// expression. Flavor is the context in which we're performing this
1190/// conversion, for use in error messages.
Mike Stump11289f42009-09-09 15:08:12 +00001191bool
Douglas Gregor39c16d42008-10-24 04:54:22 +00001192Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor47d3f272008-12-19 17:40:08 +00001193 const StandardConversionSequence& SCS,
Sebastian Redl7c353682009-11-14 21:15:49 +00001194 const char *Flavor, bool IgnoreBaseAccess) {
Mike Stump87c57ac2009-05-16 07:39:55 +00001195 // Overall FIXME: we are recomputing too many types here and doing far too
1196 // much extra work. What this means is that we need to keep track of more
1197 // information that is computed when we try the implicit conversion initially,
1198 // so that we don't need to recompute anything here.
Douglas Gregor39c16d42008-10-24 04:54:22 +00001199 QualType FromType = From->getType();
1200
Douglas Gregor2fe98832008-11-03 19:09:14 +00001201 if (SCS.CopyConstructor) {
Anders Carlsson549c5bd2009-05-19 04:45:15 +00001202 // FIXME: When can ToType be a reference type?
1203 assert(!ToType->isReferenceType());
Fariborz Jahanian49850df2009-09-25 18:59:21 +00001204 if (SCS.Second == ICK_Derived_To_Base) {
1205 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1206 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
1207 MultiExprArg(*this, (void **)&From, 1),
1208 /*FIXME:ConstructLoc*/SourceLocation(),
1209 ConstructorArgs))
1210 return true;
1211 OwningExprResult FromResult =
1212 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1213 ToType, SCS.CopyConstructor,
1214 move_arg(ConstructorArgs));
1215 if (FromResult.isInvalid())
1216 return true;
1217 From = FromResult.takeAs<Expr>();
1218 return false;
1219 }
Mike Stump11289f42009-09-09 15:08:12 +00001220 OwningExprResult FromResult =
1221 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1222 ToType, SCS.CopyConstructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00001223 MultiExprArg(*this, (void**)&From, 1));
Mike Stump11289f42009-09-09 15:08:12 +00001224
Anders Carlsson6eb55572009-08-25 05:12:04 +00001225 if (FromResult.isInvalid())
1226 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001227
Anders Carlsson6eb55572009-08-25 05:12:04 +00001228 From = FromResult.takeAs<Expr>();
Douglas Gregor2fe98832008-11-03 19:09:14 +00001229 return false;
1230 }
1231
Douglas Gregor39c16d42008-10-24 04:54:22 +00001232 // Perform the first implicit conversion.
1233 switch (SCS.First) {
1234 case ICK_Identity:
1235 case ICK_Lvalue_To_Rvalue:
1236 // Nothing to do.
1237 break;
1238
1239 case ICK_Array_To_Pointer:
Douglas Gregor171c45a2009-02-18 21:56:37 +00001240 FromType = Context.getArrayDecayedType(FromType);
Anders Carlsson2c101b32009-08-08 21:04:35 +00001241 ImpCastExprToType(From, FromType, CastExpr::CK_ArrayToPointerDecay);
Douglas Gregor171c45a2009-02-18 21:56:37 +00001242 break;
1243
1244 case ICK_Function_To_Pointer:
Douglas Gregor1baf54e2009-03-13 18:40:31 +00001245 if (Context.getCanonicalType(FromType) == Context.OverloadTy) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00001246 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, true);
1247 if (!Fn)
1248 return true;
1249
Douglas Gregor171c45a2009-02-18 21:56:37 +00001250 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
1251 return true;
1252
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00001253 From = FixOverloadedFunctionReference(From, Fn);
Douglas Gregorcd695e52008-11-10 20:40:00 +00001254 FromType = From->getType();
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00001255
Sebastian Redlfef1c0d2009-10-17 20:50:27 +00001256 // If there's already an address-of operator in the expression, we have
1257 // the right type already, and the code below would just introduce an
1258 // invalid additional pointer level.
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00001259 if (FromType->isPointerType() || FromType->isMemberFunctionPointerType())
Sebastian Redlfef1c0d2009-10-17 20:50:27 +00001260 break;
Douglas Gregorcd695e52008-11-10 20:40:00 +00001261 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00001262 FromType = Context.getPointerType(FromType);
Anders Carlsson6904f642009-09-01 20:37:18 +00001263 ImpCastExprToType(From, FromType, CastExpr::CK_FunctionToPointerDecay);
Douglas Gregor39c16d42008-10-24 04:54:22 +00001264 break;
1265
1266 default:
1267 assert(false && "Improper first standard conversion");
1268 break;
1269 }
1270
1271 // Perform the second implicit conversion
1272 switch (SCS.Second) {
1273 case ICK_Identity:
Sebastian Redl5d431642009-10-10 12:04:10 +00001274 // If both sides are functions (or pointers/references to them), there could
1275 // be incompatible exception declarations.
1276 if (CheckExceptionSpecCompatibility(From, ToType))
1277 return true;
1278 // Nothing else to do.
Douglas Gregor39c16d42008-10-24 04:54:22 +00001279 break;
1280
1281 case ICK_Integral_Promotion:
Douglas Gregor39c16d42008-10-24 04:54:22 +00001282 case ICK_Integral_Conversion:
Eli Friedman06ed2a52009-10-20 08:27:19 +00001283 ImpCastExprToType(From, ToType, CastExpr::CK_IntegralCast);
1284 break;
1285
1286 case ICK_Floating_Promotion:
Douglas Gregor39c16d42008-10-24 04:54:22 +00001287 case ICK_Floating_Conversion:
Eli Friedman06ed2a52009-10-20 08:27:19 +00001288 ImpCastExprToType(From, ToType, CastExpr::CK_FloatingCast);
1289 break;
1290
1291 case ICK_Complex_Promotion:
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001292 case ICK_Complex_Conversion:
Eli Friedman06ed2a52009-10-20 08:27:19 +00001293 ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1294 break;
1295
Douglas Gregor39c16d42008-10-24 04:54:22 +00001296 case ICK_Floating_Integral:
Eli Friedman06ed2a52009-10-20 08:27:19 +00001297 if (ToType->isFloatingType())
1298 ImpCastExprToType(From, ToType, CastExpr::CK_IntegralToFloating);
1299 else
1300 ImpCastExprToType(From, ToType, CastExpr::CK_FloatingToIntegral);
1301 break;
1302
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001303 case ICK_Complex_Real:
Eli Friedman06ed2a52009-10-20 08:27:19 +00001304 ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1305 break;
1306
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001307 case ICK_Compatible_Conversion:
Eli Friedman06ed2a52009-10-20 08:27:19 +00001308 ImpCastExprToType(From, ToType, CastExpr::CK_NoOp);
Douglas Gregor39c16d42008-10-24 04:54:22 +00001309 break;
1310
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001311 case ICK_Pointer_Conversion: {
Douglas Gregor47d3f272008-12-19 17:40:08 +00001312 if (SCS.IncompatibleObjC) {
1313 // Diagnose incompatible Objective-C conversions
Mike Stump11289f42009-09-09 15:08:12 +00001314 Diag(From->getSourceRange().getBegin(),
Douglas Gregor47d3f272008-12-19 17:40:08 +00001315 diag::ext_typecheck_convert_incompatible_pointer)
1316 << From->getType() << ToType << Flavor
1317 << From->getSourceRange();
1318 }
1319
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001320
1321 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Sebastian Redl7c353682009-11-14 21:15:49 +00001322 if (CheckPointerConversion(From, ToType, Kind, IgnoreBaseAccess))
Douglas Gregor39c16d42008-10-24 04:54:22 +00001323 return true;
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001324 ImpCastExprToType(From, ToType, Kind);
Douglas Gregor39c16d42008-10-24 04:54:22 +00001325 break;
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001326 }
1327
1328 case ICK_Pointer_Member: {
1329 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Sebastian Redl7c353682009-11-14 21:15:49 +00001330 if (CheckMemberPointerConversion(From, ToType, Kind, IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001331 return true;
Sebastian Redl5d431642009-10-10 12:04:10 +00001332 if (CheckExceptionSpecCompatibility(From, ToType))
1333 return true;
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001334 ImpCastExprToType(From, ToType, Kind);
1335 break;
1336 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00001337 case ICK_Boolean_Conversion:
Eli Friedman06ed2a52009-10-20 08:27:19 +00001338 ImpCastExprToType(From, Context.BoolTy, CastExpr::CK_Unknown);
Douglas Gregor39c16d42008-10-24 04:54:22 +00001339 break;
1340
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00001341 case ICK_Derived_To_Base:
1342 if (CheckDerivedToBaseConversion(From->getType(),
1343 ToType.getNonReferenceType(),
1344 From->getLocStart(),
Sebastian Redl7c353682009-11-14 21:15:49 +00001345 From->getSourceRange(),
1346 IgnoreBaseAccess))
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00001347 return true;
1348 ImpCastExprToType(From, ToType.getNonReferenceType(),
1349 CastExpr::CK_DerivedToBase);
1350 break;
1351
Douglas Gregor39c16d42008-10-24 04:54:22 +00001352 default:
1353 assert(false && "Improper second standard conversion");
1354 break;
1355 }
1356
1357 switch (SCS.Third) {
1358 case ICK_Identity:
1359 // Nothing to do.
1360 break;
1361
1362 case ICK_Qualification:
Mike Stump87c57ac2009-05-16 07:39:55 +00001363 // FIXME: Not sure about lvalue vs rvalue here in the presence of rvalue
1364 // references.
Mike Stump11289f42009-09-09 15:08:12 +00001365 ImpCastExprToType(From, ToType.getNonReferenceType(),
Eli Friedman06ed2a52009-10-20 08:27:19 +00001366 CastExpr::CK_NoOp,
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001367 ToType->isLValueReferenceType());
Douglas Gregor39c16d42008-10-24 04:54:22 +00001368 break;
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00001369
Douglas Gregor39c16d42008-10-24 04:54:22 +00001370 default:
1371 assert(false && "Improper second standard conversion");
1372 break;
1373 }
1374
1375 return false;
1376}
1377
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001378Sema::OwningExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
1379 SourceLocation KWLoc,
1380 SourceLocation LParen,
1381 TypeTy *Ty,
1382 SourceLocation RParen) {
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00001383 QualType T = GetTypeFromParser(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00001384
Anders Carlsson1f9648d2009-07-07 19:06:02 +00001385 // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
1386 // all traits except __is_class, __is_enum and __is_union require a the type
1387 // to be complete.
1388 if (OTT != UTT_IsClass && OTT != UTT_IsEnum && OTT != UTT_IsUnion) {
Mike Stump11289f42009-09-09 15:08:12 +00001389 if (RequireCompleteType(KWLoc, T,
Anders Carlsson029fc692009-08-26 22:59:12 +00001390 diag::err_incomplete_type_used_in_type_trait_expr))
Anders Carlsson1f9648d2009-07-07 19:06:02 +00001391 return ExprError();
1392 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001393
1394 // There is no point in eagerly computing the value. The traits are designed
1395 // to be used from type trait templates, so Ty will be a template parameter
1396 // 99% of the time.
Anders Carlsson1f9648d2009-07-07 19:06:02 +00001397 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT, T,
1398 RParen, Context.BoolTy));
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001399}
Sebastian Redl5822f082009-02-07 20:10:22 +00001400
1401QualType Sema::CheckPointerToMemberOperands(
Mike Stump11289f42009-09-09 15:08:12 +00001402 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect) {
Sebastian Redl5822f082009-02-07 20:10:22 +00001403 const char *OpSpelling = isIndirect ? "->*" : ".*";
1404 // C++ 5.5p2
1405 // The binary operator .* [p3: ->*] binds its second operand, which shall
1406 // be of type "pointer to member of T" (where T is a completely-defined
1407 // class type) [...]
1408 QualType RType = rex->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001409 const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
Douglas Gregorac1fb652009-03-24 19:52:54 +00001410 if (!MemPtr) {
Sebastian Redl5822f082009-02-07 20:10:22 +00001411 Diag(Loc, diag::err_bad_memptr_rhs)
1412 << OpSpelling << RType << rex->getSourceRange();
1413 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00001414 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00001415
Sebastian Redl5822f082009-02-07 20:10:22 +00001416 QualType Class(MemPtr->getClass(), 0);
1417
1418 // C++ 5.5p2
1419 // [...] to its first operand, which shall be of class T or of a class of
1420 // which T is an unambiguous and accessible base class. [p3: a pointer to
1421 // such a class]
1422 QualType LType = lex->getType();
1423 if (isIndirect) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001424 if (const PointerType *Ptr = LType->getAs<PointerType>())
Sebastian Redl5822f082009-02-07 20:10:22 +00001425 LType = Ptr->getPointeeType().getNonReferenceType();
1426 else {
1427 Diag(Loc, diag::err_bad_memptr_lhs)
Fariborz Jahanian59f64202009-10-26 20:45:27 +00001428 << OpSpelling << 1 << LType
1429 << CodeModificationHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl5822f082009-02-07 20:10:22 +00001430 return QualType();
1431 }
1432 }
1433
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001434 if (!Context.hasSameUnqualifiedType(Class, LType)) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001435 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1436 /*DetectVirtual=*/false);
Mike Stump87c57ac2009-05-16 07:39:55 +00001437 // FIXME: Would it be useful to print full ambiguity paths, or is that
1438 // overkill?
Sebastian Redl5822f082009-02-07 20:10:22 +00001439 if (!IsDerivedFrom(LType, Class, Paths) ||
1440 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
Fariborz Jahanian59f64202009-10-26 20:45:27 +00001441 const char *ReplaceStr = isIndirect ? ".*" : "->*";
Sebastian Redl5822f082009-02-07 20:10:22 +00001442 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Fariborz Jahanian59f64202009-10-26 20:45:27 +00001443 << (int)isIndirect << lex->getType() <<
1444 CodeModificationHint::CreateReplacement(SourceRange(Loc), ReplaceStr);
Sebastian Redl5822f082009-02-07 20:10:22 +00001445 return QualType();
1446 }
1447 }
1448
1449 // C++ 5.5p2
1450 // The result is an object or a function of the type specified by the
1451 // second operand.
1452 // The cv qualifiers are the union of those in the pointer and the left side,
1453 // in accordance with 5.5p5 and 5.2.5.
1454 // FIXME: This returns a dereferenced member function pointer as a normal
1455 // function type. However, the only operation valid on such functions is
Mike Stump87c57ac2009-05-16 07:39:55 +00001456 // calling them. There's also a GCC extension to get a function pointer to the
1457 // thing, which is another complication, because this type - unlike the type
1458 // that is the result of this expression - takes the class as the first
Sebastian Redl5822f082009-02-07 20:10:22 +00001459 // argument.
1460 // We probably need a "MemberFunctionClosureType" or something like that.
1461 QualType Result = MemPtr->getPointeeType();
John McCall8ccfcb52009-09-24 19:53:00 +00001462 Result = Context.getCVRQualifiedType(Result, LType.getCVRQualifiers());
Sebastian Redl5822f082009-02-07 20:10:22 +00001463 return Result;
1464}
Sebastian Redl1a99f442009-04-16 17:51:27 +00001465
1466/// \brief Get the target type of a standard or user-defined conversion.
1467static QualType TargetType(const ImplicitConversionSequence &ICS) {
1468 assert((ICS.ConversionKind ==
1469 ImplicitConversionSequence::StandardConversion ||
1470 ICS.ConversionKind ==
1471 ImplicitConversionSequence::UserDefinedConversion) &&
1472 "function only valid for standard or user-defined conversions");
1473 if (ICS.ConversionKind == ImplicitConversionSequence::StandardConversion)
1474 return QualType::getFromOpaquePtr(ICS.Standard.ToTypePtr);
1475 return QualType::getFromOpaquePtr(ICS.UserDefined.After.ToTypePtr);
1476}
1477
1478/// \brief Try to convert a type to another according to C++0x 5.16p3.
1479///
1480/// This is part of the parameter validation for the ? operator. If either
1481/// value operand is a class type, the two operands are attempted to be
1482/// converted to each other. This function does the conversion in one direction.
1483/// It emits a diagnostic and returns true only if it finds an ambiguous
1484/// conversion.
1485static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
1486 SourceLocation QuestionLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001487 ImplicitConversionSequence &ICS) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00001488 // C++0x 5.16p3
1489 // The process for determining whether an operand expression E1 of type T1
1490 // can be converted to match an operand expression E2 of type T2 is defined
1491 // as follows:
1492 // -- If E2 is an lvalue:
1493 if (To->isLvalue(Self.Context) == Expr::LV_Valid) {
1494 // E1 can be converted to match E2 if E1 can be implicitly converted to
1495 // type "lvalue reference to T2", subject to the constraint that in the
1496 // conversion the reference must bind directly to E1.
1497 if (!Self.CheckReferenceInit(From,
1498 Self.Context.getLValueReferenceType(To->getType()),
Douglas Gregorc809cc22009-09-23 23:04:10 +00001499 To->getLocStart(),
Anders Carlsson271e3a42009-08-27 17:30:43 +00001500 /*SuppressUserConversions=*/false,
1501 /*AllowExplicit=*/false,
1502 /*ForceRValue=*/false,
1503 &ICS))
Sebastian Redl1a99f442009-04-16 17:51:27 +00001504 {
1505 assert((ICS.ConversionKind ==
1506 ImplicitConversionSequence::StandardConversion ||
1507 ICS.ConversionKind ==
1508 ImplicitConversionSequence::UserDefinedConversion) &&
1509 "expected a definite conversion");
1510 bool DirectBinding =
1511 ICS.ConversionKind == ImplicitConversionSequence::StandardConversion ?
1512 ICS.Standard.DirectBinding : ICS.UserDefined.After.DirectBinding;
1513 if (DirectBinding)
1514 return false;
1515 }
1516 }
1517 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1518 // -- If E2 is an rvalue, or if the conversion above cannot be done:
1519 // -- if E1 and E2 have class type, and the underlying class types are
1520 // the same or one is a base class of the other:
1521 QualType FTy = From->getType();
1522 QualType TTy = To->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001523 const RecordType *FRec = FTy->getAs<RecordType>();
1524 const RecordType *TRec = TTy->getAs<RecordType>();
Sebastian Redl1a99f442009-04-16 17:51:27 +00001525 bool FDerivedFromT = FRec && TRec && Self.IsDerivedFrom(FTy, TTy);
1526 if (FRec && TRec && (FRec == TRec ||
1527 FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
1528 // E1 can be converted to match E2 if the class of T2 is the
1529 // same type as, or a base class of, the class of T1, and
1530 // [cv2 > cv1].
1531 if ((FRec == TRec || FDerivedFromT) && TTy.isAtLeastAsQualifiedAs(FTy)) {
1532 // Could still fail if there's no copy constructor.
1533 // FIXME: Is this a hard error then, or just a conversion failure? The
1534 // standard doesn't say.
Mike Stump11289f42009-09-09 15:08:12 +00001535 ICS = Self.TryCopyInitialization(From, TTy,
Anders Carlsson03068aa2009-08-27 17:18:13 +00001536 /*SuppressUserConversions=*/false,
Anders Carlsson20d13322009-08-27 17:37:39 +00001537 /*ForceRValue=*/false,
1538 /*InOverloadResolution=*/false);
Sebastian Redl1a99f442009-04-16 17:51:27 +00001539 }
1540 } else {
1541 // -- Otherwise: E1 can be converted to match E2 if E1 can be
1542 // implicitly converted to the type that expression E2 would have
1543 // if E2 were converted to an rvalue.
1544 // First find the decayed type.
1545 if (TTy->isFunctionType())
1546 TTy = Self.Context.getPointerType(TTy);
Mike Stump11289f42009-09-09 15:08:12 +00001547 else if (TTy->isArrayType())
Sebastian Redl1a99f442009-04-16 17:51:27 +00001548 TTy = Self.Context.getArrayDecayedType(TTy);
1549
1550 // Now try the implicit conversion.
1551 // FIXME: This doesn't detect ambiguities.
Anders Carlssonef4c7212009-08-27 17:24:15 +00001552 ICS = Self.TryImplicitConversion(From, TTy,
1553 /*SuppressUserConversions=*/false,
1554 /*AllowExplicit=*/false,
Anders Carlsson228eea32009-08-28 15:33:32 +00001555 /*ForceRValue=*/false,
1556 /*InOverloadResolution=*/false);
Sebastian Redl1a99f442009-04-16 17:51:27 +00001557 }
1558 return false;
1559}
1560
1561/// \brief Try to find a common type for two according to C++0x 5.16p5.
1562///
1563/// This is part of the parameter validation for the ? operator. If either
1564/// value operand is a class type, overload resolution is used to find a
1565/// conversion to a common type.
1566static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
1567 SourceLocation Loc) {
1568 Expr *Args[2] = { LHS, RHS };
1569 OverloadCandidateSet CandidateSet;
Douglas Gregorc02cfe22009-10-21 23:19:44 +00001570 Self.AddBuiltinOperatorCandidates(OO_Conditional, Loc, Args, 2, CandidateSet);
Sebastian Redl1a99f442009-04-16 17:51:27 +00001571
1572 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00001573 switch (Self.BestViableFunction(CandidateSet, Loc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00001574 case Sema::OR_Success:
1575 // We found a match. Perform the conversions on the arguments and move on.
1576 if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
1577 Best->Conversions[0], "converting") ||
1578 Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
1579 Best->Conversions[1], "converting"))
1580 break;
1581 return false;
1582
1583 case Sema::OR_No_Viable_Function:
1584 Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
1585 << LHS->getType() << RHS->getType()
1586 << LHS->getSourceRange() << RHS->getSourceRange();
1587 return true;
1588
1589 case Sema::OR_Ambiguous:
1590 Self.Diag(Loc, diag::err_conditional_ambiguous_ovl)
1591 << LHS->getType() << RHS->getType()
1592 << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stump87c57ac2009-05-16 07:39:55 +00001593 // FIXME: Print the possible common types by printing the return types of
1594 // the viable candidates.
Sebastian Redl1a99f442009-04-16 17:51:27 +00001595 break;
1596
1597 case Sema::OR_Deleted:
1598 assert(false && "Conditional operator has only built-in overloads");
1599 break;
1600 }
1601 return true;
1602}
1603
Sebastian Redl5775af1a2009-04-17 16:30:52 +00001604/// \brief Perform an "extended" implicit conversion as returned by
1605/// TryClassUnification.
1606///
1607/// TryClassUnification generates ICSs that include reference bindings.
1608/// PerformImplicitConversion is not suitable for this; it chokes if the
1609/// second part of a standard conversion is ICK_DerivedToBase. This function
1610/// handles the reference binding specially.
1611static bool ConvertForConditional(Sema &Self, Expr *&E,
Mike Stump11289f42009-09-09 15:08:12 +00001612 const ImplicitConversionSequence &ICS) {
Sebastian Redl5775af1a2009-04-17 16:30:52 +00001613 if (ICS.ConversionKind == ImplicitConversionSequence::StandardConversion &&
1614 ICS.Standard.ReferenceBinding) {
1615 assert(ICS.Standard.DirectBinding &&
1616 "TryClassUnification should never generate indirect ref bindings");
Sebastian Redlf79d3972009-04-26 11:21:02 +00001617 // FIXME: CheckReferenceInit should be able to reuse the ICS instead of
1618 // redoing all the work.
1619 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
Anders Carlsson271e3a42009-08-27 17:30:43 +00001620 TargetType(ICS)),
Douglas Gregorc809cc22009-09-23 23:04:10 +00001621 /*FIXME:*/E->getLocStart(),
Anders Carlsson271e3a42009-08-27 17:30:43 +00001622 /*SuppressUserConversions=*/false,
1623 /*AllowExplicit=*/false,
1624 /*ForceRValue=*/false);
Sebastian Redl5775af1a2009-04-17 16:30:52 +00001625 }
1626 if (ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion &&
1627 ICS.UserDefined.After.ReferenceBinding) {
1628 assert(ICS.UserDefined.After.DirectBinding &&
1629 "TryClassUnification should never generate indirect ref bindings");
Sebastian Redlf79d3972009-04-26 11:21:02 +00001630 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
Anders Carlsson271e3a42009-08-27 17:30:43 +00001631 TargetType(ICS)),
Douglas Gregorc809cc22009-09-23 23:04:10 +00001632 /*FIXME:*/E->getLocStart(),
Anders Carlsson271e3a42009-08-27 17:30:43 +00001633 /*SuppressUserConversions=*/false,
1634 /*AllowExplicit=*/false,
1635 /*ForceRValue=*/false);
Sebastian Redl5775af1a2009-04-17 16:30:52 +00001636 }
1637 if (Self.PerformImplicitConversion(E, TargetType(ICS), ICS, "converting"))
1638 return true;
1639 return false;
1640}
1641
Sebastian Redl1a99f442009-04-16 17:51:27 +00001642/// \brief Check the operands of ?: under C++ semantics.
1643///
1644/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
1645/// extension. In this case, LHS == Cond. (But they're not aliases.)
1646QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
1647 SourceLocation QuestionLoc) {
Mike Stump87c57ac2009-05-16 07:39:55 +00001648 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
1649 // interface pointers.
Sebastian Redl1a99f442009-04-16 17:51:27 +00001650
1651 // C++0x 5.16p1
1652 // The first expression is contextually converted to bool.
1653 if (!Cond->isTypeDependent()) {
1654 if (CheckCXXBooleanCondition(Cond))
1655 return QualType();
1656 }
1657
1658 // Either of the arguments dependent?
1659 if (LHS->isTypeDependent() || RHS->isTypeDependent())
1660 return Context.DependentTy;
1661
John McCall1fa36b72009-11-05 09:23:39 +00001662 CheckSignCompare(LHS, RHS, QuestionLoc, diag::warn_mixed_sign_conditional);
1663
Sebastian Redl1a99f442009-04-16 17:51:27 +00001664 // C++0x 5.16p2
1665 // If either the second or the third operand has type (cv) void, ...
1666 QualType LTy = LHS->getType();
1667 QualType RTy = RHS->getType();
1668 bool LVoid = LTy->isVoidType();
1669 bool RVoid = RTy->isVoidType();
1670 if (LVoid || RVoid) {
1671 // ... then the [l2r] conversions are performed on the second and third
1672 // operands ...
1673 DefaultFunctionArrayConversion(LHS);
1674 DefaultFunctionArrayConversion(RHS);
1675 LTy = LHS->getType();
1676 RTy = RHS->getType();
1677
1678 // ... and one of the following shall hold:
1679 // -- The second or the third operand (but not both) is a throw-
1680 // expression; the result is of the type of the other and is an rvalue.
1681 bool LThrow = isa<CXXThrowExpr>(LHS);
1682 bool RThrow = isa<CXXThrowExpr>(RHS);
1683 if (LThrow && !RThrow)
1684 return RTy;
1685 if (RThrow && !LThrow)
1686 return LTy;
1687
1688 // -- Both the second and third operands have type void; the result is of
1689 // type void and is an rvalue.
1690 if (LVoid && RVoid)
1691 return Context.VoidTy;
1692
1693 // Neither holds, error.
1694 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
1695 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
1696 << LHS->getSourceRange() << RHS->getSourceRange();
1697 return QualType();
1698 }
1699
1700 // Neither is void.
1701
1702 // C++0x 5.16p3
1703 // Otherwise, if the second and third operand have different types, and
1704 // either has (cv) class type, and attempt is made to convert each of those
1705 // operands to the other.
1706 if (Context.getCanonicalType(LTy) != Context.getCanonicalType(RTy) &&
1707 (LTy->isRecordType() || RTy->isRecordType())) {
1708 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
1709 // These return true if a single direction is already ambiguous.
1710 if (TryClassUnification(*this, LHS, RHS, QuestionLoc, ICSLeftToRight))
1711 return QualType();
1712 if (TryClassUnification(*this, RHS, LHS, QuestionLoc, ICSRightToLeft))
1713 return QualType();
1714
1715 bool HaveL2R = ICSLeftToRight.ConversionKind !=
1716 ImplicitConversionSequence::BadConversion;
1717 bool HaveR2L = ICSRightToLeft.ConversionKind !=
1718 ImplicitConversionSequence::BadConversion;
1719 // If both can be converted, [...] the program is ill-formed.
1720 if (HaveL2R && HaveR2L) {
1721 Diag(QuestionLoc, diag::err_conditional_ambiguous)
1722 << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
1723 return QualType();
1724 }
1725
1726 // If exactly one conversion is possible, that conversion is applied to
1727 // the chosen operand and the converted operands are used in place of the
1728 // original operands for the remainder of this section.
1729 if (HaveL2R) {
Sebastian Redl5775af1a2009-04-17 16:30:52 +00001730 if (ConvertForConditional(*this, LHS, ICSLeftToRight))
Sebastian Redl1a99f442009-04-16 17:51:27 +00001731 return QualType();
1732 LTy = LHS->getType();
1733 } else if (HaveR2L) {
Sebastian Redl5775af1a2009-04-17 16:30:52 +00001734 if (ConvertForConditional(*this, RHS, ICSRightToLeft))
Sebastian Redl1a99f442009-04-16 17:51:27 +00001735 return QualType();
1736 RTy = RHS->getType();
1737 }
1738 }
1739
1740 // C++0x 5.16p4
1741 // If the second and third operands are lvalues and have the same type,
1742 // the result is of that type [...]
1743 bool Same = Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy);
1744 if (Same && LHS->isLvalue(Context) == Expr::LV_Valid &&
1745 RHS->isLvalue(Context) == Expr::LV_Valid)
1746 return LTy;
1747
1748 // C++0x 5.16p5
1749 // Otherwise, the result is an rvalue. If the second and third operands
1750 // do not have the same type, and either has (cv) class type, ...
1751 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
1752 // ... overload resolution is used to determine the conversions (if any)
1753 // to be applied to the operands. If the overload resolution fails, the
1754 // program is ill-formed.
1755 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
1756 return QualType();
1757 }
1758
1759 // C++0x 5.16p6
1760 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
1761 // conversions are performed on the second and third operands.
1762 DefaultFunctionArrayConversion(LHS);
1763 DefaultFunctionArrayConversion(RHS);
1764 LTy = LHS->getType();
1765 RTy = RHS->getType();
1766
1767 // After those conversions, one of the following shall hold:
1768 // -- The second and third operands have the same type; the result
1769 // is of that type.
1770 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy))
1771 return LTy;
1772
1773 // -- The second and third operands have arithmetic or enumeration type;
1774 // the usual arithmetic conversions are performed to bring them to a
1775 // common type, and the result is of that type.
1776 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
1777 UsualArithmeticConversions(LHS, RHS);
1778 return LHS->getType();
1779 }
1780
1781 // -- The second and third operands have pointer type, or one has pointer
1782 // type and the other is a null pointer constant; pointer conversions
1783 // and qualification conversions are performed to bring them to their
1784 // composite pointer type. The result is of the composite pointer type.
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00001785 QualType Composite = FindCompositePointerType(LHS, RHS);
1786 if (!Composite.isNull())
1787 return Composite;
Sebastian Redl1a99f442009-04-16 17:51:27 +00001788
Sebastian Redl0753c6f2009-04-19 21:15:26 +00001789 // Fourth bullet is same for pointers-to-member. However, the possible
1790 // conversions are far more limited: we have null-to-pointer, upcast of
1791 // containing class, and second-level cv-ness.
1792 // cv-ness is not a union, but must match one of the two operands. (Which,
1793 // frankly, is stupid.)
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001794 const MemberPointerType *LMemPtr = LTy->getAs<MemberPointerType>();
1795 const MemberPointerType *RMemPtr = RTy->getAs<MemberPointerType>();
Douglas Gregor56751b52009-09-25 04:25:58 +00001796 if (LMemPtr &&
1797 RHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00001798 ImpCastExprToType(RHS, LTy, CastExpr::CK_NullToMemberPointer);
Sebastian Redl0753c6f2009-04-19 21:15:26 +00001799 return LTy;
1800 }
Douglas Gregor56751b52009-09-25 04:25:58 +00001801 if (RMemPtr &&
1802 LHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00001803 ImpCastExprToType(LHS, RTy, CastExpr::CK_NullToMemberPointer);
Sebastian Redl0753c6f2009-04-19 21:15:26 +00001804 return RTy;
1805 }
1806 if (LMemPtr && RMemPtr) {
1807 QualType LPointee = LMemPtr->getPointeeType();
1808 QualType RPointee = RMemPtr->getPointeeType();
John McCall8ccfcb52009-09-24 19:53:00 +00001809
1810 QualifierCollector LPQuals, RPQuals;
1811 const Type *LPCan = LPQuals.strip(Context.getCanonicalType(LPointee));
1812 const Type *RPCan = RPQuals.strip(Context.getCanonicalType(RPointee));
1813
Sebastian Redl0753c6f2009-04-19 21:15:26 +00001814 // First, we check that the unqualified pointee type is the same. If it's
1815 // not, there's no conversion that will unify the two pointers.
John McCall8ccfcb52009-09-24 19:53:00 +00001816 if (LPCan == RPCan) {
1817
1818 // Second, we take the greater of the two qualifications. If neither
Sebastian Redl0753c6f2009-04-19 21:15:26 +00001819 // is greater than the other, the conversion is not possible.
John McCall8ccfcb52009-09-24 19:53:00 +00001820
1821 Qualifiers MergedQuals = LPQuals + RPQuals;
1822
1823 bool CompatibleQuals = true;
1824 if (MergedQuals.getCVRQualifiers() != LPQuals.getCVRQualifiers() &&
1825 MergedQuals.getCVRQualifiers() != RPQuals.getCVRQualifiers())
1826 CompatibleQuals = false;
1827 else if (LPQuals.getAddressSpace() != RPQuals.getAddressSpace())
1828 // FIXME:
1829 // C99 6.5.15 as modified by TR 18037:
1830 // If the second and third operands are pointers into different
1831 // address spaces, the address spaces must overlap.
1832 CompatibleQuals = false;
1833 // FIXME: GC qualifiers?
1834
1835 if (CompatibleQuals) {
Sebastian Redl0753c6f2009-04-19 21:15:26 +00001836 // Third, we check if either of the container classes is derived from
1837 // the other.
1838 QualType LContainer(LMemPtr->getClass(), 0);
1839 QualType RContainer(RMemPtr->getClass(), 0);
1840 QualType MoreDerived;
1841 if (Context.getCanonicalType(LContainer) ==
1842 Context.getCanonicalType(RContainer))
1843 MoreDerived = LContainer;
1844 else if (IsDerivedFrom(LContainer, RContainer))
1845 MoreDerived = LContainer;
1846 else if (IsDerivedFrom(RContainer, LContainer))
1847 MoreDerived = RContainer;
1848
1849 if (!MoreDerived.isNull()) {
1850 // The type 'Q Pointee (MoreDerived::*)' is the common type.
1851 // We don't use ImpCastExprToType here because this could still fail
1852 // for ambiguous or inaccessible conversions.
John McCall8ccfcb52009-09-24 19:53:00 +00001853 LPointee = Context.getQualifiedType(LPointee, MergedQuals);
1854 QualType Common
1855 = Context.getMemberPointerType(LPointee, MoreDerived.getTypePtr());
Sebastian Redl0753c6f2009-04-19 21:15:26 +00001856 if (PerformImplicitConversion(LHS, Common, "converting"))
1857 return QualType();
1858 if (PerformImplicitConversion(RHS, Common, "converting"))
1859 return QualType();
1860 return Common;
1861 }
1862 }
1863 }
1864 }
1865
Sebastian Redl1a99f442009-04-16 17:51:27 +00001866 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
1867 << LHS->getType() << RHS->getType()
1868 << LHS->getSourceRange() << RHS->getSourceRange();
1869 return QualType();
1870}
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00001871
1872/// \brief Find a merged pointer type and convert the two expressions to it.
1873///
Douglas Gregorb00b10e2009-08-24 17:42:35 +00001874/// This finds the composite pointer type (or member pointer type) for @p E1
1875/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
1876/// type and returns it.
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00001877/// It does not emit diagnostics.
1878QualType Sema::FindCompositePointerType(Expr *&E1, Expr *&E2) {
1879 assert(getLangOptions().CPlusPlus && "This function assumes C++");
1880 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump11289f42009-09-09 15:08:12 +00001881
Douglas Gregorb00b10e2009-08-24 17:42:35 +00001882 if (!T1->isPointerType() && !T1->isMemberPointerType() &&
1883 !T2->isPointerType() && !T2->isMemberPointerType())
1884 return QualType();
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00001885
1886 // C++0x 5.9p2
1887 // Pointer conversions and qualification conversions are performed on
1888 // pointer operands to bring them to their composite pointer type. If
1889 // one operand is a null pointer constant, the composite pointer type is
1890 // the type of the other operand.
Douglas Gregor56751b52009-09-25 04:25:58 +00001891 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00001892 if (T2->isMemberPointerType())
1893 ImpCastExprToType(E1, T2, CastExpr::CK_NullToMemberPointer);
1894 else
1895 ImpCastExprToType(E1, T2, CastExpr::CK_IntegralToPointer);
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00001896 return T2;
1897 }
Douglas Gregor56751b52009-09-25 04:25:58 +00001898 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00001899 if (T1->isMemberPointerType())
1900 ImpCastExprToType(E2, T1, CastExpr::CK_NullToMemberPointer);
1901 else
1902 ImpCastExprToType(E2, T1, CastExpr::CK_IntegralToPointer);
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00001903 return T1;
1904 }
Mike Stump11289f42009-09-09 15:08:12 +00001905
Douglas Gregorb00b10e2009-08-24 17:42:35 +00001906 // Now both have to be pointers or member pointers.
Sebastian Redl658262f2009-11-16 21:03:45 +00001907 if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
1908 (!T2->isPointerType() && !T2->isMemberPointerType()))
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00001909 return QualType();
1910
1911 // Otherwise, of one of the operands has type "pointer to cv1 void," then
1912 // the other has type "pointer to cv2 T" and the composite pointer type is
1913 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
1914 // Otherwise, the composite pointer type is a pointer type similar to the
1915 // type of one of the operands, with a cv-qualification signature that is
1916 // the union of the cv-qualification signatures of the operand types.
1917 // In practice, the first part here is redundant; it's subsumed by the second.
1918 // What we do here is, we build the two possible composite types, and try the
1919 // conversions in both directions. If only one works, or if the two composite
1920 // types are the same, we have succeeded.
John McCall8ccfcb52009-09-24 19:53:00 +00001921 // FIXME: extended qualifiers?
Sebastian Redl658262f2009-11-16 21:03:45 +00001922 typedef llvm::SmallVector<unsigned, 4> QualifierVector;
1923 QualifierVector QualifierUnion;
1924 typedef llvm::SmallVector<std::pair<const Type *, const Type *>, 4>
1925 ContainingClassVector;
1926 ContainingClassVector MemberOfClass;
1927 QualType Composite1 = Context.getCanonicalType(T1),
1928 Composite2 = Context.getCanonicalType(T2);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00001929 do {
1930 const PointerType *Ptr1, *Ptr2;
1931 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
1932 (Ptr2 = Composite2->getAs<PointerType>())) {
1933 Composite1 = Ptr1->getPointeeType();
1934 Composite2 = Ptr2->getPointeeType();
1935 QualifierUnion.push_back(
1936 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
1937 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
1938 continue;
1939 }
Mike Stump11289f42009-09-09 15:08:12 +00001940
Douglas Gregorb00b10e2009-08-24 17:42:35 +00001941 const MemberPointerType *MemPtr1, *MemPtr2;
1942 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
1943 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
1944 Composite1 = MemPtr1->getPointeeType();
1945 Composite2 = MemPtr2->getPointeeType();
1946 QualifierUnion.push_back(
1947 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
1948 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
1949 MemPtr2->getClass()));
1950 continue;
1951 }
Mike Stump11289f42009-09-09 15:08:12 +00001952
Douglas Gregorb00b10e2009-08-24 17:42:35 +00001953 // FIXME: block pointer types?
Mike Stump11289f42009-09-09 15:08:12 +00001954
Douglas Gregorb00b10e2009-08-24 17:42:35 +00001955 // Cannot unwrap any more types.
1956 break;
1957 } while (true);
Mike Stump11289f42009-09-09 15:08:12 +00001958
Douglas Gregorb00b10e2009-08-24 17:42:35 +00001959 // Rewrap the composites as pointers or member pointers with the union CVRs.
Sebastian Redl658262f2009-11-16 21:03:45 +00001960 ContainingClassVector::reverse_iterator MOC
1961 = MemberOfClass.rbegin();
1962 for (QualifierVector::reverse_iterator
1963 I = QualifierUnion.rbegin(),
1964 E = QualifierUnion.rend();
Douglas Gregorb00b10e2009-08-24 17:42:35 +00001965 I != E; (void)++I, ++MOC) {
John McCall8ccfcb52009-09-24 19:53:00 +00001966 Qualifiers Quals = Qualifiers::fromCVRMask(*I);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00001967 if (MOC->first && MOC->second) {
1968 // Rebuild member pointer type
John McCall8ccfcb52009-09-24 19:53:00 +00001969 Composite1 = Context.getMemberPointerType(
1970 Context.getQualifiedType(Composite1, Quals),
1971 MOC->first);
1972 Composite2 = Context.getMemberPointerType(
1973 Context.getQualifiedType(Composite2, Quals),
1974 MOC->second);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00001975 } else {
1976 // Rebuild pointer type
John McCall8ccfcb52009-09-24 19:53:00 +00001977 Composite1
1978 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
1979 Composite2
1980 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregorb00b10e2009-08-24 17:42:35 +00001981 }
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00001982 }
1983
Mike Stump11289f42009-09-09 15:08:12 +00001984 ImplicitConversionSequence E1ToC1 =
Anders Carlssonef4c7212009-08-27 17:24:15 +00001985 TryImplicitConversion(E1, Composite1,
1986 /*SuppressUserConversions=*/false,
1987 /*AllowExplicit=*/false,
Anders Carlsson228eea32009-08-28 15:33:32 +00001988 /*ForceRValue=*/false,
1989 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00001990 ImplicitConversionSequence E2ToC1 =
Anders Carlssonef4c7212009-08-27 17:24:15 +00001991 TryImplicitConversion(E2, Composite1,
1992 /*SuppressUserConversions=*/false,
1993 /*AllowExplicit=*/false,
Anders Carlsson228eea32009-08-28 15:33:32 +00001994 /*ForceRValue=*/false,
1995 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00001996
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00001997 ImplicitConversionSequence E1ToC2, E2ToC2;
1998 E1ToC2.ConversionKind = ImplicitConversionSequence::BadConversion;
1999 E2ToC2.ConversionKind = ImplicitConversionSequence::BadConversion;
2000 if (Context.getCanonicalType(Composite1) !=
2001 Context.getCanonicalType(Composite2)) {
Anders Carlssonef4c7212009-08-27 17:24:15 +00002002 E1ToC2 = TryImplicitConversion(E1, Composite2,
2003 /*SuppressUserConversions=*/false,
2004 /*AllowExplicit=*/false,
Anders Carlsson228eea32009-08-28 15:33:32 +00002005 /*ForceRValue=*/false,
2006 /*InOverloadResolution=*/false);
Anders Carlssonef4c7212009-08-27 17:24:15 +00002007 E2ToC2 = TryImplicitConversion(E2, Composite2,
2008 /*SuppressUserConversions=*/false,
2009 /*AllowExplicit=*/false,
Anders Carlsson228eea32009-08-28 15:33:32 +00002010 /*ForceRValue=*/false,
2011 /*InOverloadResolution=*/false);
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002012 }
2013
2014 bool ToC1Viable = E1ToC1.ConversionKind !=
2015 ImplicitConversionSequence::BadConversion
2016 && E2ToC1.ConversionKind !=
2017 ImplicitConversionSequence::BadConversion;
2018 bool ToC2Viable = E1ToC2.ConversionKind !=
2019 ImplicitConversionSequence::BadConversion
2020 && E2ToC2.ConversionKind !=
2021 ImplicitConversionSequence::BadConversion;
2022 if (ToC1Viable && !ToC2Viable) {
2023 if (!PerformImplicitConversion(E1, Composite1, E1ToC1, "converting") &&
2024 !PerformImplicitConversion(E2, Composite1, E2ToC1, "converting"))
2025 return Composite1;
2026 }
2027 if (ToC2Viable && !ToC1Viable) {
2028 if (!PerformImplicitConversion(E1, Composite2, E1ToC2, "converting") &&
2029 !PerformImplicitConversion(E2, Composite2, E2ToC2, "converting"))
2030 return Composite2;
2031 }
2032 return QualType();
2033}
Anders Carlsson85a307d2009-05-17 18:41:29 +00002034
Anders Carlsson2d4cada2009-05-30 20:36:53 +00002035Sema::OwningExprResult Sema::MaybeBindToTemporary(Expr *E) {
Anders Carlssonf86a8d12009-08-15 23:41:35 +00002036 if (!Context.getLangOptions().CPlusPlus)
2037 return Owned(E);
Mike Stump11289f42009-09-09 15:08:12 +00002038
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002039 const RecordType *RT = E->getType()->getAs<RecordType>();
Anders Carlsson2d4cada2009-05-30 20:36:53 +00002040 if (!RT)
2041 return Owned(E);
Mike Stump11289f42009-09-09 15:08:12 +00002042
Anders Carlsson2d4cada2009-05-30 20:36:53 +00002043 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2044 if (RD->hasTrivialDestructor())
2045 return Owned(E);
Mike Stump11289f42009-09-09 15:08:12 +00002046
Anders Carlssonaedb46f2009-09-14 01:30:44 +00002047 if (CallExpr *CE = dyn_cast<CallExpr>(E)) {
2048 QualType Ty = CE->getCallee()->getType();
2049 if (const PointerType *PT = Ty->getAs<PointerType>())
2050 Ty = PT->getPointeeType();
2051
John McCall9dd450b2009-09-21 23:43:11 +00002052 const FunctionType *FTy = Ty->getAs<FunctionType>();
Anders Carlssonaedb46f2009-09-14 01:30:44 +00002053 if (FTy->getResultType()->isReferenceType())
2054 return Owned(E);
2055 }
Mike Stump11289f42009-09-09 15:08:12 +00002056 CXXTemporary *Temp = CXXTemporary::Create(Context,
Anders Carlsson2d4cada2009-05-30 20:36:53 +00002057 RD->getDestructor(Context));
Anders Carlssonc78576e2009-05-30 21:21:49 +00002058 ExprTemporaries.push_back(Temp);
Fariborz Jahanian67828442009-08-03 19:13:25 +00002059 if (CXXDestructorDecl *Destructor =
2060 const_cast<CXXDestructorDecl*>(RD->getDestructor(Context)))
2061 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
Anders Carlsson2d4cada2009-05-30 20:36:53 +00002062 // FIXME: Add the temporary to the temporaries vector.
2063 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
2064}
2065
Mike Stump11289f42009-09-09 15:08:12 +00002066Expr *Sema::MaybeCreateCXXExprWithTemporaries(Expr *SubExpr,
Anders Carlssona42ab8f2009-06-16 03:37:31 +00002067 bool ShouldDestroyTemps) {
Anders Carlssonb3d05d62009-06-05 15:38:08 +00002068 assert(SubExpr && "sub expression can't be null!");
Mike Stump11289f42009-09-09 15:08:12 +00002069
Anders Carlssonb3d05d62009-06-05 15:38:08 +00002070 if (ExprTemporaries.empty())
2071 return SubExpr;
Mike Stump11289f42009-09-09 15:08:12 +00002072
Anders Carlssonb3d05d62009-06-05 15:38:08 +00002073 Expr *E = CXXExprWithTemporaries::Create(Context, SubExpr,
Mike Stump11289f42009-09-09 15:08:12 +00002074 &ExprTemporaries[0],
Anders Carlssonb3d05d62009-06-05 15:38:08 +00002075 ExprTemporaries.size(),
Anders Carlssona42ab8f2009-06-16 03:37:31 +00002076 ShouldDestroyTemps);
Anders Carlssonb3d05d62009-06-05 15:38:08 +00002077 ExprTemporaries.clear();
Mike Stump11289f42009-09-09 15:08:12 +00002078
Anders Carlssonb3d05d62009-06-05 15:38:08 +00002079 return E;
2080}
2081
Mike Stump11289f42009-09-09 15:08:12 +00002082Sema::OwningExprResult
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002083Sema::ActOnStartCXXMemberReference(Scope *S, ExprArg Base, SourceLocation OpLoc,
2084 tok::TokenKind OpKind, TypeTy *&ObjectType) {
2085 // Since this might be a postfix expression, get rid of ParenListExprs.
2086 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
Mike Stump11289f42009-09-09 15:08:12 +00002087
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002088 Expr *BaseExpr = (Expr*)Base.get();
2089 assert(BaseExpr && "no record expansion");
Mike Stump11289f42009-09-09 15:08:12 +00002090
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002091 QualType BaseType = BaseExpr->getType();
2092 if (BaseType->isDependentType()) {
Douglas Gregor41127182009-11-04 22:49:18 +00002093 // If we have a pointer to a dependent type and are using the -> operator,
2094 // the object type is the type that the pointer points to. We might still
2095 // have enough information about that type to do something useful.
2096 if (OpKind == tok::arrow)
2097 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
2098 BaseType = Ptr->getPointeeType();
2099
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002100 ObjectType = BaseType.getAsOpaquePtr();
2101 return move(Base);
2102 }
Mike Stump11289f42009-09-09 15:08:12 +00002103
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002104 // C++ [over.match.oper]p8:
Mike Stump11289f42009-09-09 15:08:12 +00002105 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002106 // returned, with the original second operand.
2107 if (OpKind == tok::arrow) {
John McCallc1538c02009-09-30 01:01:30 +00002108 // The set of types we've considered so far.
John McCallbd0465b2009-09-30 01:30:54 +00002109 llvm::SmallPtrSet<CanQualType,8> CTypes;
Fariborz Jahanianac3005c2009-09-30 17:46:20 +00002110 llvm::SmallVector<SourceLocation, 8> Locations;
John McCallbd0465b2009-09-30 01:30:54 +00002111 CTypes.insert(Context.getCanonicalType(BaseType));
John McCallc1538c02009-09-30 01:01:30 +00002112
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002113 while (BaseType->isRecordType()) {
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00002114 Base = BuildOverloadedArrowExpr(S, move(Base), OpLoc);
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002115 BaseExpr = (Expr*)Base.get();
2116 if (BaseExpr == NULL)
2117 return ExprError();
Fariborz Jahanianac3005c2009-09-30 17:46:20 +00002118 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(BaseExpr))
Anders Carlssonfbd2d492009-10-13 22:55:59 +00002119 Locations.push_back(OpCall->getDirectCallee()->getLocation());
John McCallc1538c02009-09-30 01:01:30 +00002120 BaseType = BaseExpr->getType();
2121 CanQualType CBaseType = Context.getCanonicalType(BaseType);
John McCallbd0465b2009-09-30 01:30:54 +00002122 if (!CTypes.insert(CBaseType)) {
Fariborz Jahanian10ce9582009-09-30 00:19:41 +00002123 Diag(OpLoc, diag::err_operator_arrow_circular);
Fariborz Jahanianac3005c2009-09-30 17:46:20 +00002124 for (unsigned i = 0; i < Locations.size(); i++)
2125 Diag(Locations[i], diag::note_declared_at);
Fariborz Jahanian10ce9582009-09-30 00:19:41 +00002126 return ExprError();
2127 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002128 }
2129 }
Mike Stump11289f42009-09-09 15:08:12 +00002130
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002131 if (BaseType->isPointerType())
2132 BaseType = BaseType->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00002133
2134 // We could end up with various non-record types here, such as extended
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002135 // vector types or Objective-C interfaces. Just return early and let
2136 // ActOnMemberReferenceExpr do the work.
Douglas Gregor2b6ca462009-09-03 21:38:09 +00002137 if (!BaseType->isRecordType()) {
2138 // C++ [basic.lookup.classref]p2:
2139 // [...] If the type of the object expression is of pointer to scalar
2140 // type, the unqualified-id is looked up in the context of the complete
2141 // postfix-expression.
2142 ObjectType = 0;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002143 return move(Base);
Douglas Gregor2b6ca462009-09-03 21:38:09 +00002144 }
Mike Stump11289f42009-09-09 15:08:12 +00002145
Douglas Gregor2b6ca462009-09-03 21:38:09 +00002146 // C++ [basic.lookup.classref]p2:
Mike Stump11289f42009-09-09 15:08:12 +00002147 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor2b6ca462009-09-03 21:38:09 +00002148 // unqualified-id, and the type of the object expres- sion is of a class
2149 // type C (or of pointer to a class type C), the unqualified-id is looked
2150 // up in the scope of class C. [...]
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002151 ObjectType = BaseType.getAsOpaquePtr();
Mike Stump11289f42009-09-09 15:08:12 +00002152 return move(Base);
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002153}
2154
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00002155CXXMemberCallExpr *Sema::BuildCXXMemberCallExpr(Expr *Exp,
2156 CXXMethodDecl *Method) {
2157 MemberExpr *ME =
2158 new (Context) MemberExpr(Exp, /*IsArrow=*/false, Method,
2159 SourceLocation(), Method->getType());
2160 QualType ResultType;
2161 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(Method))
2162 ResultType = Conv->getConversionType().getNonReferenceType();
2163 else
2164 ResultType = Method->getResultType().getNonReferenceType();
2165
2166 CXXMemberCallExpr *CE =
2167 new (Context) CXXMemberCallExpr(Context, ME, 0, 0,
2168 ResultType,
Douglas Gregoref986e82009-11-12 15:31:47 +00002169 Exp->getLocEnd());
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00002170 return CE;
2171}
2172
Anders Carlssone9766d52009-09-09 21:33:21 +00002173Sema::OwningExprResult Sema::BuildCXXCastArgument(SourceLocation CastLoc,
2174 QualType Ty,
2175 CastExpr::CastKind Kind,
2176 CXXMethodDecl *Method,
2177 ExprArg Arg) {
2178 Expr *From = Arg.takeAs<Expr>();
2179
2180 switch (Kind) {
2181 default: assert(0 && "Unhandled cast kind!");
2182 case CastExpr::CK_ConstructorConversion: {
Douglas Gregor5d3507d2009-09-09 23:08:42 +00002183 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
2184
2185 if (CompleteConstructorCall(cast<CXXConstructorDecl>(Method),
2186 MultiExprArg(*this, (void **)&From, 1),
2187 CastLoc, ConstructorArgs))
2188 return ExprError();
Anders Carlsson8f741bf2009-10-18 21:20:14 +00002189
2190 OwningExprResult Result =
2191 BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
2192 move_arg(ConstructorArgs));
2193 if (Result.isInvalid())
2194 return ExprError();
2195
2196 return MaybeBindToTemporary(Result.takeAs<Expr>());
Anders Carlssone9766d52009-09-09 21:33:21 +00002197 }
2198
2199 case CastExpr::CK_UserDefinedConversion: {
Anders Carlsson6b2737d2009-09-15 07:42:44 +00002200 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
2201
2202 // Cast to base if needed.
2203 if (PerformObjectArgumentInitialization(From, Method))
2204 return ExprError();
2205
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00002206 // Create an implicit call expr that calls it.
2207 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(From, Method);
Anders Carlsson8f741bf2009-10-18 21:20:14 +00002208 return MaybeBindToTemporary(CE);
Anders Carlssone9766d52009-09-09 21:33:21 +00002209 }
Anders Carlssone9766d52009-09-09 21:33:21 +00002210 }
2211}
2212
Anders Carlsson85a307d2009-05-17 18:41:29 +00002213Sema::OwningExprResult Sema::ActOnFinishFullExpr(ExprArg Arg) {
2214 Expr *FullExpr = Arg.takeAs<Expr>();
Anders Carlssonb3d05d62009-06-05 15:38:08 +00002215 if (FullExpr)
Mike Stump11289f42009-09-09 15:08:12 +00002216 FullExpr = MaybeCreateCXXExprWithTemporaries(FullExpr,
Anders Carlssona42ab8f2009-06-16 03:37:31 +00002217 /*ShouldDestroyTemps=*/true);
Anders Carlsson85a307d2009-05-17 18:41:29 +00002218
Anders Carlsson7e3f0e42009-08-25 23:46:41 +00002219
Anders Carlsson85a307d2009-05-17 18:41:29 +00002220 return Owned(FullExpr);
2221}
Douglas Gregor6493d9c2009-10-22 07:08:30 +00002222
2223/// \brief Determine whether a reference to the given declaration in the
2224/// current context is an implicit member access
2225/// (C++ [class.mfct.non-static]p2).
2226///
2227/// FIXME: Should Objective-C also use this approach?
2228///
2229/// \param SS if non-NULL, the C++ nested-name-specifier that precedes the
2230/// name of the declaration referenced.
2231///
2232/// \param D the declaration being referenced from the current scope.
2233///
2234/// \param NameLoc the location of the name in the source.
2235///
2236/// \param ThisType if the reference to this declaration is an implicit member
2237/// access, will be set to the type of the "this" pointer to be used when
2238/// building that implicit member access.
2239///
2240/// \param MemberType if the reference to this declaration is an implicit
2241/// member access, will be set to the type of the member being referenced
2242/// (for use at the type of the resulting member access expression).
2243///
2244/// \returns true if this is an implicit member reference (in which case
2245/// \p ThisType and \p MemberType will be set), or false if it is not an
2246/// implicit member reference.
2247bool Sema::isImplicitMemberReference(const CXXScopeSpec *SS, NamedDecl *D,
2248 SourceLocation NameLoc, QualType &ThisType,
2249 QualType &MemberType) {
2250 // If this isn't a C++ method, then it isn't an implicit member reference.
2251 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext);
2252 if (!MD || MD->isStatic())
2253 return false;
2254
2255 // C++ [class.mfct.nonstatic]p2:
2256 // [...] if name lookup (3.4.1) resolves the name in the
2257 // id-expression to a nonstatic nontype member of class X or of
2258 // a base class of X, the id-expression is transformed into a
2259 // class member access expression (5.2.5) using (*this) (9.3.2)
2260 // as the postfix-expression to the left of the '.' operator.
2261 DeclContext *Ctx = 0;
2262 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
2263 Ctx = FD->getDeclContext();
2264 MemberType = FD->getType();
2265
2266 if (const ReferenceType *RefType = MemberType->getAs<ReferenceType>())
2267 MemberType = RefType->getPointeeType();
2268 else if (!FD->isMutable())
2269 MemberType
2270 = Context.getQualifiedType(MemberType,
2271 Qualifiers::fromCVRMask(MD->getTypeQualifiers()));
2272 } else {
2273 for (OverloadIterator Ovl(D), OvlEnd; Ovl != OvlEnd; ++Ovl) {
2274 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*Ovl);
2275 FunctionTemplateDecl *FunTmpl = 0;
2276 if (!Method && (FunTmpl = dyn_cast<FunctionTemplateDecl>(*Ovl)))
2277 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
2278
Douglas Gregord3319842009-10-24 04:59:53 +00002279 // FIXME: Do we have to know if there are explicit template arguments?
Douglas Gregor6493d9c2009-10-22 07:08:30 +00002280 if (Method && !Method->isStatic()) {
2281 Ctx = Method->getParent();
2282 if (isa<CXXMethodDecl>(D) && !FunTmpl)
2283 MemberType = Method->getType();
2284 else
2285 MemberType = Context.OverloadTy;
2286 break;
2287 }
2288 }
2289 }
2290
2291 if (!Ctx || !Ctx->isRecord())
2292 return false;
2293
2294 // Determine whether the declaration(s) we found are actually in a base
2295 // class. If not, this isn't an implicit member reference.
2296 ThisType = MD->getThisType(Context);
Douglas Gregor5897e092009-11-01 17:08:18 +00002297
2298 // If the type of "this" is dependent, we can't tell if the member is in a
2299 // base class or not, so treat this as a dependent implicit member reference.
2300 if (ThisType->isDependentType())
2301 return true;
2302
Douglas Gregor6493d9c2009-10-22 07:08:30 +00002303 QualType CtxType = Context.getTypeDeclType(cast<CXXRecordDecl>(Ctx));
2304 QualType ClassType
2305 = Context.getTypeDeclType(cast<CXXRecordDecl>(MD->getParent()));
2306 return Context.hasSameType(CtxType, ClassType) ||
2307 IsDerivedFrom(ClassType, CtxType);
2308}
2309