blob: 0eea169b07278bf801ceb4f99207f588d70bb2e8 [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"
John McCall7d384dd2009-11-18 07:57:50 +000015#include "Lookup.h"
Steve Naroff210679c2007-08-25 14:02:58 +000016#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000017#include "clang/AST/CXXInheritance.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000018#include "clang/AST/ExprCXX.h"
19#include "clang/Basic/PartialDiagnostic.h"
Sebastian Redlb5a57a62008-12-03 20:26:15 +000020#include "clang/Basic/TargetInfo.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000021#include "clang/Lex/Preprocessor.h"
22#include "clang/Parse/DeclSpec.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000023#include "llvm/ADT/STLExtras.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000024using namespace clang;
25
Sebastian Redlc42e1182008-11-11 11:37:55 +000026/// ActOnCXXTypeidOfType - Parse typeid( type-id ).
Sebastian Redlf53597f2009-03-15 17:47:39 +000027Action::OwningExprResult
Sebastian Redlc42e1182008-11-11 11:37:55 +000028Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
29 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +000030 if (!StdNamespace)
Sebastian Redlf53597f2009-03-15 17:47:39 +000031 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +000032
33 if (isType)
34 // FIXME: Preserve type source info.
35 TyOrExpr = GetTypeFromParser(TyOrExpr).getAsOpaquePtr();
36
Chris Lattner572af492008-11-20 05:51:55 +000037 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
John McCalla24dc2e2009-11-17 02:14:36 +000038 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
39 LookupQualifiedName(R, StdNamespace);
John McCallf36e02d2009-10-09 21:13:30 +000040 Decl *TypeInfoDecl = R.getAsSingleDecl(Context);
Sebastian Redlc42e1182008-11-11 11:37:55 +000041 RecordDecl *TypeInfoRecordDecl = dyn_cast_or_null<RecordDecl>(TypeInfoDecl);
Chris Lattner572af492008-11-20 05:51:55 +000042 if (!TypeInfoRecordDecl)
Sebastian Redlf53597f2009-03-15 17:47:39 +000043 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Sebastian Redlc42e1182008-11-11 11:37:55 +000044
45 QualType TypeInfoType = Context.getTypeDeclType(TypeInfoRecordDecl);
46
Douglas Gregorac7610d2009-06-22 20:57:11 +000047 if (!isType) {
48 // C++0x [expr.typeid]p3:
Mike Stump1eb44332009-09-09 15:08:12 +000049 // When typeid is applied to an expression other than an lvalue of a
50 // polymorphic class type [...] [the] expression is an unevaluated
Douglas Gregorac7610d2009-06-22 20:57:11 +000051 // operand.
Mike Stump1eb44332009-09-09 15:08:12 +000052
Douglas Gregorac7610d2009-06-22 20:57:11 +000053 // FIXME: if the type of the expression is a class type, the class
54 // shall be completely defined.
55 bool isUnevaluatedOperand = true;
56 Expr *E = static_cast<Expr *>(TyOrExpr);
57 if (E && !E->isTypeDependent() && E->isLvalue(Context) == Expr::LV_Valid) {
58 QualType T = E->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +000059 if (const RecordType *RecordT = T->getAs<RecordType>()) {
Douglas Gregorac7610d2009-06-22 20:57:11 +000060 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
61 if (RecordD->isPolymorphic())
62 isUnevaluatedOperand = false;
63 }
64 }
Mike Stump1eb44332009-09-09 15:08:12 +000065
Douglas Gregorac7610d2009-06-22 20:57:11 +000066 // If this is an unevaluated operand, clear out the set of declaration
67 // references we have been computing.
68 if (isUnevaluatedOperand)
69 PotentiallyReferencedDeclStack.back().clear();
70 }
Mike Stump1eb44332009-09-09 15:08:12 +000071
Sebastian Redlf53597f2009-03-15 17:47:39 +000072 return Owned(new (Context) CXXTypeidExpr(isType, TyOrExpr,
73 TypeInfoType.withConst(),
74 SourceRange(OpLoc, RParenLoc)));
Sebastian Redlc42e1182008-11-11 11:37:55 +000075}
76
Steve Naroff1b273c42007-09-16 14:56:35 +000077/// ActOnCXXBoolLiteral - Parse {true,false} literals.
Sebastian Redlf53597f2009-03-15 17:47:39 +000078Action::OwningExprResult
Steve Naroff1b273c42007-09-16 14:56:35 +000079Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor2f639b92008-10-24 15:36:09 +000080 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Reid Spencer5f016e22007-07-11 17:01:13 +000081 "Unknown C++ Boolean value!");
Sebastian Redlf53597f2009-03-15 17:47:39 +000082 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
83 Context.BoolTy, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +000084}
Chris Lattner50dd2892008-02-26 00:51:44 +000085
Sebastian Redl6e8ed162009-05-10 18:38:11 +000086/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
87Action::OwningExprResult
88Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
89 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
90}
91
Chris Lattner50dd2892008-02-26 00:51:44 +000092/// ActOnCXXThrow - Parse throw expressions.
Sebastian Redlf53597f2009-03-15 17:47:39 +000093Action::OwningExprResult
94Sema::ActOnCXXThrow(SourceLocation OpLoc, ExprArg E) {
Sebastian Redl972041f2009-04-27 20:27:31 +000095 Expr *Ex = E.takeAs<Expr>();
96 if (Ex && !Ex->isTypeDependent() && CheckCXXThrowOperand(OpLoc, Ex))
97 return ExprError();
98 return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc));
99}
100
101/// CheckCXXThrowOperand - Validate the operand of a throw.
102bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *&E) {
103 // C++ [except.throw]p3:
104 // [...] adjusting the type from "array of T" or "function returning T"
105 // to "pointer to T" or "pointer to function returning T", [...]
106 DefaultFunctionArrayConversion(E);
107
108 // If the type of the exception would be an incomplete type or a pointer
109 // to an incomplete type other than (cv) void the program is ill-formed.
110 QualType Ty = E->getType();
111 int isPointer = 0;
Ted Kremenek6217b802009-07-29 21:53:49 +0000112 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000113 Ty = Ptr->getPointeeType();
114 isPointer = 1;
115 }
116 if (!isPointer || !Ty->isVoidType()) {
117 if (RequireCompleteType(ThrowLoc, Ty,
Anders Carlssond497ba72009-08-26 22:59:12 +0000118 PDiag(isPointer ? diag::err_throw_incomplete_ptr
119 : diag::err_throw_incomplete)
120 << E->getSourceRange()))
Sebastian Redl972041f2009-04-27 20:27:31 +0000121 return true;
122 }
123
124 // FIXME: Construct a temporary here.
125 return false;
Chris Lattner50dd2892008-02-26 00:51:44 +0000126}
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000127
Sebastian Redlf53597f2009-03-15 17:47:39 +0000128Action::OwningExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000129 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
130 /// is a non-lvalue expression whose value is the address of the object for
131 /// which the function is called.
132
Sebastian Redlf53597f2009-03-15 17:47:39 +0000133 if (!isa<FunctionDecl>(CurContext))
134 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000135
136 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext))
137 if (MD->isInstance())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000138 return Owned(new (Context) CXXThisExpr(ThisLoc,
139 MD->getThisType(Context)));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000140
Sebastian Redlf53597f2009-03-15 17:47:39 +0000141 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000142}
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000143
144/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
145/// Can be interpreted either as function-style casting ("int(x)")
146/// or class type construction ("ClassType(x,y,z)")
147/// or creation of a value-initialized type ("int()").
Sebastian Redlf53597f2009-03-15 17:47:39 +0000148Action::OwningExprResult
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000149Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep,
150 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000151 MultiExprArg exprs,
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000152 SourceLocation *CommaLocs,
153 SourceLocation RParenLoc) {
154 assert(TypeRep && "Missing type!");
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000155 // FIXME: Preserve type source info.
156 QualType Ty = GetTypeFromParser(TypeRep);
Sebastian Redlf53597f2009-03-15 17:47:39 +0000157 unsigned NumExprs = exprs.size();
158 Expr **Exprs = (Expr**)exprs.get();
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000159 SourceLocation TyBeginLoc = TypeRange.getBegin();
160 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
161
Sebastian Redlf53597f2009-03-15 17:47:39 +0000162 if (Ty->isDependentType() ||
Douglas Gregorba498172009-03-13 21:01:28 +0000163 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
Sebastian Redlf53597f2009-03-15 17:47:39 +0000164 exprs.release();
Mike Stump1eb44332009-09-09 15:08:12 +0000165
166 return Owned(CXXUnresolvedConstructExpr::Create(Context,
167 TypeRange.getBegin(), Ty,
Douglas Gregord81e6ca2009-05-20 18:46:25 +0000168 LParenLoc,
169 Exprs, NumExprs,
170 RParenLoc));
Douglas Gregorba498172009-03-13 21:01:28 +0000171 }
172
Anders Carlssonbb60a502009-08-27 03:53:50 +0000173 if (Ty->isArrayType())
174 return ExprError(Diag(TyBeginLoc,
175 diag::err_value_init_for_array_type) << FullRange);
176 if (!Ty->isVoidType() &&
177 RequireCompleteType(TyBeginLoc, Ty,
178 PDiag(diag::err_invalid_incomplete_type_use)
179 << FullRange))
180 return ExprError();
Fariborz Jahanianf071e9b2009-10-23 21:01:39 +0000181
Anders Carlssonbb60a502009-08-27 03:53:50 +0000182 if (RequireNonAbstractType(TyBeginLoc, Ty,
183 diag::err_allocation_of_abstract_type))
184 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000185
186
Douglas Gregor506ae412009-01-16 18:33:17 +0000187 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000188 // If the expression list is a single expression, the type conversion
189 // expression is equivalent (in definedness, and if defined in meaning) to the
190 // corresponding cast expression.
191 //
192 if (NumExprs == 1) {
Anders Carlssoncdb61972009-08-07 22:21:05 +0000193 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Anders Carlsson0aebc812009-09-09 21:33:21 +0000194 CXXMethodDecl *Method = 0;
195 if (CheckCastTypes(TypeRange, Ty, Exprs[0], Kind, Method,
196 /*FunctionalStyle=*/true))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000197 return ExprError();
Anders Carlsson0aebc812009-09-09 21:33:21 +0000198
199 exprs.release();
200 if (Method) {
201 OwningExprResult CastArg
202 = BuildCXXCastArgument(TypeRange.getBegin(), Ty.getNonReferenceType(),
203 Kind, Method, Owned(Exprs[0]));
204 if (CastArg.isInvalid())
205 return ExprError();
206
207 Exprs[0] = CastArg.takeAs<Expr>();
Fariborz Jahanian4fc7ab32009-08-28 15:11:24 +0000208 }
Anders Carlsson0aebc812009-09-09 21:33:21 +0000209
210 return Owned(new (Context) CXXFunctionalCastExpr(Ty.getNonReferenceType(),
211 Ty, TyBeginLoc, Kind,
212 Exprs[0], RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000213 }
214
Ted Kremenek6217b802009-07-29 21:53:49 +0000215 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Douglas Gregor506ae412009-01-16 18:33:17 +0000216 CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
Sebastian Redlf53597f2009-03-15 17:47:39 +0000217
Mike Stump1eb44332009-09-09 15:08:12 +0000218 if (NumExprs > 1 || !Record->hasTrivialConstructor() ||
Anders Carlssone7624a72009-08-27 05:08:22 +0000219 !Record->hasTrivialDestructor()) {
Douglas Gregor39da0b82009-09-09 23:08:42 +0000220 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
221
Douglas Gregor506ae412009-01-16 18:33:17 +0000222 CXXConstructorDecl *Constructor
Douglas Gregor39da0b82009-09-09 23:08:42 +0000223 = PerformInitializationByConstructor(Ty, move(exprs),
Douglas Gregor506ae412009-01-16 18:33:17 +0000224 TypeRange.getBegin(),
225 SourceRange(TypeRange.getBegin(),
226 RParenLoc),
227 DeclarationName(),
Douglas Gregor39da0b82009-09-09 23:08:42 +0000228 IK_Direct,
229 ConstructorArgs);
Douglas Gregor506ae412009-01-16 18:33:17 +0000230
Sebastian Redlf53597f2009-03-15 17:47:39 +0000231 if (!Constructor)
232 return ExprError();
233
Mike Stump1eb44332009-09-09 15:08:12 +0000234 OwningExprResult Result =
235 BuildCXXTemporaryObjectExpr(Constructor, Ty, TyBeginLoc,
Douglas Gregor39da0b82009-09-09 23:08:42 +0000236 move_arg(ConstructorArgs), RParenLoc);
Anders Carlssone7624a72009-08-27 05:08:22 +0000237 if (Result.isInvalid())
238 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000239
Anders Carlssone7624a72009-08-27 05:08:22 +0000240 return MaybeBindToTemporary(Result.takeAs<Expr>());
Douglas Gregor506ae412009-01-16 18:33:17 +0000241 }
242
243 // Fall through to value-initialize an object of class type that
244 // doesn't have a user-declared default constructor.
245 }
246
247 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000248 // If the expression list specifies more than a single value, the type shall
249 // be a class with a suitably declared constructor.
250 //
251 if (NumExprs > 1)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000252 return ExprError(Diag(CommaLocs[0],
253 diag::err_builtin_func_cast_more_than_one_arg)
254 << FullRange);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000255
256 assert(NumExprs == 0 && "Expected 0 expressions");
Douglas Gregor506ae412009-01-16 18:33:17 +0000257 // C++ [expr.type.conv]p2:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000258 // The expression T(), where T is a simple-type-specifier for a non-array
259 // complete object type or the (possibly cv-qualified) void type, creates an
260 // rvalue of the specified type, which is value-initialized.
261 //
Sebastian Redlf53597f2009-03-15 17:47:39 +0000262 exprs.release();
263 return Owned(new (Context) CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000264}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000265
266
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000267/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
268/// @code new (memory) int[size][4] @endcode
269/// or
270/// @code ::new Foo(23, "hello") @endcode
271/// For the interpretation of this heap of arguments, consult the base version.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000272Action::OwningExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000273Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000274 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000275 SourceLocation PlacementRParen, bool ParenTypeId,
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000276 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000277 MultiExprArg ConstructorArgs,
Mike Stump1eb44332009-09-09 15:08:12 +0000278 SourceLocation ConstructorRParen) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000279 Expr *ArraySize = 0;
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000280 // If the specified type is an array, unwrap it and save the expression.
281 if (D.getNumTypeObjects() > 0 &&
282 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
283 DeclaratorChunk &Chunk = D.getTypeObject(0);
284 if (Chunk.Arr.hasStatic)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000285 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
286 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000287 if (!Chunk.Arr.NumElts)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000288 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
289 << D.getSourceRange());
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000290
291 if (ParenTypeId) {
292 // Can't have dynamic array size when the type-id is in parentheses.
293 Expr *NumElts = (Expr *)Chunk.Arr.NumElts;
294 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
295 !NumElts->isIntegerConstantExpr(Context)) {
296 Diag(D.getTypeObject(0).Loc, diag::err_new_paren_array_nonconst)
297 << NumElts->getSourceRange();
298 return ExprError();
299 }
300 }
301
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000302 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000303 D.DropFirstTypeObject();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000304 }
305
Douglas Gregor043cad22009-09-11 00:18:58 +0000306 // Every dimension shall be of constant size.
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000307 if (ArraySize) {
308 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor043cad22009-09-11 00:18:58 +0000309 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
310 break;
311
312 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
313 if (Expr *NumElts = (Expr *)Array.NumElts) {
314 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
315 !NumElts->isIntegerConstantExpr(Context)) {
316 Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst)
317 << NumElts->getSourceRange();
318 return ExprError();
319 }
320 }
321 }
322 }
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000323
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000324 //FIXME: Store DeclaratorInfo in CXXNew expression.
325 DeclaratorInfo *DInfo = 0;
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000326 QualType AllocType = GetTypeForDeclarator(D, /*Scope=*/0, &DInfo);
Chris Lattnereaaebc72009-04-25 08:06:05 +0000327 if (D.isInvalidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000328 return ExprError();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000329
Mike Stump1eb44332009-09-09 15:08:12 +0000330 return BuildCXXNew(StartLoc, UseGlobal,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000331 PlacementLParen,
Mike Stump1eb44332009-09-09 15:08:12 +0000332 move(PlacementArgs),
Douglas Gregor3433cf72009-05-21 00:00:09 +0000333 PlacementRParen,
334 ParenTypeId,
Mike Stump1eb44332009-09-09 15:08:12 +0000335 AllocType,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000336 D.getSourceRange().getBegin(),
337 D.getSourceRange(),
338 Owned(ArraySize),
339 ConstructorLParen,
340 move(ConstructorArgs),
341 ConstructorRParen);
342}
343
Mike Stump1eb44332009-09-09 15:08:12 +0000344Sema::OwningExprResult
Douglas Gregor3433cf72009-05-21 00:00:09 +0000345Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
346 SourceLocation PlacementLParen,
347 MultiExprArg PlacementArgs,
348 SourceLocation PlacementRParen,
Mike Stump1eb44332009-09-09 15:08:12 +0000349 bool ParenTypeId,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000350 QualType AllocType,
351 SourceLocation TypeLoc,
352 SourceRange TypeRange,
353 ExprArg ArraySizeE,
354 SourceLocation ConstructorLParen,
355 MultiExprArg ConstructorArgs,
356 SourceLocation ConstructorRParen) {
357 if (CheckAllocatedType(AllocType, TypeLoc, TypeRange))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000358 return ExprError();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000359
Douglas Gregor3433cf72009-05-21 00:00:09 +0000360 QualType ResultType = Context.getPointerType(AllocType);
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000361
362 // That every array dimension except the first is constant was already
363 // checked by the type check above.
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000364
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000365 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
366 // or enumeration type with a non-negative value."
Douglas Gregor3433cf72009-05-21 00:00:09 +0000367 Expr *ArraySize = (Expr *)ArraySizeE.get();
Sebastian Redl28507842009-02-26 14:39:58 +0000368 if (ArraySize && !ArraySize->isTypeDependent()) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000369 QualType SizeType = ArraySize->getType();
370 if (!SizeType->isIntegralType() && !SizeType->isEnumeralType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000371 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
372 diag::err_array_size_not_integral)
373 << SizeType << ArraySize->getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000374 // Let's see if this is a constant < 0. If so, we reject it out of hand.
375 // We don't care about special rules, so we tell the machinery it's not
376 // evaluated - it gives us a result in more cases.
Sebastian Redl28507842009-02-26 14:39:58 +0000377 if (!ArraySize->isValueDependent()) {
378 llvm::APSInt Value;
379 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
380 if (Value < llvm::APSInt(
Anders Carlssonac18b2e2009-09-23 00:37:25 +0000381 llvm::APInt::getNullValue(Value.getBitWidth()),
382 Value.isUnsigned()))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000383 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
384 diag::err_typecheck_negative_array_size)
385 << ArraySize->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +0000386 }
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000387 }
Anders Carlssonac18b2e2009-09-23 00:37:25 +0000388
Eli Friedman73c39ab2009-10-20 08:27:19 +0000389 ImpCastExprToType(ArraySize, Context.getSizeType(),
390 CastExpr::CK_IntegralCast);
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000391 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000392
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000393 FunctionDecl *OperatorNew = 0;
394 FunctionDecl *OperatorDelete = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000395 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
396 unsigned NumPlaceArgs = PlacementArgs.size();
Douglas Gregor089407b2009-10-17 21:40:42 +0000397
Sebastian Redl28507842009-02-26 14:39:58 +0000398 if (!AllocType->isDependentType() &&
399 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
400 FindAllocationFunctions(StartLoc,
Sebastian Redl00e68e22009-02-09 18:24:27 +0000401 SourceRange(PlacementLParen, PlacementRParen),
402 UseGlobal, AllocType, ArraySize, PlaceArgs,
403 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000404 return ExprError();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000405
406 bool Init = ConstructorLParen.isValid();
407 // --- Choosing a constructor ---
408 // C++ 5.3.4p15
409 // 1) If T is a POD and there's no initializer (ConstructorLParen is invalid)
410 // the object is not initialized. If the object, or any part of it, is
411 // const-qualified, it's an error.
412 // 2) If T is a POD and there's an empty initializer, the object is value-
413 // initialized.
414 // 3) If T is a POD and there's one initializer argument, the object is copy-
415 // constructed.
416 // 4) If T is a POD and there's more initializer arguments, it's an error.
417 // 5) If T is not a POD, the initializer arguments are used as constructor
418 // arguments.
419 //
420 // Or by the C++0x formulation:
421 // 1) If there's no initializer, the object is default-initialized according
422 // to C++0x rules.
423 // 2) Otherwise, the object is direct-initialized.
424 CXXConstructorDecl *Constructor = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000425 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
Sebastian Redl4f149632009-05-07 16:14:23 +0000426 const RecordType *RT;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000427 unsigned NumConsArgs = ConstructorArgs.size();
Eli Friedmana8ce9ec2009-11-08 22:15:39 +0000428 ASTOwningVector<&ActionBase::DeleteExpr> ConvertedConstructorArgs(*this);
429
Douglas Gregor089407b2009-10-17 21:40:42 +0000430 if (AllocType->isDependentType() ||
431 Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) {
Sebastian Redl28507842009-02-26 14:39:58 +0000432 // Skip all the checks.
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000433 } else if ((RT = AllocType->getAs<RecordType>()) &&
434 !AllocType->isAggregateType()) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000435 Constructor = PerformInitializationByConstructor(
Douglas Gregor39da0b82009-09-09 23:08:42 +0000436 AllocType, move(ConstructorArgs),
Douglas Gregor3433cf72009-05-21 00:00:09 +0000437 TypeLoc,
438 SourceRange(TypeLoc, ConstructorRParen),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000439 RT->getDecl()->getDeclName(),
Douglas Gregor39da0b82009-09-09 23:08:42 +0000440 NumConsArgs != 0 ? IK_Direct : IK_Default,
441 ConvertedConstructorArgs);
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000442 if (!Constructor)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000443 return ExprError();
Douglas Gregor39da0b82009-09-09 23:08:42 +0000444
445 // Take the converted constructor arguments and use them for the new
446 // expression.
447 NumConsArgs = ConvertedConstructorArgs.size();
448 ConsArgs = (Expr **)ConvertedConstructorArgs.take();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000449 } else {
450 if (!Init) {
451 // FIXME: Check that no subpart is const.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000452 if (AllocType.isConstQualified())
453 return ExprError(Diag(StartLoc, diag::err_new_uninitialized_const)
Douglas Gregor3433cf72009-05-21 00:00:09 +0000454 << TypeRange);
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000455 } else if (NumConsArgs == 0) {
Fariborz Jahanian6f269202009-11-03 20:38:53 +0000456 // Object is value-initialized. Do nothing.
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000457 } else if (NumConsArgs == 1) {
458 // Object is direct-initialized.
Sebastian Redl4f149632009-05-07 16:14:23 +0000459 // FIXME: What DeclarationName do we pass in here?
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000460 if (CheckInitializerTypes(ConsArgs[0], AllocType, StartLoc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000461 DeclarationName() /*AllocType.getAsString()*/,
462 /*DirectInit=*/true))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000463 return ExprError();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000464 } else {
Sebastian Redlf53597f2009-03-15 17:47:39 +0000465 return ExprError(Diag(StartLoc,
466 diag::err_builtin_direct_init_more_than_one_arg)
467 << SourceRange(ConstructorLParen, ConstructorRParen));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000468 }
469 }
470
471 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
Douglas Gregor089407b2009-10-17 21:40:42 +0000472
Sebastian Redlf53597f2009-03-15 17:47:39 +0000473 PlacementArgs.release();
474 ConstructorArgs.release();
Douglas Gregor3433cf72009-05-21 00:00:09 +0000475 ArraySizeE.release();
Sebastian Redlf53597f2009-03-15 17:47:39 +0000476 return Owned(new (Context) CXXNewExpr(UseGlobal, OperatorNew, PlaceArgs,
Ted Kremenek8189cde2009-02-07 01:47:29 +0000477 NumPlaceArgs, ParenTypeId, ArraySize, Constructor, Init,
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000478 ConsArgs, NumConsArgs, OperatorDelete, ResultType,
Mike Stump1eb44332009-09-09 15:08:12 +0000479 StartLoc, Init ? ConstructorRParen : SourceLocation()));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000480}
481
482/// CheckAllocatedType - Checks that a type is suitable as the allocated type
483/// in a new-expression.
484/// dimension off and stores the size expression in ArraySize.
Douglas Gregor3433cf72009-05-21 00:00:09 +0000485bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +0000486 SourceRange R) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000487 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
488 // abstract class type or array thereof.
Douglas Gregore7450f52009-03-24 19:52:54 +0000489 if (AllocType->isFunctionType())
Douglas Gregor3433cf72009-05-21 00:00:09 +0000490 return Diag(Loc, diag::err_bad_new_type)
491 << AllocType << 0 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +0000492 else if (AllocType->isReferenceType())
Douglas Gregor3433cf72009-05-21 00:00:09 +0000493 return Diag(Loc, diag::err_bad_new_type)
494 << AllocType << 1 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +0000495 else if (!AllocType->isDependentType() &&
Douglas Gregor3433cf72009-05-21 00:00:09 +0000496 RequireCompleteType(Loc, AllocType,
Anders Carlssonb7906612009-08-26 23:45:07 +0000497 PDiag(diag::err_new_incomplete_type)
498 << R))
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000499 return true;
Douglas Gregor3433cf72009-05-21 00:00:09 +0000500 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregore7450f52009-03-24 19:52:54 +0000501 diag::err_allocation_of_abstract_type))
502 return true;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000503
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000504 return false;
505}
506
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000507/// FindAllocationFunctions - Finds the overloads of operator new and delete
508/// that are appropriate for the allocation.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000509bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
510 bool UseGlobal, QualType AllocType,
511 bool IsArray, Expr **PlaceArgs,
512 unsigned NumPlaceArgs,
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000513 FunctionDecl *&OperatorNew,
Mike Stump1eb44332009-09-09 15:08:12 +0000514 FunctionDecl *&OperatorDelete) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000515 // --- Choosing an allocation function ---
516 // C++ 5.3.4p8 - 14 & 18
517 // 1) If UseGlobal is true, only look in the global scope. Else, also look
518 // in the scope of the allocated class.
519 // 2) If an array size is given, look for operator new[], else look for
520 // operator new.
521 // 3) The first argument is always size_t. Append the arguments from the
522 // placement form.
523 // FIXME: Also find the appropriate delete operator.
524
525 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
526 // We don't care about the actual value of this argument.
527 // FIXME: Should the Sema create the expression and embed it in the syntax
528 // tree? Or should the consumer just recalculate the value?
Anders Carlssond67c4c32009-08-16 20:29:29 +0000529 IntegerLiteral Size(llvm::APInt::getNullValue(
530 Context.Target.getPointerWidth(0)),
531 Context.getSizeType(),
532 SourceLocation());
533 AllocArgs[0] = &Size;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000534 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
535
536 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
537 IsArray ? OO_Array_New : OO_New);
538 if (AllocType->isRecordType() && !UseGlobal) {
Mike Stump1eb44332009-09-09 15:08:12 +0000539 CXXRecordDecl *Record
Ted Kremenek6217b802009-07-29 21:53:49 +0000540 = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl());
Sebastian Redl7f662392008-12-04 22:20:51 +0000541 // FIXME: We fail to find inherited overloads.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000542 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000543 AllocArgs.size(), Record, /*AllowMissing=*/true,
544 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000545 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000546 }
547 if (!OperatorNew) {
548 // Didn't find a member overload. Look for a global one.
549 DeclareGlobalNewDelete();
Sebastian Redl7f662392008-12-04 22:20:51 +0000550 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl00e68e22009-02-09 18:24:27 +0000551 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000552 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
553 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000554 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000555 }
556
Anders Carlssond9583892009-05-31 20:26:12 +0000557 // FindAllocationOverload can change the passed in arguments, so we need to
558 // copy them back.
559 if (NumPlaceArgs > 0)
560 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
Mike Stump1eb44332009-09-09 15:08:12 +0000561
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000562 return false;
563}
564
Sebastian Redl7f662392008-12-04 22:20:51 +0000565/// FindAllocationOverload - Find an fitting overload for the allocation
566/// function in the specified scope.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000567bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
568 DeclarationName Name, Expr** Args,
569 unsigned NumArgs, DeclContext *Ctx,
Mike Stump1eb44332009-09-09 15:08:12 +0000570 bool AllowMissing, FunctionDecl *&Operator) {
John McCalla24dc2e2009-11-17 02:14:36 +0000571 LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
572 LookupQualifiedName(R, Ctx);
John McCallf36e02d2009-10-09 21:13:30 +0000573 if (R.empty()) {
Sebastian Redl7f662392008-12-04 22:20:51 +0000574 if (AllowMissing)
575 return false;
Sebastian Redl7f662392008-12-04 22:20:51 +0000576 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +0000577 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +0000578 }
579
John McCallf36e02d2009-10-09 21:13:30 +0000580 // FIXME: handle ambiguity
581
Sebastian Redl7f662392008-12-04 22:20:51 +0000582 OverloadCandidateSet Candidates;
Douglas Gregor5d64e5b2009-09-30 00:03:47 +0000583 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
584 Alloc != AllocEnd; ++Alloc) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000585 // Even member operator new/delete are implicitly treated as
586 // static, so don't use AddMemberCandidate.
Douglas Gregor90916562009-09-29 18:16:17 +0000587 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>(*Alloc)) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000588 AddOverloadCandidate(Fn, Args, NumArgs, Candidates,
589 /*SuppressUserConversions=*/false);
Douglas Gregor90916562009-09-29 18:16:17 +0000590 continue;
591 }
592
593 // FIXME: Handle function templates
Sebastian Redl7f662392008-12-04 22:20:51 +0000594 }
595
596 // Do the resolution.
597 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +0000598 switch(BestViableFunction(Candidates, StartLoc, Best)) {
Sebastian Redl7f662392008-12-04 22:20:51 +0000599 case OR_Success: {
600 // Got one!
601 FunctionDecl *FnDecl = Best->Function;
602 // The first argument is size_t, and the first parameter must be size_t,
603 // too. This is checked on declaration and can be assumed. (It can't be
604 // asserted on, though, since invalid decls are left in there.)
Douglas Gregor90916562009-09-29 18:16:17 +0000605 for (unsigned i = 0; i < NumArgs; ++i) {
Sebastian Redl7f662392008-12-04 22:20:51 +0000606 // FIXME: Passing word to diagnostic.
Anders Carlssonfc27d262009-05-31 19:49:47 +0000607 if (PerformCopyInitialization(Args[i],
Sebastian Redl7f662392008-12-04 22:20:51 +0000608 FnDecl->getParamDecl(i)->getType(),
609 "passing"))
610 return true;
611 }
612 Operator = FnDecl;
613 return false;
614 }
615
616 case OR_No_Viable_Function:
Sebastian Redl7f662392008-12-04 22:20:51 +0000617 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +0000618 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +0000619 PrintOverloadCandidates(Candidates, /*OnlyViable=*/false);
620 return true;
621
622 case OR_Ambiguous:
Sebastian Redl7f662392008-12-04 22:20:51 +0000623 Diag(StartLoc, diag::err_ovl_ambiguous_call)
Sebastian Redl00e68e22009-02-09 18:24:27 +0000624 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +0000625 PrintOverloadCandidates(Candidates, /*OnlyViable=*/true);
626 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000627
628 case OR_Deleted:
629 Diag(StartLoc, diag::err_ovl_deleted_call)
630 << Best->Function->isDeleted()
631 << Name << Range;
632 PrintOverloadCandidates(Candidates, /*OnlyViable=*/true);
633 return true;
Sebastian Redl7f662392008-12-04 22:20:51 +0000634 }
635 assert(false && "Unreachable, bad result from BestViableFunction");
636 return true;
637}
638
639
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000640/// DeclareGlobalNewDelete - Declare the global forms of operator new and
641/// delete. These are:
642/// @code
643/// void* operator new(std::size_t) throw(std::bad_alloc);
644/// void* operator new[](std::size_t) throw(std::bad_alloc);
645/// void operator delete(void *) throw();
646/// void operator delete[](void *) throw();
647/// @endcode
648/// Note that the placement and nothrow forms of new are *not* implicitly
649/// declared. Their use requires including \<new\>.
Mike Stump1eb44332009-09-09 15:08:12 +0000650void Sema::DeclareGlobalNewDelete() {
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000651 if (GlobalNewDeleteDeclared)
652 return;
Douglas Gregor7adb10f2009-09-15 22:30:29 +0000653
654 // C++ [basic.std.dynamic]p2:
655 // [...] The following allocation and deallocation functions (18.4) are
656 // implicitly declared in global scope in each translation unit of a
657 // program
658 //
659 // void* operator new(std::size_t) throw(std::bad_alloc);
660 // void* operator new[](std::size_t) throw(std::bad_alloc);
661 // void operator delete(void*) throw();
662 // void operator delete[](void*) throw();
663 //
664 // These implicit declarations introduce only the function names operator
665 // new, operator new[], operator delete, operator delete[].
666 //
667 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
668 // "std" or "bad_alloc" as necessary to form the exception specification.
669 // However, we do not make these implicit declarations visible to name
670 // lookup.
671 if (!StdNamespace) {
672 // The "std" namespace has not yet been defined, so build one implicitly.
673 StdNamespace = NamespaceDecl::Create(Context,
674 Context.getTranslationUnitDecl(),
675 SourceLocation(),
676 &PP.getIdentifierTable().get("std"));
677 StdNamespace->setImplicit(true);
678 }
679
680 if (!StdBadAlloc) {
681 // The "std::bad_alloc" class has not yet been declared, so build it
682 // implicitly.
683 StdBadAlloc = CXXRecordDecl::Create(Context, TagDecl::TK_class,
684 StdNamespace,
685 SourceLocation(),
686 &PP.getIdentifierTable().get("bad_alloc"),
687 SourceLocation(), 0);
688 StdBadAlloc->setImplicit(true);
689 }
690
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000691 GlobalNewDeleteDeclared = true;
692
693 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
694 QualType SizeT = Context.getSizeType();
695
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000696 DeclareGlobalAllocationFunction(
697 Context.DeclarationNames.getCXXOperatorName(OO_New),
698 VoidPtr, SizeT);
699 DeclareGlobalAllocationFunction(
700 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
701 VoidPtr, SizeT);
702 DeclareGlobalAllocationFunction(
703 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
704 Context.VoidTy, VoidPtr);
705 DeclareGlobalAllocationFunction(
706 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
707 Context.VoidTy, VoidPtr);
708}
709
710/// DeclareGlobalAllocationFunction - Declares a single implicit global
711/// allocation function if it doesn't already exist.
712void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Mike Stump1eb44332009-09-09 15:08:12 +0000713 QualType Return, QualType Argument) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000714 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
715
716 // Check if this function is already declared.
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000717 {
Douglas Gregor5cc37092008-12-23 22:05:29 +0000718 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000719 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000720 Alloc != AllocEnd; ++Alloc) {
721 // FIXME: Do we need to check for default arguments here?
722 FunctionDecl *Func = cast<FunctionDecl>(*Alloc);
723 if (Func->getNumParams() == 1 &&
Ted Kremenek8189cde2009-02-07 01:47:29 +0000724 Context.getCanonicalType(Func->getParamDecl(0)->getType())==Argument)
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000725 return;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000726 }
727 }
728
Douglas Gregor7adb10f2009-09-15 22:30:29 +0000729 QualType BadAllocType;
730 bool HasBadAllocExceptionSpec
731 = (Name.getCXXOverloadedOperator() == OO_New ||
732 Name.getCXXOverloadedOperator() == OO_Array_New);
733 if (HasBadAllocExceptionSpec) {
734 assert(StdBadAlloc && "Must have std::bad_alloc declared");
735 BadAllocType = Context.getTypeDeclType(StdBadAlloc);
736 }
737
738 QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0,
739 true, false,
740 HasBadAllocExceptionSpec? 1 : 0,
741 &BadAllocType);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000742 FunctionDecl *Alloc =
743 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +0000744 FnType, /*DInfo=*/0, FunctionDecl::None, false, true);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000745 Alloc->setImplicit();
746 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000747 0, Argument, /*DInfo=*/0,
748 VarDecl::None, 0);
Ted Kremenekfc767612009-01-14 00:42:25 +0000749 Alloc->setParams(Context, &Param, 1);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000750
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000751 // FIXME: Also add this declaration to the IdentifierResolver, but
752 // make sure it is at the end of the chain to coincide with the
753 // global scope.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000754 ((DeclContext *)TUScope->getEntity())->addDecl(Alloc);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000755}
756
Anders Carlsson78f74552009-11-15 18:45:20 +0000757bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
758 DeclarationName Name,
759 FunctionDecl* &Operator) {
John McCalla24dc2e2009-11-17 02:14:36 +0000760 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlsson78f74552009-11-15 18:45:20 +0000761 // Try to find operator delete/operator delete[] in class scope.
John McCalla24dc2e2009-11-17 02:14:36 +0000762 LookupQualifiedName(Found, RD);
Anders Carlsson78f74552009-11-15 18:45:20 +0000763
John McCalla24dc2e2009-11-17 02:14:36 +0000764 if (Found.isAmbiguous())
Anders Carlsson78f74552009-11-15 18:45:20 +0000765 return true;
Anders Carlsson78f74552009-11-15 18:45:20 +0000766
767 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
768 F != FEnd; ++F) {
769 if (CXXMethodDecl *Delete = dyn_cast<CXXMethodDecl>(*F))
770 if (Delete->isUsualDeallocationFunction()) {
771 Operator = Delete;
772 return false;
773 }
774 }
775
776 // We did find operator delete/operator delete[] declarations, but
777 // none of them were suitable.
778 if (!Found.empty()) {
779 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
780 << Name << RD;
781
782 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
783 F != FEnd; ++F) {
784 Diag((*F)->getLocation(),
785 diag::note_delete_member_function_declared_here)
786 << Name;
787 }
788
789 return true;
790 }
791
792 // Look for a global declaration.
793 DeclareGlobalNewDelete();
794 DeclContext *TUDecl = Context.getTranslationUnitDecl();
795
796 CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation());
797 Expr* DeallocArgs[1];
798 DeallocArgs[0] = &Null;
799 if (FindAllocationOverload(StartLoc, SourceRange(), Name,
800 DeallocArgs, 1, TUDecl, /*AllowMissing=*/false,
801 Operator))
802 return true;
803
804 assert(Operator && "Did not find a deallocation function!");
805 return false;
806}
807
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000808/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
809/// @code ::delete ptr; @endcode
810/// or
811/// @code delete [] ptr; @endcode
Sebastian Redlf53597f2009-03-15 17:47:39 +0000812Action::OwningExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000813Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
Mike Stump1eb44332009-09-09 15:08:12 +0000814 bool ArrayForm, ExprArg Operand) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000815 // C++ [expr.delete]p1:
816 // The operand shall have a pointer type, or a class type having a single
817 // conversion function to a pointer type. The result has type void.
818 //
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000819 // DR599 amends "pointer type" to "pointer to object type" in both cases.
820
Anders Carlssond67c4c32009-08-16 20:29:29 +0000821 FunctionDecl *OperatorDelete = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000822
Sebastian Redlf53597f2009-03-15 17:47:39 +0000823 Expr *Ex = (Expr *)Operand.get();
Sebastian Redl28507842009-02-26 14:39:58 +0000824 if (!Ex->isTypeDependent()) {
825 QualType Type = Ex->getType();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000826
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000827 if (const RecordType *Record = Type->getAs<RecordType>()) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000828 llvm::SmallVector<CXXConversionDecl *, 4> ObjectPtrConversions;
Fariborz Jahanian53462782009-09-11 21:44:33 +0000829 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
830 OverloadedFunctionDecl *Conversions =
Fariborz Jahanian62509212009-09-12 18:26:03 +0000831 RD->getVisibleConversionFunctions();
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000832
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000833 for (OverloadedFunctionDecl::function_iterator
834 Func = Conversions->function_begin(),
835 FuncEnd = Conversions->function_end();
836 Func != FuncEnd; ++Func) {
837 // Skip over templated conversion functions; they aren't considered.
838 if (isa<FunctionTemplateDecl>(*Func))
839 continue;
840
841 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
842
843 QualType ConvType = Conv->getConversionType().getNonReferenceType();
844 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
845 if (ConvPtrType->getPointeeType()->isObjectType())
Fariborz Jahanian8b915e72009-09-15 22:15:23 +0000846 ObjectPtrConversions.push_back(Conv);
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000847 }
Fariborz Jahanian8b915e72009-09-15 22:15:23 +0000848 if (ObjectPtrConversions.size() == 1) {
849 // We have a single conversion to a pointer-to-object type. Perform
850 // that conversion.
851 Operand.release();
852 if (!PerformImplicitConversion(Ex,
853 ObjectPtrConversions.front()->getConversionType(),
854 "converting")) {
855 Operand = Owned(Ex);
856 Type = Ex->getType();
857 }
858 }
859 else if (ObjectPtrConversions.size() > 1) {
860 Diag(StartLoc, diag::err_ambiguous_delete_operand)
861 << Type << Ex->getSourceRange();
862 for (unsigned i= 0; i < ObjectPtrConversions.size(); i++) {
863 CXXConversionDecl *Conv = ObjectPtrConversions[i];
864 Diag(Conv->getLocation(), diag::err_ovl_candidate);
865 }
866 return ExprError();
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000867 }
Sebastian Redl28507842009-02-26 14:39:58 +0000868 }
869
Sebastian Redlf53597f2009-03-15 17:47:39 +0000870 if (!Type->isPointerType())
871 return ExprError(Diag(StartLoc, diag::err_delete_operand)
872 << Type << Ex->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +0000873
Ted Kremenek6217b802009-07-29 21:53:49 +0000874 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Douglas Gregor8dcb29d2009-03-24 20:13:58 +0000875 if (Pointee->isFunctionType() || Pointee->isVoidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000876 return ExprError(Diag(StartLoc, diag::err_delete_operand)
877 << Type << Ex->getSourceRange());
Douglas Gregor8dcb29d2009-03-24 20:13:58 +0000878 else if (!Pointee->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +0000879 RequireCompleteType(StartLoc, Pointee,
Anders Carlssonb7906612009-08-26 23:45:07 +0000880 PDiag(diag::warn_delete_incomplete)
881 << Ex->getSourceRange()))
Douglas Gregor8dcb29d2009-03-24 20:13:58 +0000882 return ExprError();
Sebastian Redl28507842009-02-26 14:39:58 +0000883
Douglas Gregor1070c9f2009-09-29 21:38:53 +0000884 // C++ [expr.delete]p2:
885 // [Note: a pointer to a const type can be the operand of a
886 // delete-expression; it is not necessary to cast away the constness
887 // (5.2.11) of the pointer expression before it is used as the operand
888 // of the delete-expression. ]
889 ImpCastExprToType(Ex, Context.getPointerType(Context.VoidTy),
890 CastExpr::CK_NoOp);
891
892 // Update the operand.
893 Operand.take();
894 Operand = ExprArg(*this, Ex);
895
Anders Carlssond67c4c32009-08-16 20:29:29 +0000896 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
897 ArrayForm ? OO_Array_Delete : OO_Delete);
898
Anders Carlsson78f74552009-11-15 18:45:20 +0000899 if (const RecordType *RT = Pointee->getAs<RecordType>()) {
900 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
901
902 if (!UseGlobal &&
903 FindDeallocationFunction(StartLoc, RD, DeleteName, OperatorDelete))
Anders Carlsson0ba63ea2009-11-14 03:17:38 +0000904 return ExprError();
Anders Carlsson0ba63ea2009-11-14 03:17:38 +0000905
Anders Carlsson78f74552009-11-15 18:45:20 +0000906 if (!RD->hasTrivialDestructor())
907 if (const CXXDestructorDecl *Dtor = RD->getDestructor(Context))
Mike Stump1eb44332009-09-09 15:08:12 +0000908 MarkDeclarationReferenced(StartLoc,
Fariborz Jahanian34374e62009-09-03 23:18:17 +0000909 const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssond67c4c32009-08-16 20:29:29 +0000910 }
Anders Carlsson78f74552009-11-15 18:45:20 +0000911
Anders Carlssond67c4c32009-08-16 20:29:29 +0000912 if (!OperatorDelete) {
Anders Carlsson78f74552009-11-15 18:45:20 +0000913 // Look for a global declaration.
Anders Carlssond67c4c32009-08-16 20:29:29 +0000914 DeclareGlobalNewDelete();
915 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000916 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
Douglas Gregor90916562009-09-29 18:16:17 +0000917 &Ex, 1, TUDecl, /*AllowMissing=*/false,
Anders Carlssond67c4c32009-08-16 20:29:29 +0000918 OperatorDelete))
919 return ExprError();
920 }
Mike Stump1eb44332009-09-09 15:08:12 +0000921
Sebastian Redl28507842009-02-26 14:39:58 +0000922 // FIXME: Check access and ambiguity of operator delete and destructor.
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000923 }
924
Sebastian Redlf53597f2009-03-15 17:47:39 +0000925 Operand.release();
926 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
Anders Carlssond67c4c32009-08-16 20:29:29 +0000927 OperatorDelete, Ex, StartLoc));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000928}
929
930
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000931/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
932/// C++ if/switch/while/for statement.
933/// e.g: "if (int x = f()) {...}"
Sebastian Redlf53597f2009-03-15 17:47:39 +0000934Action::OwningExprResult
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000935Sema::ActOnCXXConditionDeclarationExpr(Scope *S, SourceLocation StartLoc,
936 Declarator &D,
937 SourceLocation EqualLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000938 ExprArg AssignExprVal) {
939 assert(AssignExprVal.get() && "Null assignment expression");
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000940
941 // C++ 6.4p2:
942 // The declarator shall not specify a function or an array.
943 // The type-specifier-seq shall not contain typedef and shall not declare a
944 // new class or enumeration.
945
946 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
947 "Parser allowed 'typedef' as storage class of condition decl.");
948
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000949 // FIXME: Store DeclaratorInfo in the expression.
950 DeclaratorInfo *DInfo = 0;
Argyrios Kyrtzidise955e722009-08-11 05:20:41 +0000951 TagDecl *OwnedTag = 0;
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000952 QualType Ty = GetTypeForDeclarator(D, S, &DInfo, &OwnedTag);
Mike Stump1eb44332009-09-09 15:08:12 +0000953
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000954 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
955 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
956 // would be created and CXXConditionDeclExpr wants a VarDecl.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000957 return ExprError(Diag(StartLoc, diag::err_invalid_use_of_function_type)
958 << SourceRange(StartLoc, EqualLoc));
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000959 } else if (Ty->isArrayType()) { // ...or an array.
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000960 Diag(StartLoc, diag::err_invalid_use_of_array_type)
961 << SourceRange(StartLoc, EqualLoc);
Argyrios Kyrtzidise955e722009-08-11 05:20:41 +0000962 } else if (OwnedTag && OwnedTag->isDefinition()) {
963 // The type-specifier-seq shall not declare a new class or enumeration.
964 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000965 }
966
Douglas Gregor2e01cda2009-06-23 21:43:56 +0000967 DeclPtrTy Dcl = ActOnDeclarator(S, D);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000968 if (!Dcl)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000969 return ExprError();
Anders Carlssonf5dcd382009-05-30 21:37:25 +0000970 AddInitializerToDecl(Dcl, move(AssignExprVal), /*DirectInit=*/false);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000971
Douglas Gregorcaaf29a2008-12-10 23:01:14 +0000972 // Mark this variable as one that is declared within a conditional.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000973 // We know that the decl had to be a VarDecl because that is the only type of
974 // decl that can be assigned and the grammar requires an '='.
975 VarDecl *VD = cast<VarDecl>(Dcl.getAs<Decl>());
976 VD->setDeclaredInCondition(true);
977 return Owned(new (Context) CXXConditionDeclExpr(StartLoc, EqualLoc, VD));
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000978}
979
980/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
981bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
982 // C++ 6.4p4:
983 // The value of a condition that is an initialized declaration in a statement
984 // other than a switch statement is the value of the declared variable
985 // implicitly converted to type bool. If that conversion is ill-formed, the
986 // program is ill-formed.
987 // The value of a condition that is an expression is the value of the
988 // expression, implicitly converted to bool.
989 //
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000990 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000991}
Douglas Gregor77a52232008-09-12 00:47:35 +0000992
993/// Helper function to determine whether this is the (deprecated) C++
994/// conversion from a string literal to a pointer to non-const char or
995/// non-const wchar_t (for narrow and wide string literals,
996/// respectively).
Mike Stump1eb44332009-09-09 15:08:12 +0000997bool
Douglas Gregor77a52232008-09-12 00:47:35 +0000998Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
999 // Look inside the implicit cast, if it exists.
1000 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
1001 From = Cast->getSubExpr();
1002
1003 // A string literal (2.13.4) that is not a wide string literal can
1004 // be converted to an rvalue of type "pointer to char"; a wide
1005 // string literal can be converted to an rvalue of type "pointer
1006 // to wchar_t" (C++ 4.2p2).
1007 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From))
Ted Kremenek6217b802009-07-29 21:53:49 +00001008 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump1eb44332009-09-09 15:08:12 +00001009 if (const BuiltinType *ToPointeeType
John McCall183700f2009-09-21 23:43:11 +00001010 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregor77a52232008-09-12 00:47:35 +00001011 // This conversion is considered only when there is an
1012 // explicit appropriate pointer target type (C++ 4.2p2).
John McCall0953e762009-09-24 19:53:00 +00001013 if (!ToPtrType->getPointeeType().hasQualifiers() &&
Douglas Gregor77a52232008-09-12 00:47:35 +00001014 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
1015 (!StrLit->isWide() &&
1016 (ToPointeeType->getKind() == BuiltinType::Char_U ||
1017 ToPointeeType->getKind() == BuiltinType::Char_S))))
1018 return true;
1019 }
1020
1021 return false;
1022}
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001023
1024/// PerformImplicitConversion - Perform an implicit conversion of the
1025/// expression From to the type ToType. Returns true if there was an
1026/// error, false otherwise. The expression From is replaced with the
Douglas Gregor45920e82008-12-19 17:40:08 +00001027/// converted expression. Flavor is the kind of conversion we're
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001028/// performing, used in the error message. If @p AllowExplicit,
Sebastian Redle2b68332009-04-12 17:16:29 +00001029/// explicit user-defined conversions are permitted. @p Elidable should be true
1030/// when called for copies which may be elided (C++ 12.8p15). C++0x overload
1031/// resolution works differently in that case.
1032bool
Douglas Gregor45920e82008-12-19 17:40:08 +00001033Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Sebastian Redle2b68332009-04-12 17:16:29 +00001034 const char *Flavor, bool AllowExplicit,
Mike Stump1eb44332009-09-09 15:08:12 +00001035 bool Elidable) {
Sebastian Redle2b68332009-04-12 17:16:29 +00001036 ImplicitConversionSequence ICS;
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00001037 return PerformImplicitConversion(From, ToType, Flavor, AllowExplicit,
1038 Elidable, ICS);
1039}
1040
1041bool
1042Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
1043 const char *Flavor, bool AllowExplicit,
1044 bool Elidable,
1045 ImplicitConversionSequence& ICS) {
Sebastian Redle2b68332009-04-12 17:16:29 +00001046 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1047 if (Elidable && getLangOptions().CPlusPlus0x) {
Mike Stump1eb44332009-09-09 15:08:12 +00001048 ICS = TryImplicitConversion(From, ToType,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001049 /*SuppressUserConversions=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +00001050 AllowExplicit,
Anders Carlsson08972922009-08-28 15:33:32 +00001051 /*ForceRValue=*/true,
1052 /*InOverloadResolution=*/false);
Sebastian Redle2b68332009-04-12 17:16:29 +00001053 }
1054 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion) {
Mike Stump1eb44332009-09-09 15:08:12 +00001055 ICS = TryImplicitConversion(From, ToType,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001056 /*SuppressUserConversions=*/false,
1057 AllowExplicit,
Anders Carlsson08972922009-08-28 15:33:32 +00001058 /*ForceRValue=*/false,
1059 /*InOverloadResolution=*/false);
Sebastian Redle2b68332009-04-12 17:16:29 +00001060 }
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001061 return PerformImplicitConversion(From, ToType, ICS, Flavor);
1062}
1063
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001064/// BuildCXXDerivedToBaseExpr - This routine generates the suitable AST
1065/// for the derived to base conversion of the expression 'From'. All
1066/// necessary information is passed in ICS.
1067bool
1068Sema::BuildCXXDerivedToBaseExpr(Expr *&From, CastExpr::CastKind CastKind,
1069 const ImplicitConversionSequence& ICS,
1070 const char *Flavor) {
1071 QualType BaseType =
1072 QualType::getFromOpaquePtr(ICS.UserDefined.After.ToTypePtr);
1073 // Must do additional defined to base conversion.
1074 QualType DerivedType =
1075 QualType::getFromOpaquePtr(ICS.UserDefined.After.FromTypePtr);
1076
1077 From = new (Context) ImplicitCastExpr(
1078 DerivedType.getNonReferenceType(),
1079 CastKind,
1080 From,
1081 DerivedType->isLValueReferenceType());
1082 From = new (Context) ImplicitCastExpr(BaseType.getNonReferenceType(),
1083 CastExpr::CK_DerivedToBase, From,
1084 BaseType->isLValueReferenceType());
1085 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1086 OwningExprResult FromResult =
1087 BuildCXXConstructExpr(
1088 ICS.UserDefined.After.CopyConstructor->getLocation(),
1089 BaseType,
1090 ICS.UserDefined.After.CopyConstructor,
1091 MultiExprArg(*this, (void **)&From, 1));
1092 if (FromResult.isInvalid())
1093 return true;
1094 From = FromResult.takeAs<Expr>();
1095 return false;
1096}
1097
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001098/// PerformImplicitConversion - Perform an implicit conversion of the
1099/// expression From to the type ToType using the pre-computed implicit
1100/// conversion sequence ICS. Returns true if there was an error, false
1101/// otherwise. The expression From is replaced with the converted
1102/// expression. Flavor is the kind of conversion we're performing,
1103/// used in the error message.
1104bool
1105Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
1106 const ImplicitConversionSequence &ICS,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001107 const char* Flavor, bool IgnoreBaseAccess) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001108 switch (ICS.ConversionKind) {
1109 case ImplicitConversionSequence::StandardConversion:
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001110 if (PerformImplicitConversion(From, ToType, ICS.Standard, Flavor,
1111 IgnoreBaseAccess))
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001112 return true;
1113 break;
1114
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001115 case ImplicitConversionSequence::UserDefinedConversion: {
1116
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00001117 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
1118 CastExpr::CastKind CastKind = CastExpr::CK_Unknown;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001119 QualType BeforeToType;
1120 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00001121 CastKind = CastExpr::CK_UserDefinedConversion;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001122
1123 // If the user-defined conversion is specified by a conversion function,
1124 // the initial standard conversion sequence converts the source type to
1125 // the implicit object parameter of the conversion function.
1126 BeforeToType = Context.getTagDeclType(Conv->getParent());
1127 } else if (const CXXConstructorDecl *Ctor =
1128 dyn_cast<CXXConstructorDecl>(FD)) {
Anders Carlsson0aebc812009-09-09 21:33:21 +00001129 CastKind = CastExpr::CK_ConstructorConversion;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001130 // Do no conversion if dealing with ... for the first conversion.
1131 if (!ICS.UserDefined.EllipsisConversion)
1132 // If the user-defined conversion is specified by a constructor, the
1133 // initial standard conversion sequence converts the source type to the
1134 // type required by the argument of the constructor
1135 BeforeToType = Ctor->getParamDecl(0)->getType();
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001136 }
Anders Carlsson0aebc812009-09-09 21:33:21 +00001137 else
1138 assert(0 && "Unknown conversion function kind!");
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001139 // Whatch out for elipsis conversion.
Fariborz Jahanian4c0cea22009-11-06 00:55:14 +00001140 if (!ICS.UserDefined.EllipsisConversion) {
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001141 if (PerformImplicitConversion(From, BeforeToType,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001142 ICS.UserDefined.Before, "converting",
1143 IgnoreBaseAccess))
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001144 return true;
1145 }
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001146
Anders Carlsson0aebc812009-09-09 21:33:21 +00001147 OwningExprResult CastArg
1148 = BuildCXXCastArgument(From->getLocStart(),
1149 ToType.getNonReferenceType(),
1150 CastKind, cast<CXXMethodDecl>(FD),
1151 Owned(From));
1152
1153 if (CastArg.isInvalid())
1154 return true;
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001155
1156 if (ICS.UserDefined.After.Second == ICK_Derived_To_Base &&
1157 ICS.UserDefined.After.CopyConstructor) {
1158 From = CastArg.takeAs<Expr>();
1159 return BuildCXXDerivedToBaseExpr(From, CastKind, ICS, Flavor);
1160 }
Fariborz Jahanian7a1f4cc2009-10-23 18:08:22 +00001161
1162 if (ICS.UserDefined.After.Second == ICK_Pointer_Member &&
1163 ToType.getNonReferenceType()->isMemberFunctionPointerType())
1164 CastKind = CastExpr::CK_BaseToDerivedMemberPointer;
Anders Carlsson0aebc812009-09-09 21:33:21 +00001165
Anders Carlsson626c2d62009-09-15 05:49:31 +00001166 From = new (Context) ImplicitCastExpr(ToType.getNonReferenceType(),
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001167 CastKind, CastArg.takeAs<Expr>(),
Anders Carlsson626c2d62009-09-15 05:49:31 +00001168 ToType->isLValueReferenceType());
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00001169 return false;
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001170 }
1171
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001172 case ImplicitConversionSequence::EllipsisConversion:
1173 assert(false && "Cannot perform an ellipsis conversion");
Douglas Gregor60d62c22008-10-31 16:23:19 +00001174 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001175
1176 case ImplicitConversionSequence::BadConversion:
1177 return true;
1178 }
1179
1180 // Everything went well.
1181 return false;
1182}
1183
1184/// PerformImplicitConversion - Perform an implicit conversion of the
1185/// expression From to the type ToType by following the standard
1186/// conversion sequence SCS. Returns true if there was an error, false
1187/// otherwise. The expression From is replaced with the converted
Douglas Gregor45920e82008-12-19 17:40:08 +00001188/// expression. Flavor is the context in which we're performing this
1189/// conversion, for use in error messages.
Mike Stump1eb44332009-09-09 15:08:12 +00001190bool
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001191Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor45920e82008-12-19 17:40:08 +00001192 const StandardConversionSequence& SCS,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001193 const char *Flavor, bool IgnoreBaseAccess) {
Mike Stump390b4cc2009-05-16 07:39:55 +00001194 // Overall FIXME: we are recomputing too many types here and doing far too
1195 // much extra work. What this means is that we need to keep track of more
1196 // information that is computed when we try the implicit conversion initially,
1197 // so that we don't need to recompute anything here.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001198 QualType FromType = From->getType();
1199
Douglas Gregor225c41e2008-11-03 19:09:14 +00001200 if (SCS.CopyConstructor) {
Anders Carlsson7c3e8a12009-05-19 04:45:15 +00001201 // FIXME: When can ToType be a reference type?
1202 assert(!ToType->isReferenceType());
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00001203 if (SCS.Second == ICK_Derived_To_Base) {
1204 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1205 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
1206 MultiExprArg(*this, (void **)&From, 1),
1207 /*FIXME:ConstructLoc*/SourceLocation(),
1208 ConstructorArgs))
1209 return true;
1210 OwningExprResult FromResult =
1211 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1212 ToType, SCS.CopyConstructor,
1213 move_arg(ConstructorArgs));
1214 if (FromResult.isInvalid())
1215 return true;
1216 From = FromResult.takeAs<Expr>();
1217 return false;
1218 }
Mike Stump1eb44332009-09-09 15:08:12 +00001219 OwningExprResult FromResult =
1220 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1221 ToType, SCS.CopyConstructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00001222 MultiExprArg(*this, (void**)&From, 1));
Mike Stump1eb44332009-09-09 15:08:12 +00001223
Anders Carlssonda3f4e22009-08-25 05:12:04 +00001224 if (FromResult.isInvalid())
1225 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001226
Anders Carlssonda3f4e22009-08-25 05:12:04 +00001227 From = FromResult.takeAs<Expr>();
Douglas Gregor225c41e2008-11-03 19:09:14 +00001228 return false;
1229 }
1230
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001231 // Perform the first implicit conversion.
1232 switch (SCS.First) {
1233 case ICK_Identity:
1234 case ICK_Lvalue_To_Rvalue:
1235 // Nothing to do.
1236 break;
1237
1238 case ICK_Array_To_Pointer:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001239 FromType = Context.getArrayDecayedType(FromType);
Anders Carlsson82495762009-08-08 21:04:35 +00001240 ImpCastExprToType(From, FromType, CastExpr::CK_ArrayToPointerDecay);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001241 break;
1242
1243 case ICK_Function_To_Pointer:
Douglas Gregor063daf62009-03-13 18:40:31 +00001244 if (Context.getCanonicalType(FromType) == Context.OverloadTy) {
Douglas Gregor904eed32008-11-10 20:40:00 +00001245 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, true);
1246 if (!Fn)
1247 return true;
1248
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001249 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
1250 return true;
1251
Anders Carlsson96ad5332009-10-21 17:16:23 +00001252 From = FixOverloadedFunctionReference(From, Fn);
Douglas Gregor904eed32008-11-10 20:40:00 +00001253 FromType = From->getType();
Anders Carlsson96ad5332009-10-21 17:16:23 +00001254
Sebastian Redl759986e2009-10-17 20:50:27 +00001255 // If there's already an address-of operator in the expression, we have
1256 // the right type already, and the code below would just introduce an
1257 // invalid additional pointer level.
Anders Carlsson96ad5332009-10-21 17:16:23 +00001258 if (FromType->isPointerType() || FromType->isMemberFunctionPointerType())
Sebastian Redl759986e2009-10-17 20:50:27 +00001259 break;
Douglas Gregor904eed32008-11-10 20:40:00 +00001260 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001261 FromType = Context.getPointerType(FromType);
Anders Carlssonb633c4e2009-09-01 20:37:18 +00001262 ImpCastExprToType(From, FromType, CastExpr::CK_FunctionToPointerDecay);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001263 break;
1264
1265 default:
1266 assert(false && "Improper first standard conversion");
1267 break;
1268 }
1269
1270 // Perform the second implicit conversion
1271 switch (SCS.Second) {
1272 case ICK_Identity:
Sebastian Redl2c7588f2009-10-10 12:04:10 +00001273 // If both sides are functions (or pointers/references to them), there could
1274 // be incompatible exception declarations.
1275 if (CheckExceptionSpecCompatibility(From, ToType))
1276 return true;
1277 // Nothing else to do.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001278 break;
1279
1280 case ICK_Integral_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001281 case ICK_Integral_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001282 ImpCastExprToType(From, ToType, CastExpr::CK_IntegralCast);
1283 break;
1284
1285 case ICK_Floating_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001286 case ICK_Floating_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001287 ImpCastExprToType(From, ToType, CastExpr::CK_FloatingCast);
1288 break;
1289
1290 case ICK_Complex_Promotion:
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001291 case ICK_Complex_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001292 ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1293 break;
1294
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001295 case ICK_Floating_Integral:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001296 if (ToType->isFloatingType())
1297 ImpCastExprToType(From, ToType, CastExpr::CK_IntegralToFloating);
1298 else
1299 ImpCastExprToType(From, ToType, CastExpr::CK_FloatingToIntegral);
1300 break;
1301
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001302 case ICK_Complex_Real:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001303 ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1304 break;
1305
Douglas Gregorf9201e02009-02-11 23:02:49 +00001306 case ICK_Compatible_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001307 ImpCastExprToType(From, ToType, CastExpr::CK_NoOp);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001308 break;
1309
Anders Carlsson61faec12009-09-12 04:46:44 +00001310 case ICK_Pointer_Conversion: {
Douglas Gregor45920e82008-12-19 17:40:08 +00001311 if (SCS.IncompatibleObjC) {
1312 // Diagnose incompatible Objective-C conversions
Mike Stump1eb44332009-09-09 15:08:12 +00001313 Diag(From->getSourceRange().getBegin(),
Douglas Gregor45920e82008-12-19 17:40:08 +00001314 diag::ext_typecheck_convert_incompatible_pointer)
1315 << From->getType() << ToType << Flavor
1316 << From->getSourceRange();
1317 }
1318
Anders Carlsson61faec12009-09-12 04:46:44 +00001319
1320 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001321 if (CheckPointerConversion(From, ToType, Kind, IgnoreBaseAccess))
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001322 return true;
Anders Carlsson61faec12009-09-12 04:46:44 +00001323 ImpCastExprToType(From, ToType, Kind);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001324 break;
Anders Carlsson61faec12009-09-12 04:46:44 +00001325 }
1326
1327 case ICK_Pointer_Member: {
1328 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001329 if (CheckMemberPointerConversion(From, ToType, Kind, IgnoreBaseAccess))
Anders Carlsson61faec12009-09-12 04:46:44 +00001330 return true;
Sebastian Redl2c7588f2009-10-10 12:04:10 +00001331 if (CheckExceptionSpecCompatibility(From, ToType))
1332 return true;
Anders Carlsson61faec12009-09-12 04:46:44 +00001333 ImpCastExprToType(From, ToType, Kind);
1334 break;
1335 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001336 case ICK_Boolean_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001337 ImpCastExprToType(From, Context.BoolTy, CastExpr::CK_Unknown);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001338 break;
1339
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001340 case ICK_Derived_To_Base:
1341 if (CheckDerivedToBaseConversion(From->getType(),
1342 ToType.getNonReferenceType(),
1343 From->getLocStart(),
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001344 From->getSourceRange(),
1345 IgnoreBaseAccess))
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001346 return true;
1347 ImpCastExprToType(From, ToType.getNonReferenceType(),
1348 CastExpr::CK_DerivedToBase);
1349 break;
1350
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001351 default:
1352 assert(false && "Improper second standard conversion");
1353 break;
1354 }
1355
1356 switch (SCS.Third) {
1357 case ICK_Identity:
1358 // Nothing to do.
1359 break;
1360
1361 case ICK_Qualification:
Mike Stump390b4cc2009-05-16 07:39:55 +00001362 // FIXME: Not sure about lvalue vs rvalue here in the presence of rvalue
1363 // references.
Mike Stump1eb44332009-09-09 15:08:12 +00001364 ImpCastExprToType(From, ToType.getNonReferenceType(),
Eli Friedman73c39ab2009-10-20 08:27:19 +00001365 CastExpr::CK_NoOp,
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001366 ToType->isLValueReferenceType());
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001367 break;
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001368
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001369 default:
1370 assert(false && "Improper second standard conversion");
1371 break;
1372 }
1373
1374 return false;
1375}
1376
Sebastian Redl64b45f72009-01-05 20:52:13 +00001377Sema::OwningExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
1378 SourceLocation KWLoc,
1379 SourceLocation LParen,
1380 TypeTy *Ty,
1381 SourceLocation RParen) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00001382 QualType T = GetTypeFromParser(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00001383
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001384 // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
1385 // all traits except __is_class, __is_enum and __is_union require a the type
1386 // to be complete.
1387 if (OTT != UTT_IsClass && OTT != UTT_IsEnum && OTT != UTT_IsUnion) {
Mike Stump1eb44332009-09-09 15:08:12 +00001388 if (RequireCompleteType(KWLoc, T,
Anders Carlssond497ba72009-08-26 22:59:12 +00001389 diag::err_incomplete_type_used_in_type_trait_expr))
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001390 return ExprError();
1391 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00001392
1393 // There is no point in eagerly computing the value. The traits are designed
1394 // to be used from type trait templates, so Ty will be a template parameter
1395 // 99% of the time.
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001396 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT, T,
1397 RParen, Context.BoolTy));
Sebastian Redl64b45f72009-01-05 20:52:13 +00001398}
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001399
1400QualType Sema::CheckPointerToMemberOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00001401 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001402 const char *OpSpelling = isIndirect ? "->*" : ".*";
1403 // C++ 5.5p2
1404 // The binary operator .* [p3: ->*] binds its second operand, which shall
1405 // be of type "pointer to member of T" (where T is a completely-defined
1406 // class type) [...]
1407 QualType RType = rex->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001408 const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
Douglas Gregore7450f52009-03-24 19:52:54 +00001409 if (!MemPtr) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001410 Diag(Loc, diag::err_bad_memptr_rhs)
1411 << OpSpelling << RType << rex->getSourceRange();
1412 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00001413 }
Douglas Gregore7450f52009-03-24 19:52:54 +00001414
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001415 QualType Class(MemPtr->getClass(), 0);
1416
1417 // C++ 5.5p2
1418 // [...] to its first operand, which shall be of class T or of a class of
1419 // which T is an unambiguous and accessible base class. [p3: a pointer to
1420 // such a class]
1421 QualType LType = lex->getType();
1422 if (isIndirect) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001423 if (const PointerType *Ptr = LType->getAs<PointerType>())
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001424 LType = Ptr->getPointeeType().getNonReferenceType();
1425 else {
1426 Diag(Loc, diag::err_bad_memptr_lhs)
Fariborz Jahanianef78ac62009-10-26 20:45:27 +00001427 << OpSpelling << 1 << LType
1428 << CodeModificationHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001429 return QualType();
1430 }
1431 }
1432
Douglas Gregora4923eb2009-11-16 21:35:15 +00001433 if (!Context.hasSameUnqualifiedType(Class, LType)) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001434 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1435 /*DetectVirtual=*/false);
Mike Stump390b4cc2009-05-16 07:39:55 +00001436 // FIXME: Would it be useful to print full ambiguity paths, or is that
1437 // overkill?
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001438 if (!IsDerivedFrom(LType, Class, Paths) ||
1439 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
Fariborz Jahanianef78ac62009-10-26 20:45:27 +00001440 const char *ReplaceStr = isIndirect ? ".*" : "->*";
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001441 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Fariborz Jahanianef78ac62009-10-26 20:45:27 +00001442 << (int)isIndirect << lex->getType() <<
1443 CodeModificationHint::CreateReplacement(SourceRange(Loc), ReplaceStr);
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001444 return QualType();
1445 }
1446 }
1447
1448 // C++ 5.5p2
1449 // The result is an object or a function of the type specified by the
1450 // second operand.
1451 // The cv qualifiers are the union of those in the pointer and the left side,
1452 // in accordance with 5.5p5 and 5.2.5.
1453 // FIXME: This returns a dereferenced member function pointer as a normal
1454 // function type. However, the only operation valid on such functions is
Mike Stump390b4cc2009-05-16 07:39:55 +00001455 // calling them. There's also a GCC extension to get a function pointer to the
1456 // thing, which is another complication, because this type - unlike the type
1457 // that is the result of this expression - takes the class as the first
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001458 // argument.
1459 // We probably need a "MemberFunctionClosureType" or something like that.
1460 QualType Result = MemPtr->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00001461 Result = Context.getCVRQualifiedType(Result, LType.getCVRQualifiers());
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001462 return Result;
1463}
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001464
1465/// \brief Get the target type of a standard or user-defined conversion.
1466static QualType TargetType(const ImplicitConversionSequence &ICS) {
1467 assert((ICS.ConversionKind ==
1468 ImplicitConversionSequence::StandardConversion ||
1469 ICS.ConversionKind ==
1470 ImplicitConversionSequence::UserDefinedConversion) &&
1471 "function only valid for standard or user-defined conversions");
1472 if (ICS.ConversionKind == ImplicitConversionSequence::StandardConversion)
1473 return QualType::getFromOpaquePtr(ICS.Standard.ToTypePtr);
1474 return QualType::getFromOpaquePtr(ICS.UserDefined.After.ToTypePtr);
1475}
1476
1477/// \brief Try to convert a type to another according to C++0x 5.16p3.
1478///
1479/// This is part of the parameter validation for the ? operator. If either
1480/// value operand is a class type, the two operands are attempted to be
1481/// converted to each other. This function does the conversion in one direction.
1482/// It emits a diagnostic and returns true only if it finds an ambiguous
1483/// conversion.
1484static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
1485 SourceLocation QuestionLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00001486 ImplicitConversionSequence &ICS) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001487 // C++0x 5.16p3
1488 // The process for determining whether an operand expression E1 of type T1
1489 // can be converted to match an operand expression E2 of type T2 is defined
1490 // as follows:
1491 // -- If E2 is an lvalue:
1492 if (To->isLvalue(Self.Context) == Expr::LV_Valid) {
1493 // E1 can be converted to match E2 if E1 can be implicitly converted to
1494 // type "lvalue reference to T2", subject to the constraint that in the
1495 // conversion the reference must bind directly to E1.
1496 if (!Self.CheckReferenceInit(From,
1497 Self.Context.getLValueReferenceType(To->getType()),
Douglas Gregor739d8282009-09-23 23:04:10 +00001498 To->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001499 /*SuppressUserConversions=*/false,
1500 /*AllowExplicit=*/false,
1501 /*ForceRValue=*/false,
1502 &ICS))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001503 {
1504 assert((ICS.ConversionKind ==
1505 ImplicitConversionSequence::StandardConversion ||
1506 ICS.ConversionKind ==
1507 ImplicitConversionSequence::UserDefinedConversion) &&
1508 "expected a definite conversion");
1509 bool DirectBinding =
1510 ICS.ConversionKind == ImplicitConversionSequence::StandardConversion ?
1511 ICS.Standard.DirectBinding : ICS.UserDefined.After.DirectBinding;
1512 if (DirectBinding)
1513 return false;
1514 }
1515 }
1516 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1517 // -- If E2 is an rvalue, or if the conversion above cannot be done:
1518 // -- if E1 and E2 have class type, and the underlying class types are
1519 // the same or one is a base class of the other:
1520 QualType FTy = From->getType();
1521 QualType TTy = To->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001522 const RecordType *FRec = FTy->getAs<RecordType>();
1523 const RecordType *TRec = TTy->getAs<RecordType>();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001524 bool FDerivedFromT = FRec && TRec && Self.IsDerivedFrom(FTy, TTy);
1525 if (FRec && TRec && (FRec == TRec ||
1526 FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
1527 // E1 can be converted to match E2 if the class of T2 is the
1528 // same type as, or a base class of, the class of T1, and
1529 // [cv2 > cv1].
1530 if ((FRec == TRec || FDerivedFromT) && TTy.isAtLeastAsQualifiedAs(FTy)) {
1531 // Could still fail if there's no copy constructor.
1532 // FIXME: Is this a hard error then, or just a conversion failure? The
1533 // standard doesn't say.
Mike Stump1eb44332009-09-09 15:08:12 +00001534 ICS = Self.TryCopyInitialization(From, TTy,
Anders Carlssond28b4282009-08-27 17:18:13 +00001535 /*SuppressUserConversions=*/false,
Anders Carlsson7b361b52009-08-27 17:37:39 +00001536 /*ForceRValue=*/false,
1537 /*InOverloadResolution=*/false);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001538 }
1539 } else {
1540 // -- Otherwise: E1 can be converted to match E2 if E1 can be
1541 // implicitly converted to the type that expression E2 would have
1542 // if E2 were converted to an rvalue.
1543 // First find the decayed type.
1544 if (TTy->isFunctionType())
1545 TTy = Self.Context.getPointerType(TTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001546 else if (TTy->isArrayType())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001547 TTy = Self.Context.getArrayDecayedType(TTy);
1548
1549 // Now try the implicit conversion.
1550 // FIXME: This doesn't detect ambiguities.
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001551 ICS = Self.TryImplicitConversion(From, TTy,
1552 /*SuppressUserConversions=*/false,
1553 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00001554 /*ForceRValue=*/false,
1555 /*InOverloadResolution=*/false);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001556 }
1557 return false;
1558}
1559
1560/// \brief Try to find a common type for two according to C++0x 5.16p5.
1561///
1562/// This is part of the parameter validation for the ? operator. If either
1563/// value operand is a class type, overload resolution is used to find a
1564/// conversion to a common type.
1565static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
1566 SourceLocation Loc) {
1567 Expr *Args[2] = { LHS, RHS };
1568 OverloadCandidateSet CandidateSet;
Douglas Gregor573d9c32009-10-21 23:19:44 +00001569 Self.AddBuiltinOperatorCandidates(OO_Conditional, Loc, Args, 2, CandidateSet);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001570
1571 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00001572 switch (Self.BestViableFunction(CandidateSet, Loc, Best)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001573 case Sema::OR_Success:
1574 // We found a match. Perform the conversions on the arguments and move on.
1575 if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
1576 Best->Conversions[0], "converting") ||
1577 Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
1578 Best->Conversions[1], "converting"))
1579 break;
1580 return false;
1581
1582 case Sema::OR_No_Viable_Function:
1583 Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
1584 << LHS->getType() << RHS->getType()
1585 << LHS->getSourceRange() << RHS->getSourceRange();
1586 return true;
1587
1588 case Sema::OR_Ambiguous:
1589 Self.Diag(Loc, diag::err_conditional_ambiguous_ovl)
1590 << LHS->getType() << RHS->getType()
1591 << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stump390b4cc2009-05-16 07:39:55 +00001592 // FIXME: Print the possible common types by printing the return types of
1593 // the viable candidates.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001594 break;
1595
1596 case Sema::OR_Deleted:
1597 assert(false && "Conditional operator has only built-in overloads");
1598 break;
1599 }
1600 return true;
1601}
1602
Sebastian Redl76458502009-04-17 16:30:52 +00001603/// \brief Perform an "extended" implicit conversion as returned by
1604/// TryClassUnification.
1605///
1606/// TryClassUnification generates ICSs that include reference bindings.
1607/// PerformImplicitConversion is not suitable for this; it chokes if the
1608/// second part of a standard conversion is ICK_DerivedToBase. This function
1609/// handles the reference binding specially.
1610static bool ConvertForConditional(Sema &Self, Expr *&E,
Mike Stump1eb44332009-09-09 15:08:12 +00001611 const ImplicitConversionSequence &ICS) {
Sebastian Redl76458502009-04-17 16:30:52 +00001612 if (ICS.ConversionKind == ImplicitConversionSequence::StandardConversion &&
1613 ICS.Standard.ReferenceBinding) {
1614 assert(ICS.Standard.DirectBinding &&
1615 "TryClassUnification should never generate indirect ref bindings");
Sebastian Redla5cd2cd2009-04-26 11:21:02 +00001616 // FIXME: CheckReferenceInit should be able to reuse the ICS instead of
1617 // redoing all the work.
1618 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001619 TargetType(ICS)),
Douglas Gregor739d8282009-09-23 23:04:10 +00001620 /*FIXME:*/E->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001621 /*SuppressUserConversions=*/false,
1622 /*AllowExplicit=*/false,
1623 /*ForceRValue=*/false);
Sebastian Redl76458502009-04-17 16:30:52 +00001624 }
1625 if (ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion &&
1626 ICS.UserDefined.After.ReferenceBinding) {
1627 assert(ICS.UserDefined.After.DirectBinding &&
1628 "TryClassUnification should never generate indirect ref bindings");
Sebastian Redla5cd2cd2009-04-26 11:21:02 +00001629 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001630 TargetType(ICS)),
Douglas Gregor739d8282009-09-23 23:04:10 +00001631 /*FIXME:*/E->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001632 /*SuppressUserConversions=*/false,
1633 /*AllowExplicit=*/false,
1634 /*ForceRValue=*/false);
Sebastian Redl76458502009-04-17 16:30:52 +00001635 }
1636 if (Self.PerformImplicitConversion(E, TargetType(ICS), ICS, "converting"))
1637 return true;
1638 return false;
1639}
1640
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001641/// \brief Check the operands of ?: under C++ semantics.
1642///
1643/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
1644/// extension. In this case, LHS == Cond. (But they're not aliases.)
1645QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
1646 SourceLocation QuestionLoc) {
Mike Stump390b4cc2009-05-16 07:39:55 +00001647 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
1648 // interface pointers.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001649
1650 // C++0x 5.16p1
1651 // The first expression is contextually converted to bool.
1652 if (!Cond->isTypeDependent()) {
1653 if (CheckCXXBooleanCondition(Cond))
1654 return QualType();
1655 }
1656
1657 // Either of the arguments dependent?
1658 if (LHS->isTypeDependent() || RHS->isTypeDependent())
1659 return Context.DependentTy;
1660
John McCallb13c87f2009-11-05 09:23:39 +00001661 CheckSignCompare(LHS, RHS, QuestionLoc, diag::warn_mixed_sign_conditional);
1662
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001663 // C++0x 5.16p2
1664 // If either the second or the third operand has type (cv) void, ...
1665 QualType LTy = LHS->getType();
1666 QualType RTy = RHS->getType();
1667 bool LVoid = LTy->isVoidType();
1668 bool RVoid = RTy->isVoidType();
1669 if (LVoid || RVoid) {
1670 // ... then the [l2r] conversions are performed on the second and third
1671 // operands ...
1672 DefaultFunctionArrayConversion(LHS);
1673 DefaultFunctionArrayConversion(RHS);
1674 LTy = LHS->getType();
1675 RTy = RHS->getType();
1676
1677 // ... and one of the following shall hold:
1678 // -- The second or the third operand (but not both) is a throw-
1679 // expression; the result is of the type of the other and is an rvalue.
1680 bool LThrow = isa<CXXThrowExpr>(LHS);
1681 bool RThrow = isa<CXXThrowExpr>(RHS);
1682 if (LThrow && !RThrow)
1683 return RTy;
1684 if (RThrow && !LThrow)
1685 return LTy;
1686
1687 // -- Both the second and third operands have type void; the result is of
1688 // type void and is an rvalue.
1689 if (LVoid && RVoid)
1690 return Context.VoidTy;
1691
1692 // Neither holds, error.
1693 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
1694 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
1695 << LHS->getSourceRange() << RHS->getSourceRange();
1696 return QualType();
1697 }
1698
1699 // Neither is void.
1700
1701 // C++0x 5.16p3
1702 // Otherwise, if the second and third operand have different types, and
1703 // either has (cv) class type, and attempt is made to convert each of those
1704 // operands to the other.
1705 if (Context.getCanonicalType(LTy) != Context.getCanonicalType(RTy) &&
1706 (LTy->isRecordType() || RTy->isRecordType())) {
1707 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
1708 // These return true if a single direction is already ambiguous.
1709 if (TryClassUnification(*this, LHS, RHS, QuestionLoc, ICSLeftToRight))
1710 return QualType();
1711 if (TryClassUnification(*this, RHS, LHS, QuestionLoc, ICSRightToLeft))
1712 return QualType();
1713
1714 bool HaveL2R = ICSLeftToRight.ConversionKind !=
1715 ImplicitConversionSequence::BadConversion;
1716 bool HaveR2L = ICSRightToLeft.ConversionKind !=
1717 ImplicitConversionSequence::BadConversion;
1718 // If both can be converted, [...] the program is ill-formed.
1719 if (HaveL2R && HaveR2L) {
1720 Diag(QuestionLoc, diag::err_conditional_ambiguous)
1721 << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
1722 return QualType();
1723 }
1724
1725 // If exactly one conversion is possible, that conversion is applied to
1726 // the chosen operand and the converted operands are used in place of the
1727 // original operands for the remainder of this section.
1728 if (HaveL2R) {
Sebastian Redl76458502009-04-17 16:30:52 +00001729 if (ConvertForConditional(*this, LHS, ICSLeftToRight))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001730 return QualType();
1731 LTy = LHS->getType();
1732 } else if (HaveR2L) {
Sebastian Redl76458502009-04-17 16:30:52 +00001733 if (ConvertForConditional(*this, RHS, ICSRightToLeft))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001734 return QualType();
1735 RTy = RHS->getType();
1736 }
1737 }
1738
1739 // C++0x 5.16p4
1740 // If the second and third operands are lvalues and have the same type,
1741 // the result is of that type [...]
1742 bool Same = Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy);
1743 if (Same && LHS->isLvalue(Context) == Expr::LV_Valid &&
1744 RHS->isLvalue(Context) == Expr::LV_Valid)
1745 return LTy;
1746
1747 // C++0x 5.16p5
1748 // Otherwise, the result is an rvalue. If the second and third operands
1749 // do not have the same type, and either has (cv) class type, ...
1750 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
1751 // ... overload resolution is used to determine the conversions (if any)
1752 // to be applied to the operands. If the overload resolution fails, the
1753 // program is ill-formed.
1754 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
1755 return QualType();
1756 }
1757
1758 // C++0x 5.16p6
1759 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
1760 // conversions are performed on the second and third operands.
1761 DefaultFunctionArrayConversion(LHS);
1762 DefaultFunctionArrayConversion(RHS);
1763 LTy = LHS->getType();
1764 RTy = RHS->getType();
1765
1766 // After those conversions, one of the following shall hold:
1767 // -- The second and third operands have the same type; the result
1768 // is of that type.
1769 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy))
1770 return LTy;
1771
1772 // -- The second and third operands have arithmetic or enumeration type;
1773 // the usual arithmetic conversions are performed to bring them to a
1774 // common type, and the result is of that type.
1775 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
1776 UsualArithmeticConversions(LHS, RHS);
1777 return LHS->getType();
1778 }
1779
1780 // -- The second and third operands have pointer type, or one has pointer
1781 // type and the other is a null pointer constant; pointer conversions
1782 // and qualification conversions are performed to bring them to their
1783 // composite pointer type. The result is of the composite pointer type.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001784 QualType Composite = FindCompositePointerType(LHS, RHS);
1785 if (!Composite.isNull())
1786 return Composite;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001787
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001788 // Fourth bullet is same for pointers-to-member. However, the possible
1789 // conversions are far more limited: we have null-to-pointer, upcast of
1790 // containing class, and second-level cv-ness.
1791 // cv-ness is not a union, but must match one of the two operands. (Which,
1792 // frankly, is stupid.)
Ted Kremenek6217b802009-07-29 21:53:49 +00001793 const MemberPointerType *LMemPtr = LTy->getAs<MemberPointerType>();
1794 const MemberPointerType *RMemPtr = RTy->getAs<MemberPointerType>();
Douglas Gregorce940492009-09-25 04:25:58 +00001795 if (LMemPtr &&
1796 RHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00001797 ImpCastExprToType(RHS, LTy, CastExpr::CK_NullToMemberPointer);
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001798 return LTy;
1799 }
Douglas Gregorce940492009-09-25 04:25:58 +00001800 if (RMemPtr &&
1801 LHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00001802 ImpCastExprToType(LHS, RTy, CastExpr::CK_NullToMemberPointer);
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001803 return RTy;
1804 }
1805 if (LMemPtr && RMemPtr) {
1806 QualType LPointee = LMemPtr->getPointeeType();
1807 QualType RPointee = RMemPtr->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00001808
1809 QualifierCollector LPQuals, RPQuals;
1810 const Type *LPCan = LPQuals.strip(Context.getCanonicalType(LPointee));
1811 const Type *RPCan = RPQuals.strip(Context.getCanonicalType(RPointee));
1812
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001813 // First, we check that the unqualified pointee type is the same. If it's
1814 // not, there's no conversion that will unify the two pointers.
John McCall0953e762009-09-24 19:53:00 +00001815 if (LPCan == RPCan) {
1816
1817 // Second, we take the greater of the two qualifications. If neither
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001818 // is greater than the other, the conversion is not possible.
John McCall0953e762009-09-24 19:53:00 +00001819
1820 Qualifiers MergedQuals = LPQuals + RPQuals;
1821
1822 bool CompatibleQuals = true;
1823 if (MergedQuals.getCVRQualifiers() != LPQuals.getCVRQualifiers() &&
1824 MergedQuals.getCVRQualifiers() != RPQuals.getCVRQualifiers())
1825 CompatibleQuals = false;
1826 else if (LPQuals.getAddressSpace() != RPQuals.getAddressSpace())
1827 // FIXME:
1828 // C99 6.5.15 as modified by TR 18037:
1829 // If the second and third operands are pointers into different
1830 // address spaces, the address spaces must overlap.
1831 CompatibleQuals = false;
1832 // FIXME: GC qualifiers?
1833
1834 if (CompatibleQuals) {
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001835 // Third, we check if either of the container classes is derived from
1836 // the other.
1837 QualType LContainer(LMemPtr->getClass(), 0);
1838 QualType RContainer(RMemPtr->getClass(), 0);
1839 QualType MoreDerived;
1840 if (Context.getCanonicalType(LContainer) ==
1841 Context.getCanonicalType(RContainer))
1842 MoreDerived = LContainer;
1843 else if (IsDerivedFrom(LContainer, RContainer))
1844 MoreDerived = LContainer;
1845 else if (IsDerivedFrom(RContainer, LContainer))
1846 MoreDerived = RContainer;
1847
1848 if (!MoreDerived.isNull()) {
1849 // The type 'Q Pointee (MoreDerived::*)' is the common type.
1850 // We don't use ImpCastExprToType here because this could still fail
1851 // for ambiguous or inaccessible conversions.
John McCall0953e762009-09-24 19:53:00 +00001852 LPointee = Context.getQualifiedType(LPointee, MergedQuals);
1853 QualType Common
1854 = Context.getMemberPointerType(LPointee, MoreDerived.getTypePtr());
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001855 if (PerformImplicitConversion(LHS, Common, "converting"))
1856 return QualType();
1857 if (PerformImplicitConversion(RHS, Common, "converting"))
1858 return QualType();
1859 return Common;
1860 }
1861 }
1862 }
1863 }
1864
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001865 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
1866 << LHS->getType() << RHS->getType()
1867 << LHS->getSourceRange() << RHS->getSourceRange();
1868 return QualType();
1869}
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001870
1871/// \brief Find a merged pointer type and convert the two expressions to it.
1872///
Douglas Gregor20b3e992009-08-24 17:42:35 +00001873/// This finds the composite pointer type (or member pointer type) for @p E1
1874/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
1875/// type and returns it.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001876/// It does not emit diagnostics.
1877QualType Sema::FindCompositePointerType(Expr *&E1, Expr *&E2) {
1878 assert(getLangOptions().CPlusPlus && "This function assumes C++");
1879 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001880
Douglas Gregor20b3e992009-08-24 17:42:35 +00001881 if (!T1->isPointerType() && !T1->isMemberPointerType() &&
1882 !T2->isPointerType() && !T2->isMemberPointerType())
1883 return QualType();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001884
1885 // C++0x 5.9p2
1886 // Pointer conversions and qualification conversions are performed on
1887 // pointer operands to bring them to their composite pointer type. If
1888 // one operand is a null pointer constant, the composite pointer type is
1889 // the type of the other operand.
Douglas Gregorce940492009-09-25 04:25:58 +00001890 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00001891 if (T2->isMemberPointerType())
1892 ImpCastExprToType(E1, T2, CastExpr::CK_NullToMemberPointer);
1893 else
1894 ImpCastExprToType(E1, T2, CastExpr::CK_IntegralToPointer);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001895 return T2;
1896 }
Douglas Gregorce940492009-09-25 04:25:58 +00001897 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00001898 if (T1->isMemberPointerType())
1899 ImpCastExprToType(E2, T1, CastExpr::CK_NullToMemberPointer);
1900 else
1901 ImpCastExprToType(E2, T1, CastExpr::CK_IntegralToPointer);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001902 return T1;
1903 }
Mike Stump1eb44332009-09-09 15:08:12 +00001904
Douglas Gregor20b3e992009-08-24 17:42:35 +00001905 // Now both have to be pointers or member pointers.
Sebastian Redla439e6f2009-11-16 21:03:45 +00001906 if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
1907 (!T2->isPointerType() && !T2->isMemberPointerType()))
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001908 return QualType();
1909
1910 // Otherwise, of one of the operands has type "pointer to cv1 void," then
1911 // the other has type "pointer to cv2 T" and the composite pointer type is
1912 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
1913 // Otherwise, the composite pointer type is a pointer type similar to the
1914 // type of one of the operands, with a cv-qualification signature that is
1915 // the union of the cv-qualification signatures of the operand types.
1916 // In practice, the first part here is redundant; it's subsumed by the second.
1917 // What we do here is, we build the two possible composite types, and try the
1918 // conversions in both directions. If only one works, or if the two composite
1919 // types are the same, we have succeeded.
John McCall0953e762009-09-24 19:53:00 +00001920 // FIXME: extended qualifiers?
Sebastian Redla439e6f2009-11-16 21:03:45 +00001921 typedef llvm::SmallVector<unsigned, 4> QualifierVector;
1922 QualifierVector QualifierUnion;
1923 typedef llvm::SmallVector<std::pair<const Type *, const Type *>, 4>
1924 ContainingClassVector;
1925 ContainingClassVector MemberOfClass;
1926 QualType Composite1 = Context.getCanonicalType(T1),
1927 Composite2 = Context.getCanonicalType(T2);
Douglas Gregor20b3e992009-08-24 17:42:35 +00001928 do {
1929 const PointerType *Ptr1, *Ptr2;
1930 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
1931 (Ptr2 = Composite2->getAs<PointerType>())) {
1932 Composite1 = Ptr1->getPointeeType();
1933 Composite2 = Ptr2->getPointeeType();
1934 QualifierUnion.push_back(
1935 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
1936 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
1937 continue;
1938 }
Mike Stump1eb44332009-09-09 15:08:12 +00001939
Douglas Gregor20b3e992009-08-24 17:42:35 +00001940 const MemberPointerType *MemPtr1, *MemPtr2;
1941 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
1942 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
1943 Composite1 = MemPtr1->getPointeeType();
1944 Composite2 = MemPtr2->getPointeeType();
1945 QualifierUnion.push_back(
1946 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
1947 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
1948 MemPtr2->getClass()));
1949 continue;
1950 }
Mike Stump1eb44332009-09-09 15:08:12 +00001951
Douglas Gregor20b3e992009-08-24 17:42:35 +00001952 // FIXME: block pointer types?
Mike Stump1eb44332009-09-09 15:08:12 +00001953
Douglas Gregor20b3e992009-08-24 17:42:35 +00001954 // Cannot unwrap any more types.
1955 break;
1956 } while (true);
Mike Stump1eb44332009-09-09 15:08:12 +00001957
Douglas Gregor20b3e992009-08-24 17:42:35 +00001958 // Rewrap the composites as pointers or member pointers with the union CVRs.
Sebastian Redla439e6f2009-11-16 21:03:45 +00001959 ContainingClassVector::reverse_iterator MOC
1960 = MemberOfClass.rbegin();
1961 for (QualifierVector::reverse_iterator
1962 I = QualifierUnion.rbegin(),
1963 E = QualifierUnion.rend();
Douglas Gregor20b3e992009-08-24 17:42:35 +00001964 I != E; (void)++I, ++MOC) {
John McCall0953e762009-09-24 19:53:00 +00001965 Qualifiers Quals = Qualifiers::fromCVRMask(*I);
Douglas Gregor20b3e992009-08-24 17:42:35 +00001966 if (MOC->first && MOC->second) {
1967 // Rebuild member pointer type
John McCall0953e762009-09-24 19:53:00 +00001968 Composite1 = Context.getMemberPointerType(
1969 Context.getQualifiedType(Composite1, Quals),
1970 MOC->first);
1971 Composite2 = Context.getMemberPointerType(
1972 Context.getQualifiedType(Composite2, Quals),
1973 MOC->second);
Douglas Gregor20b3e992009-08-24 17:42:35 +00001974 } else {
1975 // Rebuild pointer type
John McCall0953e762009-09-24 19:53:00 +00001976 Composite1
1977 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
1978 Composite2
1979 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregor20b3e992009-08-24 17:42:35 +00001980 }
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001981 }
1982
Mike Stump1eb44332009-09-09 15:08:12 +00001983 ImplicitConversionSequence E1ToC1 =
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001984 TryImplicitConversion(E1, Composite1,
1985 /*SuppressUserConversions=*/false,
1986 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00001987 /*ForceRValue=*/false,
1988 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00001989 ImplicitConversionSequence E2ToC1 =
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001990 TryImplicitConversion(E2, Composite1,
1991 /*SuppressUserConversions=*/false,
1992 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00001993 /*ForceRValue=*/false,
1994 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00001995
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001996 ImplicitConversionSequence E1ToC2, E2ToC2;
1997 E1ToC2.ConversionKind = ImplicitConversionSequence::BadConversion;
1998 E2ToC2.ConversionKind = ImplicitConversionSequence::BadConversion;
1999 if (Context.getCanonicalType(Composite1) !=
2000 Context.getCanonicalType(Composite2)) {
Anders Carlssonda7a18b2009-08-27 17:24:15 +00002001 E1ToC2 = TryImplicitConversion(E1, Composite2,
2002 /*SuppressUserConversions=*/false,
2003 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00002004 /*ForceRValue=*/false,
2005 /*InOverloadResolution=*/false);
Anders Carlssonda7a18b2009-08-27 17:24:15 +00002006 E2ToC2 = TryImplicitConversion(E2, Composite2,
2007 /*SuppressUserConversions=*/false,
2008 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00002009 /*ForceRValue=*/false,
2010 /*InOverloadResolution=*/false);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002011 }
2012
2013 bool ToC1Viable = E1ToC1.ConversionKind !=
2014 ImplicitConversionSequence::BadConversion
2015 && E2ToC1.ConversionKind !=
2016 ImplicitConversionSequence::BadConversion;
2017 bool ToC2Viable = E1ToC2.ConversionKind !=
2018 ImplicitConversionSequence::BadConversion
2019 && E2ToC2.ConversionKind !=
2020 ImplicitConversionSequence::BadConversion;
2021 if (ToC1Viable && !ToC2Viable) {
2022 if (!PerformImplicitConversion(E1, Composite1, E1ToC1, "converting") &&
2023 !PerformImplicitConversion(E2, Composite1, E2ToC1, "converting"))
2024 return Composite1;
2025 }
2026 if (ToC2Viable && !ToC1Viable) {
2027 if (!PerformImplicitConversion(E1, Composite2, E1ToC2, "converting") &&
2028 !PerformImplicitConversion(E2, Composite2, E2ToC2, "converting"))
2029 return Composite2;
2030 }
2031 return QualType();
2032}
Anders Carlsson165a0a02009-05-17 18:41:29 +00002033
Anders Carlssondef11992009-05-30 20:36:53 +00002034Sema::OwningExprResult Sema::MaybeBindToTemporary(Expr *E) {
Anders Carlsson089c2602009-08-15 23:41:35 +00002035 if (!Context.getLangOptions().CPlusPlus)
2036 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002037
Ted Kremenek6217b802009-07-29 21:53:49 +00002038 const RecordType *RT = E->getType()->getAs<RecordType>();
Anders Carlssondef11992009-05-30 20:36:53 +00002039 if (!RT)
2040 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002041
Anders Carlssondef11992009-05-30 20:36:53 +00002042 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2043 if (RD->hasTrivialDestructor())
2044 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002045
Anders Carlsson283e4d52009-09-14 01:30:44 +00002046 if (CallExpr *CE = dyn_cast<CallExpr>(E)) {
2047 QualType Ty = CE->getCallee()->getType();
2048 if (const PointerType *PT = Ty->getAs<PointerType>())
2049 Ty = PT->getPointeeType();
2050
John McCall183700f2009-09-21 23:43:11 +00002051 const FunctionType *FTy = Ty->getAs<FunctionType>();
Anders Carlsson283e4d52009-09-14 01:30:44 +00002052 if (FTy->getResultType()->isReferenceType())
2053 return Owned(E);
2054 }
Mike Stump1eb44332009-09-09 15:08:12 +00002055 CXXTemporary *Temp = CXXTemporary::Create(Context,
Anders Carlssondef11992009-05-30 20:36:53 +00002056 RD->getDestructor(Context));
Anders Carlsson860306e2009-05-30 21:21:49 +00002057 ExprTemporaries.push_back(Temp);
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00002058 if (CXXDestructorDecl *Destructor =
2059 const_cast<CXXDestructorDecl*>(RD->getDestructor(Context)))
2060 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
Anders Carlssondef11992009-05-30 20:36:53 +00002061 // FIXME: Add the temporary to the temporaries vector.
2062 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
2063}
2064
Mike Stump1eb44332009-09-09 15:08:12 +00002065Expr *Sema::MaybeCreateCXXExprWithTemporaries(Expr *SubExpr,
Anders Carlssonf54741e2009-06-16 03:37:31 +00002066 bool ShouldDestroyTemps) {
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002067 assert(SubExpr && "sub expression can't be null!");
Mike Stump1eb44332009-09-09 15:08:12 +00002068
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002069 if (ExprTemporaries.empty())
2070 return SubExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00002071
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002072 Expr *E = CXXExprWithTemporaries::Create(Context, SubExpr,
Mike Stump1eb44332009-09-09 15:08:12 +00002073 &ExprTemporaries[0],
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002074 ExprTemporaries.size(),
Anders Carlssonf54741e2009-06-16 03:37:31 +00002075 ShouldDestroyTemps);
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002076 ExprTemporaries.clear();
Mike Stump1eb44332009-09-09 15:08:12 +00002077
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002078 return E;
2079}
2080
Mike Stump1eb44332009-09-09 15:08:12 +00002081Sema::OwningExprResult
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002082Sema::ActOnStartCXXMemberReference(Scope *S, ExprArg Base, SourceLocation OpLoc,
2083 tok::TokenKind OpKind, TypeTy *&ObjectType) {
2084 // Since this might be a postfix expression, get rid of ParenListExprs.
2085 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
Mike Stump1eb44332009-09-09 15:08:12 +00002086
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002087 Expr *BaseExpr = (Expr*)Base.get();
2088 assert(BaseExpr && "no record expansion");
Mike Stump1eb44332009-09-09 15:08:12 +00002089
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002090 QualType BaseType = BaseExpr->getType();
2091 if (BaseType->isDependentType()) {
Douglas Gregor43d88632009-11-04 22:49:18 +00002092 // If we have a pointer to a dependent type and are using the -> operator,
2093 // the object type is the type that the pointer points to. We might still
2094 // have enough information about that type to do something useful.
2095 if (OpKind == tok::arrow)
2096 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
2097 BaseType = Ptr->getPointeeType();
2098
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002099 ObjectType = BaseType.getAsOpaquePtr();
2100 return move(Base);
2101 }
Mike Stump1eb44332009-09-09 15:08:12 +00002102
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002103 // C++ [over.match.oper]p8:
Mike Stump1eb44332009-09-09 15:08:12 +00002104 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002105 // returned, with the original second operand.
2106 if (OpKind == tok::arrow) {
John McCallc4e83212009-09-30 01:01:30 +00002107 // The set of types we've considered so far.
John McCall432887f2009-09-30 01:30:54 +00002108 llvm::SmallPtrSet<CanQualType,8> CTypes;
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002109 llvm::SmallVector<SourceLocation, 8> Locations;
John McCall432887f2009-09-30 01:30:54 +00002110 CTypes.insert(Context.getCanonicalType(BaseType));
John McCallc4e83212009-09-30 01:01:30 +00002111
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002112 while (BaseType->isRecordType()) {
Anders Carlsson15ea3782009-10-13 22:43:21 +00002113 Base = BuildOverloadedArrowExpr(S, move(Base), OpLoc);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002114 BaseExpr = (Expr*)Base.get();
2115 if (BaseExpr == NULL)
2116 return ExprError();
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002117 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(BaseExpr))
Anders Carlssonde699e52009-10-13 22:55:59 +00002118 Locations.push_back(OpCall->getDirectCallee()->getLocation());
John McCallc4e83212009-09-30 01:01:30 +00002119 BaseType = BaseExpr->getType();
2120 CanQualType CBaseType = Context.getCanonicalType(BaseType);
John McCall432887f2009-09-30 01:30:54 +00002121 if (!CTypes.insert(CBaseType)) {
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00002122 Diag(OpLoc, diag::err_operator_arrow_circular);
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002123 for (unsigned i = 0; i < Locations.size(); i++)
2124 Diag(Locations[i], diag::note_declared_at);
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00002125 return ExprError();
2126 }
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002127 }
2128 }
Mike Stump1eb44332009-09-09 15:08:12 +00002129
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002130 if (BaseType->isPointerType())
2131 BaseType = BaseType->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00002132
2133 // We could end up with various non-record types here, such as extended
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002134 // vector types or Objective-C interfaces. Just return early and let
2135 // ActOnMemberReferenceExpr do the work.
Douglas Gregorc68afe22009-09-03 21:38:09 +00002136 if (!BaseType->isRecordType()) {
2137 // C++ [basic.lookup.classref]p2:
2138 // [...] If the type of the object expression is of pointer to scalar
2139 // type, the unqualified-id is looked up in the context of the complete
2140 // postfix-expression.
2141 ObjectType = 0;
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002142 return move(Base);
Douglas Gregorc68afe22009-09-03 21:38:09 +00002143 }
Mike Stump1eb44332009-09-09 15:08:12 +00002144
Douglas Gregor03c57052009-11-17 05:17:33 +00002145 // The object type must be complete (or dependent).
2146 if (!BaseType->isDependentType() &&
2147 RequireCompleteType(OpLoc, BaseType,
2148 PDiag(diag::err_incomplete_member_access)))
2149 return ExprError();
2150
Douglas Gregorc68afe22009-09-03 21:38:09 +00002151 // C++ [basic.lookup.classref]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00002152 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor03c57052009-11-17 05:17:33 +00002153 // unqualified-id, and the type of the object expression is of a class
Douglas Gregorc68afe22009-09-03 21:38:09 +00002154 // type C (or of pointer to a class type C), the unqualified-id is looked
2155 // up in the scope of class C. [...]
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002156 ObjectType = BaseType.getAsOpaquePtr();
Douglas Gregor03c57052009-11-17 05:17:33 +00002157
Mike Stump1eb44332009-09-09 15:08:12 +00002158 return move(Base);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002159}
2160
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002161CXXMemberCallExpr *Sema::BuildCXXMemberCallExpr(Expr *Exp,
2162 CXXMethodDecl *Method) {
2163 MemberExpr *ME =
2164 new (Context) MemberExpr(Exp, /*IsArrow=*/false, Method,
2165 SourceLocation(), Method->getType());
2166 QualType ResultType;
2167 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(Method))
2168 ResultType = Conv->getConversionType().getNonReferenceType();
2169 else
2170 ResultType = Method->getResultType().getNonReferenceType();
2171
2172 CXXMemberCallExpr *CE =
2173 new (Context) CXXMemberCallExpr(Context, ME, 0, 0,
2174 ResultType,
Douglas Gregor00b98c22009-11-12 15:31:47 +00002175 Exp->getLocEnd());
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002176 return CE;
2177}
2178
Anders Carlsson0aebc812009-09-09 21:33:21 +00002179Sema::OwningExprResult Sema::BuildCXXCastArgument(SourceLocation CastLoc,
2180 QualType Ty,
2181 CastExpr::CastKind Kind,
2182 CXXMethodDecl *Method,
2183 ExprArg Arg) {
2184 Expr *From = Arg.takeAs<Expr>();
2185
2186 switch (Kind) {
2187 default: assert(0 && "Unhandled cast kind!");
2188 case CastExpr::CK_ConstructorConversion: {
Douglas Gregor39da0b82009-09-09 23:08:42 +00002189 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
2190
2191 if (CompleteConstructorCall(cast<CXXConstructorDecl>(Method),
2192 MultiExprArg(*this, (void **)&From, 1),
2193 CastLoc, ConstructorArgs))
2194 return ExprError();
Anders Carlsson4fa26842009-10-18 21:20:14 +00002195
2196 OwningExprResult Result =
2197 BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
2198 move_arg(ConstructorArgs));
2199 if (Result.isInvalid())
2200 return ExprError();
2201
2202 return MaybeBindToTemporary(Result.takeAs<Expr>());
Anders Carlsson0aebc812009-09-09 21:33:21 +00002203 }
2204
2205 case CastExpr::CK_UserDefinedConversion: {
Anders Carlssonaac6e3a2009-09-15 07:42:44 +00002206 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
2207
2208 // Cast to base if needed.
2209 if (PerformObjectArgumentInitialization(From, Method))
2210 return ExprError();
2211
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002212 // Create an implicit call expr that calls it.
2213 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(From, Method);
Anders Carlsson4fa26842009-10-18 21:20:14 +00002214 return MaybeBindToTemporary(CE);
Anders Carlsson0aebc812009-09-09 21:33:21 +00002215 }
Anders Carlsson0aebc812009-09-09 21:33:21 +00002216 }
2217}
2218
Anders Carlsson165a0a02009-05-17 18:41:29 +00002219Sema::OwningExprResult Sema::ActOnFinishFullExpr(ExprArg Arg) {
2220 Expr *FullExpr = Arg.takeAs<Expr>();
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002221 if (FullExpr)
Mike Stump1eb44332009-09-09 15:08:12 +00002222 FullExpr = MaybeCreateCXXExprWithTemporaries(FullExpr,
Anders Carlssonf54741e2009-06-16 03:37:31 +00002223 /*ShouldDestroyTemps=*/true);
Anders Carlsson165a0a02009-05-17 18:41:29 +00002224
Anders Carlssonec773872009-08-25 23:46:41 +00002225
Anders Carlsson165a0a02009-05-17 18:41:29 +00002226 return Owned(FullExpr);
2227}
Douglas Gregore961afb2009-10-22 07:08:30 +00002228
2229/// \brief Determine whether a reference to the given declaration in the
2230/// current context is an implicit member access
2231/// (C++ [class.mfct.non-static]p2).
2232///
2233/// FIXME: Should Objective-C also use this approach?
2234///
2235/// \param SS if non-NULL, the C++ nested-name-specifier that precedes the
2236/// name of the declaration referenced.
2237///
2238/// \param D the declaration being referenced from the current scope.
2239///
2240/// \param NameLoc the location of the name in the source.
2241///
2242/// \param ThisType if the reference to this declaration is an implicit member
2243/// access, will be set to the type of the "this" pointer to be used when
2244/// building that implicit member access.
2245///
2246/// \param MemberType if the reference to this declaration is an implicit
2247/// member access, will be set to the type of the member being referenced
2248/// (for use at the type of the resulting member access expression).
2249///
2250/// \returns true if this is an implicit member reference (in which case
2251/// \p ThisType and \p MemberType will be set), or false if it is not an
2252/// implicit member reference.
2253bool Sema::isImplicitMemberReference(const CXXScopeSpec *SS, NamedDecl *D,
2254 SourceLocation NameLoc, QualType &ThisType,
2255 QualType &MemberType) {
2256 // If this isn't a C++ method, then it isn't an implicit member reference.
2257 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext);
2258 if (!MD || MD->isStatic())
2259 return false;
2260
2261 // C++ [class.mfct.nonstatic]p2:
2262 // [...] if name lookup (3.4.1) resolves the name in the
2263 // id-expression to a nonstatic nontype member of class X or of
2264 // a base class of X, the id-expression is transformed into a
2265 // class member access expression (5.2.5) using (*this) (9.3.2)
2266 // as the postfix-expression to the left of the '.' operator.
2267 DeclContext *Ctx = 0;
2268 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
2269 Ctx = FD->getDeclContext();
2270 MemberType = FD->getType();
2271
2272 if (const ReferenceType *RefType = MemberType->getAs<ReferenceType>())
2273 MemberType = RefType->getPointeeType();
2274 else if (!FD->isMutable())
2275 MemberType
2276 = Context.getQualifiedType(MemberType,
2277 Qualifiers::fromCVRMask(MD->getTypeQualifiers()));
2278 } else {
2279 for (OverloadIterator Ovl(D), OvlEnd; Ovl != OvlEnd; ++Ovl) {
2280 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*Ovl);
2281 FunctionTemplateDecl *FunTmpl = 0;
2282 if (!Method && (FunTmpl = dyn_cast<FunctionTemplateDecl>(*Ovl)))
2283 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
2284
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00002285 // FIXME: Do we have to know if there are explicit template arguments?
Douglas Gregore961afb2009-10-22 07:08:30 +00002286 if (Method && !Method->isStatic()) {
2287 Ctx = Method->getParent();
2288 if (isa<CXXMethodDecl>(D) && !FunTmpl)
2289 MemberType = Method->getType();
2290 else
2291 MemberType = Context.OverloadTy;
2292 break;
2293 }
2294 }
2295 }
2296
2297 if (!Ctx || !Ctx->isRecord())
2298 return false;
2299
2300 // Determine whether the declaration(s) we found are actually in a base
2301 // class. If not, this isn't an implicit member reference.
2302 ThisType = MD->getThisType(Context);
Douglas Gregor7a343142009-11-01 17:08:18 +00002303
2304 // If the type of "this" is dependent, we can't tell if the member is in a
2305 // base class or not, so treat this as a dependent implicit member reference.
2306 if (ThisType->isDependentType())
2307 return true;
2308
Douglas Gregore961afb2009-10-22 07:08:30 +00002309 QualType CtxType = Context.getTypeDeclType(cast<CXXRecordDecl>(Ctx));
2310 QualType ClassType
2311 = Context.getTypeDeclType(cast<CXXRecordDecl>(MD->getParent()));
2312 return Context.hasSameType(CtxType, ClassType) ||
2313 IsDerivedFrom(ClassType, CtxType);
2314}
2315