blob: afb5c54d65c796a9c4632e56a82a445352d19178 [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"
Douglas Gregor20093b42009-12-09 23:02:17 +000015#include "SemaInit.h"
John McCall7d384dd2009-11-18 07:57:50 +000016#include "Lookup.h"
Steve Naroff210679c2007-08-25 14:02:58 +000017#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000018#include "clang/AST/CXXInheritance.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000019#include "clang/AST/ExprCXX.h"
20#include "clang/Basic/PartialDiagnostic.h"
Sebastian Redlb5a57a62008-12-03 20:26:15 +000021#include "clang/Basic/TargetInfo.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000022#include "clang/Lex/Preprocessor.h"
23#include "clang/Parse/DeclSpec.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000024#include "llvm/ADT/STLExtras.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000025using namespace clang;
26
Sebastian Redlc42e1182008-11-11 11:37:55 +000027/// ActOnCXXTypeidOfType - Parse typeid( type-id ).
Sebastian Redlf53597f2009-03-15 17:47:39 +000028Action::OwningExprResult
Sebastian Redlc42e1182008-11-11 11:37:55 +000029Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
30 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +000031 if (!StdNamespace)
Sebastian Redlf53597f2009-03-15 17:47:39 +000032 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +000033
Douglas Gregorf57f2072009-12-23 20:51:04 +000034 if (isType) {
35 // C++ [expr.typeid]p4:
36 // The top-level cv-qualifiers of the lvalue expression or the type-id
37 // that is the operand of typeid are always ignored.
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +000038 // FIXME: Preserve type source info.
Douglas Gregorf57f2072009-12-23 20:51:04 +000039 // FIXME: Preserve the type before we stripped the cv-qualifiers?
Douglas Gregor765ccba2009-12-23 21:06:06 +000040 QualType T = GetTypeFromParser(TyOrExpr);
41 if (T.isNull())
42 return ExprError();
43
44 // C++ [expr.typeid]p4:
45 // If the type of the type-id is a class type or a reference to a class
46 // type, the class shall be completely-defined.
47 QualType CheckT = T;
48 if (const ReferenceType *RefType = CheckT->getAs<ReferenceType>())
49 CheckT = RefType->getPointeeType();
50
51 if (CheckT->getAs<RecordType>() &&
52 RequireCompleteType(OpLoc, CheckT, diag::err_incomplete_typeid))
53 return ExprError();
54
55 TyOrExpr = T.getUnqualifiedType().getAsOpaquePtr();
Douglas Gregorf57f2072009-12-23 20:51:04 +000056 }
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +000057
Chris Lattner572af492008-11-20 05:51:55 +000058 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
John McCalla24dc2e2009-11-17 02:14:36 +000059 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
60 LookupQualifiedName(R, StdNamespace);
John McCall1bcee0a2009-12-02 08:25:40 +000061 RecordDecl *TypeInfoRecordDecl = R.getAsSingle<RecordDecl>();
Chris Lattner572af492008-11-20 05:51:55 +000062 if (!TypeInfoRecordDecl)
Sebastian Redlf53597f2009-03-15 17:47:39 +000063 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Sebastian Redlc42e1182008-11-11 11:37:55 +000064
65 QualType TypeInfoType = Context.getTypeDeclType(TypeInfoRecordDecl);
66
Douglas Gregorac7610d2009-06-22 20:57:11 +000067 if (!isType) {
Douglas Gregorac7610d2009-06-22 20:57:11 +000068 bool isUnevaluatedOperand = true;
69 Expr *E = static_cast<Expr *>(TyOrExpr);
Douglas Gregorf57f2072009-12-23 20:51:04 +000070 if (E && !E->isTypeDependent()) {
Douglas Gregorac7610d2009-06-22 20:57:11 +000071 QualType T = E->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +000072 if (const RecordType *RecordT = T->getAs<RecordType>()) {
Douglas Gregorac7610d2009-06-22 20:57:11 +000073 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
Douglas Gregorf57f2072009-12-23 20:51:04 +000074 // C++ [expr.typeid]p3:
75 // When typeid is applied to an expression other than an lvalue of a
76 // polymorphic class type [...] [the] expression is an unevaluated
77 // operand. [...]
78 if (RecordD->isPolymorphic() && E->isLvalue(Context) == Expr::LV_Valid)
Douglas Gregorac7610d2009-06-22 20:57:11 +000079 isUnevaluatedOperand = false;
Douglas Gregorf57f2072009-12-23 20:51:04 +000080 else {
81 // C++ [expr.typeid]p3:
82 // [...] If the type of the expression is a class type, the class
83 // shall be completely-defined.
Douglas Gregor765ccba2009-12-23 21:06:06 +000084 if (RequireCompleteType(OpLoc, T, diag::err_incomplete_typeid))
85 return ExprError();
Douglas Gregorf57f2072009-12-23 20:51:04 +000086 }
87 }
88
89 // C++ [expr.typeid]p4:
90 // [...] If the type of the type-id is a reference to a possibly
91 // cv-qualified type, the result of the typeid expression refers to a
92 // std::type_info object representing the cv-unqualified referenced
93 // type.
94 if (T.hasQualifiers()) {
95 ImpCastExprToType(E, T.getUnqualifiedType(), CastExpr::CK_NoOp,
96 E->isLvalue(Context));
97 TyOrExpr = E;
Douglas Gregorac7610d2009-06-22 20:57:11 +000098 }
99 }
Mike Stump1eb44332009-09-09 15:08:12 +0000100
Douglas Gregor2afce722009-11-26 00:44:06 +0000101 // If this is an unevaluated operand, clear out the set of
102 // declaration references we have been computing and eliminate any
103 // temporaries introduced in its computation.
Douglas Gregorac7610d2009-06-22 20:57:11 +0000104 if (isUnevaluatedOperand)
Douglas Gregor2afce722009-11-26 00:44:06 +0000105 ExprEvalContexts.back().Context = Unevaluated;
Douglas Gregorac7610d2009-06-22 20:57:11 +0000106 }
Mike Stump1eb44332009-09-09 15:08:12 +0000107
Sebastian Redlf53597f2009-03-15 17:47:39 +0000108 return Owned(new (Context) CXXTypeidExpr(isType, TyOrExpr,
109 TypeInfoType.withConst(),
110 SourceRange(OpLoc, RParenLoc)));
Sebastian Redlc42e1182008-11-11 11:37:55 +0000111}
112
Steve Naroff1b273c42007-09-16 14:56:35 +0000113/// ActOnCXXBoolLiteral - Parse {true,false} literals.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000114Action::OwningExprResult
Steve Naroff1b273c42007-09-16 14:56:35 +0000115Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor2f639b92008-10-24 15:36:09 +0000116 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000117 "Unknown C++ Boolean value!");
Sebastian Redlf53597f2009-03-15 17:47:39 +0000118 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
119 Context.BoolTy, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000120}
Chris Lattner50dd2892008-02-26 00:51:44 +0000121
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000122/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
123Action::OwningExprResult
124Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
125 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
126}
127
Chris Lattner50dd2892008-02-26 00:51:44 +0000128/// ActOnCXXThrow - Parse throw expressions.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000129Action::OwningExprResult
130Sema::ActOnCXXThrow(SourceLocation OpLoc, ExprArg E) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000131 Expr *Ex = E.takeAs<Expr>();
132 if (Ex && !Ex->isTypeDependent() && CheckCXXThrowOperand(OpLoc, Ex))
133 return ExprError();
134 return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc));
135}
136
137/// CheckCXXThrowOperand - Validate the operand of a throw.
138bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *&E) {
139 // C++ [except.throw]p3:
140 // [...] adjusting the type from "array of T" or "function returning T"
141 // to "pointer to T" or "pointer to function returning T", [...]
142 DefaultFunctionArrayConversion(E);
143
144 // If the type of the exception would be an incomplete type or a pointer
145 // to an incomplete type other than (cv) void the program is ill-formed.
146 QualType Ty = E->getType();
147 int isPointer = 0;
Ted Kremenek6217b802009-07-29 21:53:49 +0000148 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000149 Ty = Ptr->getPointeeType();
150 isPointer = 1;
151 }
152 if (!isPointer || !Ty->isVoidType()) {
153 if (RequireCompleteType(ThrowLoc, Ty,
Anders Carlssond497ba72009-08-26 22:59:12 +0000154 PDiag(isPointer ? diag::err_throw_incomplete_ptr
155 : diag::err_throw_incomplete)
156 << E->getSourceRange()))
Sebastian Redl972041f2009-04-27 20:27:31 +0000157 return true;
158 }
159
160 // FIXME: Construct a temporary here.
161 return false;
Chris Lattner50dd2892008-02-26 00:51:44 +0000162}
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000163
Sebastian Redlf53597f2009-03-15 17:47:39 +0000164Action::OwningExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000165 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
166 /// is a non-lvalue expression whose value is the address of the object for
167 /// which the function is called.
168
Sebastian Redlf53597f2009-03-15 17:47:39 +0000169 if (!isa<FunctionDecl>(CurContext))
170 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000171
172 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext))
173 if (MD->isInstance())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000174 return Owned(new (Context) CXXThisExpr(ThisLoc,
175 MD->getThisType(Context)));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000176
Sebastian Redlf53597f2009-03-15 17:47:39 +0000177 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000178}
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000179
180/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
181/// Can be interpreted either as function-style casting ("int(x)")
182/// or class type construction ("ClassType(x,y,z)")
183/// or creation of a value-initialized type ("int()").
Sebastian Redlf53597f2009-03-15 17:47:39 +0000184Action::OwningExprResult
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000185Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep,
186 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000187 MultiExprArg exprs,
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000188 SourceLocation *CommaLocs,
189 SourceLocation RParenLoc) {
190 assert(TypeRep && "Missing type!");
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000191 // FIXME: Preserve type source info.
192 QualType Ty = GetTypeFromParser(TypeRep);
Sebastian Redlf53597f2009-03-15 17:47:39 +0000193 unsigned NumExprs = exprs.size();
194 Expr **Exprs = (Expr**)exprs.get();
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000195 SourceLocation TyBeginLoc = TypeRange.getBegin();
196 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
197
Sebastian Redlf53597f2009-03-15 17:47:39 +0000198 if (Ty->isDependentType() ||
Douglas Gregorba498172009-03-13 21:01:28 +0000199 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
Sebastian Redlf53597f2009-03-15 17:47:39 +0000200 exprs.release();
Mike Stump1eb44332009-09-09 15:08:12 +0000201
202 return Owned(CXXUnresolvedConstructExpr::Create(Context,
203 TypeRange.getBegin(), Ty,
Douglas Gregord81e6ca2009-05-20 18:46:25 +0000204 LParenLoc,
205 Exprs, NumExprs,
206 RParenLoc));
Douglas Gregorba498172009-03-13 21:01:28 +0000207 }
208
Anders Carlssonbb60a502009-08-27 03:53:50 +0000209 if (Ty->isArrayType())
210 return ExprError(Diag(TyBeginLoc,
211 diag::err_value_init_for_array_type) << FullRange);
212 if (!Ty->isVoidType() &&
213 RequireCompleteType(TyBeginLoc, Ty,
214 PDiag(diag::err_invalid_incomplete_type_use)
215 << FullRange))
216 return ExprError();
Fariborz Jahanianf071e9b2009-10-23 21:01:39 +0000217
Anders Carlssonbb60a502009-08-27 03:53:50 +0000218 if (RequireNonAbstractType(TyBeginLoc, Ty,
219 diag::err_allocation_of_abstract_type))
220 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000221
222
Douglas Gregor506ae412009-01-16 18:33:17 +0000223 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000224 // If the expression list is a single expression, the type conversion
225 // expression is equivalent (in definedness, and if defined in meaning) to the
226 // corresponding cast expression.
227 //
228 if (NumExprs == 1) {
Anders Carlssoncdb61972009-08-07 22:21:05 +0000229 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Anders Carlsson0aebc812009-09-09 21:33:21 +0000230 CXXMethodDecl *Method = 0;
231 if (CheckCastTypes(TypeRange, Ty, Exprs[0], Kind, Method,
232 /*FunctionalStyle=*/true))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000233 return ExprError();
Anders Carlsson0aebc812009-09-09 21:33:21 +0000234
235 exprs.release();
236 if (Method) {
237 OwningExprResult CastArg
238 = BuildCXXCastArgument(TypeRange.getBegin(), Ty.getNonReferenceType(),
239 Kind, Method, Owned(Exprs[0]));
240 if (CastArg.isInvalid())
241 return ExprError();
242
243 Exprs[0] = CastArg.takeAs<Expr>();
Fariborz Jahanian4fc7ab32009-08-28 15:11:24 +0000244 }
Anders Carlsson0aebc812009-09-09 21:33:21 +0000245
246 return Owned(new (Context) CXXFunctionalCastExpr(Ty.getNonReferenceType(),
247 Ty, TyBeginLoc, Kind,
248 Exprs[0], RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000249 }
250
Ted Kremenek6217b802009-07-29 21:53:49 +0000251 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Douglas Gregor506ae412009-01-16 18:33:17 +0000252 CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
Sebastian Redlf53597f2009-03-15 17:47:39 +0000253
Mike Stump1eb44332009-09-09 15:08:12 +0000254 if (NumExprs > 1 || !Record->hasTrivialConstructor() ||
Anders Carlssone7624a72009-08-27 05:08:22 +0000255 !Record->hasTrivialDestructor()) {
Douglas Gregor39da0b82009-09-09 23:08:42 +0000256 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
257
Douglas Gregor506ae412009-01-16 18:33:17 +0000258 CXXConstructorDecl *Constructor
Douglas Gregor39da0b82009-09-09 23:08:42 +0000259 = PerformInitializationByConstructor(Ty, move(exprs),
Douglas Gregor506ae412009-01-16 18:33:17 +0000260 TypeRange.getBegin(),
261 SourceRange(TypeRange.getBegin(),
262 RParenLoc),
263 DeclarationName(),
Douglas Gregor20093b42009-12-09 23:02:17 +0000264 InitializationKind::CreateDirect(TypeRange.getBegin(),
265 LParenLoc,
266 RParenLoc),
Douglas Gregor39da0b82009-09-09 23:08:42 +0000267 ConstructorArgs);
Douglas Gregor506ae412009-01-16 18:33:17 +0000268
Sebastian Redlf53597f2009-03-15 17:47:39 +0000269 if (!Constructor)
270 return ExprError();
271
Mike Stump1eb44332009-09-09 15:08:12 +0000272 OwningExprResult Result =
273 BuildCXXTemporaryObjectExpr(Constructor, Ty, TyBeginLoc,
Douglas Gregor39da0b82009-09-09 23:08:42 +0000274 move_arg(ConstructorArgs), RParenLoc);
Anders Carlssone7624a72009-08-27 05:08:22 +0000275 if (Result.isInvalid())
276 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000277
Anders Carlssone7624a72009-08-27 05:08:22 +0000278 return MaybeBindToTemporary(Result.takeAs<Expr>());
Douglas Gregor506ae412009-01-16 18:33:17 +0000279 }
280
281 // Fall through to value-initialize an object of class type that
282 // doesn't have a user-declared default constructor.
283 }
284
285 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000286 // If the expression list specifies more than a single value, the type shall
287 // be a class with a suitably declared constructor.
288 //
289 if (NumExprs > 1)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000290 return ExprError(Diag(CommaLocs[0],
291 diag::err_builtin_func_cast_more_than_one_arg)
292 << FullRange);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000293
294 assert(NumExprs == 0 && "Expected 0 expressions");
Douglas Gregor506ae412009-01-16 18:33:17 +0000295 // C++ [expr.type.conv]p2:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000296 // The expression T(), where T is a simple-type-specifier for a non-array
297 // complete object type or the (possibly cv-qualified) void type, creates an
298 // rvalue of the specified type, which is value-initialized.
299 //
Sebastian Redlf53597f2009-03-15 17:47:39 +0000300 exprs.release();
301 return Owned(new (Context) CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000302}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000303
304
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000305/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
306/// @code new (memory) int[size][4] @endcode
307/// or
308/// @code ::new Foo(23, "hello") @endcode
309/// For the interpretation of this heap of arguments, consult the base version.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000310Action::OwningExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000311Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000312 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000313 SourceLocation PlacementRParen, bool ParenTypeId,
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000314 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000315 MultiExprArg ConstructorArgs,
Mike Stump1eb44332009-09-09 15:08:12 +0000316 SourceLocation ConstructorRParen) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000317 Expr *ArraySize = 0;
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000318 // If the specified type is an array, unwrap it and save the expression.
319 if (D.getNumTypeObjects() > 0 &&
320 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
321 DeclaratorChunk &Chunk = D.getTypeObject(0);
322 if (Chunk.Arr.hasStatic)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000323 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
324 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000325 if (!Chunk.Arr.NumElts)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000326 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
327 << D.getSourceRange());
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000328
329 if (ParenTypeId) {
330 // Can't have dynamic array size when the type-id is in parentheses.
331 Expr *NumElts = (Expr *)Chunk.Arr.NumElts;
332 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
333 !NumElts->isIntegerConstantExpr(Context)) {
334 Diag(D.getTypeObject(0).Loc, diag::err_new_paren_array_nonconst)
335 << NumElts->getSourceRange();
336 return ExprError();
337 }
338 }
339
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000340 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000341 D.DropFirstTypeObject();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000342 }
343
Douglas Gregor043cad22009-09-11 00:18:58 +0000344 // Every dimension shall be of constant size.
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000345 if (ArraySize) {
346 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor043cad22009-09-11 00:18:58 +0000347 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
348 break;
349
350 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
351 if (Expr *NumElts = (Expr *)Array.NumElts) {
352 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
353 !NumElts->isIntegerConstantExpr(Context)) {
354 Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst)
355 << NumElts->getSourceRange();
356 return ExprError();
357 }
358 }
359 }
360 }
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000361
John McCalla93c9342009-12-07 02:54:59 +0000362 //FIXME: Store TypeSourceInfo in CXXNew expression.
363 TypeSourceInfo *TInfo = 0;
364 QualType AllocType = GetTypeForDeclarator(D, /*Scope=*/0, &TInfo);
Chris Lattnereaaebc72009-04-25 08:06:05 +0000365 if (D.isInvalidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000366 return ExprError();
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000367
Mike Stump1eb44332009-09-09 15:08:12 +0000368 return BuildCXXNew(StartLoc, UseGlobal,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000369 PlacementLParen,
Mike Stump1eb44332009-09-09 15:08:12 +0000370 move(PlacementArgs),
Douglas Gregor3433cf72009-05-21 00:00:09 +0000371 PlacementRParen,
372 ParenTypeId,
Mike Stump1eb44332009-09-09 15:08:12 +0000373 AllocType,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000374 D.getSourceRange().getBegin(),
375 D.getSourceRange(),
376 Owned(ArraySize),
377 ConstructorLParen,
378 move(ConstructorArgs),
379 ConstructorRParen);
380}
381
Mike Stump1eb44332009-09-09 15:08:12 +0000382Sema::OwningExprResult
Douglas Gregor3433cf72009-05-21 00:00:09 +0000383Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
384 SourceLocation PlacementLParen,
385 MultiExprArg PlacementArgs,
386 SourceLocation PlacementRParen,
Mike Stump1eb44332009-09-09 15:08:12 +0000387 bool ParenTypeId,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000388 QualType AllocType,
389 SourceLocation TypeLoc,
390 SourceRange TypeRange,
391 ExprArg ArraySizeE,
392 SourceLocation ConstructorLParen,
393 MultiExprArg ConstructorArgs,
394 SourceLocation ConstructorRParen) {
395 if (CheckAllocatedType(AllocType, TypeLoc, TypeRange))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000396 return ExprError();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000397
Douglas Gregor3433cf72009-05-21 00:00:09 +0000398 QualType ResultType = Context.getPointerType(AllocType);
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000399
400 // That every array dimension except the first is constant was already
401 // checked by the type check above.
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000402
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000403 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
404 // or enumeration type with a non-negative value."
Douglas Gregor3433cf72009-05-21 00:00:09 +0000405 Expr *ArraySize = (Expr *)ArraySizeE.get();
Sebastian Redl28507842009-02-26 14:39:58 +0000406 if (ArraySize && !ArraySize->isTypeDependent()) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000407 QualType SizeType = ArraySize->getType();
408 if (!SizeType->isIntegralType() && !SizeType->isEnumeralType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000409 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
410 diag::err_array_size_not_integral)
411 << SizeType << ArraySize->getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000412 // Let's see if this is a constant < 0. If so, we reject it out of hand.
413 // We don't care about special rules, so we tell the machinery it's not
414 // evaluated - it gives us a result in more cases.
Sebastian Redl28507842009-02-26 14:39:58 +0000415 if (!ArraySize->isValueDependent()) {
416 llvm::APSInt Value;
417 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
418 if (Value < llvm::APSInt(
Anders Carlssonac18b2e2009-09-23 00:37:25 +0000419 llvm::APInt::getNullValue(Value.getBitWidth()),
420 Value.isUnsigned()))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000421 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
422 diag::err_typecheck_negative_array_size)
423 << ArraySize->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +0000424 }
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000425 }
Anders Carlssonac18b2e2009-09-23 00:37:25 +0000426
Eli Friedman73c39ab2009-10-20 08:27:19 +0000427 ImpCastExprToType(ArraySize, Context.getSizeType(),
428 CastExpr::CK_IntegralCast);
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000429 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000430
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000431 FunctionDecl *OperatorNew = 0;
432 FunctionDecl *OperatorDelete = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000433 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
434 unsigned NumPlaceArgs = PlacementArgs.size();
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000435
Sebastian Redl28507842009-02-26 14:39:58 +0000436 if (!AllocType->isDependentType() &&
437 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
438 FindAllocationFunctions(StartLoc,
Sebastian Redl00e68e22009-02-09 18:24:27 +0000439 SourceRange(PlacementLParen, PlacementRParen),
440 UseGlobal, AllocType, ArraySize, PlaceArgs,
441 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000442 return ExprError();
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000443 llvm::SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000444 if (OperatorNew) {
445 // Add default arguments, if any.
446 const FunctionProtoType *Proto =
447 OperatorNew->getType()->getAs<FunctionProtoType>();
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +0000448 VariadicCallType CallType =
449 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000450 bool Invalid = GatherArgumentsForCall(PlacementLParen, OperatorNew,
451 Proto, 1, PlaceArgs, NumPlaceArgs,
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +0000452 AllPlaceArgs, CallType);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000453 if (Invalid)
454 return ExprError();
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000455
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000456 NumPlaceArgs = AllPlaceArgs.size();
457 if (NumPlaceArgs > 0)
458 PlaceArgs = &AllPlaceArgs[0];
459 }
460
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000461 bool Init = ConstructorLParen.isValid();
462 // --- Choosing a constructor ---
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000463 CXXConstructorDecl *Constructor = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000464 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
465 unsigned NumConsArgs = ConstructorArgs.size();
Eli Friedmana8ce9ec2009-11-08 22:15:39 +0000466 ASTOwningVector<&ActionBase::DeleteExpr> ConvertedConstructorArgs(*this);
467
Douglas Gregor99a2e602009-12-16 01:38:02 +0000468 if (!AllocType->isDependentType() &&
469 !Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) {
470 // C++0x [expr.new]p15:
471 // A new-expression that creates an object of type T initializes that
472 // object as follows:
473 InitializationKind Kind
474 // - If the new-initializer is omitted, the object is default-
475 // initialized (8.5); if no initialization is performed,
476 // the object has indeterminate value
477 = !Init? InitializationKind::CreateDefault(TypeLoc)
478 // - Otherwise, the new-initializer is interpreted according to the
479 // initialization rules of 8.5 for direct-initialization.
480 : InitializationKind::CreateDirect(TypeLoc,
481 ConstructorLParen,
482 ConstructorRParen);
483
Douglas Gregor99a2e602009-12-16 01:38:02 +0000484 InitializedEntity Entity
Douglas Gregord6542d82009-12-22 15:35:07 +0000485 = InitializedEntity::InitializeNew(StartLoc, AllocType);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000486 InitializationSequence InitSeq(*this, Entity, Kind, ConsArgs, NumConsArgs);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000487 OwningExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
488 move(ConstructorArgs));
489 if (FullInit.isInvalid())
490 return ExprError();
491
492 // FullInit is our initializer; walk through it to determine if it's a
493 // constructor call, which CXXNewExpr handles directly.
494 if (Expr *FullInitExpr = (Expr *)FullInit.get()) {
495 if (CXXBindTemporaryExpr *Binder
496 = dyn_cast<CXXBindTemporaryExpr>(FullInitExpr))
497 FullInitExpr = Binder->getSubExpr();
498 if (CXXConstructExpr *Construct
499 = dyn_cast<CXXConstructExpr>(FullInitExpr)) {
500 Constructor = Construct->getConstructor();
501 for (CXXConstructExpr::arg_iterator A = Construct->arg_begin(),
502 AEnd = Construct->arg_end();
503 A != AEnd; ++A)
504 ConvertedConstructorArgs.push_back(A->Retain());
505 } else {
506 // Take the converted initializer.
507 ConvertedConstructorArgs.push_back(FullInit.release());
508 }
509 } else {
510 // No initialization required.
511 }
512
513 // Take the converted arguments and use them for the new expression.
Douglas Gregor39da0b82009-09-09 23:08:42 +0000514 NumConsArgs = ConvertedConstructorArgs.size();
515 ConsArgs = (Expr **)ConvertedConstructorArgs.take();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000516 }
Douglas Gregor99a2e602009-12-16 01:38:02 +0000517
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000518 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
Douglas Gregor089407b2009-10-17 21:40:42 +0000519
Sebastian Redlf53597f2009-03-15 17:47:39 +0000520 PlacementArgs.release();
521 ConstructorArgs.release();
Douglas Gregor3433cf72009-05-21 00:00:09 +0000522 ArraySizeE.release();
Sebastian Redlf53597f2009-03-15 17:47:39 +0000523 return Owned(new (Context) CXXNewExpr(UseGlobal, OperatorNew, PlaceArgs,
Ted Kremenek8189cde2009-02-07 01:47:29 +0000524 NumPlaceArgs, ParenTypeId, ArraySize, Constructor, Init,
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000525 ConsArgs, NumConsArgs, OperatorDelete, ResultType,
Mike Stump1eb44332009-09-09 15:08:12 +0000526 StartLoc, Init ? ConstructorRParen : SourceLocation()));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000527}
528
529/// CheckAllocatedType - Checks that a type is suitable as the allocated type
530/// in a new-expression.
531/// dimension off and stores the size expression in ArraySize.
Douglas Gregor3433cf72009-05-21 00:00:09 +0000532bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +0000533 SourceRange R) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000534 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
535 // abstract class type or array thereof.
Douglas Gregore7450f52009-03-24 19:52:54 +0000536 if (AllocType->isFunctionType())
Douglas Gregor3433cf72009-05-21 00:00:09 +0000537 return Diag(Loc, diag::err_bad_new_type)
538 << AllocType << 0 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +0000539 else if (AllocType->isReferenceType())
Douglas Gregor3433cf72009-05-21 00:00:09 +0000540 return Diag(Loc, diag::err_bad_new_type)
541 << AllocType << 1 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +0000542 else if (!AllocType->isDependentType() &&
Douglas Gregor3433cf72009-05-21 00:00:09 +0000543 RequireCompleteType(Loc, AllocType,
Anders Carlssonb7906612009-08-26 23:45:07 +0000544 PDiag(diag::err_new_incomplete_type)
545 << R))
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000546 return true;
Douglas Gregor3433cf72009-05-21 00:00:09 +0000547 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregore7450f52009-03-24 19:52:54 +0000548 diag::err_allocation_of_abstract_type))
549 return true;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000550
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000551 return false;
552}
553
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000554/// FindAllocationFunctions - Finds the overloads of operator new and delete
555/// that are appropriate for the allocation.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000556bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
557 bool UseGlobal, QualType AllocType,
558 bool IsArray, Expr **PlaceArgs,
559 unsigned NumPlaceArgs,
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000560 FunctionDecl *&OperatorNew,
Mike Stump1eb44332009-09-09 15:08:12 +0000561 FunctionDecl *&OperatorDelete) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000562 // --- Choosing an allocation function ---
563 // C++ 5.3.4p8 - 14 & 18
564 // 1) If UseGlobal is true, only look in the global scope. Else, also look
565 // in the scope of the allocated class.
566 // 2) If an array size is given, look for operator new[], else look for
567 // operator new.
568 // 3) The first argument is always size_t. Append the arguments from the
569 // placement form.
570 // FIXME: Also find the appropriate delete operator.
571
572 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
573 // We don't care about the actual value of this argument.
574 // FIXME: Should the Sema create the expression and embed it in the syntax
575 // tree? Or should the consumer just recalculate the value?
Anders Carlssond67c4c32009-08-16 20:29:29 +0000576 IntegerLiteral Size(llvm::APInt::getNullValue(
577 Context.Target.getPointerWidth(0)),
578 Context.getSizeType(),
579 SourceLocation());
580 AllocArgs[0] = &Size;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000581 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
582
583 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
584 IsArray ? OO_Array_New : OO_New);
585 if (AllocType->isRecordType() && !UseGlobal) {
Mike Stump1eb44332009-09-09 15:08:12 +0000586 CXXRecordDecl *Record
Ted Kremenek6217b802009-07-29 21:53:49 +0000587 = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl());
Sebastian Redl7f662392008-12-04 22:20:51 +0000588 // FIXME: We fail to find inherited overloads.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000589 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000590 AllocArgs.size(), Record, /*AllowMissing=*/true,
591 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000592 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000593 }
594 if (!OperatorNew) {
595 // Didn't find a member overload. Look for a global one.
596 DeclareGlobalNewDelete();
Sebastian Redl7f662392008-12-04 22:20:51 +0000597 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl00e68e22009-02-09 18:24:27 +0000598 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000599 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
600 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000601 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000602 }
603
Anders Carlssond9583892009-05-31 20:26:12 +0000604 // FindAllocationOverload can change the passed in arguments, so we need to
605 // copy them back.
606 if (NumPlaceArgs > 0)
607 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
Mike Stump1eb44332009-09-09 15:08:12 +0000608
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000609 return false;
610}
611
Sebastian Redl7f662392008-12-04 22:20:51 +0000612/// FindAllocationOverload - Find an fitting overload for the allocation
613/// function in the specified scope.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000614bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
615 DeclarationName Name, Expr** Args,
616 unsigned NumArgs, DeclContext *Ctx,
Mike Stump1eb44332009-09-09 15:08:12 +0000617 bool AllowMissing, FunctionDecl *&Operator) {
John McCalla24dc2e2009-11-17 02:14:36 +0000618 LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
619 LookupQualifiedName(R, Ctx);
John McCallf36e02d2009-10-09 21:13:30 +0000620 if (R.empty()) {
Sebastian Redl7f662392008-12-04 22:20:51 +0000621 if (AllowMissing)
622 return false;
Sebastian Redl7f662392008-12-04 22:20:51 +0000623 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +0000624 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +0000625 }
626
John McCallf36e02d2009-10-09 21:13:30 +0000627 // FIXME: handle ambiguity
628
Sebastian Redl7f662392008-12-04 22:20:51 +0000629 OverloadCandidateSet Candidates;
Douglas Gregor5d64e5b2009-09-30 00:03:47 +0000630 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
631 Alloc != AllocEnd; ++Alloc) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000632 // Even member operator new/delete are implicitly treated as
633 // static, so don't use AddMemberCandidate.
Anders Carlssoneac81392009-12-09 07:39:44 +0000634 if (FunctionDecl *Fn =
635 dyn_cast<FunctionDecl>((*Alloc)->getUnderlyingDecl())) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000636 AddOverloadCandidate(Fn, Args, NumArgs, Candidates,
637 /*SuppressUserConversions=*/false);
Douglas Gregor90916562009-09-29 18:16:17 +0000638 continue;
639 }
640
641 // FIXME: Handle function templates
Sebastian Redl7f662392008-12-04 22:20:51 +0000642 }
643
644 // Do the resolution.
645 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +0000646 switch(BestViableFunction(Candidates, StartLoc, Best)) {
Sebastian Redl7f662392008-12-04 22:20:51 +0000647 case OR_Success: {
648 // Got one!
649 FunctionDecl *FnDecl = Best->Function;
650 // The first argument is size_t, and the first parameter must be size_t,
651 // too. This is checked on declaration and can be assumed. (It can't be
652 // asserted on, though, since invalid decls are left in there.)
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000653 // Whatch out for variadic allocator function.
654 unsigned NumArgsInFnDecl = FnDecl->getNumParams();
655 for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) {
Anders Carlssonfc27d262009-05-31 19:49:47 +0000656 if (PerformCopyInitialization(Args[i],
Sebastian Redl7f662392008-12-04 22:20:51 +0000657 FnDecl->getParamDecl(i)->getType(),
Douglas Gregor68647482009-12-16 03:45:30 +0000658 AA_Passing))
Sebastian Redl7f662392008-12-04 22:20:51 +0000659 return true;
660 }
661 Operator = FnDecl;
662 return false;
663 }
664
665 case OR_No_Viable_Function:
Sebastian Redl7f662392008-12-04 22:20:51 +0000666 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +0000667 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +0000668 PrintOverloadCandidates(Candidates, /*OnlyViable=*/false);
669 return true;
670
671 case OR_Ambiguous:
Sebastian Redl7f662392008-12-04 22:20:51 +0000672 Diag(StartLoc, diag::err_ovl_ambiguous_call)
Sebastian Redl00e68e22009-02-09 18:24:27 +0000673 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +0000674 PrintOverloadCandidates(Candidates, /*OnlyViable=*/true);
675 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000676
677 case OR_Deleted:
678 Diag(StartLoc, diag::err_ovl_deleted_call)
679 << Best->Function->isDeleted()
680 << Name << Range;
681 PrintOverloadCandidates(Candidates, /*OnlyViable=*/true);
682 return true;
Sebastian Redl7f662392008-12-04 22:20:51 +0000683 }
684 assert(false && "Unreachable, bad result from BestViableFunction");
685 return true;
686}
687
688
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000689/// DeclareGlobalNewDelete - Declare the global forms of operator new and
690/// delete. These are:
691/// @code
692/// void* operator new(std::size_t) throw(std::bad_alloc);
693/// void* operator new[](std::size_t) throw(std::bad_alloc);
694/// void operator delete(void *) throw();
695/// void operator delete[](void *) throw();
696/// @endcode
697/// Note that the placement and nothrow forms of new are *not* implicitly
698/// declared. Their use requires including \<new\>.
Mike Stump1eb44332009-09-09 15:08:12 +0000699void Sema::DeclareGlobalNewDelete() {
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000700 if (GlobalNewDeleteDeclared)
701 return;
Douglas Gregor7adb10f2009-09-15 22:30:29 +0000702
703 // C++ [basic.std.dynamic]p2:
704 // [...] The following allocation and deallocation functions (18.4) are
705 // implicitly declared in global scope in each translation unit of a
706 // program
707 //
708 // void* operator new(std::size_t) throw(std::bad_alloc);
709 // void* operator new[](std::size_t) throw(std::bad_alloc);
710 // void operator delete(void*) throw();
711 // void operator delete[](void*) throw();
712 //
713 // These implicit declarations introduce only the function names operator
714 // new, operator new[], operator delete, operator delete[].
715 //
716 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
717 // "std" or "bad_alloc" as necessary to form the exception specification.
718 // However, we do not make these implicit declarations visible to name
719 // lookup.
720 if (!StdNamespace) {
721 // The "std" namespace has not yet been defined, so build one implicitly.
722 StdNamespace = NamespaceDecl::Create(Context,
723 Context.getTranslationUnitDecl(),
724 SourceLocation(),
725 &PP.getIdentifierTable().get("std"));
726 StdNamespace->setImplicit(true);
727 }
728
729 if (!StdBadAlloc) {
730 // The "std::bad_alloc" class has not yet been declared, so build it
731 // implicitly.
732 StdBadAlloc = CXXRecordDecl::Create(Context, TagDecl::TK_class,
733 StdNamespace,
734 SourceLocation(),
735 &PP.getIdentifierTable().get("bad_alloc"),
736 SourceLocation(), 0);
737 StdBadAlloc->setImplicit(true);
738 }
739
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000740 GlobalNewDeleteDeclared = true;
741
742 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
743 QualType SizeT = Context.getSizeType();
Nuno Lopesfc284482009-12-16 16:59:22 +0000744 bool AssumeSaneOperatorNew = getLangOptions().AssumeSaneOperatorNew;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000745
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000746 DeclareGlobalAllocationFunction(
747 Context.DeclarationNames.getCXXOperatorName(OO_New),
Nuno Lopesfc284482009-12-16 16:59:22 +0000748 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000749 DeclareGlobalAllocationFunction(
750 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
Nuno Lopesfc284482009-12-16 16:59:22 +0000751 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000752 DeclareGlobalAllocationFunction(
753 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
754 Context.VoidTy, VoidPtr);
755 DeclareGlobalAllocationFunction(
756 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
757 Context.VoidTy, VoidPtr);
758}
759
760/// DeclareGlobalAllocationFunction - Declares a single implicit global
761/// allocation function if it doesn't already exist.
762void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Nuno Lopesfc284482009-12-16 16:59:22 +0000763 QualType Return, QualType Argument,
764 bool AddMallocAttr) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000765 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
766
767 // Check if this function is already declared.
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000768 {
Douglas Gregor5cc37092008-12-23 22:05:29 +0000769 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000770 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000771 Alloc != AllocEnd; ++Alloc) {
772 // FIXME: Do we need to check for default arguments here?
773 FunctionDecl *Func = cast<FunctionDecl>(*Alloc);
774 if (Func->getNumParams() == 1 &&
Douglas Gregor6e790ab2009-12-22 23:42:49 +0000775 Context.getCanonicalType(
776 Func->getParamDecl(0)->getType().getUnqualifiedType()) == Argument)
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000777 return;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000778 }
779 }
780
Douglas Gregor7adb10f2009-09-15 22:30:29 +0000781 QualType BadAllocType;
782 bool HasBadAllocExceptionSpec
783 = (Name.getCXXOverloadedOperator() == OO_New ||
784 Name.getCXXOverloadedOperator() == OO_Array_New);
785 if (HasBadAllocExceptionSpec) {
786 assert(StdBadAlloc && "Must have std::bad_alloc declared");
787 BadAllocType = Context.getTypeDeclType(StdBadAlloc);
788 }
789
790 QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0,
791 true, false,
792 HasBadAllocExceptionSpec? 1 : 0,
793 &BadAllocType);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000794 FunctionDecl *Alloc =
795 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
John McCalla93c9342009-12-07 02:54:59 +0000796 FnType, /*TInfo=*/0, FunctionDecl::None, false, true);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000797 Alloc->setImplicit();
Nuno Lopesfc284482009-12-16 16:59:22 +0000798
799 if (AddMallocAttr)
800 Alloc->addAttr(::new (Context) MallocAttr());
801
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000802 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
John McCalla93c9342009-12-07 02:54:59 +0000803 0, Argument, /*TInfo=*/0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000804 VarDecl::None, 0);
Ted Kremenekfc767612009-01-14 00:42:25 +0000805 Alloc->setParams(Context, &Param, 1);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000806
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000807 // FIXME: Also add this declaration to the IdentifierResolver, but
808 // make sure it is at the end of the chain to coincide with the
809 // global scope.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000810 ((DeclContext *)TUScope->getEntity())->addDecl(Alloc);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000811}
812
Anders Carlsson78f74552009-11-15 18:45:20 +0000813bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
814 DeclarationName Name,
Anders Carlsson5ec02ae2009-12-02 17:15:43 +0000815 FunctionDecl* &Operator) {
John McCalla24dc2e2009-11-17 02:14:36 +0000816 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlsson78f74552009-11-15 18:45:20 +0000817 // Try to find operator delete/operator delete[] in class scope.
John McCalla24dc2e2009-11-17 02:14:36 +0000818 LookupQualifiedName(Found, RD);
Anders Carlsson78f74552009-11-15 18:45:20 +0000819
John McCalla24dc2e2009-11-17 02:14:36 +0000820 if (Found.isAmbiguous())
Anders Carlsson78f74552009-11-15 18:45:20 +0000821 return true;
Anders Carlsson78f74552009-11-15 18:45:20 +0000822
823 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
824 F != FEnd; ++F) {
825 if (CXXMethodDecl *Delete = dyn_cast<CXXMethodDecl>(*F))
826 if (Delete->isUsualDeallocationFunction()) {
827 Operator = Delete;
828 return false;
829 }
830 }
831
832 // We did find operator delete/operator delete[] declarations, but
833 // none of them were suitable.
834 if (!Found.empty()) {
835 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
836 << Name << RD;
837
838 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
839 F != FEnd; ++F) {
840 Diag((*F)->getLocation(),
841 diag::note_delete_member_function_declared_here)
842 << Name;
843 }
844
845 return true;
846 }
847
848 // Look for a global declaration.
849 DeclareGlobalNewDelete();
850 DeclContext *TUDecl = Context.getTranslationUnitDecl();
851
852 CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation());
853 Expr* DeallocArgs[1];
854 DeallocArgs[0] = &Null;
855 if (FindAllocationOverload(StartLoc, SourceRange(), Name,
856 DeallocArgs, 1, TUDecl, /*AllowMissing=*/false,
857 Operator))
858 return true;
859
860 assert(Operator && "Did not find a deallocation function!");
861 return false;
862}
863
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000864/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
865/// @code ::delete ptr; @endcode
866/// or
867/// @code delete [] ptr; @endcode
Sebastian Redlf53597f2009-03-15 17:47:39 +0000868Action::OwningExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000869Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
Mike Stump1eb44332009-09-09 15:08:12 +0000870 bool ArrayForm, ExprArg Operand) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000871 // C++ [expr.delete]p1:
872 // The operand shall have a pointer type, or a class type having a single
873 // conversion function to a pointer type. The result has type void.
874 //
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000875 // DR599 amends "pointer type" to "pointer to object type" in both cases.
876
Anders Carlssond67c4c32009-08-16 20:29:29 +0000877 FunctionDecl *OperatorDelete = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000878
Sebastian Redlf53597f2009-03-15 17:47:39 +0000879 Expr *Ex = (Expr *)Operand.get();
Sebastian Redl28507842009-02-26 14:39:58 +0000880 if (!Ex->isTypeDependent()) {
881 QualType Type = Ex->getType();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000882
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000883 if (const RecordType *Record = Type->getAs<RecordType>()) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000884 llvm::SmallVector<CXXConversionDecl *, 4> ObjectPtrConversions;
Fariborz Jahanian53462782009-09-11 21:44:33 +0000885 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
John McCallba135432009-11-21 08:51:07 +0000886 const UnresolvedSet *Conversions = RD->getVisibleConversionFunctions();
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000887
John McCallba135432009-11-21 08:51:07 +0000888 for (UnresolvedSet::iterator I = Conversions->begin(),
889 E = Conversions->end(); I != E; ++I) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000890 // Skip over templated conversion functions; they aren't considered.
John McCallba135432009-11-21 08:51:07 +0000891 if (isa<FunctionTemplateDecl>(*I))
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000892 continue;
893
John McCallba135432009-11-21 08:51:07 +0000894 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*I);
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000895
896 QualType ConvType = Conv->getConversionType().getNonReferenceType();
897 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
898 if (ConvPtrType->getPointeeType()->isObjectType())
Fariborz Jahanian8b915e72009-09-15 22:15:23 +0000899 ObjectPtrConversions.push_back(Conv);
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000900 }
Fariborz Jahanian8b915e72009-09-15 22:15:23 +0000901 if (ObjectPtrConversions.size() == 1) {
902 // We have a single conversion to a pointer-to-object type. Perform
903 // that conversion.
904 Operand.release();
905 if (!PerformImplicitConversion(Ex,
906 ObjectPtrConversions.front()->getConversionType(),
Douglas Gregor68647482009-12-16 03:45:30 +0000907 AA_Converting)) {
Fariborz Jahanian8b915e72009-09-15 22:15:23 +0000908 Operand = Owned(Ex);
909 Type = Ex->getType();
910 }
911 }
912 else if (ObjectPtrConversions.size() > 1) {
913 Diag(StartLoc, diag::err_ambiguous_delete_operand)
914 << Type << Ex->getSourceRange();
915 for (unsigned i= 0; i < ObjectPtrConversions.size(); i++) {
916 CXXConversionDecl *Conv = ObjectPtrConversions[i];
917 Diag(Conv->getLocation(), diag::err_ovl_candidate);
918 }
919 return ExprError();
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000920 }
Sebastian Redl28507842009-02-26 14:39:58 +0000921 }
922
Sebastian Redlf53597f2009-03-15 17:47:39 +0000923 if (!Type->isPointerType())
924 return ExprError(Diag(StartLoc, diag::err_delete_operand)
925 << Type << Ex->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +0000926
Ted Kremenek6217b802009-07-29 21:53:49 +0000927 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Douglas Gregor8dcb29d2009-03-24 20:13:58 +0000928 if (Pointee->isFunctionType() || Pointee->isVoidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000929 return ExprError(Diag(StartLoc, diag::err_delete_operand)
930 << Type << Ex->getSourceRange());
Douglas Gregor8dcb29d2009-03-24 20:13:58 +0000931 else if (!Pointee->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +0000932 RequireCompleteType(StartLoc, Pointee,
Anders Carlssonb7906612009-08-26 23:45:07 +0000933 PDiag(diag::warn_delete_incomplete)
934 << Ex->getSourceRange()))
Douglas Gregor8dcb29d2009-03-24 20:13:58 +0000935 return ExprError();
Sebastian Redl28507842009-02-26 14:39:58 +0000936
Douglas Gregor1070c9f2009-09-29 21:38:53 +0000937 // C++ [expr.delete]p2:
938 // [Note: a pointer to a const type can be the operand of a
939 // delete-expression; it is not necessary to cast away the constness
940 // (5.2.11) of the pointer expression before it is used as the operand
941 // of the delete-expression. ]
942 ImpCastExprToType(Ex, Context.getPointerType(Context.VoidTy),
943 CastExpr::CK_NoOp);
944
945 // Update the operand.
946 Operand.take();
947 Operand = ExprArg(*this, Ex);
948
Anders Carlssond67c4c32009-08-16 20:29:29 +0000949 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
950 ArrayForm ? OO_Array_Delete : OO_Delete);
951
Anders Carlsson78f74552009-11-15 18:45:20 +0000952 if (const RecordType *RT = Pointee->getAs<RecordType>()) {
953 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
954
955 if (!UseGlobal &&
956 FindDeallocationFunction(StartLoc, RD, DeleteName, OperatorDelete))
Anders Carlsson0ba63ea2009-11-14 03:17:38 +0000957 return ExprError();
Anders Carlsson0ba63ea2009-11-14 03:17:38 +0000958
Anders Carlsson78f74552009-11-15 18:45:20 +0000959 if (!RD->hasTrivialDestructor())
960 if (const CXXDestructorDecl *Dtor = RD->getDestructor(Context))
Mike Stump1eb44332009-09-09 15:08:12 +0000961 MarkDeclarationReferenced(StartLoc,
Fariborz Jahanian34374e62009-09-03 23:18:17 +0000962 const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssond67c4c32009-08-16 20:29:29 +0000963 }
Anders Carlsson78f74552009-11-15 18:45:20 +0000964
Anders Carlssond67c4c32009-08-16 20:29:29 +0000965 if (!OperatorDelete) {
Anders Carlsson78f74552009-11-15 18:45:20 +0000966 // Look for a global declaration.
Anders Carlssond67c4c32009-08-16 20:29:29 +0000967 DeclareGlobalNewDelete();
968 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000969 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
Douglas Gregor90916562009-09-29 18:16:17 +0000970 &Ex, 1, TUDecl, /*AllowMissing=*/false,
Anders Carlssond67c4c32009-08-16 20:29:29 +0000971 OperatorDelete))
972 return ExprError();
973 }
Mike Stump1eb44332009-09-09 15:08:12 +0000974
Sebastian Redl28507842009-02-26 14:39:58 +0000975 // FIXME: Check access and ambiguity of operator delete and destructor.
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000976 }
977
Sebastian Redlf53597f2009-03-15 17:47:39 +0000978 Operand.release();
979 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
Anders Carlssond67c4c32009-08-16 20:29:29 +0000980 OperatorDelete, Ex, StartLoc));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000981}
982
Douglas Gregor8cfe5a72009-11-23 23:44:04 +0000983/// \brief Check the use of the given variable as a C++ condition in an if,
984/// while, do-while, or switch statement.
985Action::OwningExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar) {
986 QualType T = ConditionVar->getType();
987
988 // C++ [stmt.select]p2:
989 // The declarator shall not specify a function or an array.
990 if (T->isFunctionType())
991 return ExprError(Diag(ConditionVar->getLocation(),
992 diag::err_invalid_use_of_function_type)
993 << ConditionVar->getSourceRange());
994 else if (T->isArrayType())
995 return ExprError(Diag(ConditionVar->getLocation(),
996 diag::err_invalid_use_of_array_type)
997 << ConditionVar->getSourceRange());
Douglas Gregora7605db2009-11-24 16:07:02 +0000998
Douglas Gregor8cfe5a72009-11-23 23:44:04 +0000999 return Owned(DeclRefExpr::Create(Context, 0, SourceRange(), ConditionVar,
1000 ConditionVar->getLocation(),
1001 ConditionVar->getType().getNonReferenceType()));
1002}
1003
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001004/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
1005bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
1006 // C++ 6.4p4:
1007 // The value of a condition that is an initialized declaration in a statement
1008 // other than a switch statement is the value of the declared variable
1009 // implicitly converted to type bool. If that conversion is ill-formed, the
1010 // program is ill-formed.
1011 // The value of a condition that is an expression is the value of the
1012 // expression, implicitly converted to bool.
1013 //
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001014 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001015}
Douglas Gregor77a52232008-09-12 00:47:35 +00001016
1017/// Helper function to determine whether this is the (deprecated) C++
1018/// conversion from a string literal to a pointer to non-const char or
1019/// non-const wchar_t (for narrow and wide string literals,
1020/// respectively).
Mike Stump1eb44332009-09-09 15:08:12 +00001021bool
Douglas Gregor77a52232008-09-12 00:47:35 +00001022Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
1023 // Look inside the implicit cast, if it exists.
1024 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
1025 From = Cast->getSubExpr();
1026
1027 // A string literal (2.13.4) that is not a wide string literal can
1028 // be converted to an rvalue of type "pointer to char"; a wide
1029 // string literal can be converted to an rvalue of type "pointer
1030 // to wchar_t" (C++ 4.2p2).
1031 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From))
Ted Kremenek6217b802009-07-29 21:53:49 +00001032 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump1eb44332009-09-09 15:08:12 +00001033 if (const BuiltinType *ToPointeeType
John McCall183700f2009-09-21 23:43:11 +00001034 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregor77a52232008-09-12 00:47:35 +00001035 // This conversion is considered only when there is an
1036 // explicit appropriate pointer target type (C++ 4.2p2).
John McCall0953e762009-09-24 19:53:00 +00001037 if (!ToPtrType->getPointeeType().hasQualifiers() &&
Douglas Gregor77a52232008-09-12 00:47:35 +00001038 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
1039 (!StrLit->isWide() &&
1040 (ToPointeeType->getKind() == BuiltinType::Char_U ||
1041 ToPointeeType->getKind() == BuiltinType::Char_S))))
1042 return true;
1043 }
1044
1045 return false;
1046}
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001047
1048/// PerformImplicitConversion - Perform an implicit conversion of the
1049/// expression From to the type ToType. Returns true if there was an
1050/// error, false otherwise. The expression From is replaced with the
Douglas Gregor45920e82008-12-19 17:40:08 +00001051/// converted expression. Flavor is the kind of conversion we're
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001052/// performing, used in the error message. If @p AllowExplicit,
Sebastian Redle2b68332009-04-12 17:16:29 +00001053/// explicit user-defined conversions are permitted. @p Elidable should be true
1054/// when called for copies which may be elided (C++ 12.8p15). C++0x overload
1055/// resolution works differently in that case.
1056bool
Douglas Gregor45920e82008-12-19 17:40:08 +00001057Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor68647482009-12-16 03:45:30 +00001058 AssignmentAction Action, bool AllowExplicit,
Mike Stump1eb44332009-09-09 15:08:12 +00001059 bool Elidable) {
Sebastian Redle2b68332009-04-12 17:16:29 +00001060 ImplicitConversionSequence ICS;
Douglas Gregor68647482009-12-16 03:45:30 +00001061 return PerformImplicitConversion(From, ToType, Action, AllowExplicit,
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00001062 Elidable, ICS);
1063}
1064
1065bool
1066Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor68647482009-12-16 03:45:30 +00001067 AssignmentAction Action, bool AllowExplicit,
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00001068 bool Elidable,
1069 ImplicitConversionSequence& ICS) {
Sebastian Redle2b68332009-04-12 17:16:29 +00001070 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1071 if (Elidable && getLangOptions().CPlusPlus0x) {
Mike Stump1eb44332009-09-09 15:08:12 +00001072 ICS = TryImplicitConversion(From, ToType,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001073 /*SuppressUserConversions=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +00001074 AllowExplicit,
Anders Carlsson08972922009-08-28 15:33:32 +00001075 /*ForceRValue=*/true,
1076 /*InOverloadResolution=*/false);
Sebastian Redle2b68332009-04-12 17:16:29 +00001077 }
1078 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion) {
Mike Stump1eb44332009-09-09 15:08:12 +00001079 ICS = TryImplicitConversion(From, ToType,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001080 /*SuppressUserConversions=*/false,
1081 AllowExplicit,
Anders Carlsson08972922009-08-28 15:33:32 +00001082 /*ForceRValue=*/false,
1083 /*InOverloadResolution=*/false);
Sebastian Redle2b68332009-04-12 17:16:29 +00001084 }
Douglas Gregor68647482009-12-16 03:45:30 +00001085 return PerformImplicitConversion(From, ToType, ICS, Action);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001086}
1087
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001088/// BuildCXXDerivedToBaseExpr - This routine generates the suitable AST
1089/// for the derived to base conversion of the expression 'From'. All
1090/// necessary information is passed in ICS.
1091bool
1092Sema::BuildCXXDerivedToBaseExpr(Expr *&From, CastExpr::CastKind CastKind,
Douglas Gregor68647482009-12-16 03:45:30 +00001093 const ImplicitConversionSequence& ICS) {
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001094 QualType BaseType =
1095 QualType::getFromOpaquePtr(ICS.UserDefined.After.ToTypePtr);
1096 // Must do additional defined to base conversion.
1097 QualType DerivedType =
1098 QualType::getFromOpaquePtr(ICS.UserDefined.After.FromTypePtr);
1099
1100 From = new (Context) ImplicitCastExpr(
1101 DerivedType.getNonReferenceType(),
1102 CastKind,
1103 From,
1104 DerivedType->isLValueReferenceType());
1105 From = new (Context) ImplicitCastExpr(BaseType.getNonReferenceType(),
1106 CastExpr::CK_DerivedToBase, From,
1107 BaseType->isLValueReferenceType());
1108 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1109 OwningExprResult FromResult =
1110 BuildCXXConstructExpr(
1111 ICS.UserDefined.After.CopyConstructor->getLocation(),
1112 BaseType,
1113 ICS.UserDefined.After.CopyConstructor,
1114 MultiExprArg(*this, (void **)&From, 1));
1115 if (FromResult.isInvalid())
1116 return true;
1117 From = FromResult.takeAs<Expr>();
1118 return false;
1119}
1120
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001121/// PerformImplicitConversion - Perform an implicit conversion of the
1122/// expression From to the type ToType using the pre-computed implicit
1123/// conversion sequence ICS. Returns true if there was an error, false
1124/// otherwise. The expression From is replaced with the converted
Douglas Gregor68647482009-12-16 03:45:30 +00001125/// expression. Action is the kind of conversion we're performing,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001126/// used in the error message.
1127bool
1128Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
1129 const ImplicitConversionSequence &ICS,
Douglas Gregor68647482009-12-16 03:45:30 +00001130 AssignmentAction Action, bool IgnoreBaseAccess) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001131 switch (ICS.ConversionKind) {
1132 case ImplicitConversionSequence::StandardConversion:
Douglas Gregor68647482009-12-16 03:45:30 +00001133 if (PerformImplicitConversion(From, ToType, ICS.Standard, Action,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001134 IgnoreBaseAccess))
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001135 return true;
1136 break;
1137
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001138 case ImplicitConversionSequence::UserDefinedConversion: {
1139
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00001140 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
1141 CastExpr::CastKind CastKind = CastExpr::CK_Unknown;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001142 QualType BeforeToType;
1143 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00001144 CastKind = CastExpr::CK_UserDefinedConversion;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001145
1146 // If the user-defined conversion is specified by a conversion function,
1147 // the initial standard conversion sequence converts the source type to
1148 // the implicit object parameter of the conversion function.
1149 BeforeToType = Context.getTagDeclType(Conv->getParent());
1150 } else if (const CXXConstructorDecl *Ctor =
1151 dyn_cast<CXXConstructorDecl>(FD)) {
Anders Carlsson0aebc812009-09-09 21:33:21 +00001152 CastKind = CastExpr::CK_ConstructorConversion;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001153 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregore44201a2009-11-20 02:31:03 +00001154 if (!ICS.UserDefined.EllipsisConversion) {
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001155 // If the user-defined conversion is specified by a constructor, the
1156 // initial standard conversion sequence converts the source type to the
1157 // type required by the argument of the constructor
Douglas Gregore44201a2009-11-20 02:31:03 +00001158 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
1159 }
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001160 }
Anders Carlsson0aebc812009-09-09 21:33:21 +00001161 else
1162 assert(0 && "Unknown conversion function kind!");
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001163 // Whatch out for elipsis conversion.
Fariborz Jahanian4c0cea22009-11-06 00:55:14 +00001164 if (!ICS.UserDefined.EllipsisConversion) {
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001165 if (PerformImplicitConversion(From, BeforeToType,
Douglas Gregor68647482009-12-16 03:45:30 +00001166 ICS.UserDefined.Before, AA_Converting,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001167 IgnoreBaseAccess))
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001168 return true;
1169 }
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001170
Anders Carlsson0aebc812009-09-09 21:33:21 +00001171 OwningExprResult CastArg
1172 = BuildCXXCastArgument(From->getLocStart(),
1173 ToType.getNonReferenceType(),
1174 CastKind, cast<CXXMethodDecl>(FD),
1175 Owned(From));
1176
1177 if (CastArg.isInvalid())
1178 return true;
Eli Friedmand8889622009-11-27 04:41:50 +00001179
1180 From = CastArg.takeAs<Expr>();
1181
1182 // FIXME: This and the following if statement shouldn't be necessary, but
1183 // there's some nasty stuff involving MaybeBindToTemporary going on here.
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001184 if (ICS.UserDefined.After.Second == ICK_Derived_To_Base &&
1185 ICS.UserDefined.After.CopyConstructor) {
Douglas Gregor68647482009-12-16 03:45:30 +00001186 return BuildCXXDerivedToBaseExpr(From, CastKind, ICS);
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001187 }
Eli Friedmand8889622009-11-27 04:41:50 +00001188
1189 if (ICS.UserDefined.After.CopyConstructor) {
1190 From = new (Context) ImplicitCastExpr(ToType.getNonReferenceType(),
1191 CastKind, From,
1192 ToType->isLValueReferenceType());
1193 return false;
1194 }
1195
1196 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
Douglas Gregor68647482009-12-16 03:45:30 +00001197 AA_Converting, IgnoreBaseAccess);
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001198 }
1199
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001200 case ImplicitConversionSequence::EllipsisConversion:
1201 assert(false && "Cannot perform an ellipsis conversion");
Douglas Gregor60d62c22008-10-31 16:23:19 +00001202 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001203
1204 case ImplicitConversionSequence::BadConversion:
1205 return true;
1206 }
1207
1208 // Everything went well.
1209 return false;
1210}
1211
1212/// PerformImplicitConversion - Perform an implicit conversion of the
1213/// expression From to the type ToType by following the standard
1214/// conversion sequence SCS. Returns true if there was an error, false
1215/// otherwise. The expression From is replaced with the converted
Douglas Gregor45920e82008-12-19 17:40:08 +00001216/// expression. Flavor is the context in which we're performing this
1217/// conversion, for use in error messages.
Mike Stump1eb44332009-09-09 15:08:12 +00001218bool
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001219Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor45920e82008-12-19 17:40:08 +00001220 const StandardConversionSequence& SCS,
Douglas Gregor68647482009-12-16 03:45:30 +00001221 AssignmentAction Action, bool IgnoreBaseAccess) {
Mike Stump390b4cc2009-05-16 07:39:55 +00001222 // Overall FIXME: we are recomputing too many types here and doing far too
1223 // much extra work. What this means is that we need to keep track of more
1224 // information that is computed when we try the implicit conversion initially,
1225 // so that we don't need to recompute anything here.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001226 QualType FromType = From->getType();
1227
Douglas Gregor225c41e2008-11-03 19:09:14 +00001228 if (SCS.CopyConstructor) {
Anders Carlsson7c3e8a12009-05-19 04:45:15 +00001229 // FIXME: When can ToType be a reference type?
1230 assert(!ToType->isReferenceType());
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00001231 if (SCS.Second == ICK_Derived_To_Base) {
1232 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1233 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
1234 MultiExprArg(*this, (void **)&From, 1),
1235 /*FIXME:ConstructLoc*/SourceLocation(),
1236 ConstructorArgs))
1237 return true;
1238 OwningExprResult FromResult =
1239 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1240 ToType, SCS.CopyConstructor,
1241 move_arg(ConstructorArgs));
1242 if (FromResult.isInvalid())
1243 return true;
1244 From = FromResult.takeAs<Expr>();
1245 return false;
1246 }
Mike Stump1eb44332009-09-09 15:08:12 +00001247 OwningExprResult FromResult =
1248 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1249 ToType, SCS.CopyConstructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00001250 MultiExprArg(*this, (void**)&From, 1));
Mike Stump1eb44332009-09-09 15:08:12 +00001251
Anders Carlssonda3f4e22009-08-25 05:12:04 +00001252 if (FromResult.isInvalid())
1253 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001254
Anders Carlssonda3f4e22009-08-25 05:12:04 +00001255 From = FromResult.takeAs<Expr>();
Douglas Gregor225c41e2008-11-03 19:09:14 +00001256 return false;
1257 }
1258
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001259 // Perform the first implicit conversion.
1260 switch (SCS.First) {
1261 case ICK_Identity:
1262 case ICK_Lvalue_To_Rvalue:
1263 // Nothing to do.
1264 break;
1265
1266 case ICK_Array_To_Pointer:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001267 FromType = Context.getArrayDecayedType(FromType);
Anders Carlsson82495762009-08-08 21:04:35 +00001268 ImpCastExprToType(From, FromType, CastExpr::CK_ArrayToPointerDecay);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001269 break;
1270
1271 case ICK_Function_To_Pointer:
Douglas Gregor063daf62009-03-13 18:40:31 +00001272 if (Context.getCanonicalType(FromType) == Context.OverloadTy) {
Douglas Gregor904eed32008-11-10 20:40:00 +00001273 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, true);
1274 if (!Fn)
1275 return true;
1276
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001277 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
1278 return true;
1279
Anders Carlsson96ad5332009-10-21 17:16:23 +00001280 From = FixOverloadedFunctionReference(From, Fn);
Douglas Gregor904eed32008-11-10 20:40:00 +00001281 FromType = From->getType();
Anders Carlsson96ad5332009-10-21 17:16:23 +00001282
Sebastian Redl759986e2009-10-17 20:50:27 +00001283 // If there's already an address-of operator in the expression, we have
1284 // the right type already, and the code below would just introduce an
1285 // invalid additional pointer level.
Anders Carlsson96ad5332009-10-21 17:16:23 +00001286 if (FromType->isPointerType() || FromType->isMemberFunctionPointerType())
Sebastian Redl759986e2009-10-17 20:50:27 +00001287 break;
Douglas Gregor904eed32008-11-10 20:40:00 +00001288 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001289 FromType = Context.getPointerType(FromType);
Anders Carlssonb633c4e2009-09-01 20:37:18 +00001290 ImpCastExprToType(From, FromType, CastExpr::CK_FunctionToPointerDecay);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001291 break;
1292
1293 default:
1294 assert(false && "Improper first standard conversion");
1295 break;
1296 }
1297
1298 // Perform the second implicit conversion
1299 switch (SCS.Second) {
1300 case ICK_Identity:
Sebastian Redl2c7588f2009-10-10 12:04:10 +00001301 // If both sides are functions (or pointers/references to them), there could
1302 // be incompatible exception declarations.
1303 if (CheckExceptionSpecCompatibility(From, ToType))
1304 return true;
1305 // Nothing else to do.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001306 break;
1307
Douglas Gregor43c79c22009-12-09 00:47:37 +00001308 case ICK_NoReturn_Adjustment:
1309 // If both sides are functions (or pointers/references to them), there could
1310 // be incompatible exception declarations.
1311 if (CheckExceptionSpecCompatibility(From, ToType))
1312 return true;
1313
1314 ImpCastExprToType(From, Context.getNoReturnType(From->getType(), false),
1315 CastExpr::CK_NoOp);
1316 break;
1317
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001318 case ICK_Integral_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001319 case ICK_Integral_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001320 ImpCastExprToType(From, ToType, CastExpr::CK_IntegralCast);
1321 break;
1322
1323 case ICK_Floating_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001324 case ICK_Floating_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001325 ImpCastExprToType(From, ToType, CastExpr::CK_FloatingCast);
1326 break;
1327
1328 case ICK_Complex_Promotion:
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001329 case ICK_Complex_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001330 ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1331 break;
1332
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001333 case ICK_Floating_Integral:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001334 if (ToType->isFloatingType())
1335 ImpCastExprToType(From, ToType, CastExpr::CK_IntegralToFloating);
1336 else
1337 ImpCastExprToType(From, ToType, CastExpr::CK_FloatingToIntegral);
1338 break;
1339
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001340 case ICK_Complex_Real:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001341 ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1342 break;
1343
Douglas Gregorf9201e02009-02-11 23:02:49 +00001344 case ICK_Compatible_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001345 ImpCastExprToType(From, ToType, CastExpr::CK_NoOp);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001346 break;
1347
Anders Carlsson61faec12009-09-12 04:46:44 +00001348 case ICK_Pointer_Conversion: {
Douglas Gregor45920e82008-12-19 17:40:08 +00001349 if (SCS.IncompatibleObjC) {
1350 // Diagnose incompatible Objective-C conversions
Mike Stump1eb44332009-09-09 15:08:12 +00001351 Diag(From->getSourceRange().getBegin(),
Douglas Gregor45920e82008-12-19 17:40:08 +00001352 diag::ext_typecheck_convert_incompatible_pointer)
Douglas Gregor68647482009-12-16 03:45:30 +00001353 << From->getType() << ToType << Action
Douglas Gregor45920e82008-12-19 17:40:08 +00001354 << From->getSourceRange();
1355 }
1356
Anders Carlsson61faec12009-09-12 04:46:44 +00001357
1358 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001359 if (CheckPointerConversion(From, ToType, Kind, IgnoreBaseAccess))
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001360 return true;
Anders Carlsson61faec12009-09-12 04:46:44 +00001361 ImpCastExprToType(From, ToType, Kind);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001362 break;
Anders Carlsson61faec12009-09-12 04:46:44 +00001363 }
1364
1365 case ICK_Pointer_Member: {
1366 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001367 if (CheckMemberPointerConversion(From, ToType, Kind, IgnoreBaseAccess))
Anders Carlsson61faec12009-09-12 04:46:44 +00001368 return true;
Sebastian Redl2c7588f2009-10-10 12:04:10 +00001369 if (CheckExceptionSpecCompatibility(From, ToType))
1370 return true;
Anders Carlsson61faec12009-09-12 04:46:44 +00001371 ImpCastExprToType(From, ToType, Kind);
1372 break;
1373 }
Anders Carlssonbc0e0782009-11-23 20:04:44 +00001374 case ICK_Boolean_Conversion: {
1375 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
1376 if (FromType->isMemberPointerType())
1377 Kind = CastExpr::CK_MemberPointerToBoolean;
1378
1379 ImpCastExprToType(From, Context.BoolTy, Kind);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001380 break;
Anders Carlssonbc0e0782009-11-23 20:04:44 +00001381 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001382
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001383 case ICK_Derived_To_Base:
1384 if (CheckDerivedToBaseConversion(From->getType(),
1385 ToType.getNonReferenceType(),
1386 From->getLocStart(),
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001387 From->getSourceRange(),
1388 IgnoreBaseAccess))
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001389 return true;
1390 ImpCastExprToType(From, ToType.getNonReferenceType(),
1391 CastExpr::CK_DerivedToBase);
1392 break;
1393
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001394 default:
1395 assert(false && "Improper second standard conversion");
1396 break;
1397 }
1398
1399 switch (SCS.Third) {
1400 case ICK_Identity:
1401 // Nothing to do.
1402 break;
1403
1404 case ICK_Qualification:
Mike Stump390b4cc2009-05-16 07:39:55 +00001405 // FIXME: Not sure about lvalue vs rvalue here in the presence of rvalue
1406 // references.
Mike Stump1eb44332009-09-09 15:08:12 +00001407 ImpCastExprToType(From, ToType.getNonReferenceType(),
Eli Friedman73c39ab2009-10-20 08:27:19 +00001408 CastExpr::CK_NoOp,
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001409 ToType->isLValueReferenceType());
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001410 break;
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001411
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001412 default:
1413 assert(false && "Improper second standard conversion");
1414 break;
1415 }
1416
1417 return false;
1418}
1419
Sebastian Redl64b45f72009-01-05 20:52:13 +00001420Sema::OwningExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
1421 SourceLocation KWLoc,
1422 SourceLocation LParen,
1423 TypeTy *Ty,
1424 SourceLocation RParen) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00001425 QualType T = GetTypeFromParser(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00001426
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001427 // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
1428 // all traits except __is_class, __is_enum and __is_union require a the type
1429 // to be complete.
1430 if (OTT != UTT_IsClass && OTT != UTT_IsEnum && OTT != UTT_IsUnion) {
Mike Stump1eb44332009-09-09 15:08:12 +00001431 if (RequireCompleteType(KWLoc, T,
Anders Carlssond497ba72009-08-26 22:59:12 +00001432 diag::err_incomplete_type_used_in_type_trait_expr))
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001433 return ExprError();
1434 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00001435
1436 // There is no point in eagerly computing the value. The traits are designed
1437 // to be used from type trait templates, so Ty will be a template parameter
1438 // 99% of the time.
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001439 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT, T,
1440 RParen, Context.BoolTy));
Sebastian Redl64b45f72009-01-05 20:52:13 +00001441}
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001442
1443QualType Sema::CheckPointerToMemberOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00001444 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001445 const char *OpSpelling = isIndirect ? "->*" : ".*";
1446 // C++ 5.5p2
1447 // The binary operator .* [p3: ->*] binds its second operand, which shall
1448 // be of type "pointer to member of T" (where T is a completely-defined
1449 // class type) [...]
1450 QualType RType = rex->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001451 const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
Douglas Gregore7450f52009-03-24 19:52:54 +00001452 if (!MemPtr) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001453 Diag(Loc, diag::err_bad_memptr_rhs)
1454 << OpSpelling << RType << rex->getSourceRange();
1455 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00001456 }
Douglas Gregore7450f52009-03-24 19:52:54 +00001457
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001458 QualType Class(MemPtr->getClass(), 0);
1459
1460 // C++ 5.5p2
1461 // [...] to its first operand, which shall be of class T or of a class of
1462 // which T is an unambiguous and accessible base class. [p3: a pointer to
1463 // such a class]
1464 QualType LType = lex->getType();
1465 if (isIndirect) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001466 if (const PointerType *Ptr = LType->getAs<PointerType>())
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001467 LType = Ptr->getPointeeType().getNonReferenceType();
1468 else {
1469 Diag(Loc, diag::err_bad_memptr_lhs)
Fariborz Jahanianef78ac62009-10-26 20:45:27 +00001470 << OpSpelling << 1 << LType
1471 << CodeModificationHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001472 return QualType();
1473 }
1474 }
1475
Douglas Gregora4923eb2009-11-16 21:35:15 +00001476 if (!Context.hasSameUnqualifiedType(Class, LType)) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001477 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1478 /*DetectVirtual=*/false);
Mike Stump390b4cc2009-05-16 07:39:55 +00001479 // FIXME: Would it be useful to print full ambiguity paths, or is that
1480 // overkill?
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001481 if (!IsDerivedFrom(LType, Class, Paths) ||
1482 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
Fariborz Jahanianef78ac62009-10-26 20:45:27 +00001483 const char *ReplaceStr = isIndirect ? ".*" : "->*";
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001484 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Fariborz Jahanianef78ac62009-10-26 20:45:27 +00001485 << (int)isIndirect << lex->getType() <<
1486 CodeModificationHint::CreateReplacement(SourceRange(Loc), ReplaceStr);
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001487 return QualType();
1488 }
1489 }
1490
Fariborz Jahanian19d70732009-11-18 22:16:17 +00001491 if (isa<CXXZeroInitValueExpr>(rex->IgnoreParens())) {
Fariborz Jahanian05ebda92009-11-18 21:54:48 +00001492 // Diagnose use of pointer-to-member type which when used as
1493 // the functional cast in a pointer-to-member expression.
1494 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
1495 return QualType();
1496 }
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001497 // C++ 5.5p2
1498 // The result is an object or a function of the type specified by the
1499 // second operand.
1500 // The cv qualifiers are the union of those in the pointer and the left side,
1501 // in accordance with 5.5p5 and 5.2.5.
1502 // FIXME: This returns a dereferenced member function pointer as a normal
1503 // function type. However, the only operation valid on such functions is
Mike Stump390b4cc2009-05-16 07:39:55 +00001504 // calling them. There's also a GCC extension to get a function pointer to the
1505 // thing, which is another complication, because this type - unlike the type
1506 // that is the result of this expression - takes the class as the first
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001507 // argument.
1508 // We probably need a "MemberFunctionClosureType" or something like that.
1509 QualType Result = MemPtr->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00001510 Result = Context.getCVRQualifiedType(Result, LType.getCVRQualifiers());
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001511 return Result;
1512}
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001513
1514/// \brief Get the target type of a standard or user-defined conversion.
1515static QualType TargetType(const ImplicitConversionSequence &ICS) {
1516 assert((ICS.ConversionKind ==
1517 ImplicitConversionSequence::StandardConversion ||
1518 ICS.ConversionKind ==
1519 ImplicitConversionSequence::UserDefinedConversion) &&
1520 "function only valid for standard or user-defined conversions");
1521 if (ICS.ConversionKind == ImplicitConversionSequence::StandardConversion)
1522 return QualType::getFromOpaquePtr(ICS.Standard.ToTypePtr);
1523 return QualType::getFromOpaquePtr(ICS.UserDefined.After.ToTypePtr);
1524}
1525
1526/// \brief Try to convert a type to another according to C++0x 5.16p3.
1527///
1528/// This is part of the parameter validation for the ? operator. If either
1529/// value operand is a class type, the two operands are attempted to be
1530/// converted to each other. This function does the conversion in one direction.
1531/// It emits a diagnostic and returns true only if it finds an ambiguous
1532/// conversion.
1533static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
1534 SourceLocation QuestionLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00001535 ImplicitConversionSequence &ICS) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001536 // C++0x 5.16p3
1537 // The process for determining whether an operand expression E1 of type T1
1538 // can be converted to match an operand expression E2 of type T2 is defined
1539 // as follows:
1540 // -- If E2 is an lvalue:
1541 if (To->isLvalue(Self.Context) == Expr::LV_Valid) {
1542 // E1 can be converted to match E2 if E1 can be implicitly converted to
1543 // type "lvalue reference to T2", subject to the constraint that in the
1544 // conversion the reference must bind directly to E1.
1545 if (!Self.CheckReferenceInit(From,
1546 Self.Context.getLValueReferenceType(To->getType()),
Douglas Gregor739d8282009-09-23 23:04:10 +00001547 To->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001548 /*SuppressUserConversions=*/false,
1549 /*AllowExplicit=*/false,
1550 /*ForceRValue=*/false,
1551 &ICS))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001552 {
1553 assert((ICS.ConversionKind ==
1554 ImplicitConversionSequence::StandardConversion ||
1555 ICS.ConversionKind ==
1556 ImplicitConversionSequence::UserDefinedConversion) &&
1557 "expected a definite conversion");
1558 bool DirectBinding =
1559 ICS.ConversionKind == ImplicitConversionSequence::StandardConversion ?
1560 ICS.Standard.DirectBinding : ICS.UserDefined.After.DirectBinding;
1561 if (DirectBinding)
1562 return false;
1563 }
1564 }
1565 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1566 // -- If E2 is an rvalue, or if the conversion above cannot be done:
1567 // -- if E1 and E2 have class type, and the underlying class types are
1568 // the same or one is a base class of the other:
1569 QualType FTy = From->getType();
1570 QualType TTy = To->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001571 const RecordType *FRec = FTy->getAs<RecordType>();
1572 const RecordType *TRec = TTy->getAs<RecordType>();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001573 bool FDerivedFromT = FRec && TRec && Self.IsDerivedFrom(FTy, TTy);
1574 if (FRec && TRec && (FRec == TRec ||
1575 FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
1576 // E1 can be converted to match E2 if the class of T2 is the
1577 // same type as, or a base class of, the class of T1, and
1578 // [cv2 > cv1].
1579 if ((FRec == TRec || FDerivedFromT) && TTy.isAtLeastAsQualifiedAs(FTy)) {
1580 // Could still fail if there's no copy constructor.
1581 // FIXME: Is this a hard error then, or just a conversion failure? The
1582 // standard doesn't say.
Mike Stump1eb44332009-09-09 15:08:12 +00001583 ICS = Self.TryCopyInitialization(From, TTy,
Anders Carlssond28b4282009-08-27 17:18:13 +00001584 /*SuppressUserConversions=*/false,
Anders Carlsson7b361b52009-08-27 17:37:39 +00001585 /*ForceRValue=*/false,
1586 /*InOverloadResolution=*/false);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001587 }
1588 } else {
1589 // -- Otherwise: E1 can be converted to match E2 if E1 can be
1590 // implicitly converted to the type that expression E2 would have
1591 // if E2 were converted to an rvalue.
1592 // First find the decayed type.
1593 if (TTy->isFunctionType())
1594 TTy = Self.Context.getPointerType(TTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001595 else if (TTy->isArrayType())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001596 TTy = Self.Context.getArrayDecayedType(TTy);
1597
1598 // Now try the implicit conversion.
1599 // FIXME: This doesn't detect ambiguities.
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001600 ICS = Self.TryImplicitConversion(From, TTy,
1601 /*SuppressUserConversions=*/false,
1602 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00001603 /*ForceRValue=*/false,
1604 /*InOverloadResolution=*/false);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001605 }
1606 return false;
1607}
1608
1609/// \brief Try to find a common type for two according to C++0x 5.16p5.
1610///
1611/// This is part of the parameter validation for the ? operator. If either
1612/// value operand is a class type, overload resolution is used to find a
1613/// conversion to a common type.
1614static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
1615 SourceLocation Loc) {
1616 Expr *Args[2] = { LHS, RHS };
1617 OverloadCandidateSet CandidateSet;
Douglas Gregor573d9c32009-10-21 23:19:44 +00001618 Self.AddBuiltinOperatorCandidates(OO_Conditional, Loc, Args, 2, CandidateSet);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001619
1620 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00001621 switch (Self.BestViableFunction(CandidateSet, Loc, Best)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00001622 case OR_Success:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001623 // We found a match. Perform the conversions on the arguments and move on.
1624 if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00001625 Best->Conversions[0], Sema::AA_Converting) ||
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001626 Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor68647482009-12-16 03:45:30 +00001627 Best->Conversions[1], Sema::AA_Converting))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001628 break;
1629 return false;
1630
Douglas Gregor20093b42009-12-09 23:02:17 +00001631 case OR_No_Viable_Function:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001632 Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
1633 << LHS->getType() << RHS->getType()
1634 << LHS->getSourceRange() << RHS->getSourceRange();
1635 return true;
1636
Douglas Gregor20093b42009-12-09 23:02:17 +00001637 case OR_Ambiguous:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001638 Self.Diag(Loc, diag::err_conditional_ambiguous_ovl)
1639 << LHS->getType() << RHS->getType()
1640 << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stump390b4cc2009-05-16 07:39:55 +00001641 // FIXME: Print the possible common types by printing the return types of
1642 // the viable candidates.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001643 break;
1644
Douglas Gregor20093b42009-12-09 23:02:17 +00001645 case OR_Deleted:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001646 assert(false && "Conditional operator has only built-in overloads");
1647 break;
1648 }
1649 return true;
1650}
1651
Sebastian Redl76458502009-04-17 16:30:52 +00001652/// \brief Perform an "extended" implicit conversion as returned by
1653/// TryClassUnification.
1654///
1655/// TryClassUnification generates ICSs that include reference bindings.
1656/// PerformImplicitConversion is not suitable for this; it chokes if the
1657/// second part of a standard conversion is ICK_DerivedToBase. This function
1658/// handles the reference binding specially.
1659static bool ConvertForConditional(Sema &Self, Expr *&E,
Mike Stump1eb44332009-09-09 15:08:12 +00001660 const ImplicitConversionSequence &ICS) {
Sebastian Redl76458502009-04-17 16:30:52 +00001661 if (ICS.ConversionKind == ImplicitConversionSequence::StandardConversion &&
1662 ICS.Standard.ReferenceBinding) {
1663 assert(ICS.Standard.DirectBinding &&
1664 "TryClassUnification should never generate indirect ref bindings");
Sebastian Redla5cd2cd2009-04-26 11:21:02 +00001665 // FIXME: CheckReferenceInit should be able to reuse the ICS instead of
1666 // redoing all the work.
1667 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001668 TargetType(ICS)),
Douglas Gregor739d8282009-09-23 23:04:10 +00001669 /*FIXME:*/E->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001670 /*SuppressUserConversions=*/false,
1671 /*AllowExplicit=*/false,
1672 /*ForceRValue=*/false);
Sebastian Redl76458502009-04-17 16:30:52 +00001673 }
1674 if (ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion &&
1675 ICS.UserDefined.After.ReferenceBinding) {
1676 assert(ICS.UserDefined.After.DirectBinding &&
1677 "TryClassUnification should never generate indirect ref bindings");
Sebastian Redla5cd2cd2009-04-26 11:21:02 +00001678 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001679 TargetType(ICS)),
Douglas Gregor739d8282009-09-23 23:04:10 +00001680 /*FIXME:*/E->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001681 /*SuppressUserConversions=*/false,
1682 /*AllowExplicit=*/false,
1683 /*ForceRValue=*/false);
Sebastian Redl76458502009-04-17 16:30:52 +00001684 }
Douglas Gregor68647482009-12-16 03:45:30 +00001685 if (Self.PerformImplicitConversion(E, TargetType(ICS), ICS, Sema::AA_Converting))
Sebastian Redl76458502009-04-17 16:30:52 +00001686 return true;
1687 return false;
1688}
1689
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001690/// \brief Check the operands of ?: under C++ semantics.
1691///
1692/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
1693/// extension. In this case, LHS == Cond. (But they're not aliases.)
1694QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
1695 SourceLocation QuestionLoc) {
Mike Stump390b4cc2009-05-16 07:39:55 +00001696 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
1697 // interface pointers.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001698
1699 // C++0x 5.16p1
1700 // The first expression is contextually converted to bool.
1701 if (!Cond->isTypeDependent()) {
1702 if (CheckCXXBooleanCondition(Cond))
1703 return QualType();
1704 }
1705
1706 // Either of the arguments dependent?
1707 if (LHS->isTypeDependent() || RHS->isTypeDependent())
1708 return Context.DependentTy;
1709
John McCallb13c87f2009-11-05 09:23:39 +00001710 CheckSignCompare(LHS, RHS, QuestionLoc, diag::warn_mixed_sign_conditional);
1711
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001712 // C++0x 5.16p2
1713 // If either the second or the third operand has type (cv) void, ...
1714 QualType LTy = LHS->getType();
1715 QualType RTy = RHS->getType();
1716 bool LVoid = LTy->isVoidType();
1717 bool RVoid = RTy->isVoidType();
1718 if (LVoid || RVoid) {
1719 // ... then the [l2r] conversions are performed on the second and third
1720 // operands ...
1721 DefaultFunctionArrayConversion(LHS);
1722 DefaultFunctionArrayConversion(RHS);
1723 LTy = LHS->getType();
1724 RTy = RHS->getType();
1725
1726 // ... and one of the following shall hold:
1727 // -- The second or the third operand (but not both) is a throw-
1728 // expression; the result is of the type of the other and is an rvalue.
1729 bool LThrow = isa<CXXThrowExpr>(LHS);
1730 bool RThrow = isa<CXXThrowExpr>(RHS);
1731 if (LThrow && !RThrow)
1732 return RTy;
1733 if (RThrow && !LThrow)
1734 return LTy;
1735
1736 // -- Both the second and third operands have type void; the result is of
1737 // type void and is an rvalue.
1738 if (LVoid && RVoid)
1739 return Context.VoidTy;
1740
1741 // Neither holds, error.
1742 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
1743 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
1744 << LHS->getSourceRange() << RHS->getSourceRange();
1745 return QualType();
1746 }
1747
1748 // Neither is void.
1749
1750 // C++0x 5.16p3
1751 // Otherwise, if the second and third operand have different types, and
1752 // either has (cv) class type, and attempt is made to convert each of those
1753 // operands to the other.
1754 if (Context.getCanonicalType(LTy) != Context.getCanonicalType(RTy) &&
1755 (LTy->isRecordType() || RTy->isRecordType())) {
1756 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
1757 // These return true if a single direction is already ambiguous.
1758 if (TryClassUnification(*this, LHS, RHS, QuestionLoc, ICSLeftToRight))
1759 return QualType();
1760 if (TryClassUnification(*this, RHS, LHS, QuestionLoc, ICSRightToLeft))
1761 return QualType();
1762
1763 bool HaveL2R = ICSLeftToRight.ConversionKind !=
1764 ImplicitConversionSequence::BadConversion;
1765 bool HaveR2L = ICSRightToLeft.ConversionKind !=
1766 ImplicitConversionSequence::BadConversion;
1767 // If both can be converted, [...] the program is ill-formed.
1768 if (HaveL2R && HaveR2L) {
1769 Diag(QuestionLoc, diag::err_conditional_ambiguous)
1770 << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
1771 return QualType();
1772 }
1773
1774 // If exactly one conversion is possible, that conversion is applied to
1775 // the chosen operand and the converted operands are used in place of the
1776 // original operands for the remainder of this section.
1777 if (HaveL2R) {
Sebastian Redl76458502009-04-17 16:30:52 +00001778 if (ConvertForConditional(*this, LHS, ICSLeftToRight))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001779 return QualType();
1780 LTy = LHS->getType();
1781 } else if (HaveR2L) {
Sebastian Redl76458502009-04-17 16:30:52 +00001782 if (ConvertForConditional(*this, RHS, ICSRightToLeft))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001783 return QualType();
1784 RTy = RHS->getType();
1785 }
1786 }
1787
1788 // C++0x 5.16p4
1789 // If the second and third operands are lvalues and have the same type,
1790 // the result is of that type [...]
1791 bool Same = Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy);
1792 if (Same && LHS->isLvalue(Context) == Expr::LV_Valid &&
1793 RHS->isLvalue(Context) == Expr::LV_Valid)
1794 return LTy;
1795
1796 // C++0x 5.16p5
1797 // Otherwise, the result is an rvalue. If the second and third operands
1798 // do not have the same type, and either has (cv) class type, ...
1799 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
1800 // ... overload resolution is used to determine the conversions (if any)
1801 // to be applied to the operands. If the overload resolution fails, the
1802 // program is ill-formed.
1803 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
1804 return QualType();
1805 }
1806
1807 // C++0x 5.16p6
1808 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
1809 // conversions are performed on the second and third operands.
1810 DefaultFunctionArrayConversion(LHS);
1811 DefaultFunctionArrayConversion(RHS);
1812 LTy = LHS->getType();
1813 RTy = RHS->getType();
1814
1815 // After those conversions, one of the following shall hold:
1816 // -- The second and third operands have the same type; the result
1817 // is of that type.
1818 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy))
1819 return LTy;
1820
1821 // -- The second and third operands have arithmetic or enumeration type;
1822 // the usual arithmetic conversions are performed to bring them to a
1823 // common type, and the result is of that type.
1824 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
1825 UsualArithmeticConversions(LHS, RHS);
1826 return LHS->getType();
1827 }
1828
1829 // -- The second and third operands have pointer type, or one has pointer
1830 // type and the other is a null pointer constant; pointer conversions
1831 // and qualification conversions are performed to bring them to their
1832 // composite pointer type. The result is of the composite pointer type.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001833 QualType Composite = FindCompositePointerType(LHS, RHS);
1834 if (!Composite.isNull())
1835 return Composite;
Fariborz Jahanian55016362009-12-10 20:46:08 +00001836
1837 // Similarly, attempt to find composite type of twp objective-c pointers.
1838 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
1839 if (!Composite.isNull())
1840 return Composite;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001841
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001842 // Fourth bullet is same for pointers-to-member. However, the possible
1843 // conversions are far more limited: we have null-to-pointer, upcast of
1844 // containing class, and second-level cv-ness.
1845 // cv-ness is not a union, but must match one of the two operands. (Which,
1846 // frankly, is stupid.)
Ted Kremenek6217b802009-07-29 21:53:49 +00001847 const MemberPointerType *LMemPtr = LTy->getAs<MemberPointerType>();
1848 const MemberPointerType *RMemPtr = RTy->getAs<MemberPointerType>();
Douglas Gregorce940492009-09-25 04:25:58 +00001849 if (LMemPtr &&
1850 RHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00001851 ImpCastExprToType(RHS, LTy, CastExpr::CK_NullToMemberPointer);
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001852 return LTy;
1853 }
Douglas Gregorce940492009-09-25 04:25:58 +00001854 if (RMemPtr &&
1855 LHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00001856 ImpCastExprToType(LHS, RTy, CastExpr::CK_NullToMemberPointer);
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001857 return RTy;
1858 }
1859 if (LMemPtr && RMemPtr) {
1860 QualType LPointee = LMemPtr->getPointeeType();
1861 QualType RPointee = RMemPtr->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00001862
1863 QualifierCollector LPQuals, RPQuals;
1864 const Type *LPCan = LPQuals.strip(Context.getCanonicalType(LPointee));
1865 const Type *RPCan = RPQuals.strip(Context.getCanonicalType(RPointee));
1866
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001867 // First, we check that the unqualified pointee type is the same. If it's
1868 // not, there's no conversion that will unify the two pointers.
John McCall0953e762009-09-24 19:53:00 +00001869 if (LPCan == RPCan) {
1870
1871 // Second, we take the greater of the two qualifications. If neither
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001872 // is greater than the other, the conversion is not possible.
John McCall0953e762009-09-24 19:53:00 +00001873
1874 Qualifiers MergedQuals = LPQuals + RPQuals;
1875
1876 bool CompatibleQuals = true;
1877 if (MergedQuals.getCVRQualifiers() != LPQuals.getCVRQualifiers() &&
1878 MergedQuals.getCVRQualifiers() != RPQuals.getCVRQualifiers())
1879 CompatibleQuals = false;
1880 else if (LPQuals.getAddressSpace() != RPQuals.getAddressSpace())
1881 // FIXME:
1882 // C99 6.5.15 as modified by TR 18037:
1883 // If the second and third operands are pointers into different
1884 // address spaces, the address spaces must overlap.
1885 CompatibleQuals = false;
1886 // FIXME: GC qualifiers?
1887
1888 if (CompatibleQuals) {
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001889 // Third, we check if either of the container classes is derived from
1890 // the other.
1891 QualType LContainer(LMemPtr->getClass(), 0);
1892 QualType RContainer(RMemPtr->getClass(), 0);
1893 QualType MoreDerived;
1894 if (Context.getCanonicalType(LContainer) ==
1895 Context.getCanonicalType(RContainer))
1896 MoreDerived = LContainer;
1897 else if (IsDerivedFrom(LContainer, RContainer))
1898 MoreDerived = LContainer;
1899 else if (IsDerivedFrom(RContainer, LContainer))
1900 MoreDerived = RContainer;
1901
1902 if (!MoreDerived.isNull()) {
1903 // The type 'Q Pointee (MoreDerived::*)' is the common type.
1904 // We don't use ImpCastExprToType here because this could still fail
1905 // for ambiguous or inaccessible conversions.
John McCall0953e762009-09-24 19:53:00 +00001906 LPointee = Context.getQualifiedType(LPointee, MergedQuals);
1907 QualType Common
1908 = Context.getMemberPointerType(LPointee, MoreDerived.getTypePtr());
Douglas Gregor68647482009-12-16 03:45:30 +00001909 if (PerformImplicitConversion(LHS, Common, Sema::AA_Converting))
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001910 return QualType();
Douglas Gregor68647482009-12-16 03:45:30 +00001911 if (PerformImplicitConversion(RHS, Common, Sema::AA_Converting))
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001912 return QualType();
1913 return Common;
1914 }
1915 }
1916 }
1917 }
1918
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001919 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
1920 << LHS->getType() << RHS->getType()
1921 << LHS->getSourceRange() << RHS->getSourceRange();
1922 return QualType();
1923}
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001924
1925/// \brief Find a merged pointer type and convert the two expressions to it.
1926///
Douglas Gregor20b3e992009-08-24 17:42:35 +00001927/// This finds the composite pointer type (or member pointer type) for @p E1
1928/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
1929/// type and returns it.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001930/// It does not emit diagnostics.
1931QualType Sema::FindCompositePointerType(Expr *&E1, Expr *&E2) {
1932 assert(getLangOptions().CPlusPlus && "This function assumes C++");
1933 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001934
Fariborz Jahanian0cedfbd2009-12-08 20:04:24 +00001935 if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
1936 !T2->isAnyPointerType() && !T2->isMemberPointerType())
Douglas Gregor20b3e992009-08-24 17:42:35 +00001937 return QualType();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001938
1939 // C++0x 5.9p2
1940 // Pointer conversions and qualification conversions are performed on
1941 // pointer operands to bring them to their composite pointer type. If
1942 // one operand is a null pointer constant, the composite pointer type is
1943 // the type of the other operand.
Douglas Gregorce940492009-09-25 04:25:58 +00001944 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00001945 if (T2->isMemberPointerType())
1946 ImpCastExprToType(E1, T2, CastExpr::CK_NullToMemberPointer);
1947 else
1948 ImpCastExprToType(E1, T2, CastExpr::CK_IntegralToPointer);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001949 return T2;
1950 }
Douglas Gregorce940492009-09-25 04:25:58 +00001951 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00001952 if (T1->isMemberPointerType())
1953 ImpCastExprToType(E2, T1, CastExpr::CK_NullToMemberPointer);
1954 else
1955 ImpCastExprToType(E2, T1, CastExpr::CK_IntegralToPointer);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001956 return T1;
1957 }
Mike Stump1eb44332009-09-09 15:08:12 +00001958
Douglas Gregor20b3e992009-08-24 17:42:35 +00001959 // Now both have to be pointers or member pointers.
Sebastian Redla439e6f2009-11-16 21:03:45 +00001960 if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
1961 (!T2->isPointerType() && !T2->isMemberPointerType()))
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001962 return QualType();
1963
1964 // Otherwise, of one of the operands has type "pointer to cv1 void," then
1965 // the other has type "pointer to cv2 T" and the composite pointer type is
1966 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
1967 // Otherwise, the composite pointer type is a pointer type similar to the
1968 // type of one of the operands, with a cv-qualification signature that is
1969 // the union of the cv-qualification signatures of the operand types.
1970 // In practice, the first part here is redundant; it's subsumed by the second.
1971 // What we do here is, we build the two possible composite types, and try the
1972 // conversions in both directions. If only one works, or if the two composite
1973 // types are the same, we have succeeded.
John McCall0953e762009-09-24 19:53:00 +00001974 // FIXME: extended qualifiers?
Sebastian Redla439e6f2009-11-16 21:03:45 +00001975 typedef llvm::SmallVector<unsigned, 4> QualifierVector;
1976 QualifierVector QualifierUnion;
1977 typedef llvm::SmallVector<std::pair<const Type *, const Type *>, 4>
1978 ContainingClassVector;
1979 ContainingClassVector MemberOfClass;
1980 QualType Composite1 = Context.getCanonicalType(T1),
1981 Composite2 = Context.getCanonicalType(T2);
Douglas Gregor20b3e992009-08-24 17:42:35 +00001982 do {
1983 const PointerType *Ptr1, *Ptr2;
1984 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
1985 (Ptr2 = Composite2->getAs<PointerType>())) {
1986 Composite1 = Ptr1->getPointeeType();
1987 Composite2 = Ptr2->getPointeeType();
1988 QualifierUnion.push_back(
1989 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
1990 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
1991 continue;
1992 }
Mike Stump1eb44332009-09-09 15:08:12 +00001993
Douglas Gregor20b3e992009-08-24 17:42:35 +00001994 const MemberPointerType *MemPtr1, *MemPtr2;
1995 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
1996 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
1997 Composite1 = MemPtr1->getPointeeType();
1998 Composite2 = MemPtr2->getPointeeType();
1999 QualifierUnion.push_back(
2000 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
2001 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
2002 MemPtr2->getClass()));
2003 continue;
2004 }
Mike Stump1eb44332009-09-09 15:08:12 +00002005
Douglas Gregor20b3e992009-08-24 17:42:35 +00002006 // FIXME: block pointer types?
Mike Stump1eb44332009-09-09 15:08:12 +00002007
Douglas Gregor20b3e992009-08-24 17:42:35 +00002008 // Cannot unwrap any more types.
2009 break;
2010 } while (true);
Mike Stump1eb44332009-09-09 15:08:12 +00002011
Douglas Gregor20b3e992009-08-24 17:42:35 +00002012 // Rewrap the composites as pointers or member pointers with the union CVRs.
Sebastian Redla439e6f2009-11-16 21:03:45 +00002013 ContainingClassVector::reverse_iterator MOC
2014 = MemberOfClass.rbegin();
2015 for (QualifierVector::reverse_iterator
2016 I = QualifierUnion.rbegin(),
2017 E = QualifierUnion.rend();
Douglas Gregor20b3e992009-08-24 17:42:35 +00002018 I != E; (void)++I, ++MOC) {
John McCall0953e762009-09-24 19:53:00 +00002019 Qualifiers Quals = Qualifiers::fromCVRMask(*I);
Douglas Gregor20b3e992009-08-24 17:42:35 +00002020 if (MOC->first && MOC->second) {
2021 // Rebuild member pointer type
John McCall0953e762009-09-24 19:53:00 +00002022 Composite1 = Context.getMemberPointerType(
2023 Context.getQualifiedType(Composite1, Quals),
2024 MOC->first);
2025 Composite2 = Context.getMemberPointerType(
2026 Context.getQualifiedType(Composite2, Quals),
2027 MOC->second);
Douglas Gregor20b3e992009-08-24 17:42:35 +00002028 } else {
2029 // Rebuild pointer type
John McCall0953e762009-09-24 19:53:00 +00002030 Composite1
2031 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
2032 Composite2
2033 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregor20b3e992009-08-24 17:42:35 +00002034 }
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002035 }
2036
Mike Stump1eb44332009-09-09 15:08:12 +00002037 ImplicitConversionSequence E1ToC1 =
Anders Carlssonda7a18b2009-08-27 17:24:15 +00002038 TryImplicitConversion(E1, Composite1,
2039 /*SuppressUserConversions=*/false,
2040 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00002041 /*ForceRValue=*/false,
2042 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00002043 ImplicitConversionSequence E2ToC1 =
Anders Carlssonda7a18b2009-08-27 17:24:15 +00002044 TryImplicitConversion(E2, Composite1,
2045 /*SuppressUserConversions=*/false,
2046 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00002047 /*ForceRValue=*/false,
2048 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00002049
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002050 ImplicitConversionSequence E1ToC2, E2ToC2;
2051 E1ToC2.ConversionKind = ImplicitConversionSequence::BadConversion;
2052 E2ToC2.ConversionKind = ImplicitConversionSequence::BadConversion;
2053 if (Context.getCanonicalType(Composite1) !=
2054 Context.getCanonicalType(Composite2)) {
Anders Carlssonda7a18b2009-08-27 17:24:15 +00002055 E1ToC2 = TryImplicitConversion(E1, Composite2,
2056 /*SuppressUserConversions=*/false,
2057 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00002058 /*ForceRValue=*/false,
2059 /*InOverloadResolution=*/false);
Anders Carlssonda7a18b2009-08-27 17:24:15 +00002060 E2ToC2 = TryImplicitConversion(E2, Composite2,
2061 /*SuppressUserConversions=*/false,
2062 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00002063 /*ForceRValue=*/false,
2064 /*InOverloadResolution=*/false);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002065 }
2066
2067 bool ToC1Viable = E1ToC1.ConversionKind !=
2068 ImplicitConversionSequence::BadConversion
2069 && E2ToC1.ConversionKind !=
2070 ImplicitConversionSequence::BadConversion;
2071 bool ToC2Viable = E1ToC2.ConversionKind !=
2072 ImplicitConversionSequence::BadConversion
2073 && E2ToC2.ConversionKind !=
2074 ImplicitConversionSequence::BadConversion;
2075 if (ToC1Viable && !ToC2Viable) {
Douglas Gregor68647482009-12-16 03:45:30 +00002076 if (!PerformImplicitConversion(E1, Composite1, E1ToC1, Sema::AA_Converting) &&
2077 !PerformImplicitConversion(E2, Composite1, E2ToC1, Sema::AA_Converting))
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002078 return Composite1;
2079 }
2080 if (ToC2Viable && !ToC1Viable) {
Douglas Gregor68647482009-12-16 03:45:30 +00002081 if (!PerformImplicitConversion(E1, Composite2, E1ToC2, Sema::AA_Converting) &&
2082 !PerformImplicitConversion(E2, Composite2, E2ToC2, Sema::AA_Converting))
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002083 return Composite2;
2084 }
2085 return QualType();
2086}
Anders Carlsson165a0a02009-05-17 18:41:29 +00002087
Anders Carlssondef11992009-05-30 20:36:53 +00002088Sema::OwningExprResult Sema::MaybeBindToTemporary(Expr *E) {
Anders Carlsson089c2602009-08-15 23:41:35 +00002089 if (!Context.getLangOptions().CPlusPlus)
2090 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002091
Ted Kremenek6217b802009-07-29 21:53:49 +00002092 const RecordType *RT = E->getType()->getAs<RecordType>();
Anders Carlssondef11992009-05-30 20:36:53 +00002093 if (!RT)
2094 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002095
Anders Carlssondef11992009-05-30 20:36:53 +00002096 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2097 if (RD->hasTrivialDestructor())
2098 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002099
Anders Carlsson283e4d52009-09-14 01:30:44 +00002100 if (CallExpr *CE = dyn_cast<CallExpr>(E)) {
2101 QualType Ty = CE->getCallee()->getType();
2102 if (const PointerType *PT = Ty->getAs<PointerType>())
2103 Ty = PT->getPointeeType();
2104
John McCall183700f2009-09-21 23:43:11 +00002105 const FunctionType *FTy = Ty->getAs<FunctionType>();
Anders Carlsson283e4d52009-09-14 01:30:44 +00002106 if (FTy->getResultType()->isReferenceType())
2107 return Owned(E);
2108 }
Mike Stump1eb44332009-09-09 15:08:12 +00002109 CXXTemporary *Temp = CXXTemporary::Create(Context,
Anders Carlssondef11992009-05-30 20:36:53 +00002110 RD->getDestructor(Context));
Anders Carlsson860306e2009-05-30 21:21:49 +00002111 ExprTemporaries.push_back(Temp);
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00002112 if (CXXDestructorDecl *Destructor =
2113 const_cast<CXXDestructorDecl*>(RD->getDestructor(Context)))
2114 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
Anders Carlssondef11992009-05-30 20:36:53 +00002115 // FIXME: Add the temporary to the temporaries vector.
2116 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
2117}
2118
Anders Carlsson0ece4912009-12-15 20:51:39 +00002119Expr *Sema::MaybeCreateCXXExprWithTemporaries(Expr *SubExpr) {
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002120 assert(SubExpr && "sub expression can't be null!");
Mike Stump1eb44332009-09-09 15:08:12 +00002121
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00002122 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
2123 assert(ExprTemporaries.size() >= FirstTemporary);
2124 if (ExprTemporaries.size() == FirstTemporary)
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002125 return SubExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00002126
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002127 Expr *E = CXXExprWithTemporaries::Create(Context, SubExpr,
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00002128 &ExprTemporaries[FirstTemporary],
Anders Carlsson0ece4912009-12-15 20:51:39 +00002129 ExprTemporaries.size() - FirstTemporary);
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00002130 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
2131 ExprTemporaries.end());
Mike Stump1eb44332009-09-09 15:08:12 +00002132
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002133 return E;
2134}
2135
Douglas Gregor90f93822009-12-22 22:17:25 +00002136Sema::OwningExprResult
2137Sema::MaybeCreateCXXExprWithTemporaries(OwningExprResult SubExpr) {
2138 if (SubExpr.isInvalid())
2139 return ExprError();
2140
2141 return Owned(MaybeCreateCXXExprWithTemporaries(SubExpr.takeAs<Expr>()));
2142}
2143
Anders Carlsson5ee56e92009-12-16 02:09:40 +00002144FullExpr Sema::CreateFullExpr(Expr *SubExpr) {
2145 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
2146 assert(ExprTemporaries.size() >= FirstTemporary);
2147
2148 unsigned NumTemporaries = ExprTemporaries.size() - FirstTemporary;
2149 CXXTemporary **Temporaries =
2150 NumTemporaries == 0 ? 0 : &ExprTemporaries[FirstTemporary];
2151
2152 FullExpr E = FullExpr::Create(Context, SubExpr, Temporaries, NumTemporaries);
2153
2154 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
2155 ExprTemporaries.end());
2156
2157 return E;
2158}
2159
Mike Stump1eb44332009-09-09 15:08:12 +00002160Sema::OwningExprResult
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002161Sema::ActOnStartCXXMemberReference(Scope *S, ExprArg Base, SourceLocation OpLoc,
2162 tok::TokenKind OpKind, TypeTy *&ObjectType) {
2163 // Since this might be a postfix expression, get rid of ParenListExprs.
2164 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
Mike Stump1eb44332009-09-09 15:08:12 +00002165
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002166 Expr *BaseExpr = (Expr*)Base.get();
2167 assert(BaseExpr && "no record expansion");
Mike Stump1eb44332009-09-09 15:08:12 +00002168
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002169 QualType BaseType = BaseExpr->getType();
2170 if (BaseType->isDependentType()) {
Douglas Gregor43d88632009-11-04 22:49:18 +00002171 // If we have a pointer to a dependent type and are using the -> operator,
2172 // the object type is the type that the pointer points to. We might still
2173 // have enough information about that type to do something useful.
2174 if (OpKind == tok::arrow)
2175 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
2176 BaseType = Ptr->getPointeeType();
2177
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002178 ObjectType = BaseType.getAsOpaquePtr();
2179 return move(Base);
2180 }
Mike Stump1eb44332009-09-09 15:08:12 +00002181
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002182 // C++ [over.match.oper]p8:
Mike Stump1eb44332009-09-09 15:08:12 +00002183 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002184 // returned, with the original second operand.
2185 if (OpKind == tok::arrow) {
John McCallc4e83212009-09-30 01:01:30 +00002186 // The set of types we've considered so far.
John McCall432887f2009-09-30 01:30:54 +00002187 llvm::SmallPtrSet<CanQualType,8> CTypes;
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002188 llvm::SmallVector<SourceLocation, 8> Locations;
John McCall432887f2009-09-30 01:30:54 +00002189 CTypes.insert(Context.getCanonicalType(BaseType));
John McCallc4e83212009-09-30 01:01:30 +00002190
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002191 while (BaseType->isRecordType()) {
Anders Carlsson15ea3782009-10-13 22:43:21 +00002192 Base = BuildOverloadedArrowExpr(S, move(Base), OpLoc);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002193 BaseExpr = (Expr*)Base.get();
2194 if (BaseExpr == NULL)
2195 return ExprError();
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002196 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(BaseExpr))
Anders Carlssonde699e52009-10-13 22:55:59 +00002197 Locations.push_back(OpCall->getDirectCallee()->getLocation());
John McCallc4e83212009-09-30 01:01:30 +00002198 BaseType = BaseExpr->getType();
2199 CanQualType CBaseType = Context.getCanonicalType(BaseType);
John McCall432887f2009-09-30 01:30:54 +00002200 if (!CTypes.insert(CBaseType)) {
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00002201 Diag(OpLoc, diag::err_operator_arrow_circular);
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002202 for (unsigned i = 0; i < Locations.size(); i++)
2203 Diag(Locations[i], diag::note_declared_at);
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00002204 return ExprError();
2205 }
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002206 }
Mike Stump1eb44332009-09-09 15:08:12 +00002207
Douglas Gregor31658df2009-11-20 19:58:21 +00002208 if (BaseType->isPointerType())
2209 BaseType = BaseType->getPointeeType();
2210 }
Mike Stump1eb44332009-09-09 15:08:12 +00002211
2212 // We could end up with various non-record types here, such as extended
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002213 // vector types or Objective-C interfaces. Just return early and let
2214 // ActOnMemberReferenceExpr do the work.
Douglas Gregorc68afe22009-09-03 21:38:09 +00002215 if (!BaseType->isRecordType()) {
2216 // C++ [basic.lookup.classref]p2:
2217 // [...] If the type of the object expression is of pointer to scalar
2218 // type, the unqualified-id is looked up in the context of the complete
2219 // postfix-expression.
2220 ObjectType = 0;
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002221 return move(Base);
Douglas Gregorc68afe22009-09-03 21:38:09 +00002222 }
Mike Stump1eb44332009-09-09 15:08:12 +00002223
Douglas Gregor03c57052009-11-17 05:17:33 +00002224 // The object type must be complete (or dependent).
2225 if (!BaseType->isDependentType() &&
2226 RequireCompleteType(OpLoc, BaseType,
2227 PDiag(diag::err_incomplete_member_access)))
2228 return ExprError();
2229
Douglas Gregorc68afe22009-09-03 21:38:09 +00002230 // C++ [basic.lookup.classref]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00002231 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor03c57052009-11-17 05:17:33 +00002232 // unqualified-id, and the type of the object expression is of a class
Douglas Gregorc68afe22009-09-03 21:38:09 +00002233 // type C (or of pointer to a class type C), the unqualified-id is looked
2234 // up in the scope of class C. [...]
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002235 ObjectType = BaseType.getAsOpaquePtr();
Douglas Gregor03c57052009-11-17 05:17:33 +00002236
Mike Stump1eb44332009-09-09 15:08:12 +00002237 return move(Base);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002238}
2239
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002240CXXMemberCallExpr *Sema::BuildCXXMemberCallExpr(Expr *Exp,
2241 CXXMethodDecl *Method) {
Eli Friedman772fffa2009-12-09 04:53:56 +00002242 if (PerformObjectArgumentInitialization(Exp, Method))
2243 assert(0 && "Calling BuildCXXMemberCallExpr with invalid call?");
2244
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002245 MemberExpr *ME =
2246 new (Context) MemberExpr(Exp, /*IsArrow=*/false, Method,
2247 SourceLocation(), Method->getType());
Eli Friedman772fffa2009-12-09 04:53:56 +00002248 QualType ResultType = Method->getResultType().getNonReferenceType();
Douglas Gregor7edfb692009-11-23 12:27:39 +00002249 MarkDeclarationReferenced(Exp->getLocStart(), Method);
2250 CXXMemberCallExpr *CE =
2251 new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType,
2252 Exp->getLocEnd());
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002253 return CE;
2254}
2255
Anders Carlsson0aebc812009-09-09 21:33:21 +00002256Sema::OwningExprResult Sema::BuildCXXCastArgument(SourceLocation CastLoc,
2257 QualType Ty,
2258 CastExpr::CastKind Kind,
2259 CXXMethodDecl *Method,
2260 ExprArg Arg) {
2261 Expr *From = Arg.takeAs<Expr>();
2262
2263 switch (Kind) {
2264 default: assert(0 && "Unhandled cast kind!");
2265 case CastExpr::CK_ConstructorConversion: {
Douglas Gregor39da0b82009-09-09 23:08:42 +00002266 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
2267
2268 if (CompleteConstructorCall(cast<CXXConstructorDecl>(Method),
2269 MultiExprArg(*this, (void **)&From, 1),
2270 CastLoc, ConstructorArgs))
2271 return ExprError();
Anders Carlsson4fa26842009-10-18 21:20:14 +00002272
2273 OwningExprResult Result =
2274 BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
2275 move_arg(ConstructorArgs));
2276 if (Result.isInvalid())
2277 return ExprError();
2278
2279 return MaybeBindToTemporary(Result.takeAs<Expr>());
Anders Carlsson0aebc812009-09-09 21:33:21 +00002280 }
2281
2282 case CastExpr::CK_UserDefinedConversion: {
Anders Carlssonaac6e3a2009-09-15 07:42:44 +00002283 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
Eli Friedman772fffa2009-12-09 04:53:56 +00002284
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002285 // Create an implicit call expr that calls it.
2286 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(From, Method);
Anders Carlsson4fa26842009-10-18 21:20:14 +00002287 return MaybeBindToTemporary(CE);
Anders Carlsson0aebc812009-09-09 21:33:21 +00002288 }
Anders Carlsson0aebc812009-09-09 21:33:21 +00002289 }
2290}
2291
Anders Carlsson165a0a02009-05-17 18:41:29 +00002292Sema::OwningExprResult Sema::ActOnFinishFullExpr(ExprArg Arg) {
2293 Expr *FullExpr = Arg.takeAs<Expr>();
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002294 if (FullExpr)
Anders Carlsson0ece4912009-12-15 20:51:39 +00002295 FullExpr = MaybeCreateCXXExprWithTemporaries(FullExpr);
Anders Carlssonec773872009-08-25 23:46:41 +00002296
Anders Carlsson165a0a02009-05-17 18:41:29 +00002297 return Owned(FullExpr);
2298}
Douglas Gregore961afb2009-10-22 07:08:30 +00002299
2300/// \brief Determine whether a reference to the given declaration in the
2301/// current context is an implicit member access
2302/// (C++ [class.mfct.non-static]p2).
2303///
2304/// FIXME: Should Objective-C also use this approach?
2305///
Douglas Gregore961afb2009-10-22 07:08:30 +00002306/// \param D the declaration being referenced from the current scope.
2307///
2308/// \param NameLoc the location of the name in the source.
2309///
2310/// \param ThisType if the reference to this declaration is an implicit member
2311/// access, will be set to the type of the "this" pointer to be used when
2312/// building that implicit member access.
2313///
Douglas Gregore961afb2009-10-22 07:08:30 +00002314/// \returns true if this is an implicit member reference (in which case
2315/// \p ThisType and \p MemberType will be set), or false if it is not an
2316/// implicit member reference.
John McCall129e2df2009-11-30 22:42:35 +00002317bool Sema::isImplicitMemberReference(const LookupResult &R,
2318 QualType &ThisType) {
Douglas Gregore961afb2009-10-22 07:08:30 +00002319 // If this isn't a C++ method, then it isn't an implicit member reference.
2320 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext);
2321 if (!MD || MD->isStatic())
2322 return false;
2323
2324 // C++ [class.mfct.nonstatic]p2:
2325 // [...] if name lookup (3.4.1) resolves the name in the
2326 // id-expression to a nonstatic nontype member of class X or of
2327 // a base class of X, the id-expression is transformed into a
2328 // class member access expression (5.2.5) using (*this) (9.3.2)
2329 // as the postfix-expression to the left of the '.' operator.
2330 DeclContext *Ctx = 0;
John McCall129e2df2009-11-30 22:42:35 +00002331 if (R.isUnresolvableResult()) {
2332 // FIXME: this is just picking one at random
2333 Ctx = R.getRepresentativeDecl()->getDeclContext();
2334 } else if (FieldDecl *FD = R.getAsSingle<FieldDecl>()) {
Douglas Gregore961afb2009-10-22 07:08:30 +00002335 Ctx = FD->getDeclContext();
Douglas Gregore961afb2009-10-22 07:08:30 +00002336 } else {
John McCall129e2df2009-11-30 22:42:35 +00002337 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2338 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*I);
Douglas Gregore961afb2009-10-22 07:08:30 +00002339 FunctionTemplateDecl *FunTmpl = 0;
John McCall129e2df2009-11-30 22:42:35 +00002340 if (!Method && (FunTmpl = dyn_cast<FunctionTemplateDecl>(*I)))
Douglas Gregore961afb2009-10-22 07:08:30 +00002341 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
2342
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00002343 // FIXME: Do we have to know if there are explicit template arguments?
Douglas Gregore961afb2009-10-22 07:08:30 +00002344 if (Method && !Method->isStatic()) {
2345 Ctx = Method->getParent();
Douglas Gregore961afb2009-10-22 07:08:30 +00002346 break;
2347 }
2348 }
2349 }
2350
2351 if (!Ctx || !Ctx->isRecord())
2352 return false;
2353
2354 // Determine whether the declaration(s) we found are actually in a base
2355 // class. If not, this isn't an implicit member reference.
2356 ThisType = MD->getThisType(Context);
John McCall129e2df2009-11-30 22:42:35 +00002357
2358 // FIXME: this doesn't really work for overloaded lookups.
Douglas Gregor7a343142009-11-01 17:08:18 +00002359
Douglas Gregore961afb2009-10-22 07:08:30 +00002360 QualType CtxType = Context.getTypeDeclType(cast<CXXRecordDecl>(Ctx));
2361 QualType ClassType
2362 = Context.getTypeDeclType(cast<CXXRecordDecl>(MD->getParent()));
2363 return Context.hasSameType(CtxType, ClassType) ||
2364 IsDerivedFrom(ClassType, CtxType);
2365}
2366