blob: 3e07f3495ee7d2e380ab7f9f8726230ec4c908e0 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Steve Naroff210679c2007-08-25 14:02:58 +000015#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000016#include "clang/AST/CXXInheritance.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000017#include "clang/AST/ExprCXX.h"
18#include "clang/Basic/PartialDiagnostic.h"
Sebastian Redlb5a57a62008-12-03 20:26:15 +000019#include "clang/Basic/TargetInfo.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000020#include "clang/Lex/Preprocessor.h"
21#include "clang/Parse/DeclSpec.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000022#include "llvm/ADT/STLExtras.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000023using namespace clang;
24
Sebastian Redlc42e1182008-11-11 11:37:55 +000025/// ActOnCXXTypeidOfType - Parse typeid( type-id ).
Sebastian Redlf53597f2009-03-15 17:47:39 +000026Action::OwningExprResult
Sebastian Redlc42e1182008-11-11 11:37:55 +000027Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
28 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +000029 if (!StdNamespace)
Sebastian Redlf53597f2009-03-15 17:47:39 +000030 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +000031
32 if (isType)
33 // FIXME: Preserve type source info.
34 TyOrExpr = GetTypeFromParser(TyOrExpr).getAsOpaquePtr();
35
Chris Lattner572af492008-11-20 05:51:55 +000036 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
John McCallf36e02d2009-10-09 21:13:30 +000037 LookupResult R;
38 LookupQualifiedName(R, StdNamespace, TypeInfoII, LookupTagName);
39 Decl *TypeInfoDecl = R.getAsSingleDecl(Context);
Sebastian Redlc42e1182008-11-11 11:37:55 +000040 RecordDecl *TypeInfoRecordDecl = dyn_cast_or_null<RecordDecl>(TypeInfoDecl);
Chris Lattner572af492008-11-20 05:51:55 +000041 if (!TypeInfoRecordDecl)
Sebastian Redlf53597f2009-03-15 17:47:39 +000042 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Sebastian Redlc42e1182008-11-11 11:37:55 +000043
44 QualType TypeInfoType = Context.getTypeDeclType(TypeInfoRecordDecl);
45
Douglas Gregorac7610d2009-06-22 20:57:11 +000046 if (!isType) {
47 // C++0x [expr.typeid]p3:
Mike Stump1eb44332009-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 Gregorac7610d2009-06-22 20:57:11 +000050 // operand.
Mike Stump1eb44332009-09-09 15:08:12 +000051
Douglas Gregorac7610d2009-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 Kremenek6217b802009-07-29 21:53:49 +000058 if (const RecordType *RecordT = T->getAs<RecordType>()) {
Douglas Gregorac7610d2009-06-22 20:57:11 +000059 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
60 if (RecordD->isPolymorphic())
61 isUnevaluatedOperand = false;
62 }
63 }
Mike Stump1eb44332009-09-09 15:08:12 +000064
Douglas Gregorac7610d2009-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 Stump1eb44332009-09-09 15:08:12 +000070
Sebastian Redlf53597f2009-03-15 17:47:39 +000071 return Owned(new (Context) CXXTypeidExpr(isType, TyOrExpr,
72 TypeInfoType.withConst(),
73 SourceRange(OpLoc, RParenLoc)));
Sebastian Redlc42e1182008-11-11 11:37:55 +000074}
75
Steve Naroff1b273c42007-09-16 14:56:35 +000076/// ActOnCXXBoolLiteral - Parse {true,false} literals.
Sebastian Redlf53597f2009-03-15 17:47:39 +000077Action::OwningExprResult
Steve Naroff1b273c42007-09-16 14:56:35 +000078Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor2f639b92008-10-24 15:36:09 +000079 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Reid Spencer5f016e22007-07-11 17:01:13 +000080 "Unknown C++ Boolean value!");
Sebastian Redlf53597f2009-03-15 17:47:39 +000081 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
82 Context.BoolTy, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +000083}
Chris Lattner50dd2892008-02-26 00:51:44 +000084
Sebastian Redl6e8ed162009-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 Lattner50dd2892008-02-26 00:51:44 +000091/// ActOnCXXThrow - Parse throw expressions.
Sebastian Redlf53597f2009-03-15 17:47:39 +000092Action::OwningExprResult
93Sema::ActOnCXXThrow(SourceLocation OpLoc, ExprArg E) {
Sebastian Redl972041f2009-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 Kremenek6217b802009-07-29 21:53:49 +0000111 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000112 Ty = Ptr->getPointeeType();
113 isPointer = 1;
114 }
115 if (!isPointer || !Ty->isVoidType()) {
116 if (RequireCompleteType(ThrowLoc, Ty,
Anders Carlssond497ba72009-08-26 22:59:12 +0000117 PDiag(isPointer ? diag::err_throw_incomplete_ptr
118 : diag::err_throw_incomplete)
119 << E->getSourceRange()))
Sebastian Redl972041f2009-04-27 20:27:31 +0000120 return true;
121 }
122
123 // FIXME: Construct a temporary here.
124 return false;
Chris Lattner50dd2892008-02-26 00:51:44 +0000125}
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000126
Sebastian Redlf53597f2009-03-15 17:47:39 +0000127Action::OwningExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
Argyrios Kyrtzidis07952322008-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 Redlf53597f2009-03-15 17:47:39 +0000132 if (!isa<FunctionDecl>(CurContext))
133 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000134
135 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext))
136 if (MD->isInstance())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000137 return Owned(new (Context) CXXThisExpr(ThisLoc,
138 MD->getThisType(Context)));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000139
Sebastian Redlf53597f2009-03-15 17:47:39 +0000140 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000141}
Argyrios Kyrtzidis987a14b2008-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 Redlf53597f2009-03-15 17:47:39 +0000147Action::OwningExprResult
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000148Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep,
149 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000150 MultiExprArg exprs,
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000151 SourceLocation *CommaLocs,
152 SourceLocation RParenLoc) {
153 assert(TypeRep && "Missing type!");
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000154 // FIXME: Preserve type source info.
155 QualType Ty = GetTypeFromParser(TypeRep);
Sebastian Redlf53597f2009-03-15 17:47:39 +0000156 unsigned NumExprs = exprs.size();
157 Expr **Exprs = (Expr**)exprs.get();
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000158 SourceLocation TyBeginLoc = TypeRange.getBegin();
159 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
160
Sebastian Redlf53597f2009-03-15 17:47:39 +0000161 if (Ty->isDependentType() ||
Douglas Gregorba498172009-03-13 21:01:28 +0000162 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
Sebastian Redlf53597f2009-03-15 17:47:39 +0000163 exprs.release();
Mike Stump1eb44332009-09-09 15:08:12 +0000164
165 return Owned(CXXUnresolvedConstructExpr::Create(Context,
166 TypeRange.getBegin(), Ty,
Douglas Gregord81e6ca2009-05-20 18:46:25 +0000167 LParenLoc,
168 Exprs, NumExprs,
169 RParenLoc));
Douglas Gregorba498172009-03-13 21:01:28 +0000170 }
171
Anders Carlssonbb60a502009-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 Jahanianf071e9b2009-10-23 21:01:39 +0000180
Anders Carlssonbb60a502009-08-27 03:53:50 +0000181 if (RequireNonAbstractType(TyBeginLoc, Ty,
182 diag::err_allocation_of_abstract_type))
183 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000184
185
Douglas Gregor506ae412009-01-16 18:33:17 +0000186 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-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 Carlssoncdb61972009-08-07 22:21:05 +0000192 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Anders Carlsson0aebc812009-09-09 21:33:21 +0000193 CXXMethodDecl *Method = 0;
194 if (CheckCastTypes(TypeRange, Ty, Exprs[0], Kind, Method,
195 /*FunctionalStyle=*/true))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000196 return ExprError();
Anders Carlsson0aebc812009-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 Jahanian4fc7ab32009-08-28 15:11:24 +0000207 }
Anders Carlsson0aebc812009-09-09 21:33:21 +0000208
209 return Owned(new (Context) CXXFunctionalCastExpr(Ty.getNonReferenceType(),
210 Ty, TyBeginLoc, Kind,
211 Exprs[0], RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000212 }
213
Ted Kremenek6217b802009-07-29 21:53:49 +0000214 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Douglas Gregor506ae412009-01-16 18:33:17 +0000215 CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
Sebastian Redlf53597f2009-03-15 17:47:39 +0000216
Mike Stump1eb44332009-09-09 15:08:12 +0000217 if (NumExprs > 1 || !Record->hasTrivialConstructor() ||
Anders Carlssone7624a72009-08-27 05:08:22 +0000218 !Record->hasTrivialDestructor()) {
Douglas Gregor39da0b82009-09-09 23:08:42 +0000219 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
220
Douglas Gregor506ae412009-01-16 18:33:17 +0000221 CXXConstructorDecl *Constructor
Douglas Gregor39da0b82009-09-09 23:08:42 +0000222 = PerformInitializationByConstructor(Ty, move(exprs),
Douglas Gregor506ae412009-01-16 18:33:17 +0000223 TypeRange.getBegin(),
224 SourceRange(TypeRange.getBegin(),
225 RParenLoc),
226 DeclarationName(),
Douglas Gregor39da0b82009-09-09 23:08:42 +0000227 IK_Direct,
228 ConstructorArgs);
Douglas Gregor506ae412009-01-16 18:33:17 +0000229
Sebastian Redlf53597f2009-03-15 17:47:39 +0000230 if (!Constructor)
231 return ExprError();
232
Mike Stump1eb44332009-09-09 15:08:12 +0000233 OwningExprResult Result =
234 BuildCXXTemporaryObjectExpr(Constructor, Ty, TyBeginLoc,
Douglas Gregor39da0b82009-09-09 23:08:42 +0000235 move_arg(ConstructorArgs), RParenLoc);
Anders Carlssone7624a72009-08-27 05:08:22 +0000236 if (Result.isInvalid())
237 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000238
Anders Carlssone7624a72009-08-27 05:08:22 +0000239 return MaybeBindToTemporary(Result.takeAs<Expr>());
Douglas Gregor506ae412009-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 Kyrtzidis987a14b2008-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 Redlf53597f2009-03-15 17:47:39 +0000251 return ExprError(Diag(CommaLocs[0],
252 diag::err_builtin_func_cast_more_than_one_arg)
253 << FullRange);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000254
255 assert(NumExprs == 0 && "Expected 0 expressions");
Douglas Gregor506ae412009-01-16 18:33:17 +0000256 // C++ [expr.type.conv]p2:
Argyrios Kyrtzidis987a14b2008-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 Redlf53597f2009-03-15 17:47:39 +0000261 exprs.release();
262 return Owned(new (Context) CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000263}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000264
265
Sebastian Redl4c5d3202008-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 Redlf53597f2009-03-15 17:47:39 +0000271Action::OwningExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000272Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000273 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000274 SourceLocation PlacementRParen, bool ParenTypeId,
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000275 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000276 MultiExprArg ConstructorArgs,
Mike Stump1eb44332009-09-09 15:08:12 +0000277 SourceLocation ConstructorRParen) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000278 Expr *ArraySize = 0;
Sebastian Redlcee63fb2008-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 Redlf53597f2009-03-15 17:47:39 +0000284 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
285 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000286 if (!Chunk.Arr.NumElts)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000287 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
288 << D.getSourceRange());
Sebastian Redl8ce35b02009-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 Redlcee63fb2008-12-02 14:43:59 +0000301 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000302 D.DropFirstTypeObject();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000303 }
304
Douglas Gregor043cad22009-09-11 00:18:58 +0000305 // Every dimension shall be of constant size.
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000306 if (ArraySize) {
307 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor043cad22009-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 Redl8ce35b02009-10-25 21:45:37 +0000322
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000323 //FIXME: Store DeclaratorInfo in CXXNew expression.
324 DeclaratorInfo *DInfo = 0;
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000325 QualType AllocType = GetTypeForDeclarator(D, /*Scope=*/0, &DInfo);
Chris Lattnereaaebc72009-04-25 08:06:05 +0000326 if (D.isInvalidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000327 return ExprError();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000328
Mike Stump1eb44332009-09-09 15:08:12 +0000329 return BuildCXXNew(StartLoc, UseGlobal,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000330 PlacementLParen,
Mike Stump1eb44332009-09-09 15:08:12 +0000331 move(PlacementArgs),
Douglas Gregor3433cf72009-05-21 00:00:09 +0000332 PlacementRParen,
333 ParenTypeId,
Mike Stump1eb44332009-09-09 15:08:12 +0000334 AllocType,
Douglas Gregor3433cf72009-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 Stump1eb44332009-09-09 15:08:12 +0000343Sema::OwningExprResult
Douglas Gregor3433cf72009-05-21 00:00:09 +0000344Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
345 SourceLocation PlacementLParen,
346 MultiExprArg PlacementArgs,
347 SourceLocation PlacementRParen,
Mike Stump1eb44332009-09-09 15:08:12 +0000348 bool ParenTypeId,
Douglas Gregor3433cf72009-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 Redlf53597f2009-03-15 17:47:39 +0000357 return ExprError();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000358
Douglas Gregor3433cf72009-05-21 00:00:09 +0000359 QualType ResultType = Context.getPointerType(AllocType);
Sebastian Redl4c5d3202008-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 Redlcee63fb2008-12-02 14:43:59 +0000363
Sebastian Redl4c5d3202008-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 Gregor3433cf72009-05-21 00:00:09 +0000366 Expr *ArraySize = (Expr *)ArraySizeE.get();
Sebastian Redl28507842009-02-26 14:39:58 +0000367 if (ArraySize && !ArraySize->isTypeDependent()) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000368 QualType SizeType = ArraySize->getType();
369 if (!SizeType->isIntegralType() && !SizeType->isEnumeralType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000370 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
371 diag::err_array_size_not_integral)
372 << SizeType << ArraySize->getSourceRange());
Sebastian Redlcee63fb2008-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 Redl28507842009-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 Carlssonac18b2e2009-09-23 00:37:25 +0000380 llvm::APInt::getNullValue(Value.getBitWidth()),
381 Value.isUnsigned()))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000382 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
383 diag::err_typecheck_negative_array_size)
384 << ArraySize->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +0000385 }
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000386 }
Anders Carlssonac18b2e2009-09-23 00:37:25 +0000387
Eli Friedman73c39ab2009-10-20 08:27:19 +0000388 ImpCastExprToType(ArraySize, Context.getSizeType(),
389 CastExpr::CK_IntegralCast);
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000390 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000391
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000392 FunctionDecl *OperatorNew = 0;
393 FunctionDecl *OperatorDelete = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000394 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
395 unsigned NumPlaceArgs = PlacementArgs.size();
Douglas Gregor089407b2009-10-17 21:40:42 +0000396
Sebastian Redl28507842009-02-26 14:39:58 +0000397 if (!AllocType->isDependentType() &&
398 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
399 FindAllocationFunctions(StartLoc,
Sebastian Redl00e68e22009-02-09 18:24:27 +0000400 SourceRange(PlacementLParen, PlacementRParen),
401 UseGlobal, AllocType, ArraySize, PlaceArgs,
402 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000403 return ExprError();
Sebastian Redl4c5d3202008-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 Redlf53597f2009-03-15 17:47:39 +0000424 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
Sebastian Redl4f149632009-05-07 16:14:23 +0000425 const RecordType *RT;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000426 unsigned NumConsArgs = ConstructorArgs.size();
Eli Friedmana8ce9ec2009-11-08 22:15:39 +0000427 ASTOwningVector<&ActionBase::DeleteExpr> ConvertedConstructorArgs(*this);
428
Douglas Gregor089407b2009-10-17 21:40:42 +0000429 if (AllocType->isDependentType() ||
430 Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) {
Sebastian Redl28507842009-02-26 14:39:58 +0000431 // Skip all the checks.
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000432 } else if ((RT = AllocType->getAs<RecordType>()) &&
433 !AllocType->isAggregateType()) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000434 Constructor = PerformInitializationByConstructor(
Douglas Gregor39da0b82009-09-09 23:08:42 +0000435 AllocType, move(ConstructorArgs),
Douglas Gregor3433cf72009-05-21 00:00:09 +0000436 TypeLoc,
437 SourceRange(TypeLoc, ConstructorRParen),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000438 RT->getDecl()->getDeclName(),
Douglas Gregor39da0b82009-09-09 23:08:42 +0000439 NumConsArgs != 0 ? IK_Direct : IK_Default,
440 ConvertedConstructorArgs);
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000441 if (!Constructor)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000442 return ExprError();
Douglas Gregor39da0b82009-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 Redl4c5d3202008-11-21 19:14:01 +0000448 } else {
449 if (!Init) {
450 // FIXME: Check that no subpart is const.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000451 if (AllocType.isConstQualified())
452 return ExprError(Diag(StartLoc, diag::err_new_uninitialized_const)
Douglas Gregor3433cf72009-05-21 00:00:09 +0000453 << TypeRange);
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000454 } else if (NumConsArgs == 0) {
Fariborz Jahanian6f269202009-11-03 20:38:53 +0000455 // Object is value-initialized. Do nothing.
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000456 } else if (NumConsArgs == 1) {
457 // Object is direct-initialized.
Sebastian Redl4f149632009-05-07 16:14:23 +0000458 // FIXME: What DeclarationName do we pass in here?
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000459 if (CheckInitializerTypes(ConsArgs[0], AllocType, StartLoc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000460 DeclarationName() /*AllocType.getAsString()*/,
461 /*DirectInit=*/true))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000462 return ExprError();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000463 } else {
Sebastian Redlf53597f2009-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 Redl4c5d3202008-11-21 19:14:01 +0000467 }
468 }
469
470 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
Douglas Gregor089407b2009-10-17 21:40:42 +0000471
Sebastian Redlf53597f2009-03-15 17:47:39 +0000472 PlacementArgs.release();
473 ConstructorArgs.release();
Douglas Gregor3433cf72009-05-21 00:00:09 +0000474 ArraySizeE.release();
Sebastian Redlf53597f2009-03-15 17:47:39 +0000475 return Owned(new (Context) CXXNewExpr(UseGlobal, OperatorNew, PlaceArgs,
Ted Kremenek8189cde2009-02-07 01:47:29 +0000476 NumPlaceArgs, ParenTypeId, ArraySize, Constructor, Init,
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000477 ConsArgs, NumConsArgs, OperatorDelete, ResultType,
Mike Stump1eb44332009-09-09 15:08:12 +0000478 StartLoc, Init ? ConstructorRParen : SourceLocation()));
Sebastian Redl4c5d3202008-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 Gregor3433cf72009-05-21 00:00:09 +0000484bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +0000485 SourceRange R) {
Sebastian Redl4c5d3202008-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 Gregore7450f52009-03-24 19:52:54 +0000488 if (AllocType->isFunctionType())
Douglas Gregor3433cf72009-05-21 00:00:09 +0000489 return Diag(Loc, diag::err_bad_new_type)
490 << AllocType << 0 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +0000491 else if (AllocType->isReferenceType())
Douglas Gregor3433cf72009-05-21 00:00:09 +0000492 return Diag(Loc, diag::err_bad_new_type)
493 << AllocType << 1 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +0000494 else if (!AllocType->isDependentType() &&
Douglas Gregor3433cf72009-05-21 00:00:09 +0000495 RequireCompleteType(Loc, AllocType,
Anders Carlssonb7906612009-08-26 23:45:07 +0000496 PDiag(diag::err_new_incomplete_type)
497 << R))
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000498 return true;
Douglas Gregor3433cf72009-05-21 00:00:09 +0000499 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregore7450f52009-03-24 19:52:54 +0000500 diag::err_allocation_of_abstract_type))
501 return true;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000502
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000503 return false;
504}
505
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000506/// FindAllocationFunctions - Finds the overloads of operator new and delete
507/// that are appropriate for the allocation.
Sebastian Redl00e68e22009-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 Redlb5a57a62008-12-03 20:26:15 +0000512 FunctionDecl *&OperatorNew,
Mike Stump1eb44332009-09-09 15:08:12 +0000513 FunctionDecl *&OperatorDelete) {
Sebastian Redlb5a57a62008-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 Carlssond67c4c32009-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 Redlb5a57a62008-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 Stump1eb44332009-09-09 15:08:12 +0000538 CXXRecordDecl *Record
Ted Kremenek6217b802009-07-29 21:53:49 +0000539 = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl());
Sebastian Redl7f662392008-12-04 22:20:51 +0000540 // FIXME: We fail to find inherited overloads.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000541 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000542 AllocArgs.size(), Record, /*AllowMissing=*/true,
543 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000544 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000545 }
546 if (!OperatorNew) {
547 // Didn't find a member overload. Look for a global one.
548 DeclareGlobalNewDelete();
Sebastian Redl7f662392008-12-04 22:20:51 +0000549 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl00e68e22009-02-09 18:24:27 +0000550 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000551 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
552 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000553 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000554 }
555
Anders Carlssond9583892009-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 Stump1eb44332009-09-09 15:08:12 +0000560
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000561 return false;
562}
563
Sebastian Redl7f662392008-12-04 22:20:51 +0000564/// FindAllocationOverload - Find an fitting overload for the allocation
565/// function in the specified scope.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000566bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
567 DeclarationName Name, Expr** Args,
568 unsigned NumArgs, DeclContext *Ctx,
Mike Stump1eb44332009-09-09 15:08:12 +0000569 bool AllowMissing, FunctionDecl *&Operator) {
John McCallf36e02d2009-10-09 21:13:30 +0000570 LookupResult R;
571 LookupQualifiedName(R, Ctx, Name, LookupOrdinaryName);
572 if (R.empty()) {
Sebastian Redl7f662392008-12-04 22:20:51 +0000573 if (AllowMissing)
574 return false;
Sebastian Redl7f662392008-12-04 22:20:51 +0000575 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +0000576 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +0000577 }
578
John McCallf36e02d2009-10-09 21:13:30 +0000579 // FIXME: handle ambiguity
580
Sebastian Redl7f662392008-12-04 22:20:51 +0000581 OverloadCandidateSet Candidates;
Douglas Gregor5d64e5b2009-09-30 00:03:47 +0000582 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
583 Alloc != AllocEnd; ++Alloc) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000584 // Even member operator new/delete are implicitly treated as
585 // static, so don't use AddMemberCandidate.
Douglas Gregor90916562009-09-29 18:16:17 +0000586 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>(*Alloc)) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000587 AddOverloadCandidate(Fn, Args, NumArgs, Candidates,
588 /*SuppressUserConversions=*/false);
Douglas Gregor90916562009-09-29 18:16:17 +0000589 continue;
590 }
591
592 // FIXME: Handle function templates
Sebastian Redl7f662392008-12-04 22:20:51 +0000593 }
594
595 // Do the resolution.
596 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +0000597 switch(BestViableFunction(Candidates, StartLoc, Best)) {
Sebastian Redl7f662392008-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 Gregor90916562009-09-29 18:16:17 +0000604 for (unsigned i = 0; i < NumArgs; ++i) {
Sebastian Redl7f662392008-12-04 22:20:51 +0000605 // FIXME: Passing word to diagnostic.
Anders Carlssonfc27d262009-05-31 19:49:47 +0000606 if (PerformCopyInitialization(Args[i],
Sebastian Redl7f662392008-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 Redl7f662392008-12-04 22:20:51 +0000616 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +0000617 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +0000618 PrintOverloadCandidates(Candidates, /*OnlyViable=*/false);
619 return true;
620
621 case OR_Ambiguous:
Sebastian Redl7f662392008-12-04 22:20:51 +0000622 Diag(StartLoc, diag::err_ovl_ambiguous_call)
Sebastian Redl00e68e22009-02-09 18:24:27 +0000623 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +0000624 PrintOverloadCandidates(Candidates, /*OnlyViable=*/true);
625 return true;
Douglas Gregor48f3bb92009-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 Redl7f662392008-12-04 22:20:51 +0000633 }
634 assert(false && "Unreachable, bad result from BestViableFunction");
635 return true;
636}
637
638
Sebastian Redlb5a57a62008-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 Stump1eb44332009-09-09 15:08:12 +0000649void Sema::DeclareGlobalNewDelete() {
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000650 if (GlobalNewDeleteDeclared)
651 return;
Douglas Gregor7adb10f2009-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 Redlb5a57a62008-12-03 20:26:15 +0000690 GlobalNewDeleteDeclared = true;
691
692 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
693 QualType SizeT = Context.getSizeType();
694
Sebastian Redlb5a57a62008-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 Stump1eb44332009-09-09 15:08:12 +0000712 QualType Return, QualType Argument) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000713 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
714
715 // Check if this function is already declared.
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000716 {
Douglas Gregor5cc37092008-12-23 22:05:29 +0000717 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000718 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor6ed40e32008-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 Kremenek8189cde2009-02-07 01:47:29 +0000723 Context.getCanonicalType(Func->getParamDecl(0)->getType())==Argument)
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000724 return;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000725 }
726 }
727
Douglas Gregor7adb10f2009-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 Redlb5a57a62008-12-03 20:26:15 +0000741 FunctionDecl *Alloc =
742 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +0000743 FnType, /*DInfo=*/0, FunctionDecl::None, false, true);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000744 Alloc->setImplicit();
745 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000746 0, Argument, /*DInfo=*/0,
747 VarDecl::None, 0);
Ted Kremenekfc767612009-01-14 00:42:25 +0000748 Alloc->setParams(Context, &Param, 1);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000749
Douglas Gregor6ed40e32008-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 Kyrtzidis17945a02009-06-30 02:36:12 +0000753 ((DeclContext *)TUScope->getEntity())->addDecl(Alloc);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000754}
755
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000756/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
757/// @code ::delete ptr; @endcode
758/// or
759/// @code delete [] ptr; @endcode
Sebastian Redlf53597f2009-03-15 17:47:39 +0000760Action::OwningExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000761Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
Mike Stump1eb44332009-09-09 15:08:12 +0000762 bool ArrayForm, ExprArg Operand) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000763 // C++ [expr.delete]p1:
764 // The operand shall have a pointer type, or a class type having a single
765 // conversion function to a pointer type. The result has type void.
766 //
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000767 // DR599 amends "pointer type" to "pointer to object type" in both cases.
768
Anders Carlssond67c4c32009-08-16 20:29:29 +0000769 FunctionDecl *OperatorDelete = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000770
Sebastian Redlf53597f2009-03-15 17:47:39 +0000771 Expr *Ex = (Expr *)Operand.get();
Sebastian Redl28507842009-02-26 14:39:58 +0000772 if (!Ex->isTypeDependent()) {
773 QualType Type = Ex->getType();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000774
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000775 if (const RecordType *Record = Type->getAs<RecordType>()) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000776 llvm::SmallVector<CXXConversionDecl *, 4> ObjectPtrConversions;
Fariborz Jahanian53462782009-09-11 21:44:33 +0000777 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
778 OverloadedFunctionDecl *Conversions =
Fariborz Jahanian62509212009-09-12 18:26:03 +0000779 RD->getVisibleConversionFunctions();
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000780
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000781 for (OverloadedFunctionDecl::function_iterator
782 Func = Conversions->function_begin(),
783 FuncEnd = Conversions->function_end();
784 Func != FuncEnd; ++Func) {
785 // Skip over templated conversion functions; they aren't considered.
786 if (isa<FunctionTemplateDecl>(*Func))
787 continue;
788
789 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
790
791 QualType ConvType = Conv->getConversionType().getNonReferenceType();
792 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
793 if (ConvPtrType->getPointeeType()->isObjectType())
Fariborz Jahanian8b915e72009-09-15 22:15:23 +0000794 ObjectPtrConversions.push_back(Conv);
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000795 }
Fariborz Jahanian8b915e72009-09-15 22:15:23 +0000796 if (ObjectPtrConversions.size() == 1) {
797 // We have a single conversion to a pointer-to-object type. Perform
798 // that conversion.
799 Operand.release();
800 if (!PerformImplicitConversion(Ex,
801 ObjectPtrConversions.front()->getConversionType(),
802 "converting")) {
803 Operand = Owned(Ex);
804 Type = Ex->getType();
805 }
806 }
807 else if (ObjectPtrConversions.size() > 1) {
808 Diag(StartLoc, diag::err_ambiguous_delete_operand)
809 << Type << Ex->getSourceRange();
810 for (unsigned i= 0; i < ObjectPtrConversions.size(); i++) {
811 CXXConversionDecl *Conv = ObjectPtrConversions[i];
812 Diag(Conv->getLocation(), diag::err_ovl_candidate);
813 }
814 return ExprError();
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000815 }
Sebastian Redl28507842009-02-26 14:39:58 +0000816 }
817
Sebastian Redlf53597f2009-03-15 17:47:39 +0000818 if (!Type->isPointerType())
819 return ExprError(Diag(StartLoc, diag::err_delete_operand)
820 << Type << Ex->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +0000821
Ted Kremenek6217b802009-07-29 21:53:49 +0000822 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Douglas Gregor8dcb29d2009-03-24 20:13:58 +0000823 if (Pointee->isFunctionType() || Pointee->isVoidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000824 return ExprError(Diag(StartLoc, diag::err_delete_operand)
825 << Type << Ex->getSourceRange());
Douglas Gregor8dcb29d2009-03-24 20:13:58 +0000826 else if (!Pointee->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +0000827 RequireCompleteType(StartLoc, Pointee,
Anders Carlssonb7906612009-08-26 23:45:07 +0000828 PDiag(diag::warn_delete_incomplete)
829 << Ex->getSourceRange()))
Douglas Gregor8dcb29d2009-03-24 20:13:58 +0000830 return ExprError();
Sebastian Redl28507842009-02-26 14:39:58 +0000831
Douglas Gregor1070c9f2009-09-29 21:38:53 +0000832 // C++ [expr.delete]p2:
833 // [Note: a pointer to a const type can be the operand of a
834 // delete-expression; it is not necessary to cast away the constness
835 // (5.2.11) of the pointer expression before it is used as the operand
836 // of the delete-expression. ]
837 ImpCastExprToType(Ex, Context.getPointerType(Context.VoidTy),
838 CastExpr::CK_NoOp);
839
840 // Update the operand.
841 Operand.take();
842 Operand = ExprArg(*this, Ex);
843
Anders Carlssond67c4c32009-08-16 20:29:29 +0000844 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
845 ArrayForm ? OO_Array_Delete : OO_Delete);
846
847 if (Pointee->isRecordType() && !UseGlobal) {
Mike Stump1eb44332009-09-09 15:08:12 +0000848 CXXRecordDecl *Record
Anders Carlssond67c4c32009-08-16 20:29:29 +0000849 = cast<CXXRecordDecl>(Pointee->getAs<RecordType>()->getDecl());
Douglas Gregor90916562009-09-29 18:16:17 +0000850
851 // Try to find operator delete/operator delete[] in class scope.
John McCallf36e02d2009-10-09 21:13:30 +0000852 LookupResult Found;
853 LookupQualifiedName(Found, Record, DeleteName, LookupOrdinaryName);
Anders Carlsson0ba63ea2009-11-14 03:17:38 +0000854
855 if (Found.isAmbiguous()) {
856 DiagnoseAmbiguousLookup(Found, DeleteName, StartLoc);
857 return ExprError();
858 }
859
Douglas Gregor90916562009-09-29 18:16:17 +0000860 // FIXME: Diagnose ambiguity properly
Douglas Gregor90916562009-09-29 18:16:17 +0000861 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
862 F != FEnd; ++F) {
863 if (CXXMethodDecl *Delete = dyn_cast<CXXMethodDecl>(*F))
864 if (Delete->isUsualDeallocationFunction()) {
865 OperatorDelete = Delete;
866 break;
867 }
868 }
869
Fariborz Jahanian34374e62009-09-03 23:18:17 +0000870 if (!Record->hasTrivialDestructor())
871 if (const CXXDestructorDecl *Dtor = Record->getDestructor(Context))
Mike Stump1eb44332009-09-09 15:08:12 +0000872 MarkDeclarationReferenced(StartLoc,
Fariborz Jahanian34374e62009-09-03 23:18:17 +0000873 const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssond67c4c32009-08-16 20:29:29 +0000874 }
Mike Stump1eb44332009-09-09 15:08:12 +0000875
Anders Carlssond67c4c32009-08-16 20:29:29 +0000876 if (!OperatorDelete) {
877 // Didn't find a member overload. Look for a global one.
878 DeclareGlobalNewDelete();
879 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000880 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
Douglas Gregor90916562009-09-29 18:16:17 +0000881 &Ex, 1, TUDecl, /*AllowMissing=*/false,
Anders Carlssond67c4c32009-08-16 20:29:29 +0000882 OperatorDelete))
883 return ExprError();
884 }
Mike Stump1eb44332009-09-09 15:08:12 +0000885
Sebastian Redl28507842009-02-26 14:39:58 +0000886 // FIXME: Check access and ambiguity of operator delete and destructor.
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000887 }
888
Sebastian Redlf53597f2009-03-15 17:47:39 +0000889 Operand.release();
890 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
Anders Carlssond67c4c32009-08-16 20:29:29 +0000891 OperatorDelete, Ex, StartLoc));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000892}
893
894
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000895/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
896/// C++ if/switch/while/for statement.
897/// e.g: "if (int x = f()) {...}"
Sebastian Redlf53597f2009-03-15 17:47:39 +0000898Action::OwningExprResult
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000899Sema::ActOnCXXConditionDeclarationExpr(Scope *S, SourceLocation StartLoc,
900 Declarator &D,
901 SourceLocation EqualLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000902 ExprArg AssignExprVal) {
903 assert(AssignExprVal.get() && "Null assignment expression");
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000904
905 // C++ 6.4p2:
906 // The declarator shall not specify a function or an array.
907 // The type-specifier-seq shall not contain typedef and shall not declare a
908 // new class or enumeration.
909
910 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
911 "Parser allowed 'typedef' as storage class of condition decl.");
912
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000913 // FIXME: Store DeclaratorInfo in the expression.
914 DeclaratorInfo *DInfo = 0;
Argyrios Kyrtzidise955e722009-08-11 05:20:41 +0000915 TagDecl *OwnedTag = 0;
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000916 QualType Ty = GetTypeForDeclarator(D, S, &DInfo, &OwnedTag);
Mike Stump1eb44332009-09-09 15:08:12 +0000917
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000918 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
919 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
920 // would be created and CXXConditionDeclExpr wants a VarDecl.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000921 return ExprError(Diag(StartLoc, diag::err_invalid_use_of_function_type)
922 << SourceRange(StartLoc, EqualLoc));
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000923 } else if (Ty->isArrayType()) { // ...or an array.
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000924 Diag(StartLoc, diag::err_invalid_use_of_array_type)
925 << SourceRange(StartLoc, EqualLoc);
Argyrios Kyrtzidise955e722009-08-11 05:20:41 +0000926 } else if (OwnedTag && OwnedTag->isDefinition()) {
927 // The type-specifier-seq shall not declare a new class or enumeration.
928 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000929 }
930
Douglas Gregor2e01cda2009-06-23 21:43:56 +0000931 DeclPtrTy Dcl = ActOnDeclarator(S, D);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000932 if (!Dcl)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000933 return ExprError();
Anders Carlssonf5dcd382009-05-30 21:37:25 +0000934 AddInitializerToDecl(Dcl, move(AssignExprVal), /*DirectInit=*/false);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000935
Douglas Gregorcaaf29a2008-12-10 23:01:14 +0000936 // Mark this variable as one that is declared within a conditional.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000937 // We know that the decl had to be a VarDecl because that is the only type of
938 // decl that can be assigned and the grammar requires an '='.
939 VarDecl *VD = cast<VarDecl>(Dcl.getAs<Decl>());
940 VD->setDeclaredInCondition(true);
941 return Owned(new (Context) CXXConditionDeclExpr(StartLoc, EqualLoc, VD));
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000942}
943
944/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
945bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
946 // C++ 6.4p4:
947 // The value of a condition that is an initialized declaration in a statement
948 // other than a switch statement is the value of the declared variable
949 // implicitly converted to type bool. If that conversion is ill-formed, the
950 // program is ill-formed.
951 // The value of a condition that is an expression is the value of the
952 // expression, implicitly converted to bool.
953 //
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000954 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000955}
Douglas Gregor77a52232008-09-12 00:47:35 +0000956
957/// Helper function to determine whether this is the (deprecated) C++
958/// conversion from a string literal to a pointer to non-const char or
959/// non-const wchar_t (for narrow and wide string literals,
960/// respectively).
Mike Stump1eb44332009-09-09 15:08:12 +0000961bool
Douglas Gregor77a52232008-09-12 00:47:35 +0000962Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
963 // Look inside the implicit cast, if it exists.
964 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
965 From = Cast->getSubExpr();
966
967 // A string literal (2.13.4) that is not a wide string literal can
968 // be converted to an rvalue of type "pointer to char"; a wide
969 // string literal can be converted to an rvalue of type "pointer
970 // to wchar_t" (C++ 4.2p2).
971 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From))
Ted Kremenek6217b802009-07-29 21:53:49 +0000972 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump1eb44332009-09-09 15:08:12 +0000973 if (const BuiltinType *ToPointeeType
John McCall183700f2009-09-21 23:43:11 +0000974 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregor77a52232008-09-12 00:47:35 +0000975 // This conversion is considered only when there is an
976 // explicit appropriate pointer target type (C++ 4.2p2).
John McCall0953e762009-09-24 19:53:00 +0000977 if (!ToPtrType->getPointeeType().hasQualifiers() &&
Douglas Gregor77a52232008-09-12 00:47:35 +0000978 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
979 (!StrLit->isWide() &&
980 (ToPointeeType->getKind() == BuiltinType::Char_U ||
981 ToPointeeType->getKind() == BuiltinType::Char_S))))
982 return true;
983 }
984
985 return false;
986}
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000987
988/// PerformImplicitConversion - Perform an implicit conversion of the
989/// expression From to the type ToType. Returns true if there was an
990/// error, false otherwise. The expression From is replaced with the
Douglas Gregor45920e82008-12-19 17:40:08 +0000991/// converted expression. Flavor is the kind of conversion we're
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000992/// performing, used in the error message. If @p AllowExplicit,
Sebastian Redle2b68332009-04-12 17:16:29 +0000993/// explicit user-defined conversions are permitted. @p Elidable should be true
994/// when called for copies which may be elided (C++ 12.8p15). C++0x overload
995/// resolution works differently in that case.
996bool
Douglas Gregor45920e82008-12-19 17:40:08 +0000997Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Sebastian Redle2b68332009-04-12 17:16:29 +0000998 const char *Flavor, bool AllowExplicit,
Mike Stump1eb44332009-09-09 15:08:12 +0000999 bool Elidable) {
Sebastian Redle2b68332009-04-12 17:16:29 +00001000 ImplicitConversionSequence ICS;
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00001001 return PerformImplicitConversion(From, ToType, Flavor, AllowExplicit,
1002 Elidable, ICS);
1003}
1004
1005bool
1006Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
1007 const char *Flavor, bool AllowExplicit,
1008 bool Elidable,
1009 ImplicitConversionSequence& ICS) {
Sebastian Redle2b68332009-04-12 17:16:29 +00001010 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1011 if (Elidable && getLangOptions().CPlusPlus0x) {
Mike Stump1eb44332009-09-09 15:08:12 +00001012 ICS = TryImplicitConversion(From, ToType,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001013 /*SuppressUserConversions=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +00001014 AllowExplicit,
Anders Carlsson08972922009-08-28 15:33:32 +00001015 /*ForceRValue=*/true,
1016 /*InOverloadResolution=*/false);
Sebastian Redle2b68332009-04-12 17:16:29 +00001017 }
1018 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion) {
Mike Stump1eb44332009-09-09 15:08:12 +00001019 ICS = TryImplicitConversion(From, ToType,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001020 /*SuppressUserConversions=*/false,
1021 AllowExplicit,
Anders Carlsson08972922009-08-28 15:33:32 +00001022 /*ForceRValue=*/false,
1023 /*InOverloadResolution=*/false);
Sebastian Redle2b68332009-04-12 17:16:29 +00001024 }
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001025 return PerformImplicitConversion(From, ToType, ICS, Flavor);
1026}
1027
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001028/// BuildCXXDerivedToBaseExpr - This routine generates the suitable AST
1029/// for the derived to base conversion of the expression 'From'. All
1030/// necessary information is passed in ICS.
1031bool
1032Sema::BuildCXXDerivedToBaseExpr(Expr *&From, CastExpr::CastKind CastKind,
1033 const ImplicitConversionSequence& ICS,
1034 const char *Flavor) {
1035 QualType BaseType =
1036 QualType::getFromOpaquePtr(ICS.UserDefined.After.ToTypePtr);
1037 // Must do additional defined to base conversion.
1038 QualType DerivedType =
1039 QualType::getFromOpaquePtr(ICS.UserDefined.After.FromTypePtr);
1040
1041 From = new (Context) ImplicitCastExpr(
1042 DerivedType.getNonReferenceType(),
1043 CastKind,
1044 From,
1045 DerivedType->isLValueReferenceType());
1046 From = new (Context) ImplicitCastExpr(BaseType.getNonReferenceType(),
1047 CastExpr::CK_DerivedToBase, From,
1048 BaseType->isLValueReferenceType());
1049 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1050 OwningExprResult FromResult =
1051 BuildCXXConstructExpr(
1052 ICS.UserDefined.After.CopyConstructor->getLocation(),
1053 BaseType,
1054 ICS.UserDefined.After.CopyConstructor,
1055 MultiExprArg(*this, (void **)&From, 1));
1056 if (FromResult.isInvalid())
1057 return true;
1058 From = FromResult.takeAs<Expr>();
1059 return false;
1060}
1061
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001062/// PerformImplicitConversion - Perform an implicit conversion of the
1063/// expression From to the type ToType using the pre-computed implicit
1064/// conversion sequence ICS. Returns true if there was an error, false
1065/// otherwise. The expression From is replaced with the converted
1066/// expression. Flavor is the kind of conversion we're performing,
1067/// used in the error message.
1068bool
1069Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
1070 const ImplicitConversionSequence &ICS,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001071 const char* Flavor, bool IgnoreBaseAccess) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001072 switch (ICS.ConversionKind) {
1073 case ImplicitConversionSequence::StandardConversion:
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001074 if (PerformImplicitConversion(From, ToType, ICS.Standard, Flavor,
1075 IgnoreBaseAccess))
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001076 return true;
1077 break;
1078
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001079 case ImplicitConversionSequence::UserDefinedConversion: {
1080
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00001081 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
1082 CastExpr::CastKind CastKind = CastExpr::CK_Unknown;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001083 QualType BeforeToType;
1084 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00001085 CastKind = CastExpr::CK_UserDefinedConversion;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001086
1087 // If the user-defined conversion is specified by a conversion function,
1088 // the initial standard conversion sequence converts the source type to
1089 // the implicit object parameter of the conversion function.
1090 BeforeToType = Context.getTagDeclType(Conv->getParent());
1091 } else if (const CXXConstructorDecl *Ctor =
1092 dyn_cast<CXXConstructorDecl>(FD)) {
Anders Carlsson0aebc812009-09-09 21:33:21 +00001093 CastKind = CastExpr::CK_ConstructorConversion;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001094 // Do no conversion if dealing with ... for the first conversion.
1095 if (!ICS.UserDefined.EllipsisConversion)
1096 // If the user-defined conversion is specified by a constructor, the
1097 // initial standard conversion sequence converts the source type to the
1098 // type required by the argument of the constructor
1099 BeforeToType = Ctor->getParamDecl(0)->getType();
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001100 }
Anders Carlsson0aebc812009-09-09 21:33:21 +00001101 else
1102 assert(0 && "Unknown conversion function kind!");
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001103 // Whatch out for elipsis conversion.
Fariborz Jahanian4c0cea22009-11-06 00:55:14 +00001104 if (!ICS.UserDefined.EllipsisConversion) {
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001105 if (PerformImplicitConversion(From, BeforeToType,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001106 ICS.UserDefined.Before, "converting",
1107 IgnoreBaseAccess))
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001108 return true;
1109 }
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001110
Anders Carlsson0aebc812009-09-09 21:33:21 +00001111 OwningExprResult CastArg
1112 = BuildCXXCastArgument(From->getLocStart(),
1113 ToType.getNonReferenceType(),
1114 CastKind, cast<CXXMethodDecl>(FD),
1115 Owned(From));
1116
1117 if (CastArg.isInvalid())
1118 return true;
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001119
1120 if (ICS.UserDefined.After.Second == ICK_Derived_To_Base &&
1121 ICS.UserDefined.After.CopyConstructor) {
1122 From = CastArg.takeAs<Expr>();
1123 return BuildCXXDerivedToBaseExpr(From, CastKind, ICS, Flavor);
1124 }
Fariborz Jahanian7a1f4cc2009-10-23 18:08:22 +00001125
1126 if (ICS.UserDefined.After.Second == ICK_Pointer_Member &&
1127 ToType.getNonReferenceType()->isMemberFunctionPointerType())
1128 CastKind = CastExpr::CK_BaseToDerivedMemberPointer;
Anders Carlsson0aebc812009-09-09 21:33:21 +00001129
Anders Carlsson626c2d62009-09-15 05:49:31 +00001130 From = new (Context) ImplicitCastExpr(ToType.getNonReferenceType(),
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001131 CastKind, CastArg.takeAs<Expr>(),
Anders Carlsson626c2d62009-09-15 05:49:31 +00001132 ToType->isLValueReferenceType());
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00001133 return false;
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001134 }
1135
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001136 case ImplicitConversionSequence::EllipsisConversion:
1137 assert(false && "Cannot perform an ellipsis conversion");
Douglas Gregor60d62c22008-10-31 16:23:19 +00001138 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001139
1140 case ImplicitConversionSequence::BadConversion:
1141 return true;
1142 }
1143
1144 // Everything went well.
1145 return false;
1146}
1147
1148/// PerformImplicitConversion - Perform an implicit conversion of the
1149/// expression From to the type ToType by following the standard
1150/// conversion sequence SCS. Returns true if there was an error, false
1151/// otherwise. The expression From is replaced with the converted
Douglas Gregor45920e82008-12-19 17:40:08 +00001152/// expression. Flavor is the context in which we're performing this
1153/// conversion, for use in error messages.
Mike Stump1eb44332009-09-09 15:08:12 +00001154bool
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001155Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor45920e82008-12-19 17:40:08 +00001156 const StandardConversionSequence& SCS,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001157 const char *Flavor, bool IgnoreBaseAccess) {
Mike Stump390b4cc2009-05-16 07:39:55 +00001158 // Overall FIXME: we are recomputing too many types here and doing far too
1159 // much extra work. What this means is that we need to keep track of more
1160 // information that is computed when we try the implicit conversion initially,
1161 // so that we don't need to recompute anything here.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001162 QualType FromType = From->getType();
1163
Douglas Gregor225c41e2008-11-03 19:09:14 +00001164 if (SCS.CopyConstructor) {
Anders Carlsson7c3e8a12009-05-19 04:45:15 +00001165 // FIXME: When can ToType be a reference type?
1166 assert(!ToType->isReferenceType());
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00001167 if (SCS.Second == ICK_Derived_To_Base) {
1168 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1169 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
1170 MultiExprArg(*this, (void **)&From, 1),
1171 /*FIXME:ConstructLoc*/SourceLocation(),
1172 ConstructorArgs))
1173 return true;
1174 OwningExprResult FromResult =
1175 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1176 ToType, SCS.CopyConstructor,
1177 move_arg(ConstructorArgs));
1178 if (FromResult.isInvalid())
1179 return true;
1180 From = FromResult.takeAs<Expr>();
1181 return false;
1182 }
Mike Stump1eb44332009-09-09 15:08:12 +00001183 OwningExprResult FromResult =
1184 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1185 ToType, SCS.CopyConstructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00001186 MultiExprArg(*this, (void**)&From, 1));
Mike Stump1eb44332009-09-09 15:08:12 +00001187
Anders Carlssonda3f4e22009-08-25 05:12:04 +00001188 if (FromResult.isInvalid())
1189 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001190
Anders Carlssonda3f4e22009-08-25 05:12:04 +00001191 From = FromResult.takeAs<Expr>();
Douglas Gregor225c41e2008-11-03 19:09:14 +00001192 return false;
1193 }
1194
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001195 // Perform the first implicit conversion.
1196 switch (SCS.First) {
1197 case ICK_Identity:
1198 case ICK_Lvalue_To_Rvalue:
1199 // Nothing to do.
1200 break;
1201
1202 case ICK_Array_To_Pointer:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001203 FromType = Context.getArrayDecayedType(FromType);
Anders Carlsson82495762009-08-08 21:04:35 +00001204 ImpCastExprToType(From, FromType, CastExpr::CK_ArrayToPointerDecay);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001205 break;
1206
1207 case ICK_Function_To_Pointer:
Douglas Gregor063daf62009-03-13 18:40:31 +00001208 if (Context.getCanonicalType(FromType) == Context.OverloadTy) {
Douglas Gregor904eed32008-11-10 20:40:00 +00001209 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, true);
1210 if (!Fn)
1211 return true;
1212
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001213 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
1214 return true;
1215
Anders Carlsson96ad5332009-10-21 17:16:23 +00001216 From = FixOverloadedFunctionReference(From, Fn);
Douglas Gregor904eed32008-11-10 20:40:00 +00001217 FromType = From->getType();
Anders Carlsson96ad5332009-10-21 17:16:23 +00001218
Sebastian Redl759986e2009-10-17 20:50:27 +00001219 // If there's already an address-of operator in the expression, we have
1220 // the right type already, and the code below would just introduce an
1221 // invalid additional pointer level.
Anders Carlsson96ad5332009-10-21 17:16:23 +00001222 if (FromType->isPointerType() || FromType->isMemberFunctionPointerType())
Sebastian Redl759986e2009-10-17 20:50:27 +00001223 break;
Douglas Gregor904eed32008-11-10 20:40:00 +00001224 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001225 FromType = Context.getPointerType(FromType);
Anders Carlssonb633c4e2009-09-01 20:37:18 +00001226 ImpCastExprToType(From, FromType, CastExpr::CK_FunctionToPointerDecay);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001227 break;
1228
1229 default:
1230 assert(false && "Improper first standard conversion");
1231 break;
1232 }
1233
1234 // Perform the second implicit conversion
1235 switch (SCS.Second) {
1236 case ICK_Identity:
Sebastian Redl2c7588f2009-10-10 12:04:10 +00001237 // If both sides are functions (or pointers/references to them), there could
1238 // be incompatible exception declarations.
1239 if (CheckExceptionSpecCompatibility(From, ToType))
1240 return true;
1241 // Nothing else to do.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001242 break;
1243
1244 case ICK_Integral_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001245 case ICK_Integral_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001246 ImpCastExprToType(From, ToType, CastExpr::CK_IntegralCast);
1247 break;
1248
1249 case ICK_Floating_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001250 case ICK_Floating_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001251 ImpCastExprToType(From, ToType, CastExpr::CK_FloatingCast);
1252 break;
1253
1254 case ICK_Complex_Promotion:
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001255 case ICK_Complex_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001256 ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1257 break;
1258
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001259 case ICK_Floating_Integral:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001260 if (ToType->isFloatingType())
1261 ImpCastExprToType(From, ToType, CastExpr::CK_IntegralToFloating);
1262 else
1263 ImpCastExprToType(From, ToType, CastExpr::CK_FloatingToIntegral);
1264 break;
1265
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001266 case ICK_Complex_Real:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001267 ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1268 break;
1269
Douglas Gregorf9201e02009-02-11 23:02:49 +00001270 case ICK_Compatible_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001271 ImpCastExprToType(From, ToType, CastExpr::CK_NoOp);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001272 break;
1273
Anders Carlsson61faec12009-09-12 04:46:44 +00001274 case ICK_Pointer_Conversion: {
Douglas Gregor45920e82008-12-19 17:40:08 +00001275 if (SCS.IncompatibleObjC) {
1276 // Diagnose incompatible Objective-C conversions
Mike Stump1eb44332009-09-09 15:08:12 +00001277 Diag(From->getSourceRange().getBegin(),
Douglas Gregor45920e82008-12-19 17:40:08 +00001278 diag::ext_typecheck_convert_incompatible_pointer)
1279 << From->getType() << ToType << Flavor
1280 << From->getSourceRange();
1281 }
1282
Anders Carlsson61faec12009-09-12 04:46:44 +00001283
1284 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001285 if (CheckPointerConversion(From, ToType, Kind, IgnoreBaseAccess))
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001286 return true;
Anders Carlsson61faec12009-09-12 04:46:44 +00001287 ImpCastExprToType(From, ToType, Kind);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001288 break;
Anders Carlsson61faec12009-09-12 04:46:44 +00001289 }
1290
1291 case ICK_Pointer_Member: {
1292 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001293 if (CheckMemberPointerConversion(From, ToType, Kind, IgnoreBaseAccess))
Anders Carlsson61faec12009-09-12 04:46:44 +00001294 return true;
Sebastian Redl2c7588f2009-10-10 12:04:10 +00001295 if (CheckExceptionSpecCompatibility(From, ToType))
1296 return true;
Anders Carlsson61faec12009-09-12 04:46:44 +00001297 ImpCastExprToType(From, ToType, Kind);
1298 break;
1299 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001300 case ICK_Boolean_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001301 ImpCastExprToType(From, Context.BoolTy, CastExpr::CK_Unknown);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001302 break;
1303
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001304 case ICK_Derived_To_Base:
1305 if (CheckDerivedToBaseConversion(From->getType(),
1306 ToType.getNonReferenceType(),
1307 From->getLocStart(),
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001308 From->getSourceRange(),
1309 IgnoreBaseAccess))
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001310 return true;
1311 ImpCastExprToType(From, ToType.getNonReferenceType(),
1312 CastExpr::CK_DerivedToBase);
1313 break;
1314
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001315 default:
1316 assert(false && "Improper second standard conversion");
1317 break;
1318 }
1319
1320 switch (SCS.Third) {
1321 case ICK_Identity:
1322 // Nothing to do.
1323 break;
1324
1325 case ICK_Qualification:
Mike Stump390b4cc2009-05-16 07:39:55 +00001326 // FIXME: Not sure about lvalue vs rvalue here in the presence of rvalue
1327 // references.
Mike Stump1eb44332009-09-09 15:08:12 +00001328 ImpCastExprToType(From, ToType.getNonReferenceType(),
Eli Friedman73c39ab2009-10-20 08:27:19 +00001329 CastExpr::CK_NoOp,
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001330 ToType->isLValueReferenceType());
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001331 break;
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001332
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001333 default:
1334 assert(false && "Improper second standard conversion");
1335 break;
1336 }
1337
1338 return false;
1339}
1340
Sebastian Redl64b45f72009-01-05 20:52:13 +00001341Sema::OwningExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
1342 SourceLocation KWLoc,
1343 SourceLocation LParen,
1344 TypeTy *Ty,
1345 SourceLocation RParen) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00001346 QualType T = GetTypeFromParser(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00001347
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001348 // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
1349 // all traits except __is_class, __is_enum and __is_union require a the type
1350 // to be complete.
1351 if (OTT != UTT_IsClass && OTT != UTT_IsEnum && OTT != UTT_IsUnion) {
Mike Stump1eb44332009-09-09 15:08:12 +00001352 if (RequireCompleteType(KWLoc, T,
Anders Carlssond497ba72009-08-26 22:59:12 +00001353 diag::err_incomplete_type_used_in_type_trait_expr))
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001354 return ExprError();
1355 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00001356
1357 // There is no point in eagerly computing the value. The traits are designed
1358 // to be used from type trait templates, so Ty will be a template parameter
1359 // 99% of the time.
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001360 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT, T,
1361 RParen, Context.BoolTy));
Sebastian Redl64b45f72009-01-05 20:52:13 +00001362}
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001363
1364QualType Sema::CheckPointerToMemberOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00001365 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001366 const char *OpSpelling = isIndirect ? "->*" : ".*";
1367 // C++ 5.5p2
1368 // The binary operator .* [p3: ->*] binds its second operand, which shall
1369 // be of type "pointer to member of T" (where T is a completely-defined
1370 // class type) [...]
1371 QualType RType = rex->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001372 const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
Douglas Gregore7450f52009-03-24 19:52:54 +00001373 if (!MemPtr) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001374 Diag(Loc, diag::err_bad_memptr_rhs)
1375 << OpSpelling << RType << rex->getSourceRange();
1376 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00001377 }
Douglas Gregore7450f52009-03-24 19:52:54 +00001378
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001379 QualType Class(MemPtr->getClass(), 0);
1380
1381 // C++ 5.5p2
1382 // [...] to its first operand, which shall be of class T or of a class of
1383 // which T is an unambiguous and accessible base class. [p3: a pointer to
1384 // such a class]
1385 QualType LType = lex->getType();
1386 if (isIndirect) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001387 if (const PointerType *Ptr = LType->getAs<PointerType>())
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001388 LType = Ptr->getPointeeType().getNonReferenceType();
1389 else {
1390 Diag(Loc, diag::err_bad_memptr_lhs)
Fariborz Jahanianef78ac62009-10-26 20:45:27 +00001391 << OpSpelling << 1 << LType
1392 << CodeModificationHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001393 return QualType();
1394 }
1395 }
1396
1397 if (Context.getCanonicalType(Class).getUnqualifiedType() !=
1398 Context.getCanonicalType(LType).getUnqualifiedType()) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001399 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1400 /*DetectVirtual=*/false);
Mike Stump390b4cc2009-05-16 07:39:55 +00001401 // FIXME: Would it be useful to print full ambiguity paths, or is that
1402 // overkill?
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001403 if (!IsDerivedFrom(LType, Class, Paths) ||
1404 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
Fariborz Jahanianef78ac62009-10-26 20:45:27 +00001405 const char *ReplaceStr = isIndirect ? ".*" : "->*";
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001406 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Fariborz Jahanianef78ac62009-10-26 20:45:27 +00001407 << (int)isIndirect << lex->getType() <<
1408 CodeModificationHint::CreateReplacement(SourceRange(Loc), ReplaceStr);
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001409 return QualType();
1410 }
1411 }
1412
1413 // C++ 5.5p2
1414 // The result is an object or a function of the type specified by the
1415 // second operand.
1416 // The cv qualifiers are the union of those in the pointer and the left side,
1417 // in accordance with 5.5p5 and 5.2.5.
1418 // FIXME: This returns a dereferenced member function pointer as a normal
1419 // function type. However, the only operation valid on such functions is
Mike Stump390b4cc2009-05-16 07:39:55 +00001420 // calling them. There's also a GCC extension to get a function pointer to the
1421 // thing, which is another complication, because this type - unlike the type
1422 // that is the result of this expression - takes the class as the first
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001423 // argument.
1424 // We probably need a "MemberFunctionClosureType" or something like that.
1425 QualType Result = MemPtr->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00001426 Result = Context.getCVRQualifiedType(Result, LType.getCVRQualifiers());
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001427 return Result;
1428}
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001429
1430/// \brief Get the target type of a standard or user-defined conversion.
1431static QualType TargetType(const ImplicitConversionSequence &ICS) {
1432 assert((ICS.ConversionKind ==
1433 ImplicitConversionSequence::StandardConversion ||
1434 ICS.ConversionKind ==
1435 ImplicitConversionSequence::UserDefinedConversion) &&
1436 "function only valid for standard or user-defined conversions");
1437 if (ICS.ConversionKind == ImplicitConversionSequence::StandardConversion)
1438 return QualType::getFromOpaquePtr(ICS.Standard.ToTypePtr);
1439 return QualType::getFromOpaquePtr(ICS.UserDefined.After.ToTypePtr);
1440}
1441
1442/// \brief Try to convert a type to another according to C++0x 5.16p3.
1443///
1444/// This is part of the parameter validation for the ? operator. If either
1445/// value operand is a class type, the two operands are attempted to be
1446/// converted to each other. This function does the conversion in one direction.
1447/// It emits a diagnostic and returns true only if it finds an ambiguous
1448/// conversion.
1449static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
1450 SourceLocation QuestionLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00001451 ImplicitConversionSequence &ICS) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001452 // C++0x 5.16p3
1453 // The process for determining whether an operand expression E1 of type T1
1454 // can be converted to match an operand expression E2 of type T2 is defined
1455 // as follows:
1456 // -- If E2 is an lvalue:
1457 if (To->isLvalue(Self.Context) == Expr::LV_Valid) {
1458 // E1 can be converted to match E2 if E1 can be implicitly converted to
1459 // type "lvalue reference to T2", subject to the constraint that in the
1460 // conversion the reference must bind directly to E1.
1461 if (!Self.CheckReferenceInit(From,
1462 Self.Context.getLValueReferenceType(To->getType()),
Douglas Gregor739d8282009-09-23 23:04:10 +00001463 To->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001464 /*SuppressUserConversions=*/false,
1465 /*AllowExplicit=*/false,
1466 /*ForceRValue=*/false,
1467 &ICS))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001468 {
1469 assert((ICS.ConversionKind ==
1470 ImplicitConversionSequence::StandardConversion ||
1471 ICS.ConversionKind ==
1472 ImplicitConversionSequence::UserDefinedConversion) &&
1473 "expected a definite conversion");
1474 bool DirectBinding =
1475 ICS.ConversionKind == ImplicitConversionSequence::StandardConversion ?
1476 ICS.Standard.DirectBinding : ICS.UserDefined.After.DirectBinding;
1477 if (DirectBinding)
1478 return false;
1479 }
1480 }
1481 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1482 // -- If E2 is an rvalue, or if the conversion above cannot be done:
1483 // -- if E1 and E2 have class type, and the underlying class types are
1484 // the same or one is a base class of the other:
1485 QualType FTy = From->getType();
1486 QualType TTy = To->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001487 const RecordType *FRec = FTy->getAs<RecordType>();
1488 const RecordType *TRec = TTy->getAs<RecordType>();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001489 bool FDerivedFromT = FRec && TRec && Self.IsDerivedFrom(FTy, TTy);
1490 if (FRec && TRec && (FRec == TRec ||
1491 FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
1492 // E1 can be converted to match E2 if the class of T2 is the
1493 // same type as, or a base class of, the class of T1, and
1494 // [cv2 > cv1].
1495 if ((FRec == TRec || FDerivedFromT) && TTy.isAtLeastAsQualifiedAs(FTy)) {
1496 // Could still fail if there's no copy constructor.
1497 // FIXME: Is this a hard error then, or just a conversion failure? The
1498 // standard doesn't say.
Mike Stump1eb44332009-09-09 15:08:12 +00001499 ICS = Self.TryCopyInitialization(From, TTy,
Anders Carlssond28b4282009-08-27 17:18:13 +00001500 /*SuppressUserConversions=*/false,
Anders Carlsson7b361b52009-08-27 17:37:39 +00001501 /*ForceRValue=*/false,
1502 /*InOverloadResolution=*/false);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001503 }
1504 } else {
1505 // -- Otherwise: E1 can be converted to match E2 if E1 can be
1506 // implicitly converted to the type that expression E2 would have
1507 // if E2 were converted to an rvalue.
1508 // First find the decayed type.
1509 if (TTy->isFunctionType())
1510 TTy = Self.Context.getPointerType(TTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001511 else if (TTy->isArrayType())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001512 TTy = Self.Context.getArrayDecayedType(TTy);
1513
1514 // Now try the implicit conversion.
1515 // FIXME: This doesn't detect ambiguities.
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001516 ICS = Self.TryImplicitConversion(From, TTy,
1517 /*SuppressUserConversions=*/false,
1518 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00001519 /*ForceRValue=*/false,
1520 /*InOverloadResolution=*/false);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001521 }
1522 return false;
1523}
1524
1525/// \brief Try to find a common type for two according to C++0x 5.16p5.
1526///
1527/// This is part of the parameter validation for the ? operator. If either
1528/// value operand is a class type, overload resolution is used to find a
1529/// conversion to a common type.
1530static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
1531 SourceLocation Loc) {
1532 Expr *Args[2] = { LHS, RHS };
1533 OverloadCandidateSet CandidateSet;
Douglas Gregor573d9c32009-10-21 23:19:44 +00001534 Self.AddBuiltinOperatorCandidates(OO_Conditional, Loc, Args, 2, CandidateSet);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001535
1536 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00001537 switch (Self.BestViableFunction(CandidateSet, Loc, Best)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001538 case Sema::OR_Success:
1539 // We found a match. Perform the conversions on the arguments and move on.
1540 if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
1541 Best->Conversions[0], "converting") ||
1542 Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
1543 Best->Conversions[1], "converting"))
1544 break;
1545 return false;
1546
1547 case Sema::OR_No_Viable_Function:
1548 Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
1549 << LHS->getType() << RHS->getType()
1550 << LHS->getSourceRange() << RHS->getSourceRange();
1551 return true;
1552
1553 case Sema::OR_Ambiguous:
1554 Self.Diag(Loc, diag::err_conditional_ambiguous_ovl)
1555 << LHS->getType() << RHS->getType()
1556 << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stump390b4cc2009-05-16 07:39:55 +00001557 // FIXME: Print the possible common types by printing the return types of
1558 // the viable candidates.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001559 break;
1560
1561 case Sema::OR_Deleted:
1562 assert(false && "Conditional operator has only built-in overloads");
1563 break;
1564 }
1565 return true;
1566}
1567
Sebastian Redl76458502009-04-17 16:30:52 +00001568/// \brief Perform an "extended" implicit conversion as returned by
1569/// TryClassUnification.
1570///
1571/// TryClassUnification generates ICSs that include reference bindings.
1572/// PerformImplicitConversion is not suitable for this; it chokes if the
1573/// second part of a standard conversion is ICK_DerivedToBase. This function
1574/// handles the reference binding specially.
1575static bool ConvertForConditional(Sema &Self, Expr *&E,
Mike Stump1eb44332009-09-09 15:08:12 +00001576 const ImplicitConversionSequence &ICS) {
Sebastian Redl76458502009-04-17 16:30:52 +00001577 if (ICS.ConversionKind == ImplicitConversionSequence::StandardConversion &&
1578 ICS.Standard.ReferenceBinding) {
1579 assert(ICS.Standard.DirectBinding &&
1580 "TryClassUnification should never generate indirect ref bindings");
Sebastian Redla5cd2cd2009-04-26 11:21:02 +00001581 // FIXME: CheckReferenceInit should be able to reuse the ICS instead of
1582 // redoing all the work.
1583 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001584 TargetType(ICS)),
Douglas Gregor739d8282009-09-23 23:04:10 +00001585 /*FIXME:*/E->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001586 /*SuppressUserConversions=*/false,
1587 /*AllowExplicit=*/false,
1588 /*ForceRValue=*/false);
Sebastian Redl76458502009-04-17 16:30:52 +00001589 }
1590 if (ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion &&
1591 ICS.UserDefined.After.ReferenceBinding) {
1592 assert(ICS.UserDefined.After.DirectBinding &&
1593 "TryClassUnification should never generate indirect ref bindings");
Sebastian Redla5cd2cd2009-04-26 11:21:02 +00001594 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001595 TargetType(ICS)),
Douglas Gregor739d8282009-09-23 23:04:10 +00001596 /*FIXME:*/E->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001597 /*SuppressUserConversions=*/false,
1598 /*AllowExplicit=*/false,
1599 /*ForceRValue=*/false);
Sebastian Redl76458502009-04-17 16:30:52 +00001600 }
1601 if (Self.PerformImplicitConversion(E, TargetType(ICS), ICS, "converting"))
1602 return true;
1603 return false;
1604}
1605
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001606/// \brief Check the operands of ?: under C++ semantics.
1607///
1608/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
1609/// extension. In this case, LHS == Cond. (But they're not aliases.)
1610QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
1611 SourceLocation QuestionLoc) {
Mike Stump390b4cc2009-05-16 07:39:55 +00001612 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
1613 // interface pointers.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001614
1615 // C++0x 5.16p1
1616 // The first expression is contextually converted to bool.
1617 if (!Cond->isTypeDependent()) {
1618 if (CheckCXXBooleanCondition(Cond))
1619 return QualType();
1620 }
1621
1622 // Either of the arguments dependent?
1623 if (LHS->isTypeDependent() || RHS->isTypeDependent())
1624 return Context.DependentTy;
1625
John McCallb13c87f2009-11-05 09:23:39 +00001626 CheckSignCompare(LHS, RHS, QuestionLoc, diag::warn_mixed_sign_conditional);
1627
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001628 // C++0x 5.16p2
1629 // If either the second or the third operand has type (cv) void, ...
1630 QualType LTy = LHS->getType();
1631 QualType RTy = RHS->getType();
1632 bool LVoid = LTy->isVoidType();
1633 bool RVoid = RTy->isVoidType();
1634 if (LVoid || RVoid) {
1635 // ... then the [l2r] conversions are performed on the second and third
1636 // operands ...
1637 DefaultFunctionArrayConversion(LHS);
1638 DefaultFunctionArrayConversion(RHS);
1639 LTy = LHS->getType();
1640 RTy = RHS->getType();
1641
1642 // ... and one of the following shall hold:
1643 // -- The second or the third operand (but not both) is a throw-
1644 // expression; the result is of the type of the other and is an rvalue.
1645 bool LThrow = isa<CXXThrowExpr>(LHS);
1646 bool RThrow = isa<CXXThrowExpr>(RHS);
1647 if (LThrow && !RThrow)
1648 return RTy;
1649 if (RThrow && !LThrow)
1650 return LTy;
1651
1652 // -- Both the second and third operands have type void; the result is of
1653 // type void and is an rvalue.
1654 if (LVoid && RVoid)
1655 return Context.VoidTy;
1656
1657 // Neither holds, error.
1658 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
1659 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
1660 << LHS->getSourceRange() << RHS->getSourceRange();
1661 return QualType();
1662 }
1663
1664 // Neither is void.
1665
1666 // C++0x 5.16p3
1667 // Otherwise, if the second and third operand have different types, and
1668 // either has (cv) class type, and attempt is made to convert each of those
1669 // operands to the other.
1670 if (Context.getCanonicalType(LTy) != Context.getCanonicalType(RTy) &&
1671 (LTy->isRecordType() || RTy->isRecordType())) {
1672 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
1673 // These return true if a single direction is already ambiguous.
1674 if (TryClassUnification(*this, LHS, RHS, QuestionLoc, ICSLeftToRight))
1675 return QualType();
1676 if (TryClassUnification(*this, RHS, LHS, QuestionLoc, ICSRightToLeft))
1677 return QualType();
1678
1679 bool HaveL2R = ICSLeftToRight.ConversionKind !=
1680 ImplicitConversionSequence::BadConversion;
1681 bool HaveR2L = ICSRightToLeft.ConversionKind !=
1682 ImplicitConversionSequence::BadConversion;
1683 // If both can be converted, [...] the program is ill-formed.
1684 if (HaveL2R && HaveR2L) {
1685 Diag(QuestionLoc, diag::err_conditional_ambiguous)
1686 << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
1687 return QualType();
1688 }
1689
1690 // If exactly one conversion is possible, that conversion is applied to
1691 // the chosen operand and the converted operands are used in place of the
1692 // original operands for the remainder of this section.
1693 if (HaveL2R) {
Sebastian Redl76458502009-04-17 16:30:52 +00001694 if (ConvertForConditional(*this, LHS, ICSLeftToRight))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001695 return QualType();
1696 LTy = LHS->getType();
1697 } else if (HaveR2L) {
Sebastian Redl76458502009-04-17 16:30:52 +00001698 if (ConvertForConditional(*this, RHS, ICSRightToLeft))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001699 return QualType();
1700 RTy = RHS->getType();
1701 }
1702 }
1703
1704 // C++0x 5.16p4
1705 // If the second and third operands are lvalues and have the same type,
1706 // the result is of that type [...]
1707 bool Same = Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy);
1708 if (Same && LHS->isLvalue(Context) == Expr::LV_Valid &&
1709 RHS->isLvalue(Context) == Expr::LV_Valid)
1710 return LTy;
1711
1712 // C++0x 5.16p5
1713 // Otherwise, the result is an rvalue. If the second and third operands
1714 // do not have the same type, and either has (cv) class type, ...
1715 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
1716 // ... overload resolution is used to determine the conversions (if any)
1717 // to be applied to the operands. If the overload resolution fails, the
1718 // program is ill-formed.
1719 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
1720 return QualType();
1721 }
1722
1723 // C++0x 5.16p6
1724 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
1725 // conversions are performed on the second and third operands.
1726 DefaultFunctionArrayConversion(LHS);
1727 DefaultFunctionArrayConversion(RHS);
1728 LTy = LHS->getType();
1729 RTy = RHS->getType();
1730
1731 // After those conversions, one of the following shall hold:
1732 // -- The second and third operands have the same type; the result
1733 // is of that type.
1734 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy))
1735 return LTy;
1736
1737 // -- The second and third operands have arithmetic or enumeration type;
1738 // the usual arithmetic conversions are performed to bring them to a
1739 // common type, and the result is of that type.
1740 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
1741 UsualArithmeticConversions(LHS, RHS);
1742 return LHS->getType();
1743 }
1744
1745 // -- The second and third operands have pointer type, or one has pointer
1746 // type and the other is a null pointer constant; pointer conversions
1747 // and qualification conversions are performed to bring them to their
1748 // composite pointer type. The result is of the composite pointer type.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001749 QualType Composite = FindCompositePointerType(LHS, RHS);
1750 if (!Composite.isNull())
1751 return Composite;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001752
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001753 // Fourth bullet is same for pointers-to-member. However, the possible
1754 // conversions are far more limited: we have null-to-pointer, upcast of
1755 // containing class, and second-level cv-ness.
1756 // cv-ness is not a union, but must match one of the two operands. (Which,
1757 // frankly, is stupid.)
Ted Kremenek6217b802009-07-29 21:53:49 +00001758 const MemberPointerType *LMemPtr = LTy->getAs<MemberPointerType>();
1759 const MemberPointerType *RMemPtr = RTy->getAs<MemberPointerType>();
Douglas Gregorce940492009-09-25 04:25:58 +00001760 if (LMemPtr &&
1761 RHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00001762 ImpCastExprToType(RHS, LTy, CastExpr::CK_NullToMemberPointer);
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001763 return LTy;
1764 }
Douglas Gregorce940492009-09-25 04:25:58 +00001765 if (RMemPtr &&
1766 LHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00001767 ImpCastExprToType(LHS, RTy, CastExpr::CK_NullToMemberPointer);
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001768 return RTy;
1769 }
1770 if (LMemPtr && RMemPtr) {
1771 QualType LPointee = LMemPtr->getPointeeType();
1772 QualType RPointee = RMemPtr->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00001773
1774 QualifierCollector LPQuals, RPQuals;
1775 const Type *LPCan = LPQuals.strip(Context.getCanonicalType(LPointee));
1776 const Type *RPCan = RPQuals.strip(Context.getCanonicalType(RPointee));
1777
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001778 // First, we check that the unqualified pointee type is the same. If it's
1779 // not, there's no conversion that will unify the two pointers.
John McCall0953e762009-09-24 19:53:00 +00001780 if (LPCan == RPCan) {
1781
1782 // Second, we take the greater of the two qualifications. If neither
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001783 // is greater than the other, the conversion is not possible.
John McCall0953e762009-09-24 19:53:00 +00001784
1785 Qualifiers MergedQuals = LPQuals + RPQuals;
1786
1787 bool CompatibleQuals = true;
1788 if (MergedQuals.getCVRQualifiers() != LPQuals.getCVRQualifiers() &&
1789 MergedQuals.getCVRQualifiers() != RPQuals.getCVRQualifiers())
1790 CompatibleQuals = false;
1791 else if (LPQuals.getAddressSpace() != RPQuals.getAddressSpace())
1792 // FIXME:
1793 // C99 6.5.15 as modified by TR 18037:
1794 // If the second and third operands are pointers into different
1795 // address spaces, the address spaces must overlap.
1796 CompatibleQuals = false;
1797 // FIXME: GC qualifiers?
1798
1799 if (CompatibleQuals) {
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001800 // Third, we check if either of the container classes is derived from
1801 // the other.
1802 QualType LContainer(LMemPtr->getClass(), 0);
1803 QualType RContainer(RMemPtr->getClass(), 0);
1804 QualType MoreDerived;
1805 if (Context.getCanonicalType(LContainer) ==
1806 Context.getCanonicalType(RContainer))
1807 MoreDerived = LContainer;
1808 else if (IsDerivedFrom(LContainer, RContainer))
1809 MoreDerived = LContainer;
1810 else if (IsDerivedFrom(RContainer, LContainer))
1811 MoreDerived = RContainer;
1812
1813 if (!MoreDerived.isNull()) {
1814 // The type 'Q Pointee (MoreDerived::*)' is the common type.
1815 // We don't use ImpCastExprToType here because this could still fail
1816 // for ambiguous or inaccessible conversions.
John McCall0953e762009-09-24 19:53:00 +00001817 LPointee = Context.getQualifiedType(LPointee, MergedQuals);
1818 QualType Common
1819 = Context.getMemberPointerType(LPointee, MoreDerived.getTypePtr());
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001820 if (PerformImplicitConversion(LHS, Common, "converting"))
1821 return QualType();
1822 if (PerformImplicitConversion(RHS, Common, "converting"))
1823 return QualType();
1824 return Common;
1825 }
1826 }
1827 }
1828 }
1829
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001830 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
1831 << LHS->getType() << RHS->getType()
1832 << LHS->getSourceRange() << RHS->getSourceRange();
1833 return QualType();
1834}
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001835
1836/// \brief Find a merged pointer type and convert the two expressions to it.
1837///
Douglas Gregor20b3e992009-08-24 17:42:35 +00001838/// This finds the composite pointer type (or member pointer type) for @p E1
1839/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
1840/// type and returns it.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001841/// It does not emit diagnostics.
1842QualType Sema::FindCompositePointerType(Expr *&E1, Expr *&E2) {
1843 assert(getLangOptions().CPlusPlus && "This function assumes C++");
1844 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001845
Douglas Gregor20b3e992009-08-24 17:42:35 +00001846 if (!T1->isPointerType() && !T1->isMemberPointerType() &&
1847 !T2->isPointerType() && !T2->isMemberPointerType())
1848 return QualType();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001849
Douglas Gregor20b3e992009-08-24 17:42:35 +00001850 // FIXME: Do we need to work on the canonical types?
Mike Stump1eb44332009-09-09 15:08:12 +00001851
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001852 // C++0x 5.9p2
1853 // Pointer conversions and qualification conversions are performed on
1854 // pointer operands to bring them to their composite pointer type. If
1855 // one operand is a null pointer constant, the composite pointer type is
1856 // the type of the other operand.
Douglas Gregorce940492009-09-25 04:25:58 +00001857 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00001858 if (T2->isMemberPointerType())
1859 ImpCastExprToType(E1, T2, CastExpr::CK_NullToMemberPointer);
1860 else
1861 ImpCastExprToType(E1, T2, CastExpr::CK_IntegralToPointer);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001862 return T2;
1863 }
Douglas Gregorce940492009-09-25 04:25:58 +00001864 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00001865 if (T1->isMemberPointerType())
1866 ImpCastExprToType(E2, T1, CastExpr::CK_NullToMemberPointer);
1867 else
1868 ImpCastExprToType(E2, T1, CastExpr::CK_IntegralToPointer);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001869 return T1;
1870 }
Mike Stump1eb44332009-09-09 15:08:12 +00001871
Douglas Gregor20b3e992009-08-24 17:42:35 +00001872 // Now both have to be pointers or member pointers.
1873 if (!T1->isPointerType() && !T1->isMemberPointerType() &&
1874 !T2->isPointerType() && !T2->isMemberPointerType())
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001875 return QualType();
1876
1877 // Otherwise, of one of the operands has type "pointer to cv1 void," then
1878 // the other has type "pointer to cv2 T" and the composite pointer type is
1879 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
1880 // Otherwise, the composite pointer type is a pointer type similar to the
1881 // type of one of the operands, with a cv-qualification signature that is
1882 // the union of the cv-qualification signatures of the operand types.
1883 // In practice, the first part here is redundant; it's subsumed by the second.
1884 // What we do here is, we build the two possible composite types, and try the
1885 // conversions in both directions. If only one works, or if the two composite
1886 // types are the same, we have succeeded.
John McCall0953e762009-09-24 19:53:00 +00001887 // FIXME: extended qualifiers?
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001888 llvm::SmallVector<unsigned, 4> QualifierUnion;
Douglas Gregor20b3e992009-08-24 17:42:35 +00001889 llvm::SmallVector<std::pair<const Type *, const Type *>, 4> MemberOfClass;
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001890 QualType Composite1 = T1, Composite2 = T2;
Douglas Gregor20b3e992009-08-24 17:42:35 +00001891 do {
1892 const PointerType *Ptr1, *Ptr2;
1893 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
1894 (Ptr2 = Composite2->getAs<PointerType>())) {
1895 Composite1 = Ptr1->getPointeeType();
1896 Composite2 = Ptr2->getPointeeType();
1897 QualifierUnion.push_back(
1898 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
1899 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
1900 continue;
1901 }
Mike Stump1eb44332009-09-09 15:08:12 +00001902
Douglas Gregor20b3e992009-08-24 17:42:35 +00001903 const MemberPointerType *MemPtr1, *MemPtr2;
1904 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
1905 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
1906 Composite1 = MemPtr1->getPointeeType();
1907 Composite2 = MemPtr2->getPointeeType();
1908 QualifierUnion.push_back(
1909 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
1910 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
1911 MemPtr2->getClass()));
1912 continue;
1913 }
Mike Stump1eb44332009-09-09 15:08:12 +00001914
Douglas Gregor20b3e992009-08-24 17:42:35 +00001915 // FIXME: block pointer types?
Mike Stump1eb44332009-09-09 15:08:12 +00001916
Douglas Gregor20b3e992009-08-24 17:42:35 +00001917 // Cannot unwrap any more types.
1918 break;
1919 } while (true);
Mike Stump1eb44332009-09-09 15:08:12 +00001920
Douglas Gregor20b3e992009-08-24 17:42:35 +00001921 // Rewrap the composites as pointers or member pointers with the union CVRs.
1922 llvm::SmallVector<std::pair<const Type *, const Type *>, 4>::iterator MOC
1923 = MemberOfClass.begin();
Mike Stump1eb44332009-09-09 15:08:12 +00001924 for (llvm::SmallVector<unsigned, 4>::iterator
Douglas Gregor20b3e992009-08-24 17:42:35 +00001925 I = QualifierUnion.begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00001926 E = QualifierUnion.end();
Douglas Gregor20b3e992009-08-24 17:42:35 +00001927 I != E; (void)++I, ++MOC) {
John McCall0953e762009-09-24 19:53:00 +00001928 Qualifiers Quals = Qualifiers::fromCVRMask(*I);
Douglas Gregor20b3e992009-08-24 17:42:35 +00001929 if (MOC->first && MOC->second) {
1930 // Rebuild member pointer type
John McCall0953e762009-09-24 19:53:00 +00001931 Composite1 = Context.getMemberPointerType(
1932 Context.getQualifiedType(Composite1, Quals),
1933 MOC->first);
1934 Composite2 = Context.getMemberPointerType(
1935 Context.getQualifiedType(Composite2, Quals),
1936 MOC->second);
Douglas Gregor20b3e992009-08-24 17:42:35 +00001937 } else {
1938 // Rebuild pointer type
John McCall0953e762009-09-24 19:53:00 +00001939 Composite1
1940 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
1941 Composite2
1942 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregor20b3e992009-08-24 17:42:35 +00001943 }
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001944 }
1945
Mike Stump1eb44332009-09-09 15:08:12 +00001946 ImplicitConversionSequence E1ToC1 =
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001947 TryImplicitConversion(E1, Composite1,
1948 /*SuppressUserConversions=*/false,
1949 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00001950 /*ForceRValue=*/false,
1951 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00001952 ImplicitConversionSequence E2ToC1 =
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001953 TryImplicitConversion(E2, Composite1,
1954 /*SuppressUserConversions=*/false,
1955 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00001956 /*ForceRValue=*/false,
1957 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00001958
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001959 ImplicitConversionSequence E1ToC2, E2ToC2;
1960 E1ToC2.ConversionKind = ImplicitConversionSequence::BadConversion;
1961 E2ToC2.ConversionKind = ImplicitConversionSequence::BadConversion;
1962 if (Context.getCanonicalType(Composite1) !=
1963 Context.getCanonicalType(Composite2)) {
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001964 E1ToC2 = TryImplicitConversion(E1, Composite2,
1965 /*SuppressUserConversions=*/false,
1966 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00001967 /*ForceRValue=*/false,
1968 /*InOverloadResolution=*/false);
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001969 E2ToC2 = TryImplicitConversion(E2, Composite2,
1970 /*SuppressUserConversions=*/false,
1971 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00001972 /*ForceRValue=*/false,
1973 /*InOverloadResolution=*/false);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001974 }
1975
1976 bool ToC1Viable = E1ToC1.ConversionKind !=
1977 ImplicitConversionSequence::BadConversion
1978 && E2ToC1.ConversionKind !=
1979 ImplicitConversionSequence::BadConversion;
1980 bool ToC2Viable = E1ToC2.ConversionKind !=
1981 ImplicitConversionSequence::BadConversion
1982 && E2ToC2.ConversionKind !=
1983 ImplicitConversionSequence::BadConversion;
1984 if (ToC1Viable && !ToC2Viable) {
1985 if (!PerformImplicitConversion(E1, Composite1, E1ToC1, "converting") &&
1986 !PerformImplicitConversion(E2, Composite1, E2ToC1, "converting"))
1987 return Composite1;
1988 }
1989 if (ToC2Viable && !ToC1Viable) {
1990 if (!PerformImplicitConversion(E1, Composite2, E1ToC2, "converting") &&
1991 !PerformImplicitConversion(E2, Composite2, E2ToC2, "converting"))
1992 return Composite2;
1993 }
1994 return QualType();
1995}
Anders Carlsson165a0a02009-05-17 18:41:29 +00001996
Anders Carlssondef11992009-05-30 20:36:53 +00001997Sema::OwningExprResult Sema::MaybeBindToTemporary(Expr *E) {
Anders Carlsson089c2602009-08-15 23:41:35 +00001998 if (!Context.getLangOptions().CPlusPlus)
1999 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002000
Ted Kremenek6217b802009-07-29 21:53:49 +00002001 const RecordType *RT = E->getType()->getAs<RecordType>();
Anders Carlssondef11992009-05-30 20:36:53 +00002002 if (!RT)
2003 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002004
Anders Carlssondef11992009-05-30 20:36:53 +00002005 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2006 if (RD->hasTrivialDestructor())
2007 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002008
Anders Carlsson283e4d52009-09-14 01:30:44 +00002009 if (CallExpr *CE = dyn_cast<CallExpr>(E)) {
2010 QualType Ty = CE->getCallee()->getType();
2011 if (const PointerType *PT = Ty->getAs<PointerType>())
2012 Ty = PT->getPointeeType();
2013
John McCall183700f2009-09-21 23:43:11 +00002014 const FunctionType *FTy = Ty->getAs<FunctionType>();
Anders Carlsson283e4d52009-09-14 01:30:44 +00002015 if (FTy->getResultType()->isReferenceType())
2016 return Owned(E);
2017 }
Mike Stump1eb44332009-09-09 15:08:12 +00002018 CXXTemporary *Temp = CXXTemporary::Create(Context,
Anders Carlssondef11992009-05-30 20:36:53 +00002019 RD->getDestructor(Context));
Anders Carlsson860306e2009-05-30 21:21:49 +00002020 ExprTemporaries.push_back(Temp);
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00002021 if (CXXDestructorDecl *Destructor =
2022 const_cast<CXXDestructorDecl*>(RD->getDestructor(Context)))
2023 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
Anders Carlssondef11992009-05-30 20:36:53 +00002024 // FIXME: Add the temporary to the temporaries vector.
2025 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
2026}
2027
Mike Stump1eb44332009-09-09 15:08:12 +00002028Expr *Sema::MaybeCreateCXXExprWithTemporaries(Expr *SubExpr,
Anders Carlssonf54741e2009-06-16 03:37:31 +00002029 bool ShouldDestroyTemps) {
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002030 assert(SubExpr && "sub expression can't be null!");
Mike Stump1eb44332009-09-09 15:08:12 +00002031
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002032 if (ExprTemporaries.empty())
2033 return SubExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00002034
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002035 Expr *E = CXXExprWithTemporaries::Create(Context, SubExpr,
Mike Stump1eb44332009-09-09 15:08:12 +00002036 &ExprTemporaries[0],
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002037 ExprTemporaries.size(),
Anders Carlssonf54741e2009-06-16 03:37:31 +00002038 ShouldDestroyTemps);
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002039 ExprTemporaries.clear();
Mike Stump1eb44332009-09-09 15:08:12 +00002040
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002041 return E;
2042}
2043
Mike Stump1eb44332009-09-09 15:08:12 +00002044Sema::OwningExprResult
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002045Sema::ActOnStartCXXMemberReference(Scope *S, ExprArg Base, SourceLocation OpLoc,
2046 tok::TokenKind OpKind, TypeTy *&ObjectType) {
2047 // Since this might be a postfix expression, get rid of ParenListExprs.
2048 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
Mike Stump1eb44332009-09-09 15:08:12 +00002049
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002050 Expr *BaseExpr = (Expr*)Base.get();
2051 assert(BaseExpr && "no record expansion");
Mike Stump1eb44332009-09-09 15:08:12 +00002052
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002053 QualType BaseType = BaseExpr->getType();
2054 if (BaseType->isDependentType()) {
Douglas Gregor43d88632009-11-04 22:49:18 +00002055 // If we have a pointer to a dependent type and are using the -> operator,
2056 // the object type is the type that the pointer points to. We might still
2057 // have enough information about that type to do something useful.
2058 if (OpKind == tok::arrow)
2059 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
2060 BaseType = Ptr->getPointeeType();
2061
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002062 ObjectType = BaseType.getAsOpaquePtr();
2063 return move(Base);
2064 }
Mike Stump1eb44332009-09-09 15:08:12 +00002065
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002066 // C++ [over.match.oper]p8:
Mike Stump1eb44332009-09-09 15:08:12 +00002067 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002068 // returned, with the original second operand.
2069 if (OpKind == tok::arrow) {
John McCallc4e83212009-09-30 01:01:30 +00002070 // The set of types we've considered so far.
John McCall432887f2009-09-30 01:30:54 +00002071 llvm::SmallPtrSet<CanQualType,8> CTypes;
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002072 llvm::SmallVector<SourceLocation, 8> Locations;
John McCall432887f2009-09-30 01:30:54 +00002073 CTypes.insert(Context.getCanonicalType(BaseType));
John McCallc4e83212009-09-30 01:01:30 +00002074
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002075 while (BaseType->isRecordType()) {
Anders Carlsson15ea3782009-10-13 22:43:21 +00002076 Base = BuildOverloadedArrowExpr(S, move(Base), OpLoc);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002077 BaseExpr = (Expr*)Base.get();
2078 if (BaseExpr == NULL)
2079 return ExprError();
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002080 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(BaseExpr))
Anders Carlssonde699e52009-10-13 22:55:59 +00002081 Locations.push_back(OpCall->getDirectCallee()->getLocation());
John McCallc4e83212009-09-30 01:01:30 +00002082 BaseType = BaseExpr->getType();
2083 CanQualType CBaseType = Context.getCanonicalType(BaseType);
John McCall432887f2009-09-30 01:30:54 +00002084 if (!CTypes.insert(CBaseType)) {
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00002085 Diag(OpLoc, diag::err_operator_arrow_circular);
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002086 for (unsigned i = 0; i < Locations.size(); i++)
2087 Diag(Locations[i], diag::note_declared_at);
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00002088 return ExprError();
2089 }
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002090 }
2091 }
Mike Stump1eb44332009-09-09 15:08:12 +00002092
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002093 if (BaseType->isPointerType())
2094 BaseType = BaseType->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00002095
2096 // We could end up with various non-record types here, such as extended
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002097 // vector types or Objective-C interfaces. Just return early and let
2098 // ActOnMemberReferenceExpr do the work.
Douglas Gregorc68afe22009-09-03 21:38:09 +00002099 if (!BaseType->isRecordType()) {
2100 // C++ [basic.lookup.classref]p2:
2101 // [...] If the type of the object expression is of pointer to scalar
2102 // type, the unqualified-id is looked up in the context of the complete
2103 // postfix-expression.
2104 ObjectType = 0;
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002105 return move(Base);
Douglas Gregorc68afe22009-09-03 21:38:09 +00002106 }
Mike Stump1eb44332009-09-09 15:08:12 +00002107
Douglas Gregorc68afe22009-09-03 21:38:09 +00002108 // C++ [basic.lookup.classref]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00002109 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregorc68afe22009-09-03 21:38:09 +00002110 // unqualified-id, and the type of the object expres- sion is of a class
2111 // type C (or of pointer to a class type C), the unqualified-id is looked
2112 // up in the scope of class C. [...]
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002113 ObjectType = BaseType.getAsOpaquePtr();
Mike Stump1eb44332009-09-09 15:08:12 +00002114 return move(Base);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002115}
2116
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002117CXXMemberCallExpr *Sema::BuildCXXMemberCallExpr(Expr *Exp,
2118 CXXMethodDecl *Method) {
2119 MemberExpr *ME =
2120 new (Context) MemberExpr(Exp, /*IsArrow=*/false, Method,
2121 SourceLocation(), Method->getType());
2122 QualType ResultType;
2123 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(Method))
2124 ResultType = Conv->getConversionType().getNonReferenceType();
2125 else
2126 ResultType = Method->getResultType().getNonReferenceType();
2127
2128 CXXMemberCallExpr *CE =
2129 new (Context) CXXMemberCallExpr(Context, ME, 0, 0,
2130 ResultType,
Douglas Gregor00b98c22009-11-12 15:31:47 +00002131 Exp->getLocEnd());
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002132 return CE;
2133}
2134
Anders Carlsson0aebc812009-09-09 21:33:21 +00002135Sema::OwningExprResult Sema::BuildCXXCastArgument(SourceLocation CastLoc,
2136 QualType Ty,
2137 CastExpr::CastKind Kind,
2138 CXXMethodDecl *Method,
2139 ExprArg Arg) {
2140 Expr *From = Arg.takeAs<Expr>();
2141
2142 switch (Kind) {
2143 default: assert(0 && "Unhandled cast kind!");
2144 case CastExpr::CK_ConstructorConversion: {
Douglas Gregor39da0b82009-09-09 23:08:42 +00002145 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
2146
2147 if (CompleteConstructorCall(cast<CXXConstructorDecl>(Method),
2148 MultiExprArg(*this, (void **)&From, 1),
2149 CastLoc, ConstructorArgs))
2150 return ExprError();
Anders Carlsson4fa26842009-10-18 21:20:14 +00002151
2152 OwningExprResult Result =
2153 BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
2154 move_arg(ConstructorArgs));
2155 if (Result.isInvalid())
2156 return ExprError();
2157
2158 return MaybeBindToTemporary(Result.takeAs<Expr>());
Anders Carlsson0aebc812009-09-09 21:33:21 +00002159 }
2160
2161 case CastExpr::CK_UserDefinedConversion: {
Anders Carlssonaac6e3a2009-09-15 07:42:44 +00002162 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
2163
2164 // Cast to base if needed.
2165 if (PerformObjectArgumentInitialization(From, Method))
2166 return ExprError();
2167
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002168 // Create an implicit call expr that calls it.
2169 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(From, Method);
Anders Carlsson4fa26842009-10-18 21:20:14 +00002170 return MaybeBindToTemporary(CE);
Anders Carlsson0aebc812009-09-09 21:33:21 +00002171 }
Anders Carlsson0aebc812009-09-09 21:33:21 +00002172 }
2173}
2174
Anders Carlsson165a0a02009-05-17 18:41:29 +00002175Sema::OwningExprResult Sema::ActOnFinishFullExpr(ExprArg Arg) {
2176 Expr *FullExpr = Arg.takeAs<Expr>();
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002177 if (FullExpr)
Mike Stump1eb44332009-09-09 15:08:12 +00002178 FullExpr = MaybeCreateCXXExprWithTemporaries(FullExpr,
Anders Carlssonf54741e2009-06-16 03:37:31 +00002179 /*ShouldDestroyTemps=*/true);
Anders Carlsson165a0a02009-05-17 18:41:29 +00002180
Anders Carlssonec773872009-08-25 23:46:41 +00002181
Anders Carlsson165a0a02009-05-17 18:41:29 +00002182 return Owned(FullExpr);
2183}
Douglas Gregore961afb2009-10-22 07:08:30 +00002184
2185/// \brief Determine whether a reference to the given declaration in the
2186/// current context is an implicit member access
2187/// (C++ [class.mfct.non-static]p2).
2188///
2189/// FIXME: Should Objective-C also use this approach?
2190///
2191/// \param SS if non-NULL, the C++ nested-name-specifier that precedes the
2192/// name of the declaration referenced.
2193///
2194/// \param D the declaration being referenced from the current scope.
2195///
2196/// \param NameLoc the location of the name in the source.
2197///
2198/// \param ThisType if the reference to this declaration is an implicit member
2199/// access, will be set to the type of the "this" pointer to be used when
2200/// building that implicit member access.
2201///
2202/// \param MemberType if the reference to this declaration is an implicit
2203/// member access, will be set to the type of the member being referenced
2204/// (for use at the type of the resulting member access expression).
2205///
2206/// \returns true if this is an implicit member reference (in which case
2207/// \p ThisType and \p MemberType will be set), or false if it is not an
2208/// implicit member reference.
2209bool Sema::isImplicitMemberReference(const CXXScopeSpec *SS, NamedDecl *D,
2210 SourceLocation NameLoc, QualType &ThisType,
2211 QualType &MemberType) {
2212 // If this isn't a C++ method, then it isn't an implicit member reference.
2213 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext);
2214 if (!MD || MD->isStatic())
2215 return false;
2216
2217 // C++ [class.mfct.nonstatic]p2:
2218 // [...] if name lookup (3.4.1) resolves the name in the
2219 // id-expression to a nonstatic nontype member of class X or of
2220 // a base class of X, the id-expression is transformed into a
2221 // class member access expression (5.2.5) using (*this) (9.3.2)
2222 // as the postfix-expression to the left of the '.' operator.
2223 DeclContext *Ctx = 0;
2224 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
2225 Ctx = FD->getDeclContext();
2226 MemberType = FD->getType();
2227
2228 if (const ReferenceType *RefType = MemberType->getAs<ReferenceType>())
2229 MemberType = RefType->getPointeeType();
2230 else if (!FD->isMutable())
2231 MemberType
2232 = Context.getQualifiedType(MemberType,
2233 Qualifiers::fromCVRMask(MD->getTypeQualifiers()));
2234 } else {
2235 for (OverloadIterator Ovl(D), OvlEnd; Ovl != OvlEnd; ++Ovl) {
2236 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*Ovl);
2237 FunctionTemplateDecl *FunTmpl = 0;
2238 if (!Method && (FunTmpl = dyn_cast<FunctionTemplateDecl>(*Ovl)))
2239 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
2240
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00002241 // FIXME: Do we have to know if there are explicit template arguments?
Douglas Gregore961afb2009-10-22 07:08:30 +00002242 if (Method && !Method->isStatic()) {
2243 Ctx = Method->getParent();
2244 if (isa<CXXMethodDecl>(D) && !FunTmpl)
2245 MemberType = Method->getType();
2246 else
2247 MemberType = Context.OverloadTy;
2248 break;
2249 }
2250 }
2251 }
2252
2253 if (!Ctx || !Ctx->isRecord())
2254 return false;
2255
2256 // Determine whether the declaration(s) we found are actually in a base
2257 // class. If not, this isn't an implicit member reference.
2258 ThisType = MD->getThisType(Context);
Douglas Gregor7a343142009-11-01 17:08:18 +00002259
2260 // If the type of "this" is dependent, we can't tell if the member is in a
2261 // base class or not, so treat this as a dependent implicit member reference.
2262 if (ThisType->isDependentType())
2263 return true;
2264
Douglas Gregore961afb2009-10-22 07:08:30 +00002265 QualType CtxType = Context.getTypeDeclType(cast<CXXRecordDecl>(Ctx));
2266 QualType ClassType
2267 = Context.getTypeDeclType(cast<CXXRecordDecl>(MD->getParent()));
2268 return Context.hasSameType(CtxType, ClassType) ||
2269 IsDerivedFrom(ClassType, CtxType);
2270}
2271