blob: e27308a2b43d7cddb59ddeb23a6fa1b0e5e9f8f6 [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:
John McCall86ff3082010-02-04 22:26:26 +000075 // [...] If the type of the expression is a class type, the class
76 // shall be completely-defined.
77 if (RequireCompleteType(OpLoc, T, diag::err_incomplete_typeid))
78 return ExprError();
79
80 // C++ [expr.typeid]p3:
Douglas Gregorf57f2072009-12-23 20:51:04 +000081 // When typeid is applied to an expression other than an lvalue of a
82 // polymorphic class type [...] [the] expression is an unevaluated
83 // operand. [...]
84 if (RecordD->isPolymorphic() && E->isLvalue(Context) == Expr::LV_Valid)
Douglas Gregorac7610d2009-06-22 20:57:11 +000085 isUnevaluatedOperand = false;
Douglas Gregorf57f2072009-12-23 20:51:04 +000086 }
87
88 // C++ [expr.typeid]p4:
89 // [...] If the type of the type-id is a reference to a possibly
90 // cv-qualified type, the result of the typeid expression refers to a
91 // std::type_info object representing the cv-unqualified referenced
92 // type.
93 if (T.hasQualifiers()) {
94 ImpCastExprToType(E, T.getUnqualifiedType(), CastExpr::CK_NoOp,
95 E->isLvalue(Context));
96 TyOrExpr = E;
Douglas Gregorac7610d2009-06-22 20:57:11 +000097 }
98 }
Mike Stump1eb44332009-09-09 15:08:12 +000099
Douglas Gregor2afce722009-11-26 00:44:06 +0000100 // If this is an unevaluated operand, clear out the set of
101 // declaration references we have been computing and eliminate any
102 // temporaries introduced in its computation.
Douglas Gregorac7610d2009-06-22 20:57:11 +0000103 if (isUnevaluatedOperand)
Douglas Gregor2afce722009-11-26 00:44:06 +0000104 ExprEvalContexts.back().Context = Unevaluated;
Douglas Gregorac7610d2009-06-22 20:57:11 +0000105 }
Mike Stump1eb44332009-09-09 15:08:12 +0000106
Sebastian Redlf53597f2009-03-15 17:47:39 +0000107 return Owned(new (Context) CXXTypeidExpr(isType, TyOrExpr,
108 TypeInfoType.withConst(),
109 SourceRange(OpLoc, RParenLoc)));
Sebastian Redlc42e1182008-11-11 11:37:55 +0000110}
111
Steve Naroff1b273c42007-09-16 14:56:35 +0000112/// ActOnCXXBoolLiteral - Parse {true,false} literals.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000113Action::OwningExprResult
Steve Naroff1b273c42007-09-16 14:56:35 +0000114Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor2f639b92008-10-24 15:36:09 +0000115 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000116 "Unknown C++ Boolean value!");
Sebastian Redlf53597f2009-03-15 17:47:39 +0000117 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
118 Context.BoolTy, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000119}
Chris Lattner50dd2892008-02-26 00:51:44 +0000120
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000121/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
122Action::OwningExprResult
123Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
124 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
125}
126
Chris Lattner50dd2892008-02-26 00:51:44 +0000127/// ActOnCXXThrow - Parse throw expressions.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000128Action::OwningExprResult
129Sema::ActOnCXXThrow(SourceLocation OpLoc, ExprArg E) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000130 Expr *Ex = E.takeAs<Expr>();
131 if (Ex && !Ex->isTypeDependent() && CheckCXXThrowOperand(OpLoc, Ex))
132 return ExprError();
133 return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc));
134}
135
136/// CheckCXXThrowOperand - Validate the operand of a throw.
137bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *&E) {
138 // C++ [except.throw]p3:
Douglas Gregor154fe982009-12-23 22:04:40 +0000139 // A throw-expression initializes a temporary object, called the exception
140 // object, the type of which is determined by removing any top-level
141 // cv-qualifiers from the static type of the operand of throw and adjusting
142 // the type from "array of T" or "function returning T" to "pointer to T"
143 // or "pointer to function returning T", [...]
144 if (E->getType().hasQualifiers())
145 ImpCastExprToType(E, E->getType().getUnqualifiedType(), CastExpr::CK_NoOp,
146 E->isLvalue(Context) == Expr::LV_Valid);
147
Sebastian Redl972041f2009-04-27 20:27:31 +0000148 DefaultFunctionArrayConversion(E);
149
150 // If the type of the exception would be an incomplete type or a pointer
151 // to an incomplete type other than (cv) void the program is ill-formed.
152 QualType Ty = E->getType();
153 int isPointer = 0;
Ted Kremenek6217b802009-07-29 21:53:49 +0000154 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000155 Ty = Ptr->getPointeeType();
156 isPointer = 1;
157 }
158 if (!isPointer || !Ty->isVoidType()) {
159 if (RequireCompleteType(ThrowLoc, Ty,
Anders Carlssond497ba72009-08-26 22:59:12 +0000160 PDiag(isPointer ? diag::err_throw_incomplete_ptr
161 : diag::err_throw_incomplete)
162 << E->getSourceRange()))
Sebastian Redl972041f2009-04-27 20:27:31 +0000163 return true;
164 }
165
166 // FIXME: Construct a temporary here.
167 return false;
Chris Lattner50dd2892008-02-26 00:51:44 +0000168}
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000169
Sebastian Redlf53597f2009-03-15 17:47:39 +0000170Action::OwningExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000171 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
172 /// is a non-lvalue expression whose value is the address of the object for
173 /// which the function is called.
174
Sebastian Redlf53597f2009-03-15 17:47:39 +0000175 if (!isa<FunctionDecl>(CurContext))
176 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000177
178 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext))
179 if (MD->isInstance())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000180 return Owned(new (Context) CXXThisExpr(ThisLoc,
Douglas Gregor828a1972010-01-07 23:12:05 +0000181 MD->getThisType(Context),
182 /*isImplicit=*/false));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000183
Sebastian Redlf53597f2009-03-15 17:47:39 +0000184 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000185}
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000186
187/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
188/// Can be interpreted either as function-style casting ("int(x)")
189/// or class type construction ("ClassType(x,y,z)")
190/// or creation of a value-initialized type ("int()").
Sebastian Redlf53597f2009-03-15 17:47:39 +0000191Action::OwningExprResult
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000192Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep,
193 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000194 MultiExprArg exprs,
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000195 SourceLocation *CommaLocs,
196 SourceLocation RParenLoc) {
Douglas Gregorae4c77d2010-02-05 19:11:37 +0000197 if (!TypeRep)
198 return ExprError();
199
John McCall9d125032010-01-15 18:39:57 +0000200 TypeSourceInfo *TInfo;
201 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
202 if (!TInfo)
203 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
Sebastian Redlf53597f2009-03-15 17:47:39 +0000204 unsigned NumExprs = exprs.size();
205 Expr **Exprs = (Expr**)exprs.get();
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000206 SourceLocation TyBeginLoc = TypeRange.getBegin();
207 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
208
Sebastian Redlf53597f2009-03-15 17:47:39 +0000209 if (Ty->isDependentType() ||
Douglas Gregorba498172009-03-13 21:01:28 +0000210 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
Sebastian Redlf53597f2009-03-15 17:47:39 +0000211 exprs.release();
Mike Stump1eb44332009-09-09 15:08:12 +0000212
213 return Owned(CXXUnresolvedConstructExpr::Create(Context,
214 TypeRange.getBegin(), Ty,
Douglas Gregord81e6ca2009-05-20 18:46:25 +0000215 LParenLoc,
216 Exprs, NumExprs,
217 RParenLoc));
Douglas Gregorba498172009-03-13 21:01:28 +0000218 }
219
Anders Carlssonbb60a502009-08-27 03:53:50 +0000220 if (Ty->isArrayType())
221 return ExprError(Diag(TyBeginLoc,
222 diag::err_value_init_for_array_type) << FullRange);
223 if (!Ty->isVoidType() &&
224 RequireCompleteType(TyBeginLoc, Ty,
225 PDiag(diag::err_invalid_incomplete_type_use)
226 << FullRange))
227 return ExprError();
Fariborz Jahanianf071e9b2009-10-23 21:01:39 +0000228
Anders Carlssonbb60a502009-08-27 03:53:50 +0000229 if (RequireNonAbstractType(TyBeginLoc, Ty,
230 diag::err_allocation_of_abstract_type))
231 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000232
233
Douglas Gregor506ae412009-01-16 18:33:17 +0000234 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000235 // If the expression list is a single expression, the type conversion
236 // expression is equivalent (in definedness, and if defined in meaning) to the
237 // corresponding cast expression.
238 //
239 if (NumExprs == 1) {
Anders Carlssoncdb61972009-08-07 22:21:05 +0000240 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Anders Carlsson0aebc812009-09-09 21:33:21 +0000241 CXXMethodDecl *Method = 0;
242 if (CheckCastTypes(TypeRange, Ty, Exprs[0], Kind, Method,
243 /*FunctionalStyle=*/true))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000244 return ExprError();
Anders Carlsson0aebc812009-09-09 21:33:21 +0000245
246 exprs.release();
247 if (Method) {
248 OwningExprResult CastArg
249 = BuildCXXCastArgument(TypeRange.getBegin(), Ty.getNonReferenceType(),
250 Kind, Method, Owned(Exprs[0]));
251 if (CastArg.isInvalid())
252 return ExprError();
253
254 Exprs[0] = CastArg.takeAs<Expr>();
Fariborz Jahanian4fc7ab32009-08-28 15:11:24 +0000255 }
Anders Carlsson0aebc812009-09-09 21:33:21 +0000256
257 return Owned(new (Context) CXXFunctionalCastExpr(Ty.getNonReferenceType(),
John McCall9d125032010-01-15 18:39:57 +0000258 TInfo, TyBeginLoc, Kind,
Anders Carlsson0aebc812009-09-09 21:33:21 +0000259 Exprs[0], RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000260 }
261
Ted Kremenek6217b802009-07-29 21:53:49 +0000262 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Douglas Gregor506ae412009-01-16 18:33:17 +0000263 CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
Sebastian Redlf53597f2009-03-15 17:47:39 +0000264
Mike Stump1eb44332009-09-09 15:08:12 +0000265 if (NumExprs > 1 || !Record->hasTrivialConstructor() ||
Anders Carlssone7624a72009-08-27 05:08:22 +0000266 !Record->hasTrivialDestructor()) {
Eli Friedman6997aae2010-01-31 20:58:15 +0000267 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty);
268 InitializationKind Kind
269 = NumExprs ? InitializationKind::CreateDirect(TypeRange.getBegin(),
270 LParenLoc, RParenLoc)
271 : InitializationKind::CreateValue(TypeRange.getBegin(),
272 LParenLoc, RParenLoc);
273 InitializationSequence InitSeq(*this, Entity, Kind, Exprs, NumExprs);
274 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
275 move(exprs));
Douglas Gregor506ae412009-01-16 18:33:17 +0000276
Eli Friedman6997aae2010-01-31 20:58:15 +0000277 // FIXME: Improve AST representation?
278 return move(Result);
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
John McCall5769d612010-02-08 23:07:23 +0000629 OverloadCandidateSet Candidates(StartLoc);
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.
Chandler Carruth4a73ea92010-02-03 11:02:14 +0000634
635 if (FunctionTemplateDecl *FnTemplate =
636 dyn_cast<FunctionTemplateDecl>((*Alloc)->getUnderlyingDecl())) {
637 AddTemplateOverloadCandidate(FnTemplate, Alloc.getAccess(),
638 /*ExplicitTemplateArgs=*/0, Args, NumArgs,
639 Candidates,
640 /*SuppressUserConversions=*/false);
Douglas Gregor90916562009-09-29 18:16:17 +0000641 continue;
Chandler Carruth4a73ea92010-02-03 11:02:14 +0000642 }
643
644 FunctionDecl *Fn = cast<FunctionDecl>((*Alloc)->getUnderlyingDecl());
645 AddOverloadCandidate(Fn, Alloc.getAccess(), Args, NumArgs, Candidates,
646 /*SuppressUserConversions=*/false);
Sebastian Redl7f662392008-12-04 22:20:51 +0000647 }
648
649 // Do the resolution.
650 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +0000651 switch(BestViableFunction(Candidates, StartLoc, Best)) {
Sebastian Redl7f662392008-12-04 22:20:51 +0000652 case OR_Success: {
653 // Got one!
654 FunctionDecl *FnDecl = Best->Function;
655 // The first argument is size_t, and the first parameter must be size_t,
656 // too. This is checked on declaration and can be assumed. (It can't be
657 // asserted on, though, since invalid decls are left in there.)
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000658 // Whatch out for variadic allocator function.
659 unsigned NumArgsInFnDecl = FnDecl->getNumParams();
660 for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) {
Anders Carlssonfc27d262009-05-31 19:49:47 +0000661 if (PerformCopyInitialization(Args[i],
Sebastian Redl7f662392008-12-04 22:20:51 +0000662 FnDecl->getParamDecl(i)->getType(),
Douglas Gregor68647482009-12-16 03:45:30 +0000663 AA_Passing))
Sebastian Redl7f662392008-12-04 22:20:51 +0000664 return true;
665 }
666 Operator = FnDecl;
667 return false;
668 }
669
670 case OR_No_Viable_Function:
Sebastian Redl7f662392008-12-04 22:20:51 +0000671 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +0000672 << Name << Range;
John McCallcbce6062010-01-12 07:18:19 +0000673 PrintOverloadCandidates(Candidates, OCD_AllCandidates, Args, NumArgs);
Sebastian Redl7f662392008-12-04 22:20:51 +0000674 return true;
675
676 case OR_Ambiguous:
Sebastian Redl7f662392008-12-04 22:20:51 +0000677 Diag(StartLoc, diag::err_ovl_ambiguous_call)
Sebastian Redl00e68e22009-02-09 18:24:27 +0000678 << Name << Range;
John McCallcbce6062010-01-12 07:18:19 +0000679 PrintOverloadCandidates(Candidates, OCD_ViableCandidates, Args, NumArgs);
Sebastian Redl7f662392008-12-04 22:20:51 +0000680 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000681
682 case OR_Deleted:
683 Diag(StartLoc, diag::err_ovl_deleted_call)
684 << Best->Function->isDeleted()
685 << Name << Range;
John McCallcbce6062010-01-12 07:18:19 +0000686 PrintOverloadCandidates(Candidates, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000687 return true;
Sebastian Redl7f662392008-12-04 22:20:51 +0000688 }
689 assert(false && "Unreachable, bad result from BestViableFunction");
690 return true;
691}
692
693
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000694/// DeclareGlobalNewDelete - Declare the global forms of operator new and
695/// delete. These are:
696/// @code
697/// void* operator new(std::size_t) throw(std::bad_alloc);
698/// void* operator new[](std::size_t) throw(std::bad_alloc);
699/// void operator delete(void *) throw();
700/// void operator delete[](void *) throw();
701/// @endcode
702/// Note that the placement and nothrow forms of new are *not* implicitly
703/// declared. Their use requires including \<new\>.
Mike Stump1eb44332009-09-09 15:08:12 +0000704void Sema::DeclareGlobalNewDelete() {
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000705 if (GlobalNewDeleteDeclared)
706 return;
Douglas Gregor7adb10f2009-09-15 22:30:29 +0000707
708 // C++ [basic.std.dynamic]p2:
709 // [...] The following allocation and deallocation functions (18.4) are
710 // implicitly declared in global scope in each translation unit of a
711 // program
712 //
713 // void* operator new(std::size_t) throw(std::bad_alloc);
714 // void* operator new[](std::size_t) throw(std::bad_alloc);
715 // void operator delete(void*) throw();
716 // void operator delete[](void*) throw();
717 //
718 // These implicit declarations introduce only the function names operator
719 // new, operator new[], operator delete, operator delete[].
720 //
721 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
722 // "std" or "bad_alloc" as necessary to form the exception specification.
723 // However, we do not make these implicit declarations visible to name
724 // lookup.
725 if (!StdNamespace) {
726 // The "std" namespace has not yet been defined, so build one implicitly.
727 StdNamespace = NamespaceDecl::Create(Context,
728 Context.getTranslationUnitDecl(),
729 SourceLocation(),
730 &PP.getIdentifierTable().get("std"));
731 StdNamespace->setImplicit(true);
732 }
733
734 if (!StdBadAlloc) {
735 // The "std::bad_alloc" class has not yet been declared, so build it
736 // implicitly.
737 StdBadAlloc = CXXRecordDecl::Create(Context, TagDecl::TK_class,
738 StdNamespace,
739 SourceLocation(),
740 &PP.getIdentifierTable().get("bad_alloc"),
741 SourceLocation(), 0);
742 StdBadAlloc->setImplicit(true);
743 }
744
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000745 GlobalNewDeleteDeclared = true;
746
747 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
748 QualType SizeT = Context.getSizeType();
Nuno Lopesfc284482009-12-16 16:59:22 +0000749 bool AssumeSaneOperatorNew = getLangOptions().AssumeSaneOperatorNew;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000750
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000751 DeclareGlobalAllocationFunction(
752 Context.DeclarationNames.getCXXOperatorName(OO_New),
Nuno Lopesfc284482009-12-16 16:59:22 +0000753 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000754 DeclareGlobalAllocationFunction(
755 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
Nuno Lopesfc284482009-12-16 16:59:22 +0000756 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000757 DeclareGlobalAllocationFunction(
758 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
759 Context.VoidTy, VoidPtr);
760 DeclareGlobalAllocationFunction(
761 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
762 Context.VoidTy, VoidPtr);
763}
764
765/// DeclareGlobalAllocationFunction - Declares a single implicit global
766/// allocation function if it doesn't already exist.
767void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Nuno Lopesfc284482009-12-16 16:59:22 +0000768 QualType Return, QualType Argument,
769 bool AddMallocAttr) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000770 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
771
772 // Check if this function is already declared.
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000773 {
Douglas Gregor5cc37092008-12-23 22:05:29 +0000774 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000775 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000776 Alloc != AllocEnd; ++Alloc) {
Chandler Carruth4a73ea92010-02-03 11:02:14 +0000777 // Only look at non-template functions, as it is the predefined,
778 // non-templated allocation function we are trying to declare here.
779 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
780 QualType InitialParamType =
Douglas Gregor6e790ab2009-12-22 23:42:49 +0000781 Context.getCanonicalType(
Chandler Carruth4a73ea92010-02-03 11:02:14 +0000782 Func->getParamDecl(0)->getType().getUnqualifiedType());
783 // FIXME: Do we need to check for default arguments here?
784 if (Func->getNumParams() == 1 && InitialParamType == Argument)
785 return;
786 }
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000787 }
788 }
789
Douglas Gregor7adb10f2009-09-15 22:30:29 +0000790 QualType BadAllocType;
791 bool HasBadAllocExceptionSpec
792 = (Name.getCXXOverloadedOperator() == OO_New ||
793 Name.getCXXOverloadedOperator() == OO_Array_New);
794 if (HasBadAllocExceptionSpec) {
795 assert(StdBadAlloc && "Must have std::bad_alloc declared");
796 BadAllocType = Context.getTypeDeclType(StdBadAlloc);
797 }
798
799 QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0,
800 true, false,
801 HasBadAllocExceptionSpec? 1 : 0,
802 &BadAllocType);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000803 FunctionDecl *Alloc =
804 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
John McCalla93c9342009-12-07 02:54:59 +0000805 FnType, /*TInfo=*/0, FunctionDecl::None, false, true);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000806 Alloc->setImplicit();
Nuno Lopesfc284482009-12-16 16:59:22 +0000807
808 if (AddMallocAttr)
809 Alloc->addAttr(::new (Context) MallocAttr());
810
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000811 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
John McCalla93c9342009-12-07 02:54:59 +0000812 0, Argument, /*TInfo=*/0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000813 VarDecl::None, 0);
Ted Kremenekfc767612009-01-14 00:42:25 +0000814 Alloc->setParams(Context, &Param, 1);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000815
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000816 // FIXME: Also add this declaration to the IdentifierResolver, but
817 // make sure it is at the end of the chain to coincide with the
818 // global scope.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000819 ((DeclContext *)TUScope->getEntity())->addDecl(Alloc);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000820}
821
Anders Carlsson78f74552009-11-15 18:45:20 +0000822bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
823 DeclarationName Name,
Anders Carlsson5ec02ae2009-12-02 17:15:43 +0000824 FunctionDecl* &Operator) {
John McCalla24dc2e2009-11-17 02:14:36 +0000825 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlsson78f74552009-11-15 18:45:20 +0000826 // Try to find operator delete/operator delete[] in class scope.
John McCalla24dc2e2009-11-17 02:14:36 +0000827 LookupQualifiedName(Found, RD);
Anders Carlsson78f74552009-11-15 18:45:20 +0000828
John McCalla24dc2e2009-11-17 02:14:36 +0000829 if (Found.isAmbiguous())
Anders Carlsson78f74552009-11-15 18:45:20 +0000830 return true;
Anders Carlsson78f74552009-11-15 18:45:20 +0000831
832 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
833 F != FEnd; ++F) {
834 if (CXXMethodDecl *Delete = dyn_cast<CXXMethodDecl>(*F))
835 if (Delete->isUsualDeallocationFunction()) {
836 Operator = Delete;
837 return false;
838 }
839 }
840
841 // We did find operator delete/operator delete[] declarations, but
842 // none of them were suitable.
843 if (!Found.empty()) {
844 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
845 << Name << RD;
846
847 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
848 F != FEnd; ++F) {
849 Diag((*F)->getLocation(),
850 diag::note_delete_member_function_declared_here)
851 << Name;
852 }
853
854 return true;
855 }
856
857 // Look for a global declaration.
858 DeclareGlobalNewDelete();
859 DeclContext *TUDecl = Context.getTranslationUnitDecl();
860
861 CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation());
862 Expr* DeallocArgs[1];
863 DeallocArgs[0] = &Null;
864 if (FindAllocationOverload(StartLoc, SourceRange(), Name,
865 DeallocArgs, 1, TUDecl, /*AllowMissing=*/false,
866 Operator))
867 return true;
868
869 assert(Operator && "Did not find a deallocation function!");
870 return false;
871}
872
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000873/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
874/// @code ::delete ptr; @endcode
875/// or
876/// @code delete [] ptr; @endcode
Sebastian Redlf53597f2009-03-15 17:47:39 +0000877Action::OwningExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000878Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
Mike Stump1eb44332009-09-09 15:08:12 +0000879 bool ArrayForm, ExprArg Operand) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000880 // C++ [expr.delete]p1:
881 // The operand shall have a pointer type, or a class type having a single
882 // conversion function to a pointer type. The result has type void.
883 //
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000884 // DR599 amends "pointer type" to "pointer to object type" in both cases.
885
Anders Carlssond67c4c32009-08-16 20:29:29 +0000886 FunctionDecl *OperatorDelete = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000887
Sebastian Redlf53597f2009-03-15 17:47:39 +0000888 Expr *Ex = (Expr *)Operand.get();
Sebastian Redl28507842009-02-26 14:39:58 +0000889 if (!Ex->isTypeDependent()) {
890 QualType Type = Ex->getType();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000891
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000892 if (const RecordType *Record = Type->getAs<RecordType>()) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000893 llvm::SmallVector<CXXConversionDecl *, 4> ObjectPtrConversions;
Fariborz Jahanian53462782009-09-11 21:44:33 +0000894 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
John McCalleec51cf2010-01-20 00:46:10 +0000895 const UnresolvedSetImpl *Conversions = RD->getVisibleConversionFunctions();
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000896
John McCalleec51cf2010-01-20 00:46:10 +0000897 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +0000898 E = Conversions->end(); I != E; ++I) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000899 // Skip over templated conversion functions; they aren't considered.
John McCallba135432009-11-21 08:51:07 +0000900 if (isa<FunctionTemplateDecl>(*I))
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000901 continue;
902
John McCallba135432009-11-21 08:51:07 +0000903 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*I);
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000904
905 QualType ConvType = Conv->getConversionType().getNonReferenceType();
906 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
907 if (ConvPtrType->getPointeeType()->isObjectType())
Fariborz Jahanian8b915e72009-09-15 22:15:23 +0000908 ObjectPtrConversions.push_back(Conv);
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000909 }
Fariborz Jahanian8b915e72009-09-15 22:15:23 +0000910 if (ObjectPtrConversions.size() == 1) {
911 // We have a single conversion to a pointer-to-object type. Perform
912 // that conversion.
913 Operand.release();
914 if (!PerformImplicitConversion(Ex,
915 ObjectPtrConversions.front()->getConversionType(),
Douglas Gregor68647482009-12-16 03:45:30 +0000916 AA_Converting)) {
Fariborz Jahanian8b915e72009-09-15 22:15:23 +0000917 Operand = Owned(Ex);
918 Type = Ex->getType();
919 }
920 }
921 else if (ObjectPtrConversions.size() > 1) {
922 Diag(StartLoc, diag::err_ambiguous_delete_operand)
923 << Type << Ex->getSourceRange();
924 for (unsigned i= 0; i < ObjectPtrConversions.size(); i++) {
925 CXXConversionDecl *Conv = ObjectPtrConversions[i];
John McCallb1622a12010-01-06 09:43:14 +0000926 NoteOverloadCandidate(Conv);
Fariborz Jahanian8b915e72009-09-15 22:15:23 +0000927 }
928 return ExprError();
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000929 }
Sebastian Redl28507842009-02-26 14:39:58 +0000930 }
931
Sebastian Redlf53597f2009-03-15 17:47:39 +0000932 if (!Type->isPointerType())
933 return ExprError(Diag(StartLoc, diag::err_delete_operand)
934 << Type << Ex->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +0000935
Ted Kremenek6217b802009-07-29 21:53:49 +0000936 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Douglas Gregor8dcb29d2009-03-24 20:13:58 +0000937 if (Pointee->isFunctionType() || Pointee->isVoidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000938 return ExprError(Diag(StartLoc, diag::err_delete_operand)
939 << Type << Ex->getSourceRange());
Douglas Gregor8dcb29d2009-03-24 20:13:58 +0000940 else if (!Pointee->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +0000941 RequireCompleteType(StartLoc, Pointee,
Anders Carlssonb7906612009-08-26 23:45:07 +0000942 PDiag(diag::warn_delete_incomplete)
943 << Ex->getSourceRange()))
Douglas Gregor8dcb29d2009-03-24 20:13:58 +0000944 return ExprError();
Sebastian Redl28507842009-02-26 14:39:58 +0000945
Douglas Gregor1070c9f2009-09-29 21:38:53 +0000946 // C++ [expr.delete]p2:
947 // [Note: a pointer to a const type can be the operand of a
948 // delete-expression; it is not necessary to cast away the constness
949 // (5.2.11) of the pointer expression before it is used as the operand
950 // of the delete-expression. ]
951 ImpCastExprToType(Ex, Context.getPointerType(Context.VoidTy),
952 CastExpr::CK_NoOp);
953
954 // Update the operand.
955 Operand.take();
956 Operand = ExprArg(*this, Ex);
957
Anders Carlssond67c4c32009-08-16 20:29:29 +0000958 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
959 ArrayForm ? OO_Array_Delete : OO_Delete);
960
Anders Carlsson78f74552009-11-15 18:45:20 +0000961 if (const RecordType *RT = Pointee->getAs<RecordType>()) {
962 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
963
964 if (!UseGlobal &&
965 FindDeallocationFunction(StartLoc, RD, DeleteName, OperatorDelete))
Anders Carlsson0ba63ea2009-11-14 03:17:38 +0000966 return ExprError();
Anders Carlsson0ba63ea2009-11-14 03:17:38 +0000967
Anders Carlsson78f74552009-11-15 18:45:20 +0000968 if (!RD->hasTrivialDestructor())
969 if (const CXXDestructorDecl *Dtor = RD->getDestructor(Context))
Mike Stump1eb44332009-09-09 15:08:12 +0000970 MarkDeclarationReferenced(StartLoc,
Fariborz Jahanian34374e62009-09-03 23:18:17 +0000971 const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssond67c4c32009-08-16 20:29:29 +0000972 }
Anders Carlsson78f74552009-11-15 18:45:20 +0000973
Anders Carlssond67c4c32009-08-16 20:29:29 +0000974 if (!OperatorDelete) {
Anders Carlsson78f74552009-11-15 18:45:20 +0000975 // Look for a global declaration.
Anders Carlssond67c4c32009-08-16 20:29:29 +0000976 DeclareGlobalNewDelete();
977 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000978 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
Douglas Gregor90916562009-09-29 18:16:17 +0000979 &Ex, 1, TUDecl, /*AllowMissing=*/false,
Anders Carlssond67c4c32009-08-16 20:29:29 +0000980 OperatorDelete))
981 return ExprError();
982 }
Mike Stump1eb44332009-09-09 15:08:12 +0000983
Sebastian Redl28507842009-02-26 14:39:58 +0000984 // FIXME: Check access and ambiguity of operator delete and destructor.
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000985 }
986
Sebastian Redlf53597f2009-03-15 17:47:39 +0000987 Operand.release();
988 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
Anders Carlssond67c4c32009-08-16 20:29:29 +0000989 OperatorDelete, Ex, StartLoc));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000990}
991
Douglas Gregor8cfe5a72009-11-23 23:44:04 +0000992/// \brief Check the use of the given variable as a C++ condition in an if,
993/// while, do-while, or switch statement.
994Action::OwningExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar) {
995 QualType T = ConditionVar->getType();
996
997 // C++ [stmt.select]p2:
998 // The declarator shall not specify a function or an array.
999 if (T->isFunctionType())
1000 return ExprError(Diag(ConditionVar->getLocation(),
1001 diag::err_invalid_use_of_function_type)
1002 << ConditionVar->getSourceRange());
1003 else if (T->isArrayType())
1004 return ExprError(Diag(ConditionVar->getLocation(),
1005 diag::err_invalid_use_of_array_type)
1006 << ConditionVar->getSourceRange());
Douglas Gregora7605db2009-11-24 16:07:02 +00001007
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001008 return Owned(DeclRefExpr::Create(Context, 0, SourceRange(), ConditionVar,
1009 ConditionVar->getLocation(),
1010 ConditionVar->getType().getNonReferenceType()));
1011}
1012
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001013/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
1014bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
1015 // C++ 6.4p4:
1016 // The value of a condition that is an initialized declaration in a statement
1017 // other than a switch statement is the value of the declared variable
1018 // implicitly converted to type bool. If that conversion is ill-formed, the
1019 // program is ill-formed.
1020 // The value of a condition that is an expression is the value of the
1021 // expression, implicitly converted to bool.
1022 //
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001023 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001024}
Douglas Gregor77a52232008-09-12 00:47:35 +00001025
1026/// Helper function to determine whether this is the (deprecated) C++
1027/// conversion from a string literal to a pointer to non-const char or
1028/// non-const wchar_t (for narrow and wide string literals,
1029/// respectively).
Mike Stump1eb44332009-09-09 15:08:12 +00001030bool
Douglas Gregor77a52232008-09-12 00:47:35 +00001031Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
1032 // Look inside the implicit cast, if it exists.
1033 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
1034 From = Cast->getSubExpr();
1035
1036 // A string literal (2.13.4) that is not a wide string literal can
1037 // be converted to an rvalue of type "pointer to char"; a wide
1038 // string literal can be converted to an rvalue of type "pointer
1039 // to wchar_t" (C++ 4.2p2).
1040 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From))
Ted Kremenek6217b802009-07-29 21:53:49 +00001041 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump1eb44332009-09-09 15:08:12 +00001042 if (const BuiltinType *ToPointeeType
John McCall183700f2009-09-21 23:43:11 +00001043 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregor77a52232008-09-12 00:47:35 +00001044 // This conversion is considered only when there is an
1045 // explicit appropriate pointer target type (C++ 4.2p2).
John McCall0953e762009-09-24 19:53:00 +00001046 if (!ToPtrType->getPointeeType().hasQualifiers() &&
Douglas Gregor77a52232008-09-12 00:47:35 +00001047 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
1048 (!StrLit->isWide() &&
1049 (ToPointeeType->getKind() == BuiltinType::Char_U ||
1050 ToPointeeType->getKind() == BuiltinType::Char_S))))
1051 return true;
1052 }
1053
1054 return false;
1055}
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001056
1057/// PerformImplicitConversion - Perform an implicit conversion of the
1058/// expression From to the type ToType. Returns true if there was an
1059/// error, false otherwise. The expression From is replaced with the
Douglas Gregor45920e82008-12-19 17:40:08 +00001060/// converted expression. Flavor is the kind of conversion we're
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001061/// performing, used in the error message. If @p AllowExplicit,
Sebastian Redle2b68332009-04-12 17:16:29 +00001062/// explicit user-defined conversions are permitted. @p Elidable should be true
1063/// when called for copies which may be elided (C++ 12.8p15). C++0x overload
1064/// resolution works differently in that case.
1065bool
Douglas Gregor45920e82008-12-19 17:40:08 +00001066Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor68647482009-12-16 03:45:30 +00001067 AssignmentAction Action, bool AllowExplicit,
Mike Stump1eb44332009-09-09 15:08:12 +00001068 bool Elidable) {
Sebastian Redle2b68332009-04-12 17:16:29 +00001069 ImplicitConversionSequence ICS;
Douglas Gregor68647482009-12-16 03:45:30 +00001070 return PerformImplicitConversion(From, ToType, Action, AllowExplicit,
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00001071 Elidable, ICS);
1072}
1073
1074bool
1075Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor68647482009-12-16 03:45:30 +00001076 AssignmentAction Action, bool AllowExplicit,
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00001077 bool Elidable,
1078 ImplicitConversionSequence& ICS) {
John McCall1d318332010-01-12 00:44:57 +00001079 ICS.setBad();
John McCalladbb8f82010-01-13 09:16:55 +00001080 ICS.Bad.init(BadConversionSequence::no_conversion, From, ToType);
Sebastian Redle2b68332009-04-12 17:16:29 +00001081 if (Elidable && getLangOptions().CPlusPlus0x) {
Mike Stump1eb44332009-09-09 15:08:12 +00001082 ICS = TryImplicitConversion(From, ToType,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001083 /*SuppressUserConversions=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +00001084 AllowExplicit,
Anders Carlsson08972922009-08-28 15:33:32 +00001085 /*ForceRValue=*/true,
1086 /*InOverloadResolution=*/false);
Sebastian Redle2b68332009-04-12 17:16:29 +00001087 }
John McCall1d318332010-01-12 00:44:57 +00001088 if (ICS.isBad()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001089 ICS = TryImplicitConversion(From, ToType,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001090 /*SuppressUserConversions=*/false,
1091 AllowExplicit,
Anders Carlsson08972922009-08-28 15:33:32 +00001092 /*ForceRValue=*/false,
1093 /*InOverloadResolution=*/false);
Sebastian Redle2b68332009-04-12 17:16:29 +00001094 }
Douglas Gregor68647482009-12-16 03:45:30 +00001095 return PerformImplicitConversion(From, ToType, ICS, Action);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001096}
1097
1098/// PerformImplicitConversion - Perform an implicit conversion of the
1099/// expression From to the type ToType using the pre-computed implicit
1100/// conversion sequence ICS. Returns true if there was an error, false
1101/// otherwise. The expression From is replaced with the converted
Douglas Gregor68647482009-12-16 03:45:30 +00001102/// expression. Action is the kind of conversion we're performing,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001103/// used in the error message.
1104bool
1105Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
1106 const ImplicitConversionSequence &ICS,
Douglas Gregor68647482009-12-16 03:45:30 +00001107 AssignmentAction Action, bool IgnoreBaseAccess) {
John McCall1d318332010-01-12 00:44:57 +00001108 switch (ICS.getKind()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001109 case ImplicitConversionSequence::StandardConversion:
Douglas Gregor68647482009-12-16 03:45:30 +00001110 if (PerformImplicitConversion(From, ToType, ICS.Standard, Action,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001111 IgnoreBaseAccess))
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001112 return true;
1113 break;
1114
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001115 case ImplicitConversionSequence::UserDefinedConversion: {
1116
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00001117 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
1118 CastExpr::CastKind CastKind = CastExpr::CK_Unknown;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001119 QualType BeforeToType;
1120 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00001121 CastKind = CastExpr::CK_UserDefinedConversion;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001122
1123 // If the user-defined conversion is specified by a conversion function,
1124 // the initial standard conversion sequence converts the source type to
1125 // the implicit object parameter of the conversion function.
1126 BeforeToType = Context.getTagDeclType(Conv->getParent());
1127 } else if (const CXXConstructorDecl *Ctor =
1128 dyn_cast<CXXConstructorDecl>(FD)) {
Anders Carlsson0aebc812009-09-09 21:33:21 +00001129 CastKind = CastExpr::CK_ConstructorConversion;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001130 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregore44201a2009-11-20 02:31:03 +00001131 if (!ICS.UserDefined.EllipsisConversion) {
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001132 // If the user-defined conversion is specified by a constructor, the
1133 // initial standard conversion sequence converts the source type to the
1134 // type required by the argument of the constructor
Douglas Gregore44201a2009-11-20 02:31:03 +00001135 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
1136 }
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001137 }
Anders Carlsson0aebc812009-09-09 21:33:21 +00001138 else
1139 assert(0 && "Unknown conversion function kind!");
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001140 // Whatch out for elipsis conversion.
Fariborz Jahanian4c0cea22009-11-06 00:55:14 +00001141 if (!ICS.UserDefined.EllipsisConversion) {
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001142 if (PerformImplicitConversion(From, BeforeToType,
Douglas Gregor68647482009-12-16 03:45:30 +00001143 ICS.UserDefined.Before, AA_Converting,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001144 IgnoreBaseAccess))
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001145 return true;
1146 }
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001147
Anders Carlsson0aebc812009-09-09 21:33:21 +00001148 OwningExprResult CastArg
1149 = BuildCXXCastArgument(From->getLocStart(),
1150 ToType.getNonReferenceType(),
1151 CastKind, cast<CXXMethodDecl>(FD),
1152 Owned(From));
1153
1154 if (CastArg.isInvalid())
1155 return true;
Eli Friedmand8889622009-11-27 04:41:50 +00001156
1157 From = CastArg.takeAs<Expr>();
1158
Eli Friedmand8889622009-11-27 04:41:50 +00001159 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
Douglas Gregor68647482009-12-16 03:45:30 +00001160 AA_Converting, IgnoreBaseAccess);
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001161 }
John McCall1d318332010-01-12 00:44:57 +00001162
1163 case ImplicitConversionSequence::AmbiguousConversion:
1164 DiagnoseAmbiguousConversion(ICS, From->getExprLoc(),
1165 PDiag(diag::err_typecheck_ambiguous_condition)
1166 << From->getSourceRange());
1167 return true;
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001168
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001169 case ImplicitConversionSequence::EllipsisConversion:
1170 assert(false && "Cannot perform an ellipsis conversion");
Douglas Gregor60d62c22008-10-31 16:23:19 +00001171 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001172
1173 case ImplicitConversionSequence::BadConversion:
1174 return true;
1175 }
1176
1177 // Everything went well.
1178 return false;
1179}
1180
1181/// PerformImplicitConversion - Perform an implicit conversion of the
1182/// expression From to the type ToType by following the standard
1183/// conversion sequence SCS. Returns true if there was an error, false
1184/// otherwise. The expression From is replaced with the converted
Douglas Gregor45920e82008-12-19 17:40:08 +00001185/// expression. Flavor is the context in which we're performing this
1186/// conversion, for use in error messages.
Mike Stump1eb44332009-09-09 15:08:12 +00001187bool
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001188Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor45920e82008-12-19 17:40:08 +00001189 const StandardConversionSequence& SCS,
Douglas Gregor68647482009-12-16 03:45:30 +00001190 AssignmentAction Action, bool IgnoreBaseAccess) {
Mike Stump390b4cc2009-05-16 07:39:55 +00001191 // Overall FIXME: we are recomputing too many types here and doing far too
1192 // much extra work. What this means is that we need to keep track of more
1193 // information that is computed when we try the implicit conversion initially,
1194 // so that we don't need to recompute anything here.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001195 QualType FromType = From->getType();
1196
Douglas Gregor225c41e2008-11-03 19:09:14 +00001197 if (SCS.CopyConstructor) {
Anders Carlsson7c3e8a12009-05-19 04:45:15 +00001198 // FIXME: When can ToType be a reference type?
1199 assert(!ToType->isReferenceType());
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00001200 if (SCS.Second == ICK_Derived_To_Base) {
1201 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1202 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
1203 MultiExprArg(*this, (void **)&From, 1),
1204 /*FIXME:ConstructLoc*/SourceLocation(),
1205 ConstructorArgs))
1206 return true;
1207 OwningExprResult FromResult =
1208 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1209 ToType, SCS.CopyConstructor,
1210 move_arg(ConstructorArgs));
1211 if (FromResult.isInvalid())
1212 return true;
1213 From = FromResult.takeAs<Expr>();
1214 return false;
1215 }
Mike Stump1eb44332009-09-09 15:08:12 +00001216 OwningExprResult FromResult =
1217 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1218 ToType, SCS.CopyConstructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00001219 MultiExprArg(*this, (void**)&From, 1));
Mike Stump1eb44332009-09-09 15:08:12 +00001220
Anders Carlssonda3f4e22009-08-25 05:12:04 +00001221 if (FromResult.isInvalid())
1222 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001223
Anders Carlssonda3f4e22009-08-25 05:12:04 +00001224 From = FromResult.takeAs<Expr>();
Douglas Gregor225c41e2008-11-03 19:09:14 +00001225 return false;
1226 }
1227
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001228 // Perform the first implicit conversion.
1229 switch (SCS.First) {
1230 case ICK_Identity:
1231 case ICK_Lvalue_To_Rvalue:
1232 // Nothing to do.
1233 break;
1234
1235 case ICK_Array_To_Pointer:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001236 FromType = Context.getArrayDecayedType(FromType);
Anders Carlsson82495762009-08-08 21:04:35 +00001237 ImpCastExprToType(From, FromType, CastExpr::CK_ArrayToPointerDecay);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001238 break;
1239
1240 case ICK_Function_To_Pointer:
Douglas Gregor063daf62009-03-13 18:40:31 +00001241 if (Context.getCanonicalType(FromType) == Context.OverloadTy) {
Douglas Gregor904eed32008-11-10 20:40:00 +00001242 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, true);
1243 if (!Fn)
1244 return true;
1245
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001246 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
1247 return true;
1248
Anders Carlsson96ad5332009-10-21 17:16:23 +00001249 From = FixOverloadedFunctionReference(From, Fn);
Douglas Gregor904eed32008-11-10 20:40:00 +00001250 FromType = From->getType();
Anders Carlsson96ad5332009-10-21 17:16:23 +00001251
Sebastian Redl759986e2009-10-17 20:50:27 +00001252 // If there's already an address-of operator in the expression, we have
1253 // the right type already, and the code below would just introduce an
1254 // invalid additional pointer level.
Anders Carlsson96ad5332009-10-21 17:16:23 +00001255 if (FromType->isPointerType() || FromType->isMemberFunctionPointerType())
Sebastian Redl759986e2009-10-17 20:50:27 +00001256 break;
Douglas Gregor904eed32008-11-10 20:40:00 +00001257 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001258 FromType = Context.getPointerType(FromType);
Anders Carlssonb633c4e2009-09-01 20:37:18 +00001259 ImpCastExprToType(From, FromType, CastExpr::CK_FunctionToPointerDecay);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001260 break;
1261
1262 default:
1263 assert(false && "Improper first standard conversion");
1264 break;
1265 }
1266
1267 // Perform the second implicit conversion
1268 switch (SCS.Second) {
1269 case ICK_Identity:
Sebastian Redl2c7588f2009-10-10 12:04:10 +00001270 // If both sides are functions (or pointers/references to them), there could
1271 // be incompatible exception declarations.
1272 if (CheckExceptionSpecCompatibility(From, ToType))
1273 return true;
1274 // Nothing else to do.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001275 break;
1276
Douglas Gregor43c79c22009-12-09 00:47:37 +00001277 case ICK_NoReturn_Adjustment:
1278 // If both sides are functions (or pointers/references to them), there could
1279 // be incompatible exception declarations.
1280 if (CheckExceptionSpecCompatibility(From, ToType))
1281 return true;
1282
1283 ImpCastExprToType(From, Context.getNoReturnType(From->getType(), false),
1284 CastExpr::CK_NoOp);
1285 break;
1286
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001287 case ICK_Integral_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001288 case ICK_Integral_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001289 ImpCastExprToType(From, ToType, CastExpr::CK_IntegralCast);
1290 break;
1291
1292 case ICK_Floating_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001293 case ICK_Floating_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001294 ImpCastExprToType(From, ToType, CastExpr::CK_FloatingCast);
1295 break;
1296
1297 case ICK_Complex_Promotion:
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001298 case ICK_Complex_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001299 ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1300 break;
1301
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001302 case ICK_Floating_Integral:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001303 if (ToType->isFloatingType())
1304 ImpCastExprToType(From, ToType, CastExpr::CK_IntegralToFloating);
1305 else
1306 ImpCastExprToType(From, ToType, CastExpr::CK_FloatingToIntegral);
1307 break;
1308
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001309 case ICK_Complex_Real:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001310 ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1311 break;
1312
Douglas Gregorf9201e02009-02-11 23:02:49 +00001313 case ICK_Compatible_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001314 ImpCastExprToType(From, ToType, CastExpr::CK_NoOp);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001315 break;
1316
Anders Carlsson61faec12009-09-12 04:46:44 +00001317 case ICK_Pointer_Conversion: {
Douglas Gregor45920e82008-12-19 17:40:08 +00001318 if (SCS.IncompatibleObjC) {
1319 // Diagnose incompatible Objective-C conversions
Mike Stump1eb44332009-09-09 15:08:12 +00001320 Diag(From->getSourceRange().getBegin(),
Douglas Gregor45920e82008-12-19 17:40:08 +00001321 diag::ext_typecheck_convert_incompatible_pointer)
Douglas Gregor68647482009-12-16 03:45:30 +00001322 << From->getType() << ToType << Action
Douglas Gregor45920e82008-12-19 17:40:08 +00001323 << From->getSourceRange();
1324 }
1325
Anders Carlsson61faec12009-09-12 04:46:44 +00001326
1327 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001328 if (CheckPointerConversion(From, ToType, Kind, IgnoreBaseAccess))
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001329 return true;
Anders Carlsson61faec12009-09-12 04:46:44 +00001330 ImpCastExprToType(From, ToType, Kind);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001331 break;
Anders Carlsson61faec12009-09-12 04:46:44 +00001332 }
1333
1334 case ICK_Pointer_Member: {
1335 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001336 if (CheckMemberPointerConversion(From, ToType, Kind, IgnoreBaseAccess))
Anders Carlsson61faec12009-09-12 04:46:44 +00001337 return true;
Sebastian Redl2c7588f2009-10-10 12:04:10 +00001338 if (CheckExceptionSpecCompatibility(From, ToType))
1339 return true;
Anders Carlsson61faec12009-09-12 04:46:44 +00001340 ImpCastExprToType(From, ToType, Kind);
1341 break;
1342 }
Anders Carlssonbc0e0782009-11-23 20:04:44 +00001343 case ICK_Boolean_Conversion: {
1344 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
1345 if (FromType->isMemberPointerType())
1346 Kind = CastExpr::CK_MemberPointerToBoolean;
1347
1348 ImpCastExprToType(From, Context.BoolTy, Kind);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001349 break;
Anders Carlssonbc0e0782009-11-23 20:04:44 +00001350 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001351
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001352 case ICK_Derived_To_Base:
1353 if (CheckDerivedToBaseConversion(From->getType(),
1354 ToType.getNonReferenceType(),
1355 From->getLocStart(),
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001356 From->getSourceRange(),
1357 IgnoreBaseAccess))
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001358 return true;
1359 ImpCastExprToType(From, ToType.getNonReferenceType(),
1360 CastExpr::CK_DerivedToBase);
1361 break;
1362
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001363 default:
1364 assert(false && "Improper second standard conversion");
1365 break;
1366 }
1367
1368 switch (SCS.Third) {
1369 case ICK_Identity:
1370 // Nothing to do.
1371 break;
1372
1373 case ICK_Qualification:
Mike Stump390b4cc2009-05-16 07:39:55 +00001374 // FIXME: Not sure about lvalue vs rvalue here in the presence of rvalue
1375 // references.
Mike Stump1eb44332009-09-09 15:08:12 +00001376 ImpCastExprToType(From, ToType.getNonReferenceType(),
Eli Friedman73c39ab2009-10-20 08:27:19 +00001377 CastExpr::CK_NoOp,
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001378 ToType->isLValueReferenceType());
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001379 break;
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001380
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001381 default:
1382 assert(false && "Improper second standard conversion");
1383 break;
1384 }
1385
1386 return false;
1387}
1388
Sebastian Redl64b45f72009-01-05 20:52:13 +00001389Sema::OwningExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
1390 SourceLocation KWLoc,
1391 SourceLocation LParen,
1392 TypeTy *Ty,
1393 SourceLocation RParen) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00001394 QualType T = GetTypeFromParser(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00001395
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001396 // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
1397 // all traits except __is_class, __is_enum and __is_union require a the type
1398 // to be complete.
1399 if (OTT != UTT_IsClass && OTT != UTT_IsEnum && OTT != UTT_IsUnion) {
Mike Stump1eb44332009-09-09 15:08:12 +00001400 if (RequireCompleteType(KWLoc, T,
Anders Carlssond497ba72009-08-26 22:59:12 +00001401 diag::err_incomplete_type_used_in_type_trait_expr))
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001402 return ExprError();
1403 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00001404
1405 // There is no point in eagerly computing the value. The traits are designed
1406 // to be used from type trait templates, so Ty will be a template parameter
1407 // 99% of the time.
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001408 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT, T,
1409 RParen, Context.BoolTy));
Sebastian Redl64b45f72009-01-05 20:52:13 +00001410}
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001411
1412QualType Sema::CheckPointerToMemberOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00001413 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001414 const char *OpSpelling = isIndirect ? "->*" : ".*";
1415 // C++ 5.5p2
1416 // The binary operator .* [p3: ->*] binds its second operand, which shall
1417 // be of type "pointer to member of T" (where T is a completely-defined
1418 // class type) [...]
1419 QualType RType = rex->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001420 const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
Douglas Gregore7450f52009-03-24 19:52:54 +00001421 if (!MemPtr) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001422 Diag(Loc, diag::err_bad_memptr_rhs)
1423 << OpSpelling << RType << rex->getSourceRange();
1424 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00001425 }
Douglas Gregore7450f52009-03-24 19:52:54 +00001426
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001427 QualType Class(MemPtr->getClass(), 0);
1428
1429 // C++ 5.5p2
1430 // [...] to its first operand, which shall be of class T or of a class of
1431 // which T is an unambiguous and accessible base class. [p3: a pointer to
1432 // such a class]
1433 QualType LType = lex->getType();
1434 if (isIndirect) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001435 if (const PointerType *Ptr = LType->getAs<PointerType>())
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001436 LType = Ptr->getPointeeType().getNonReferenceType();
1437 else {
1438 Diag(Loc, diag::err_bad_memptr_lhs)
Fariborz Jahanianef78ac62009-10-26 20:45:27 +00001439 << OpSpelling << 1 << LType
1440 << CodeModificationHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001441 return QualType();
1442 }
1443 }
1444
Douglas Gregora4923eb2009-11-16 21:35:15 +00001445 if (!Context.hasSameUnqualifiedType(Class, LType)) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001446 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1447 /*DetectVirtual=*/false);
Mike Stump390b4cc2009-05-16 07:39:55 +00001448 // FIXME: Would it be useful to print full ambiguity paths, or is that
1449 // overkill?
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001450 if (!IsDerivedFrom(LType, Class, Paths) ||
1451 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
1452 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Eli Friedman3005efe2010-01-16 00:00:48 +00001453 << (int)isIndirect << lex->getType();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001454 return QualType();
1455 }
Eli Friedman3005efe2010-01-16 00:00:48 +00001456 // Cast LHS to type of use.
1457 QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
1458 bool isLValue = !isIndirect && lex->isLvalue(Context) == Expr::LV_Valid;
1459 ImpCastExprToType(lex, UseType, CastExpr::CK_DerivedToBase, isLValue);
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001460 }
1461
Fariborz Jahanian19d70732009-11-18 22:16:17 +00001462 if (isa<CXXZeroInitValueExpr>(rex->IgnoreParens())) {
Fariborz Jahanian05ebda92009-11-18 21:54:48 +00001463 // Diagnose use of pointer-to-member type which when used as
1464 // the functional cast in a pointer-to-member expression.
1465 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
1466 return QualType();
1467 }
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001468 // C++ 5.5p2
1469 // The result is an object or a function of the type specified by the
1470 // second operand.
1471 // The cv qualifiers are the union of those in the pointer and the left side,
1472 // in accordance with 5.5p5 and 5.2.5.
1473 // FIXME: This returns a dereferenced member function pointer as a normal
1474 // function type. However, the only operation valid on such functions is
Mike Stump390b4cc2009-05-16 07:39:55 +00001475 // calling them. There's also a GCC extension to get a function pointer to the
1476 // thing, which is another complication, because this type - unlike the type
1477 // that is the result of this expression - takes the class as the first
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001478 // argument.
1479 // We probably need a "MemberFunctionClosureType" or something like that.
1480 QualType Result = MemPtr->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00001481 Result = Context.getCVRQualifiedType(Result, LType.getCVRQualifiers());
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001482 return Result;
1483}
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001484
1485/// \brief Get the target type of a standard or user-defined conversion.
1486static QualType TargetType(const ImplicitConversionSequence &ICS) {
John McCall1d318332010-01-12 00:44:57 +00001487 switch (ICS.getKind()) {
1488 case ImplicitConversionSequence::StandardConversion:
Douglas Gregorad323a82010-01-27 03:51:04 +00001489 return ICS.Standard.getToType(2);
John McCall1d318332010-01-12 00:44:57 +00001490 case ImplicitConversionSequence::UserDefinedConversion:
Douglas Gregorad323a82010-01-27 03:51:04 +00001491 return ICS.UserDefined.After.getToType(2);
John McCall1d318332010-01-12 00:44:57 +00001492 case ImplicitConversionSequence::AmbiguousConversion:
1493 return ICS.Ambiguous.getToType();
1494 case ImplicitConversionSequence::EllipsisConversion:
1495 case ImplicitConversionSequence::BadConversion:
1496 llvm_unreachable("function not valid for ellipsis or bad conversions");
1497 }
1498 return QualType(); // silence warnings
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001499}
1500
1501/// \brief Try to convert a type to another according to C++0x 5.16p3.
1502///
1503/// This is part of the parameter validation for the ? operator. If either
1504/// value operand is a class type, the two operands are attempted to be
1505/// converted to each other. This function does the conversion in one direction.
1506/// It emits a diagnostic and returns true only if it finds an ambiguous
1507/// conversion.
1508static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
1509 SourceLocation QuestionLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00001510 ImplicitConversionSequence &ICS) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001511 // C++0x 5.16p3
1512 // The process for determining whether an operand expression E1 of type T1
1513 // can be converted to match an operand expression E2 of type T2 is defined
1514 // as follows:
1515 // -- If E2 is an lvalue:
1516 if (To->isLvalue(Self.Context) == Expr::LV_Valid) {
1517 // E1 can be converted to match E2 if E1 can be implicitly converted to
1518 // type "lvalue reference to T2", subject to the constraint that in the
1519 // conversion the reference must bind directly to E1.
1520 if (!Self.CheckReferenceInit(From,
1521 Self.Context.getLValueReferenceType(To->getType()),
Douglas Gregor739d8282009-09-23 23:04:10 +00001522 To->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001523 /*SuppressUserConversions=*/false,
1524 /*AllowExplicit=*/false,
1525 /*ForceRValue=*/false,
1526 &ICS))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001527 {
John McCall1d318332010-01-12 00:44:57 +00001528 assert((ICS.isStandard() || ICS.isUserDefined()) &&
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001529 "expected a definite conversion");
1530 bool DirectBinding =
John McCall1d318332010-01-12 00:44:57 +00001531 ICS.isStandard() ? ICS.Standard.DirectBinding
1532 : ICS.UserDefined.After.DirectBinding;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001533 if (DirectBinding)
1534 return false;
1535 }
1536 }
John McCall1d318332010-01-12 00:44:57 +00001537 ICS.setBad();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001538 // -- If E2 is an rvalue, or if the conversion above cannot be done:
1539 // -- if E1 and E2 have class type, and the underlying class types are
1540 // the same or one is a base class of the other:
1541 QualType FTy = From->getType();
1542 QualType TTy = To->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001543 const RecordType *FRec = FTy->getAs<RecordType>();
1544 const RecordType *TRec = TTy->getAs<RecordType>();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001545 bool FDerivedFromT = FRec && TRec && Self.IsDerivedFrom(FTy, TTy);
1546 if (FRec && TRec && (FRec == TRec ||
1547 FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
1548 // E1 can be converted to match E2 if the class of T2 is the
1549 // same type as, or a base class of, the class of T1, and
1550 // [cv2 > cv1].
1551 if ((FRec == TRec || FDerivedFromT) && TTy.isAtLeastAsQualifiedAs(FTy)) {
1552 // Could still fail if there's no copy constructor.
1553 // FIXME: Is this a hard error then, or just a conversion failure? The
1554 // standard doesn't say.
Mike Stump1eb44332009-09-09 15:08:12 +00001555 ICS = Self.TryCopyInitialization(From, TTy,
Anders Carlssond28b4282009-08-27 17:18:13 +00001556 /*SuppressUserConversions=*/false,
Anders Carlsson7b361b52009-08-27 17:37:39 +00001557 /*ForceRValue=*/false,
1558 /*InOverloadResolution=*/false);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001559 }
1560 } else {
1561 // -- Otherwise: E1 can be converted to match E2 if E1 can be
1562 // implicitly converted to the type that expression E2 would have
1563 // if E2 were converted to an rvalue.
1564 // First find the decayed type.
1565 if (TTy->isFunctionType())
1566 TTy = Self.Context.getPointerType(TTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001567 else if (TTy->isArrayType())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001568 TTy = Self.Context.getArrayDecayedType(TTy);
1569
1570 // Now try the implicit conversion.
1571 // FIXME: This doesn't detect ambiguities.
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001572 ICS = Self.TryImplicitConversion(From, TTy,
1573 /*SuppressUserConversions=*/false,
1574 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00001575 /*ForceRValue=*/false,
1576 /*InOverloadResolution=*/false);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001577 }
1578 return false;
1579}
1580
1581/// \brief Try to find a common type for two according to C++0x 5.16p5.
1582///
1583/// This is part of the parameter validation for the ? operator. If either
1584/// value operand is a class type, overload resolution is used to find a
1585/// conversion to a common type.
1586static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
1587 SourceLocation Loc) {
1588 Expr *Args[2] = { LHS, RHS };
John McCall5769d612010-02-08 23:07:23 +00001589 OverloadCandidateSet CandidateSet(Loc);
Douglas Gregor573d9c32009-10-21 23:19:44 +00001590 Self.AddBuiltinOperatorCandidates(OO_Conditional, Loc, Args, 2, CandidateSet);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001591
1592 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00001593 switch (Self.BestViableFunction(CandidateSet, Loc, Best)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00001594 case OR_Success:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001595 // We found a match. Perform the conversions on the arguments and move on.
1596 if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00001597 Best->Conversions[0], Sema::AA_Converting) ||
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001598 Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor68647482009-12-16 03:45:30 +00001599 Best->Conversions[1], Sema::AA_Converting))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001600 break;
1601 return false;
1602
Douglas Gregor20093b42009-12-09 23:02:17 +00001603 case OR_No_Viable_Function:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001604 Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
1605 << LHS->getType() << RHS->getType()
1606 << LHS->getSourceRange() << RHS->getSourceRange();
1607 return true;
1608
Douglas Gregor20093b42009-12-09 23:02:17 +00001609 case OR_Ambiguous:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001610 Self.Diag(Loc, diag::err_conditional_ambiguous_ovl)
1611 << LHS->getType() << RHS->getType()
1612 << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stump390b4cc2009-05-16 07:39:55 +00001613 // FIXME: Print the possible common types by printing the return types of
1614 // the viable candidates.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001615 break;
1616
Douglas Gregor20093b42009-12-09 23:02:17 +00001617 case OR_Deleted:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001618 assert(false && "Conditional operator has only built-in overloads");
1619 break;
1620 }
1621 return true;
1622}
1623
Sebastian Redl76458502009-04-17 16:30:52 +00001624/// \brief Perform an "extended" implicit conversion as returned by
1625/// TryClassUnification.
1626///
1627/// TryClassUnification generates ICSs that include reference bindings.
1628/// PerformImplicitConversion is not suitable for this; it chokes if the
1629/// second part of a standard conversion is ICK_DerivedToBase. This function
1630/// handles the reference binding specially.
1631static bool ConvertForConditional(Sema &Self, Expr *&E,
Mike Stump1eb44332009-09-09 15:08:12 +00001632 const ImplicitConversionSequence &ICS) {
John McCall1d318332010-01-12 00:44:57 +00001633 if (ICS.isStandard() && ICS.Standard.ReferenceBinding) {
Sebastian Redl76458502009-04-17 16:30:52 +00001634 assert(ICS.Standard.DirectBinding &&
1635 "TryClassUnification should never generate indirect ref bindings");
Sebastian Redla5cd2cd2009-04-26 11:21:02 +00001636 // FIXME: CheckReferenceInit should be able to reuse the ICS instead of
1637 // redoing all the work.
1638 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001639 TargetType(ICS)),
Douglas Gregor739d8282009-09-23 23:04:10 +00001640 /*FIXME:*/E->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001641 /*SuppressUserConversions=*/false,
1642 /*AllowExplicit=*/false,
1643 /*ForceRValue=*/false);
Sebastian Redl76458502009-04-17 16:30:52 +00001644 }
John McCall1d318332010-01-12 00:44:57 +00001645 if (ICS.isUserDefined() && ICS.UserDefined.After.ReferenceBinding) {
Sebastian Redl76458502009-04-17 16:30:52 +00001646 assert(ICS.UserDefined.After.DirectBinding &&
1647 "TryClassUnification should never generate indirect ref bindings");
Sebastian Redla5cd2cd2009-04-26 11:21:02 +00001648 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001649 TargetType(ICS)),
Douglas Gregor739d8282009-09-23 23:04:10 +00001650 /*FIXME:*/E->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001651 /*SuppressUserConversions=*/false,
1652 /*AllowExplicit=*/false,
1653 /*ForceRValue=*/false);
Sebastian Redl76458502009-04-17 16:30:52 +00001654 }
Douglas Gregor68647482009-12-16 03:45:30 +00001655 if (Self.PerformImplicitConversion(E, TargetType(ICS), ICS, Sema::AA_Converting))
Sebastian Redl76458502009-04-17 16:30:52 +00001656 return true;
1657 return false;
1658}
1659
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001660/// \brief Check the operands of ?: under C++ semantics.
1661///
1662/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
1663/// extension. In this case, LHS == Cond. (But they're not aliases.)
1664QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
1665 SourceLocation QuestionLoc) {
Mike Stump390b4cc2009-05-16 07:39:55 +00001666 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
1667 // interface pointers.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001668
1669 // C++0x 5.16p1
1670 // The first expression is contextually converted to bool.
1671 if (!Cond->isTypeDependent()) {
1672 if (CheckCXXBooleanCondition(Cond))
1673 return QualType();
1674 }
1675
1676 // Either of the arguments dependent?
1677 if (LHS->isTypeDependent() || RHS->isTypeDependent())
1678 return Context.DependentTy;
1679
John McCallb13c87f2009-11-05 09:23:39 +00001680 CheckSignCompare(LHS, RHS, QuestionLoc, diag::warn_mixed_sign_conditional);
1681
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001682 // C++0x 5.16p2
1683 // If either the second or the third operand has type (cv) void, ...
1684 QualType LTy = LHS->getType();
1685 QualType RTy = RHS->getType();
1686 bool LVoid = LTy->isVoidType();
1687 bool RVoid = RTy->isVoidType();
1688 if (LVoid || RVoid) {
1689 // ... then the [l2r] conversions are performed on the second and third
1690 // operands ...
Douglas Gregora873dfc2010-02-03 00:27:59 +00001691 DefaultFunctionArrayLvalueConversion(LHS);
1692 DefaultFunctionArrayLvalueConversion(RHS);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001693 LTy = LHS->getType();
1694 RTy = RHS->getType();
1695
1696 // ... and one of the following shall hold:
1697 // -- The second or the third operand (but not both) is a throw-
1698 // expression; the result is of the type of the other and is an rvalue.
1699 bool LThrow = isa<CXXThrowExpr>(LHS);
1700 bool RThrow = isa<CXXThrowExpr>(RHS);
1701 if (LThrow && !RThrow)
1702 return RTy;
1703 if (RThrow && !LThrow)
1704 return LTy;
1705
1706 // -- Both the second and third operands have type void; the result is of
1707 // type void and is an rvalue.
1708 if (LVoid && RVoid)
1709 return Context.VoidTy;
1710
1711 // Neither holds, error.
1712 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
1713 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
1714 << LHS->getSourceRange() << RHS->getSourceRange();
1715 return QualType();
1716 }
1717
1718 // Neither is void.
1719
1720 // C++0x 5.16p3
1721 // Otherwise, if the second and third operand have different types, and
1722 // either has (cv) class type, and attempt is made to convert each of those
1723 // operands to the other.
1724 if (Context.getCanonicalType(LTy) != Context.getCanonicalType(RTy) &&
1725 (LTy->isRecordType() || RTy->isRecordType())) {
1726 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
1727 // These return true if a single direction is already ambiguous.
1728 if (TryClassUnification(*this, LHS, RHS, QuestionLoc, ICSLeftToRight))
1729 return QualType();
1730 if (TryClassUnification(*this, RHS, LHS, QuestionLoc, ICSRightToLeft))
1731 return QualType();
1732
John McCall1d318332010-01-12 00:44:57 +00001733 bool HaveL2R = !ICSLeftToRight.isBad();
1734 bool HaveR2L = !ICSRightToLeft.isBad();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001735 // If both can be converted, [...] the program is ill-formed.
1736 if (HaveL2R && HaveR2L) {
1737 Diag(QuestionLoc, diag::err_conditional_ambiguous)
1738 << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
1739 return QualType();
1740 }
1741
1742 // If exactly one conversion is possible, that conversion is applied to
1743 // the chosen operand and the converted operands are used in place of the
1744 // original operands for the remainder of this section.
1745 if (HaveL2R) {
Sebastian Redl76458502009-04-17 16:30:52 +00001746 if (ConvertForConditional(*this, LHS, ICSLeftToRight))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001747 return QualType();
1748 LTy = LHS->getType();
1749 } else if (HaveR2L) {
Sebastian Redl76458502009-04-17 16:30:52 +00001750 if (ConvertForConditional(*this, RHS, ICSRightToLeft))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001751 return QualType();
1752 RTy = RHS->getType();
1753 }
1754 }
1755
1756 // C++0x 5.16p4
1757 // If the second and third operands are lvalues and have the same type,
1758 // the result is of that type [...]
1759 bool Same = Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy);
1760 if (Same && LHS->isLvalue(Context) == Expr::LV_Valid &&
1761 RHS->isLvalue(Context) == Expr::LV_Valid)
1762 return LTy;
1763
1764 // C++0x 5.16p5
1765 // Otherwise, the result is an rvalue. If the second and third operands
1766 // do not have the same type, and either has (cv) class type, ...
1767 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
1768 // ... overload resolution is used to determine the conversions (if any)
1769 // to be applied to the operands. If the overload resolution fails, the
1770 // program is ill-formed.
1771 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
1772 return QualType();
1773 }
1774
1775 // C++0x 5.16p6
1776 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
1777 // conversions are performed on the second and third operands.
Douglas Gregora873dfc2010-02-03 00:27:59 +00001778 DefaultFunctionArrayLvalueConversion(LHS);
1779 DefaultFunctionArrayLvalueConversion(RHS);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001780 LTy = LHS->getType();
1781 RTy = RHS->getType();
1782
1783 // After those conversions, one of the following shall hold:
1784 // -- The second and third operands have the same type; the result
1785 // is of that type.
1786 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy))
1787 return LTy;
1788
1789 // -- The second and third operands have arithmetic or enumeration type;
1790 // the usual arithmetic conversions are performed to bring them to a
1791 // common type, and the result is of that type.
1792 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
1793 UsualArithmeticConversions(LHS, RHS);
1794 return LHS->getType();
1795 }
1796
1797 // -- The second and third operands have pointer type, or one has pointer
1798 // type and the other is a null pointer constant; pointer conversions
1799 // and qualification conversions are performed to bring them to their
1800 // composite pointer type. The result is of the composite pointer type.
Eli Friedmande8ac492010-01-02 22:56:07 +00001801 // -- The second and third operands have pointer to member type, or one has
1802 // pointer to member type and the other is a null pointer constant;
1803 // pointer to member conversions and qualification conversions are
1804 // performed to bring them to a common type, whose cv-qualification
1805 // shall match the cv-qualification of either the second or the third
1806 // operand. The result is of the common type.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001807 QualType Composite = FindCompositePointerType(LHS, RHS);
1808 if (!Composite.isNull())
1809 return Composite;
Fariborz Jahanian55016362009-12-10 20:46:08 +00001810
1811 // Similarly, attempt to find composite type of twp objective-c pointers.
1812 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
1813 if (!Composite.isNull())
1814 return Composite;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001815
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001816 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
1817 << LHS->getType() << RHS->getType()
1818 << LHS->getSourceRange() << RHS->getSourceRange();
1819 return QualType();
1820}
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001821
1822/// \brief Find a merged pointer type and convert the two expressions to it.
1823///
Douglas Gregor20b3e992009-08-24 17:42:35 +00001824/// This finds the composite pointer type (or member pointer type) for @p E1
1825/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
1826/// type and returns it.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001827/// It does not emit diagnostics.
1828QualType Sema::FindCompositePointerType(Expr *&E1, Expr *&E2) {
1829 assert(getLangOptions().CPlusPlus && "This function assumes C++");
1830 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001831
Fariborz Jahanian0cedfbd2009-12-08 20:04:24 +00001832 if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
1833 !T2->isAnyPointerType() && !T2->isMemberPointerType())
Douglas Gregor20b3e992009-08-24 17:42:35 +00001834 return QualType();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001835
1836 // C++0x 5.9p2
1837 // Pointer conversions and qualification conversions are performed on
1838 // pointer operands to bring them to their composite pointer type. If
1839 // one operand is a null pointer constant, the composite pointer type is
1840 // the type of the other operand.
Douglas Gregorce940492009-09-25 04:25:58 +00001841 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00001842 if (T2->isMemberPointerType())
1843 ImpCastExprToType(E1, T2, CastExpr::CK_NullToMemberPointer);
1844 else
1845 ImpCastExprToType(E1, T2, CastExpr::CK_IntegralToPointer);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001846 return T2;
1847 }
Douglas Gregorce940492009-09-25 04:25:58 +00001848 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00001849 if (T1->isMemberPointerType())
1850 ImpCastExprToType(E2, T1, CastExpr::CK_NullToMemberPointer);
1851 else
1852 ImpCastExprToType(E2, T1, CastExpr::CK_IntegralToPointer);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001853 return T1;
1854 }
Mike Stump1eb44332009-09-09 15:08:12 +00001855
Douglas Gregor20b3e992009-08-24 17:42:35 +00001856 // Now both have to be pointers or member pointers.
Sebastian Redla439e6f2009-11-16 21:03:45 +00001857 if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
1858 (!T2->isPointerType() && !T2->isMemberPointerType()))
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001859 return QualType();
1860
1861 // Otherwise, of one of the operands has type "pointer to cv1 void," then
1862 // the other has type "pointer to cv2 T" and the composite pointer type is
1863 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
1864 // Otherwise, the composite pointer type is a pointer type similar to the
1865 // type of one of the operands, with a cv-qualification signature that is
1866 // the union of the cv-qualification signatures of the operand types.
1867 // In practice, the first part here is redundant; it's subsumed by the second.
1868 // What we do here is, we build the two possible composite types, and try the
1869 // conversions in both directions. If only one works, or if the two composite
1870 // types are the same, we have succeeded.
John McCall0953e762009-09-24 19:53:00 +00001871 // FIXME: extended qualifiers?
Sebastian Redla439e6f2009-11-16 21:03:45 +00001872 typedef llvm::SmallVector<unsigned, 4> QualifierVector;
1873 QualifierVector QualifierUnion;
1874 typedef llvm::SmallVector<std::pair<const Type *, const Type *>, 4>
1875 ContainingClassVector;
1876 ContainingClassVector MemberOfClass;
1877 QualType Composite1 = Context.getCanonicalType(T1),
1878 Composite2 = Context.getCanonicalType(T2);
Douglas Gregor20b3e992009-08-24 17:42:35 +00001879 do {
1880 const PointerType *Ptr1, *Ptr2;
1881 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
1882 (Ptr2 = Composite2->getAs<PointerType>())) {
1883 Composite1 = Ptr1->getPointeeType();
1884 Composite2 = Ptr2->getPointeeType();
1885 QualifierUnion.push_back(
1886 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
1887 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
1888 continue;
1889 }
Mike Stump1eb44332009-09-09 15:08:12 +00001890
Douglas Gregor20b3e992009-08-24 17:42:35 +00001891 const MemberPointerType *MemPtr1, *MemPtr2;
1892 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
1893 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
1894 Composite1 = MemPtr1->getPointeeType();
1895 Composite2 = MemPtr2->getPointeeType();
1896 QualifierUnion.push_back(
1897 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
1898 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
1899 MemPtr2->getClass()));
1900 continue;
1901 }
Mike Stump1eb44332009-09-09 15:08:12 +00001902
Douglas Gregor20b3e992009-08-24 17:42:35 +00001903 // FIXME: block pointer types?
Mike Stump1eb44332009-09-09 15:08:12 +00001904
Douglas Gregor20b3e992009-08-24 17:42:35 +00001905 // Cannot unwrap any more types.
1906 break;
1907 } while (true);
Mike Stump1eb44332009-09-09 15:08:12 +00001908
Douglas Gregor20b3e992009-08-24 17:42:35 +00001909 // Rewrap the composites as pointers or member pointers with the union CVRs.
Sebastian Redla439e6f2009-11-16 21:03:45 +00001910 ContainingClassVector::reverse_iterator MOC
1911 = MemberOfClass.rbegin();
1912 for (QualifierVector::reverse_iterator
1913 I = QualifierUnion.rbegin(),
1914 E = QualifierUnion.rend();
Douglas Gregor20b3e992009-08-24 17:42:35 +00001915 I != E; (void)++I, ++MOC) {
John McCall0953e762009-09-24 19:53:00 +00001916 Qualifiers Quals = Qualifiers::fromCVRMask(*I);
Douglas Gregor20b3e992009-08-24 17:42:35 +00001917 if (MOC->first && MOC->second) {
1918 // Rebuild member pointer type
John McCall0953e762009-09-24 19:53:00 +00001919 Composite1 = Context.getMemberPointerType(
1920 Context.getQualifiedType(Composite1, Quals),
1921 MOC->first);
1922 Composite2 = Context.getMemberPointerType(
1923 Context.getQualifiedType(Composite2, Quals),
1924 MOC->second);
Douglas Gregor20b3e992009-08-24 17:42:35 +00001925 } else {
1926 // Rebuild pointer type
John McCall0953e762009-09-24 19:53:00 +00001927 Composite1
1928 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
1929 Composite2
1930 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregor20b3e992009-08-24 17:42:35 +00001931 }
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001932 }
1933
Mike Stump1eb44332009-09-09 15:08:12 +00001934 ImplicitConversionSequence E1ToC1 =
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001935 TryImplicitConversion(E1, Composite1,
1936 /*SuppressUserConversions=*/false,
1937 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00001938 /*ForceRValue=*/false,
1939 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00001940 ImplicitConversionSequence E2ToC1 =
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001941 TryImplicitConversion(E2, Composite1,
1942 /*SuppressUserConversions=*/false,
1943 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00001944 /*ForceRValue=*/false,
1945 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00001946
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001947 ImplicitConversionSequence E1ToC2, E2ToC2;
John McCall1d318332010-01-12 00:44:57 +00001948 E1ToC2.setBad();
John McCalladbb8f82010-01-13 09:16:55 +00001949 E2ToC2.setBad();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001950 if (Context.getCanonicalType(Composite1) !=
1951 Context.getCanonicalType(Composite2)) {
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001952 E1ToC2 = TryImplicitConversion(E1, Composite2,
1953 /*SuppressUserConversions=*/false,
1954 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00001955 /*ForceRValue=*/false,
1956 /*InOverloadResolution=*/false);
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001957 E2ToC2 = TryImplicitConversion(E2, Composite2,
1958 /*SuppressUserConversions=*/false,
1959 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00001960 /*ForceRValue=*/false,
1961 /*InOverloadResolution=*/false);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001962 }
1963
John McCall1d318332010-01-12 00:44:57 +00001964 bool ToC1Viable = !E1ToC1.isBad() && !E2ToC1.isBad();
1965 bool ToC2Viable = !E1ToC2.isBad() && !E2ToC2.isBad();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001966 if (ToC1Viable && !ToC2Viable) {
Douglas Gregor68647482009-12-16 03:45:30 +00001967 if (!PerformImplicitConversion(E1, Composite1, E1ToC1, Sema::AA_Converting) &&
1968 !PerformImplicitConversion(E2, Composite1, E2ToC1, Sema::AA_Converting))
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001969 return Composite1;
1970 }
1971 if (ToC2Viable && !ToC1Viable) {
Douglas Gregor68647482009-12-16 03:45:30 +00001972 if (!PerformImplicitConversion(E1, Composite2, E1ToC2, Sema::AA_Converting) &&
1973 !PerformImplicitConversion(E2, Composite2, E2ToC2, Sema::AA_Converting))
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001974 return Composite2;
1975 }
1976 return QualType();
1977}
Anders Carlsson165a0a02009-05-17 18:41:29 +00001978
Anders Carlssondef11992009-05-30 20:36:53 +00001979Sema::OwningExprResult Sema::MaybeBindToTemporary(Expr *E) {
Anders Carlsson089c2602009-08-15 23:41:35 +00001980 if (!Context.getLangOptions().CPlusPlus)
1981 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001982
Douglas Gregor51326552009-12-24 18:51:59 +00001983 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
1984
Ted Kremenek6217b802009-07-29 21:53:49 +00001985 const RecordType *RT = E->getType()->getAs<RecordType>();
Anders Carlssondef11992009-05-30 20:36:53 +00001986 if (!RT)
1987 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001988
John McCall86ff3082010-02-04 22:26:26 +00001989 // If this is the result of a call expression, our source might
1990 // actually be a reference, in which case we shouldn't bind.
Anders Carlsson283e4d52009-09-14 01:30:44 +00001991 if (CallExpr *CE = dyn_cast<CallExpr>(E)) {
1992 QualType Ty = CE->getCallee()->getType();
1993 if (const PointerType *PT = Ty->getAs<PointerType>())
1994 Ty = PT->getPointeeType();
1995
John McCall183700f2009-09-21 23:43:11 +00001996 const FunctionType *FTy = Ty->getAs<FunctionType>();
Anders Carlsson283e4d52009-09-14 01:30:44 +00001997 if (FTy->getResultType()->isReferenceType())
1998 return Owned(E);
1999 }
John McCall86ff3082010-02-04 22:26:26 +00002000
2001 // That should be enough to guarantee that this type is complete.
2002 // If it has a trivial destructor, we can avoid the extra copy.
2003 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2004 if (RD->hasTrivialDestructor())
2005 return Owned(E);
2006
Mike Stump1eb44332009-09-09 15:08:12 +00002007 CXXTemporary *Temp = CXXTemporary::Create(Context,
Anders Carlssondef11992009-05-30 20:36:53 +00002008 RD->getDestructor(Context));
Anders Carlsson860306e2009-05-30 21:21:49 +00002009 ExprTemporaries.push_back(Temp);
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00002010 if (CXXDestructorDecl *Destructor =
2011 const_cast<CXXDestructorDecl*>(RD->getDestructor(Context)))
2012 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
Anders Carlssondef11992009-05-30 20:36:53 +00002013 // FIXME: Add the temporary to the temporaries vector.
2014 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
2015}
2016
Anders Carlsson0ece4912009-12-15 20:51:39 +00002017Expr *Sema::MaybeCreateCXXExprWithTemporaries(Expr *SubExpr) {
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002018 assert(SubExpr && "sub expression can't be null!");
Mike Stump1eb44332009-09-09 15:08:12 +00002019
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00002020 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
2021 assert(ExprTemporaries.size() >= FirstTemporary);
2022 if (ExprTemporaries.size() == FirstTemporary)
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002023 return SubExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00002024
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002025 Expr *E = CXXExprWithTemporaries::Create(Context, SubExpr,
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00002026 &ExprTemporaries[FirstTemporary],
Anders Carlsson0ece4912009-12-15 20:51:39 +00002027 ExprTemporaries.size() - FirstTemporary);
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00002028 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
2029 ExprTemporaries.end());
Mike Stump1eb44332009-09-09 15:08:12 +00002030
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002031 return E;
2032}
2033
Douglas Gregor90f93822009-12-22 22:17:25 +00002034Sema::OwningExprResult
2035Sema::MaybeCreateCXXExprWithTemporaries(OwningExprResult SubExpr) {
2036 if (SubExpr.isInvalid())
2037 return ExprError();
2038
2039 return Owned(MaybeCreateCXXExprWithTemporaries(SubExpr.takeAs<Expr>()));
2040}
2041
Anders Carlsson5ee56e92009-12-16 02:09:40 +00002042FullExpr Sema::CreateFullExpr(Expr *SubExpr) {
2043 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
2044 assert(ExprTemporaries.size() >= FirstTemporary);
2045
2046 unsigned NumTemporaries = ExprTemporaries.size() - FirstTemporary;
2047 CXXTemporary **Temporaries =
2048 NumTemporaries == 0 ? 0 : &ExprTemporaries[FirstTemporary];
2049
2050 FullExpr E = FullExpr::Create(Context, SubExpr, Temporaries, NumTemporaries);
2051
2052 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
2053 ExprTemporaries.end());
2054
2055 return E;
2056}
2057
Mike Stump1eb44332009-09-09 15:08:12 +00002058Sema::OwningExprResult
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002059Sema::ActOnStartCXXMemberReference(Scope *S, ExprArg Base, SourceLocation OpLoc,
2060 tok::TokenKind OpKind, TypeTy *&ObjectType) {
2061 // Since this might be a postfix expression, get rid of ParenListExprs.
2062 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
Mike Stump1eb44332009-09-09 15:08:12 +00002063
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002064 Expr *BaseExpr = (Expr*)Base.get();
2065 assert(BaseExpr && "no record expansion");
Mike Stump1eb44332009-09-09 15:08:12 +00002066
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002067 QualType BaseType = BaseExpr->getType();
2068 if (BaseType->isDependentType()) {
Douglas Gregor43d88632009-11-04 22:49:18 +00002069 // If we have a pointer to a dependent type and are using the -> operator,
2070 // the object type is the type that the pointer points to. We might still
2071 // have enough information about that type to do something useful.
2072 if (OpKind == tok::arrow)
2073 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
2074 BaseType = Ptr->getPointeeType();
2075
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002076 ObjectType = BaseType.getAsOpaquePtr();
2077 return move(Base);
2078 }
Mike Stump1eb44332009-09-09 15:08:12 +00002079
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002080 // C++ [over.match.oper]p8:
Mike Stump1eb44332009-09-09 15:08:12 +00002081 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002082 // returned, with the original second operand.
2083 if (OpKind == tok::arrow) {
John McCallc4e83212009-09-30 01:01:30 +00002084 // The set of types we've considered so far.
John McCall432887f2009-09-30 01:30:54 +00002085 llvm::SmallPtrSet<CanQualType,8> CTypes;
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002086 llvm::SmallVector<SourceLocation, 8> Locations;
John McCall432887f2009-09-30 01:30:54 +00002087 CTypes.insert(Context.getCanonicalType(BaseType));
John McCallc4e83212009-09-30 01:01:30 +00002088
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002089 while (BaseType->isRecordType()) {
Anders Carlsson15ea3782009-10-13 22:43:21 +00002090 Base = BuildOverloadedArrowExpr(S, move(Base), OpLoc);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002091 BaseExpr = (Expr*)Base.get();
2092 if (BaseExpr == NULL)
2093 return ExprError();
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002094 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(BaseExpr))
Anders Carlssonde699e52009-10-13 22:55:59 +00002095 Locations.push_back(OpCall->getDirectCallee()->getLocation());
John McCallc4e83212009-09-30 01:01:30 +00002096 BaseType = BaseExpr->getType();
2097 CanQualType CBaseType = Context.getCanonicalType(BaseType);
John McCall432887f2009-09-30 01:30:54 +00002098 if (!CTypes.insert(CBaseType)) {
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00002099 Diag(OpLoc, diag::err_operator_arrow_circular);
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002100 for (unsigned i = 0; i < Locations.size(); i++)
2101 Diag(Locations[i], diag::note_declared_at);
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00002102 return ExprError();
2103 }
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002104 }
Mike Stump1eb44332009-09-09 15:08:12 +00002105
Douglas Gregor31658df2009-11-20 19:58:21 +00002106 if (BaseType->isPointerType())
2107 BaseType = BaseType->getPointeeType();
2108 }
Mike Stump1eb44332009-09-09 15:08:12 +00002109
2110 // We could end up with various non-record types here, such as extended
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002111 // vector types or Objective-C interfaces. Just return early and let
2112 // ActOnMemberReferenceExpr do the work.
Douglas Gregorc68afe22009-09-03 21:38:09 +00002113 if (!BaseType->isRecordType()) {
2114 // C++ [basic.lookup.classref]p2:
2115 // [...] If the type of the object expression is of pointer to scalar
2116 // type, the unqualified-id is looked up in the context of the complete
2117 // postfix-expression.
2118 ObjectType = 0;
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002119 return move(Base);
Douglas Gregorc68afe22009-09-03 21:38:09 +00002120 }
Mike Stump1eb44332009-09-09 15:08:12 +00002121
Douglas Gregor03c57052009-11-17 05:17:33 +00002122 // The object type must be complete (or dependent).
2123 if (!BaseType->isDependentType() &&
2124 RequireCompleteType(OpLoc, BaseType,
2125 PDiag(diag::err_incomplete_member_access)))
2126 return ExprError();
2127
Douglas Gregorc68afe22009-09-03 21:38:09 +00002128 // C++ [basic.lookup.classref]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00002129 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor03c57052009-11-17 05:17:33 +00002130 // unqualified-id, and the type of the object expression is of a class
Douglas Gregorc68afe22009-09-03 21:38:09 +00002131 // type C (or of pointer to a class type C), the unqualified-id is looked
2132 // up in the scope of class C. [...]
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002133 ObjectType = BaseType.getAsOpaquePtr();
Douglas Gregor03c57052009-11-17 05:17:33 +00002134
Mike Stump1eb44332009-09-09 15:08:12 +00002135 return move(Base);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002136}
2137
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002138CXXMemberCallExpr *Sema::BuildCXXMemberCallExpr(Expr *Exp,
2139 CXXMethodDecl *Method) {
Eli Friedman772fffa2009-12-09 04:53:56 +00002140 if (PerformObjectArgumentInitialization(Exp, Method))
2141 assert(0 && "Calling BuildCXXMemberCallExpr with invalid call?");
2142
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002143 MemberExpr *ME =
2144 new (Context) MemberExpr(Exp, /*IsArrow=*/false, Method,
2145 SourceLocation(), Method->getType());
Eli Friedman772fffa2009-12-09 04:53:56 +00002146 QualType ResultType = Method->getResultType().getNonReferenceType();
Douglas Gregor7edfb692009-11-23 12:27:39 +00002147 MarkDeclarationReferenced(Exp->getLocStart(), Method);
2148 CXXMemberCallExpr *CE =
2149 new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType,
2150 Exp->getLocEnd());
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002151 return CE;
2152}
2153
Anders Carlsson0aebc812009-09-09 21:33:21 +00002154Sema::OwningExprResult Sema::BuildCXXCastArgument(SourceLocation CastLoc,
2155 QualType Ty,
2156 CastExpr::CastKind Kind,
2157 CXXMethodDecl *Method,
2158 ExprArg Arg) {
2159 Expr *From = Arg.takeAs<Expr>();
2160
2161 switch (Kind) {
2162 default: assert(0 && "Unhandled cast kind!");
2163 case CastExpr::CK_ConstructorConversion: {
Douglas Gregor39da0b82009-09-09 23:08:42 +00002164 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
2165
2166 if (CompleteConstructorCall(cast<CXXConstructorDecl>(Method),
2167 MultiExprArg(*this, (void **)&From, 1),
2168 CastLoc, ConstructorArgs))
2169 return ExprError();
Anders Carlsson4fa26842009-10-18 21:20:14 +00002170
2171 OwningExprResult Result =
2172 BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
2173 move_arg(ConstructorArgs));
2174 if (Result.isInvalid())
2175 return ExprError();
2176
2177 return MaybeBindToTemporary(Result.takeAs<Expr>());
Anders Carlsson0aebc812009-09-09 21:33:21 +00002178 }
2179
2180 case CastExpr::CK_UserDefinedConversion: {
Anders Carlssonaac6e3a2009-09-15 07:42:44 +00002181 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
Eli Friedman772fffa2009-12-09 04:53:56 +00002182
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002183 // Create an implicit call expr that calls it.
2184 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(From, Method);
Anders Carlsson4fa26842009-10-18 21:20:14 +00002185 return MaybeBindToTemporary(CE);
Anders Carlsson0aebc812009-09-09 21:33:21 +00002186 }
Anders Carlsson0aebc812009-09-09 21:33:21 +00002187 }
2188}
2189
Anders Carlsson165a0a02009-05-17 18:41:29 +00002190Sema::OwningExprResult Sema::ActOnFinishFullExpr(ExprArg Arg) {
2191 Expr *FullExpr = Arg.takeAs<Expr>();
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002192 if (FullExpr)
Anders Carlsson0ece4912009-12-15 20:51:39 +00002193 FullExpr = MaybeCreateCXXExprWithTemporaries(FullExpr);
Anders Carlssonec773872009-08-25 23:46:41 +00002194
Anders Carlsson165a0a02009-05-17 18:41:29 +00002195 return Owned(FullExpr);
2196}