blob: ebb5b519c1a5c3d96eaab197afe4980c2c49a257 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Steve Naroff210679c2007-08-25 14:02:58 +000015#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000016#include "clang/AST/CXXInheritance.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000017#include "clang/AST/ExprCXX.h"
18#include "clang/Basic/PartialDiagnostic.h"
Sebastian Redlb5a57a62008-12-03 20:26:15 +000019#include "clang/Basic/TargetInfo.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000020#include "clang/Lex/Preprocessor.h"
21#include "clang/Parse/DeclSpec.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000022#include "llvm/ADT/STLExtras.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000023using namespace clang;
24
Douglas Gregor487a75a2008-11-19 19:09:45 +000025/// ActOnCXXConversionFunctionExpr - Parse a C++ conversion function
Douglas Gregor2def4832008-11-17 20:34:05 +000026/// name (e.g., operator void const *) as an expression. This is
27/// very similar to ActOnIdentifierExpr, except that instead of
28/// providing an identifier the parser provides the type of the
29/// conversion function.
Sebastian Redlcd965b92009-01-18 18:53:16 +000030Sema::OwningExprResult
Douglas Gregor487a75a2008-11-19 19:09:45 +000031Sema::ActOnCXXConversionFunctionExpr(Scope *S, SourceLocation OperatorLoc,
32 TypeTy *Ty, bool HasTrailingLParen,
Sebastian Redlebc07d52009-02-03 20:19:35 +000033 const CXXScopeSpec &SS,
34 bool isAddressOfOperand) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +000035 //FIXME: Preserve type source info.
36 QualType ConvType = GetTypeFromParser(Ty);
Douglas Gregor50d62d12009-08-05 05:36:45 +000037 CanQualType ConvTypeCanon = Context.getCanonicalType(ConvType);
Mike Stump1eb44332009-09-09 15:08:12 +000038 DeclarationName ConvName
Douglas Gregor2def4832008-11-17 20:34:05 +000039 = Context.DeclarationNames.getCXXConversionFunctionName(ConvTypeCanon);
Sebastian Redlcd965b92009-01-18 18:53:16 +000040 return ActOnDeclarationNameExpr(S, OperatorLoc, ConvName, HasTrailingLParen,
Douglas Gregor17330012009-02-04 15:01:18 +000041 &SS, isAddressOfOperand);
Douglas Gregor2def4832008-11-17 20:34:05 +000042}
Sebastian Redlc42e1182008-11-11 11:37:55 +000043
Douglas Gregor487a75a2008-11-19 19:09:45 +000044/// ActOnCXXOperatorFunctionIdExpr - Parse a C++ overloaded operator
Douglas Gregore94ca9e42008-11-18 14:39:36 +000045/// name (e.g., @c operator+ ) as an expression. This is very
46/// similar to ActOnIdentifierExpr, except that instead of providing
47/// an identifier the parser provides the kind of overloaded
48/// operator that was parsed.
Sebastian Redlcd965b92009-01-18 18:53:16 +000049Sema::OwningExprResult
Douglas Gregor487a75a2008-11-19 19:09:45 +000050Sema::ActOnCXXOperatorFunctionIdExpr(Scope *S, SourceLocation OperatorLoc,
51 OverloadedOperatorKind Op,
52 bool HasTrailingLParen,
Sebastian Redlebc07d52009-02-03 20:19:35 +000053 const CXXScopeSpec &SS,
54 bool isAddressOfOperand) {
Douglas Gregore94ca9e42008-11-18 14:39:36 +000055 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(Op);
Sebastian Redlebc07d52009-02-03 20:19:35 +000056 return ActOnDeclarationNameExpr(S, OperatorLoc, Name, HasTrailingLParen, &SS,
Douglas Gregor17330012009-02-04 15:01:18 +000057 isAddressOfOperand);
Douglas Gregore94ca9e42008-11-18 14:39:36 +000058}
59
Sebastian Redlc42e1182008-11-11 11:37:55 +000060/// ActOnCXXTypeidOfType - Parse typeid( type-id ).
Sebastian Redlf53597f2009-03-15 17:47:39 +000061Action::OwningExprResult
Sebastian Redlc42e1182008-11-11 11:37:55 +000062Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
63 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +000064 if (!StdNamespace)
Sebastian Redlf53597f2009-03-15 17:47:39 +000065 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +000066
67 if (isType)
68 // FIXME: Preserve type source info.
69 TyOrExpr = GetTypeFromParser(TyOrExpr).getAsOpaquePtr();
70
Chris Lattner572af492008-11-20 05:51:55 +000071 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
John McCallf36e02d2009-10-09 21:13:30 +000072 LookupResult R;
73 LookupQualifiedName(R, StdNamespace, TypeInfoII, LookupTagName);
74 Decl *TypeInfoDecl = R.getAsSingleDecl(Context);
Sebastian Redlc42e1182008-11-11 11:37:55 +000075 RecordDecl *TypeInfoRecordDecl = dyn_cast_or_null<RecordDecl>(TypeInfoDecl);
Chris Lattner572af492008-11-20 05:51:55 +000076 if (!TypeInfoRecordDecl)
Sebastian Redlf53597f2009-03-15 17:47:39 +000077 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Sebastian Redlc42e1182008-11-11 11:37:55 +000078
79 QualType TypeInfoType = Context.getTypeDeclType(TypeInfoRecordDecl);
80
Douglas Gregorac7610d2009-06-22 20:57:11 +000081 if (!isType) {
82 // C++0x [expr.typeid]p3:
Mike Stump1eb44332009-09-09 15:08:12 +000083 // When typeid is applied to an expression other than an lvalue of a
84 // polymorphic class type [...] [the] expression is an unevaluated
Douglas Gregorac7610d2009-06-22 20:57:11 +000085 // operand.
Mike Stump1eb44332009-09-09 15:08:12 +000086
Douglas Gregorac7610d2009-06-22 20:57:11 +000087 // FIXME: if the type of the expression is a class type, the class
88 // shall be completely defined.
89 bool isUnevaluatedOperand = true;
90 Expr *E = static_cast<Expr *>(TyOrExpr);
91 if (E && !E->isTypeDependent() && E->isLvalue(Context) == Expr::LV_Valid) {
92 QualType T = E->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +000093 if (const RecordType *RecordT = T->getAs<RecordType>()) {
Douglas Gregorac7610d2009-06-22 20:57:11 +000094 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
95 if (RecordD->isPolymorphic())
96 isUnevaluatedOperand = false;
97 }
98 }
Mike Stump1eb44332009-09-09 15:08:12 +000099
Douglas Gregorac7610d2009-06-22 20:57:11 +0000100 // If this is an unevaluated operand, clear out the set of declaration
101 // references we have been computing.
102 if (isUnevaluatedOperand)
103 PotentiallyReferencedDeclStack.back().clear();
104 }
Mike Stump1eb44332009-09-09 15:08:12 +0000105
Sebastian Redlf53597f2009-03-15 17:47:39 +0000106 return Owned(new (Context) CXXTypeidExpr(isType, TyOrExpr,
107 TypeInfoType.withConst(),
108 SourceRange(OpLoc, RParenLoc)));
Sebastian Redlc42e1182008-11-11 11:37:55 +0000109}
110
Steve Naroff1b273c42007-09-16 14:56:35 +0000111/// ActOnCXXBoolLiteral - Parse {true,false} literals.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000112Action::OwningExprResult
Steve Naroff1b273c42007-09-16 14:56:35 +0000113Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor2f639b92008-10-24 15:36:09 +0000114 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000115 "Unknown C++ Boolean value!");
Sebastian Redlf53597f2009-03-15 17:47:39 +0000116 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
117 Context.BoolTy, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000118}
Chris Lattner50dd2892008-02-26 00:51:44 +0000119
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000120/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
121Action::OwningExprResult
122Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
123 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
124}
125
Chris Lattner50dd2892008-02-26 00:51:44 +0000126/// ActOnCXXThrow - Parse throw expressions.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000127Action::OwningExprResult
128Sema::ActOnCXXThrow(SourceLocation OpLoc, ExprArg E) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000129 Expr *Ex = E.takeAs<Expr>();
130 if (Ex && !Ex->isTypeDependent() && CheckCXXThrowOperand(OpLoc, Ex))
131 return ExprError();
132 return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc));
133}
134
135/// CheckCXXThrowOperand - Validate the operand of a throw.
136bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *&E) {
137 // C++ [except.throw]p3:
138 // [...] adjusting the type from "array of T" or "function returning T"
139 // to "pointer to T" or "pointer to function returning T", [...]
140 DefaultFunctionArrayConversion(E);
141
142 // If the type of the exception would be an incomplete type or a pointer
143 // to an incomplete type other than (cv) void the program is ill-formed.
144 QualType Ty = E->getType();
145 int isPointer = 0;
Ted Kremenek6217b802009-07-29 21:53:49 +0000146 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000147 Ty = Ptr->getPointeeType();
148 isPointer = 1;
149 }
150 if (!isPointer || !Ty->isVoidType()) {
151 if (RequireCompleteType(ThrowLoc, Ty,
Anders Carlssond497ba72009-08-26 22:59:12 +0000152 PDiag(isPointer ? diag::err_throw_incomplete_ptr
153 : diag::err_throw_incomplete)
154 << E->getSourceRange()))
Sebastian Redl972041f2009-04-27 20:27:31 +0000155 return true;
156 }
157
158 // FIXME: Construct a temporary here.
159 return false;
Chris Lattner50dd2892008-02-26 00:51:44 +0000160}
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000161
Sebastian Redlf53597f2009-03-15 17:47:39 +0000162Action::OwningExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000163 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
164 /// is a non-lvalue expression whose value is the address of the object for
165 /// which the function is called.
166
Sebastian Redlf53597f2009-03-15 17:47:39 +0000167 if (!isa<FunctionDecl>(CurContext))
168 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000169
170 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext))
171 if (MD->isInstance())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000172 return Owned(new (Context) CXXThisExpr(ThisLoc,
173 MD->getThisType(Context)));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000174
Sebastian Redlf53597f2009-03-15 17:47:39 +0000175 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000176}
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000177
178/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
179/// Can be interpreted either as function-style casting ("int(x)")
180/// or class type construction ("ClassType(x,y,z)")
181/// or creation of a value-initialized type ("int()").
Sebastian Redlf53597f2009-03-15 17:47:39 +0000182Action::OwningExprResult
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000183Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep,
184 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000185 MultiExprArg exprs,
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000186 SourceLocation *CommaLocs,
187 SourceLocation RParenLoc) {
188 assert(TypeRep && "Missing type!");
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000189 // FIXME: Preserve type source info.
190 QualType Ty = GetTypeFromParser(TypeRep);
Sebastian Redlf53597f2009-03-15 17:47:39 +0000191 unsigned NumExprs = exprs.size();
192 Expr **Exprs = (Expr**)exprs.get();
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000193 SourceLocation TyBeginLoc = TypeRange.getBegin();
194 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
195
Sebastian Redlf53597f2009-03-15 17:47:39 +0000196 if (Ty->isDependentType() ||
Douglas Gregorba498172009-03-13 21:01:28 +0000197 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
Sebastian Redlf53597f2009-03-15 17:47:39 +0000198 exprs.release();
Mike Stump1eb44332009-09-09 15:08:12 +0000199
200 return Owned(CXXUnresolvedConstructExpr::Create(Context,
201 TypeRange.getBegin(), Ty,
Douglas Gregord81e6ca2009-05-20 18:46:25 +0000202 LParenLoc,
203 Exprs, NumExprs,
204 RParenLoc));
Douglas Gregorba498172009-03-13 21:01:28 +0000205 }
206
Anders Carlssonbb60a502009-08-27 03:53:50 +0000207 if (Ty->isArrayType())
208 return ExprError(Diag(TyBeginLoc,
209 diag::err_value_init_for_array_type) << FullRange);
210 if (!Ty->isVoidType() &&
211 RequireCompleteType(TyBeginLoc, Ty,
212 PDiag(diag::err_invalid_incomplete_type_use)
213 << FullRange))
214 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000215
Anders Carlssonbb60a502009-08-27 03:53:50 +0000216 if (RequireNonAbstractType(TyBeginLoc, Ty,
217 diag::err_allocation_of_abstract_type))
218 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000219
220
Douglas Gregor506ae412009-01-16 18:33:17 +0000221 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000222 // If the expression list is a single expression, the type conversion
223 // expression is equivalent (in definedness, and if defined in meaning) to the
224 // corresponding cast expression.
225 //
226 if (NumExprs == 1) {
Anders Carlssoncdb61972009-08-07 22:21:05 +0000227 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Anders Carlsson0aebc812009-09-09 21:33:21 +0000228 CXXMethodDecl *Method = 0;
229 if (CheckCastTypes(TypeRange, Ty, Exprs[0], Kind, Method,
230 /*FunctionalStyle=*/true))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000231 return ExprError();
Anders Carlsson0aebc812009-09-09 21:33:21 +0000232
233 exprs.release();
234 if (Method) {
235 OwningExprResult CastArg
236 = BuildCXXCastArgument(TypeRange.getBegin(), Ty.getNonReferenceType(),
237 Kind, Method, Owned(Exprs[0]));
238 if (CastArg.isInvalid())
239 return ExprError();
240
241 Exprs[0] = CastArg.takeAs<Expr>();
Fariborz Jahanian4fc7ab32009-08-28 15:11:24 +0000242 }
Anders Carlsson0aebc812009-09-09 21:33:21 +0000243
244 return Owned(new (Context) CXXFunctionalCastExpr(Ty.getNonReferenceType(),
245 Ty, TyBeginLoc, Kind,
246 Exprs[0], RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000247 }
248
Ted Kremenek6217b802009-07-29 21:53:49 +0000249 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Douglas Gregor506ae412009-01-16 18:33:17 +0000250 CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
Sebastian Redlf53597f2009-03-15 17:47:39 +0000251
Mike Stump1eb44332009-09-09 15:08:12 +0000252 if (NumExprs > 1 || !Record->hasTrivialConstructor() ||
Anders Carlssone7624a72009-08-27 05:08:22 +0000253 !Record->hasTrivialDestructor()) {
Douglas Gregor39da0b82009-09-09 23:08:42 +0000254 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
255
Douglas Gregor506ae412009-01-16 18:33:17 +0000256 CXXConstructorDecl *Constructor
Douglas Gregor39da0b82009-09-09 23:08:42 +0000257 = PerformInitializationByConstructor(Ty, move(exprs),
Douglas Gregor506ae412009-01-16 18:33:17 +0000258 TypeRange.getBegin(),
259 SourceRange(TypeRange.getBegin(),
260 RParenLoc),
261 DeclarationName(),
Douglas Gregor39da0b82009-09-09 23:08:42 +0000262 IK_Direct,
263 ConstructorArgs);
Douglas Gregor506ae412009-01-16 18:33:17 +0000264
Sebastian Redlf53597f2009-03-15 17:47:39 +0000265 if (!Constructor)
266 return ExprError();
267
Mike Stump1eb44332009-09-09 15:08:12 +0000268 OwningExprResult Result =
269 BuildCXXTemporaryObjectExpr(Constructor, Ty, TyBeginLoc,
Douglas Gregor39da0b82009-09-09 23:08:42 +0000270 move_arg(ConstructorArgs), RParenLoc);
Anders Carlssone7624a72009-08-27 05:08:22 +0000271 if (Result.isInvalid())
272 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000273
Anders Carlssone7624a72009-08-27 05:08:22 +0000274 return MaybeBindToTemporary(Result.takeAs<Expr>());
Douglas Gregor506ae412009-01-16 18:33:17 +0000275 }
276
277 // Fall through to value-initialize an object of class type that
278 // doesn't have a user-declared default constructor.
279 }
280
281 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000282 // If the expression list specifies more than a single value, the type shall
283 // be a class with a suitably declared constructor.
284 //
285 if (NumExprs > 1)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000286 return ExprError(Diag(CommaLocs[0],
287 diag::err_builtin_func_cast_more_than_one_arg)
288 << FullRange);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000289
290 assert(NumExprs == 0 && "Expected 0 expressions");
291
Douglas Gregor506ae412009-01-16 18:33:17 +0000292 // C++ [expr.type.conv]p2:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000293 // The expression T(), where T is a simple-type-specifier for a non-array
294 // complete object type or the (possibly cv-qualified) void type, creates an
295 // rvalue of the specified type, which is value-initialized.
296 //
Sebastian Redlf53597f2009-03-15 17:47:39 +0000297 exprs.release();
298 return Owned(new (Context) CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000299}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000300
301
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000302/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
303/// @code new (memory) int[size][4] @endcode
304/// or
305/// @code ::new Foo(23, "hello") @endcode
306/// For the interpretation of this heap of arguments, consult the base version.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000307Action::OwningExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000308Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000309 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000310 SourceLocation PlacementRParen, bool ParenTypeId,
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000311 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000312 MultiExprArg ConstructorArgs,
Mike Stump1eb44332009-09-09 15:08:12 +0000313 SourceLocation ConstructorRParen) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000314 Expr *ArraySize = 0;
315 unsigned Skip = 0;
316 // If the specified type is an array, unwrap it and save the expression.
317 if (D.getNumTypeObjects() > 0 &&
318 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
319 DeclaratorChunk &Chunk = D.getTypeObject(0);
320 if (Chunk.Arr.hasStatic)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000321 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
322 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000323 if (!Chunk.Arr.NumElts)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000324 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
325 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000326 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
327 Skip = 1;
328 }
329
Douglas Gregor043cad22009-09-11 00:18:58 +0000330 // Every dimension shall be of constant size.
331 if (D.getNumTypeObjects() > 0 &&
332 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
333 for (unsigned I = 1, N = D.getNumTypeObjects(); I < N; ++I) {
334 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
335 break;
336
337 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
338 if (Expr *NumElts = (Expr *)Array.NumElts) {
339 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
340 !NumElts->isIntegerConstantExpr(Context)) {
341 Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst)
342 << NumElts->getSourceRange();
343 return ExprError();
344 }
345 }
346 }
347 }
348
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000349 //FIXME: Store DeclaratorInfo in CXXNew expression.
350 DeclaratorInfo *DInfo = 0;
351 QualType AllocType = GetTypeForDeclarator(D, /*Scope=*/0, &DInfo, Skip);
Chris Lattnereaaebc72009-04-25 08:06:05 +0000352 if (D.isInvalidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000353 return ExprError();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000354
Mike Stump1eb44332009-09-09 15:08:12 +0000355 return BuildCXXNew(StartLoc, UseGlobal,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000356 PlacementLParen,
Mike Stump1eb44332009-09-09 15:08:12 +0000357 move(PlacementArgs),
Douglas Gregor3433cf72009-05-21 00:00:09 +0000358 PlacementRParen,
359 ParenTypeId,
Mike Stump1eb44332009-09-09 15:08:12 +0000360 AllocType,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000361 D.getSourceRange().getBegin(),
362 D.getSourceRange(),
363 Owned(ArraySize),
364 ConstructorLParen,
365 move(ConstructorArgs),
366 ConstructorRParen);
367}
368
Mike Stump1eb44332009-09-09 15:08:12 +0000369Sema::OwningExprResult
Douglas Gregor3433cf72009-05-21 00:00:09 +0000370Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
371 SourceLocation PlacementLParen,
372 MultiExprArg PlacementArgs,
373 SourceLocation PlacementRParen,
Mike Stump1eb44332009-09-09 15:08:12 +0000374 bool ParenTypeId,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000375 QualType AllocType,
376 SourceLocation TypeLoc,
377 SourceRange TypeRange,
378 ExprArg ArraySizeE,
379 SourceLocation ConstructorLParen,
380 MultiExprArg ConstructorArgs,
381 SourceLocation ConstructorRParen) {
382 if (CheckAllocatedType(AllocType, TypeLoc, TypeRange))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000383 return ExprError();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000384
Douglas Gregor3433cf72009-05-21 00:00:09 +0000385 QualType ResultType = Context.getPointerType(AllocType);
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000386
387 // That every array dimension except the first is constant was already
388 // checked by the type check above.
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000389
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000390 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
391 // or enumeration type with a non-negative value."
Douglas Gregor3433cf72009-05-21 00:00:09 +0000392 Expr *ArraySize = (Expr *)ArraySizeE.get();
Sebastian Redl28507842009-02-26 14:39:58 +0000393 if (ArraySize && !ArraySize->isTypeDependent()) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000394 QualType SizeType = ArraySize->getType();
395 if (!SizeType->isIntegralType() && !SizeType->isEnumeralType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000396 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
397 diag::err_array_size_not_integral)
398 << SizeType << ArraySize->getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000399 // Let's see if this is a constant < 0. If so, we reject it out of hand.
400 // We don't care about special rules, so we tell the machinery it's not
401 // evaluated - it gives us a result in more cases.
Sebastian Redl28507842009-02-26 14:39:58 +0000402 if (!ArraySize->isValueDependent()) {
403 llvm::APSInt Value;
404 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
405 if (Value < llvm::APSInt(
Anders Carlssonac18b2e2009-09-23 00:37:25 +0000406 llvm::APInt::getNullValue(Value.getBitWidth()),
407 Value.isUnsigned()))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000408 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
409 diag::err_typecheck_negative_array_size)
410 << ArraySize->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +0000411 }
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000412 }
Anders Carlssonac18b2e2009-09-23 00:37:25 +0000413
414 ImpCastExprToType(ArraySize, Context.getSizeType());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000415 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000416
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000417 FunctionDecl *OperatorNew = 0;
418 FunctionDecl *OperatorDelete = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000419 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
420 unsigned NumPlaceArgs = PlacementArgs.size();
Douglas Gregor089407b2009-10-17 21:40:42 +0000421
Sebastian Redl28507842009-02-26 14:39:58 +0000422 if (!AllocType->isDependentType() &&
423 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
424 FindAllocationFunctions(StartLoc,
Sebastian Redl00e68e22009-02-09 18:24:27 +0000425 SourceRange(PlacementLParen, PlacementRParen),
426 UseGlobal, AllocType, ArraySize, PlaceArgs,
427 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000428 return ExprError();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000429
430 bool Init = ConstructorLParen.isValid();
431 // --- Choosing a constructor ---
432 // C++ 5.3.4p15
433 // 1) If T is a POD and there's no initializer (ConstructorLParen is invalid)
434 // the object is not initialized. If the object, or any part of it, is
435 // const-qualified, it's an error.
436 // 2) If T is a POD and there's an empty initializer, the object is value-
437 // initialized.
438 // 3) If T is a POD and there's one initializer argument, the object is copy-
439 // constructed.
440 // 4) If T is a POD and there's more initializer arguments, it's an error.
441 // 5) If T is not a POD, the initializer arguments are used as constructor
442 // arguments.
443 //
444 // Or by the C++0x formulation:
445 // 1) If there's no initializer, the object is default-initialized according
446 // to C++0x rules.
447 // 2) Otherwise, the object is direct-initialized.
448 CXXConstructorDecl *Constructor = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000449 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
Sebastian Redl4f149632009-05-07 16:14:23 +0000450 const RecordType *RT;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000451 unsigned NumConsArgs = ConstructorArgs.size();
Douglas Gregor089407b2009-10-17 21:40:42 +0000452
453 if (AllocType->isDependentType() ||
454 Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) {
Sebastian Redl28507842009-02-26 14:39:58 +0000455 // Skip all the checks.
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000456 } else if ((RT = AllocType->getAs<RecordType>()) &&
457 !AllocType->isAggregateType()) {
Douglas Gregor39da0b82009-09-09 23:08:42 +0000458 ASTOwningVector<&ActionBase::DeleteExpr> ConvertedConstructorArgs(*this);
459
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000460 Constructor = PerformInitializationByConstructor(
Douglas Gregor39da0b82009-09-09 23:08:42 +0000461 AllocType, move(ConstructorArgs),
Douglas Gregor3433cf72009-05-21 00:00:09 +0000462 TypeLoc,
463 SourceRange(TypeLoc, ConstructorRParen),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000464 RT->getDecl()->getDeclName(),
Douglas Gregor39da0b82009-09-09 23:08:42 +0000465 NumConsArgs != 0 ? IK_Direct : IK_Default,
466 ConvertedConstructorArgs);
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000467 if (!Constructor)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000468 return ExprError();
Douglas Gregor39da0b82009-09-09 23:08:42 +0000469
470 // Take the converted constructor arguments and use them for the new
471 // expression.
472 NumConsArgs = ConvertedConstructorArgs.size();
473 ConsArgs = (Expr **)ConvertedConstructorArgs.take();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000474 } else {
475 if (!Init) {
476 // FIXME: Check that no subpart is const.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000477 if (AllocType.isConstQualified())
478 return ExprError(Diag(StartLoc, diag::err_new_uninitialized_const)
Douglas Gregor3433cf72009-05-21 00:00:09 +0000479 << TypeRange);
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000480 } else if (NumConsArgs == 0) {
481 // Object is value-initialized. Do nothing.
482 } else if (NumConsArgs == 1) {
483 // Object is direct-initialized.
Sebastian Redl4f149632009-05-07 16:14:23 +0000484 // FIXME: What DeclarationName do we pass in here?
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000485 if (CheckInitializerTypes(ConsArgs[0], AllocType, StartLoc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000486 DeclarationName() /*AllocType.getAsString()*/,
487 /*DirectInit=*/true))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000488 return ExprError();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000489 } else {
Sebastian Redlf53597f2009-03-15 17:47:39 +0000490 return ExprError(Diag(StartLoc,
491 diag::err_builtin_direct_init_more_than_one_arg)
492 << SourceRange(ConstructorLParen, ConstructorRParen));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000493 }
494 }
495
496 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
Douglas Gregor089407b2009-10-17 21:40:42 +0000497
Sebastian Redlf53597f2009-03-15 17:47:39 +0000498 PlacementArgs.release();
499 ConstructorArgs.release();
Douglas Gregor3433cf72009-05-21 00:00:09 +0000500 ArraySizeE.release();
Sebastian Redlf53597f2009-03-15 17:47:39 +0000501 return Owned(new (Context) CXXNewExpr(UseGlobal, OperatorNew, PlaceArgs,
Ted Kremenek8189cde2009-02-07 01:47:29 +0000502 NumPlaceArgs, ParenTypeId, ArraySize, Constructor, Init,
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000503 ConsArgs, NumConsArgs, OperatorDelete, ResultType,
Mike Stump1eb44332009-09-09 15:08:12 +0000504 StartLoc, Init ? ConstructorRParen : SourceLocation()));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000505}
506
507/// CheckAllocatedType - Checks that a type is suitable as the allocated type
508/// in a new-expression.
509/// dimension off and stores the size expression in ArraySize.
Douglas Gregor3433cf72009-05-21 00:00:09 +0000510bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +0000511 SourceRange R) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000512 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
513 // abstract class type or array thereof.
Douglas Gregore7450f52009-03-24 19:52:54 +0000514 if (AllocType->isFunctionType())
Douglas Gregor3433cf72009-05-21 00:00:09 +0000515 return Diag(Loc, diag::err_bad_new_type)
516 << AllocType << 0 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +0000517 else if (AllocType->isReferenceType())
Douglas Gregor3433cf72009-05-21 00:00:09 +0000518 return Diag(Loc, diag::err_bad_new_type)
519 << AllocType << 1 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +0000520 else if (!AllocType->isDependentType() &&
Douglas Gregor3433cf72009-05-21 00:00:09 +0000521 RequireCompleteType(Loc, AllocType,
Anders Carlssonb7906612009-08-26 23:45:07 +0000522 PDiag(diag::err_new_incomplete_type)
523 << R))
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000524 return true;
Douglas Gregor3433cf72009-05-21 00:00:09 +0000525 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregore7450f52009-03-24 19:52:54 +0000526 diag::err_allocation_of_abstract_type))
527 return true;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000528
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000529 return false;
530}
531
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000532/// FindAllocationFunctions - Finds the overloads of operator new and delete
533/// that are appropriate for the allocation.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000534bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
535 bool UseGlobal, QualType AllocType,
536 bool IsArray, Expr **PlaceArgs,
537 unsigned NumPlaceArgs,
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000538 FunctionDecl *&OperatorNew,
Mike Stump1eb44332009-09-09 15:08:12 +0000539 FunctionDecl *&OperatorDelete) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000540 // --- Choosing an allocation function ---
541 // C++ 5.3.4p8 - 14 & 18
542 // 1) If UseGlobal is true, only look in the global scope. Else, also look
543 // in the scope of the allocated class.
544 // 2) If an array size is given, look for operator new[], else look for
545 // operator new.
546 // 3) The first argument is always size_t. Append the arguments from the
547 // placement form.
548 // FIXME: Also find the appropriate delete operator.
549
550 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
551 // We don't care about the actual value of this argument.
552 // FIXME: Should the Sema create the expression and embed it in the syntax
553 // tree? Or should the consumer just recalculate the value?
Anders Carlssond67c4c32009-08-16 20:29:29 +0000554 IntegerLiteral Size(llvm::APInt::getNullValue(
555 Context.Target.getPointerWidth(0)),
556 Context.getSizeType(),
557 SourceLocation());
558 AllocArgs[0] = &Size;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000559 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
560
561 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
562 IsArray ? OO_Array_New : OO_New);
563 if (AllocType->isRecordType() && !UseGlobal) {
Mike Stump1eb44332009-09-09 15:08:12 +0000564 CXXRecordDecl *Record
Ted Kremenek6217b802009-07-29 21:53:49 +0000565 = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl());
Sebastian Redl7f662392008-12-04 22:20:51 +0000566 // FIXME: We fail to find inherited overloads.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000567 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000568 AllocArgs.size(), Record, /*AllowMissing=*/true,
569 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000570 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000571 }
572 if (!OperatorNew) {
573 // Didn't find a member overload. Look for a global one.
574 DeclareGlobalNewDelete();
Sebastian Redl7f662392008-12-04 22:20:51 +0000575 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl00e68e22009-02-09 18:24:27 +0000576 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000577 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
578 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000579 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000580 }
581
Anders Carlssond9583892009-05-31 20:26:12 +0000582 // FindAllocationOverload can change the passed in arguments, so we need to
583 // copy them back.
584 if (NumPlaceArgs > 0)
585 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
Mike Stump1eb44332009-09-09 15:08:12 +0000586
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000587 return false;
588}
589
Sebastian Redl7f662392008-12-04 22:20:51 +0000590/// FindAllocationOverload - Find an fitting overload for the allocation
591/// function in the specified scope.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000592bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
593 DeclarationName Name, Expr** Args,
594 unsigned NumArgs, DeclContext *Ctx,
Mike Stump1eb44332009-09-09 15:08:12 +0000595 bool AllowMissing, FunctionDecl *&Operator) {
John McCallf36e02d2009-10-09 21:13:30 +0000596 LookupResult R;
597 LookupQualifiedName(R, Ctx, Name, LookupOrdinaryName);
598 if (R.empty()) {
Sebastian Redl7f662392008-12-04 22:20:51 +0000599 if (AllowMissing)
600 return false;
Sebastian Redl7f662392008-12-04 22:20:51 +0000601 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +0000602 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +0000603 }
604
John McCallf36e02d2009-10-09 21:13:30 +0000605 // FIXME: handle ambiguity
606
Sebastian Redl7f662392008-12-04 22:20:51 +0000607 OverloadCandidateSet Candidates;
Douglas Gregor5d64e5b2009-09-30 00:03:47 +0000608 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
609 Alloc != AllocEnd; ++Alloc) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000610 // Even member operator new/delete are implicitly treated as
611 // static, so don't use AddMemberCandidate.
Douglas Gregor90916562009-09-29 18:16:17 +0000612 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>(*Alloc)) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000613 AddOverloadCandidate(Fn, Args, NumArgs, Candidates,
614 /*SuppressUserConversions=*/false);
Douglas Gregor90916562009-09-29 18:16:17 +0000615 continue;
616 }
617
618 // FIXME: Handle function templates
Sebastian Redl7f662392008-12-04 22:20:51 +0000619 }
620
621 // Do the resolution.
622 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +0000623 switch(BestViableFunction(Candidates, StartLoc, Best)) {
Sebastian Redl7f662392008-12-04 22:20:51 +0000624 case OR_Success: {
625 // Got one!
626 FunctionDecl *FnDecl = Best->Function;
627 // The first argument is size_t, and the first parameter must be size_t,
628 // too. This is checked on declaration and can be assumed. (It can't be
629 // asserted on, though, since invalid decls are left in there.)
Douglas Gregor90916562009-09-29 18:16:17 +0000630 for (unsigned i = 0; i < NumArgs; ++i) {
Sebastian Redl7f662392008-12-04 22:20:51 +0000631 // FIXME: Passing word to diagnostic.
Anders Carlssonfc27d262009-05-31 19:49:47 +0000632 if (PerformCopyInitialization(Args[i],
Sebastian Redl7f662392008-12-04 22:20:51 +0000633 FnDecl->getParamDecl(i)->getType(),
634 "passing"))
635 return true;
636 }
637 Operator = FnDecl;
638 return false;
639 }
640
641 case OR_No_Viable_Function:
Sebastian Redl7f662392008-12-04 22:20:51 +0000642 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +0000643 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +0000644 PrintOverloadCandidates(Candidates, /*OnlyViable=*/false);
645 return true;
646
647 case OR_Ambiguous:
Sebastian Redl7f662392008-12-04 22:20:51 +0000648 Diag(StartLoc, diag::err_ovl_ambiguous_call)
Sebastian Redl00e68e22009-02-09 18:24:27 +0000649 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +0000650 PrintOverloadCandidates(Candidates, /*OnlyViable=*/true);
651 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000652
653 case OR_Deleted:
654 Diag(StartLoc, diag::err_ovl_deleted_call)
655 << Best->Function->isDeleted()
656 << Name << Range;
657 PrintOverloadCandidates(Candidates, /*OnlyViable=*/true);
658 return true;
Sebastian Redl7f662392008-12-04 22:20:51 +0000659 }
660 assert(false && "Unreachable, bad result from BestViableFunction");
661 return true;
662}
663
664
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000665/// DeclareGlobalNewDelete - Declare the global forms of operator new and
666/// delete. These are:
667/// @code
668/// void* operator new(std::size_t) throw(std::bad_alloc);
669/// void* operator new[](std::size_t) throw(std::bad_alloc);
670/// void operator delete(void *) throw();
671/// void operator delete[](void *) throw();
672/// @endcode
673/// Note that the placement and nothrow forms of new are *not* implicitly
674/// declared. Their use requires including \<new\>.
Mike Stump1eb44332009-09-09 15:08:12 +0000675void Sema::DeclareGlobalNewDelete() {
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000676 if (GlobalNewDeleteDeclared)
677 return;
Douglas Gregor7adb10f2009-09-15 22:30:29 +0000678
679 // C++ [basic.std.dynamic]p2:
680 // [...] The following allocation and deallocation functions (18.4) are
681 // implicitly declared in global scope in each translation unit of a
682 // program
683 //
684 // void* operator new(std::size_t) throw(std::bad_alloc);
685 // void* operator new[](std::size_t) throw(std::bad_alloc);
686 // void operator delete(void*) throw();
687 // void operator delete[](void*) throw();
688 //
689 // These implicit declarations introduce only the function names operator
690 // new, operator new[], operator delete, operator delete[].
691 //
692 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
693 // "std" or "bad_alloc" as necessary to form the exception specification.
694 // However, we do not make these implicit declarations visible to name
695 // lookup.
696 if (!StdNamespace) {
697 // The "std" namespace has not yet been defined, so build one implicitly.
698 StdNamespace = NamespaceDecl::Create(Context,
699 Context.getTranslationUnitDecl(),
700 SourceLocation(),
701 &PP.getIdentifierTable().get("std"));
702 StdNamespace->setImplicit(true);
703 }
704
705 if (!StdBadAlloc) {
706 // The "std::bad_alloc" class has not yet been declared, so build it
707 // implicitly.
708 StdBadAlloc = CXXRecordDecl::Create(Context, TagDecl::TK_class,
709 StdNamespace,
710 SourceLocation(),
711 &PP.getIdentifierTable().get("bad_alloc"),
712 SourceLocation(), 0);
713 StdBadAlloc->setImplicit(true);
714 }
715
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000716 GlobalNewDeleteDeclared = true;
717
718 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
719 QualType SizeT = Context.getSizeType();
720
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000721 DeclareGlobalAllocationFunction(
722 Context.DeclarationNames.getCXXOperatorName(OO_New),
723 VoidPtr, SizeT);
724 DeclareGlobalAllocationFunction(
725 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
726 VoidPtr, SizeT);
727 DeclareGlobalAllocationFunction(
728 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
729 Context.VoidTy, VoidPtr);
730 DeclareGlobalAllocationFunction(
731 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
732 Context.VoidTy, VoidPtr);
733}
734
735/// DeclareGlobalAllocationFunction - Declares a single implicit global
736/// allocation function if it doesn't already exist.
737void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Mike Stump1eb44332009-09-09 15:08:12 +0000738 QualType Return, QualType Argument) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000739 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
740
741 // Check if this function is already declared.
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000742 {
Douglas Gregor5cc37092008-12-23 22:05:29 +0000743 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000744 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000745 Alloc != AllocEnd; ++Alloc) {
746 // FIXME: Do we need to check for default arguments here?
747 FunctionDecl *Func = cast<FunctionDecl>(*Alloc);
748 if (Func->getNumParams() == 1 &&
Ted Kremenek8189cde2009-02-07 01:47:29 +0000749 Context.getCanonicalType(Func->getParamDecl(0)->getType())==Argument)
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000750 return;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000751 }
752 }
753
Douglas Gregor7adb10f2009-09-15 22:30:29 +0000754 QualType BadAllocType;
755 bool HasBadAllocExceptionSpec
756 = (Name.getCXXOverloadedOperator() == OO_New ||
757 Name.getCXXOverloadedOperator() == OO_Array_New);
758 if (HasBadAllocExceptionSpec) {
759 assert(StdBadAlloc && "Must have std::bad_alloc declared");
760 BadAllocType = Context.getTypeDeclType(StdBadAlloc);
761 }
762
763 QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0,
764 true, false,
765 HasBadAllocExceptionSpec? 1 : 0,
766 &BadAllocType);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000767 FunctionDecl *Alloc =
768 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +0000769 FnType, /*DInfo=*/0, FunctionDecl::None, false, true);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000770 Alloc->setImplicit();
771 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000772 0, Argument, /*DInfo=*/0,
773 VarDecl::None, 0);
Ted Kremenekfc767612009-01-14 00:42:25 +0000774 Alloc->setParams(Context, &Param, 1);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000775
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000776 // FIXME: Also add this declaration to the IdentifierResolver, but
777 // make sure it is at the end of the chain to coincide with the
778 // global scope.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000779 ((DeclContext *)TUScope->getEntity())->addDecl(Alloc);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000780}
781
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000782/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
783/// @code ::delete ptr; @endcode
784/// or
785/// @code delete [] ptr; @endcode
Sebastian Redlf53597f2009-03-15 17:47:39 +0000786Action::OwningExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000787Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
Mike Stump1eb44332009-09-09 15:08:12 +0000788 bool ArrayForm, ExprArg Operand) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000789 // C++ [expr.delete]p1:
790 // The operand shall have a pointer type, or a class type having a single
791 // conversion function to a pointer type. The result has type void.
792 //
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000793 // DR599 amends "pointer type" to "pointer to object type" in both cases.
794
Anders Carlssond67c4c32009-08-16 20:29:29 +0000795 FunctionDecl *OperatorDelete = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000796
Sebastian Redlf53597f2009-03-15 17:47:39 +0000797 Expr *Ex = (Expr *)Operand.get();
Sebastian Redl28507842009-02-26 14:39:58 +0000798 if (!Ex->isTypeDependent()) {
799 QualType Type = Ex->getType();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000800
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000801 if (const RecordType *Record = Type->getAs<RecordType>()) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000802 llvm::SmallVector<CXXConversionDecl *, 4> ObjectPtrConversions;
Fariborz Jahanian53462782009-09-11 21:44:33 +0000803 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
804 OverloadedFunctionDecl *Conversions =
Fariborz Jahanian62509212009-09-12 18:26:03 +0000805 RD->getVisibleConversionFunctions();
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000806
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000807 for (OverloadedFunctionDecl::function_iterator
808 Func = Conversions->function_begin(),
809 FuncEnd = Conversions->function_end();
810 Func != FuncEnd; ++Func) {
811 // Skip over templated conversion functions; they aren't considered.
812 if (isa<FunctionTemplateDecl>(*Func))
813 continue;
814
815 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
816
817 QualType ConvType = Conv->getConversionType().getNonReferenceType();
818 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
819 if (ConvPtrType->getPointeeType()->isObjectType())
Fariborz Jahanian8b915e72009-09-15 22:15:23 +0000820 ObjectPtrConversions.push_back(Conv);
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000821 }
Fariborz Jahanian8b915e72009-09-15 22:15:23 +0000822 if (ObjectPtrConversions.size() == 1) {
823 // We have a single conversion to a pointer-to-object type. Perform
824 // that conversion.
825 Operand.release();
826 if (!PerformImplicitConversion(Ex,
827 ObjectPtrConversions.front()->getConversionType(),
828 "converting")) {
829 Operand = Owned(Ex);
830 Type = Ex->getType();
831 }
832 }
833 else if (ObjectPtrConversions.size() > 1) {
834 Diag(StartLoc, diag::err_ambiguous_delete_operand)
835 << Type << Ex->getSourceRange();
836 for (unsigned i= 0; i < ObjectPtrConversions.size(); i++) {
837 CXXConversionDecl *Conv = ObjectPtrConversions[i];
838 Diag(Conv->getLocation(), diag::err_ovl_candidate);
839 }
840 return ExprError();
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000841 }
Sebastian Redl28507842009-02-26 14:39:58 +0000842 }
843
Sebastian Redlf53597f2009-03-15 17:47:39 +0000844 if (!Type->isPointerType())
845 return ExprError(Diag(StartLoc, diag::err_delete_operand)
846 << Type << Ex->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +0000847
Ted Kremenek6217b802009-07-29 21:53:49 +0000848 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Douglas Gregor8dcb29d2009-03-24 20:13:58 +0000849 if (Pointee->isFunctionType() || Pointee->isVoidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000850 return ExprError(Diag(StartLoc, diag::err_delete_operand)
851 << Type << Ex->getSourceRange());
Douglas Gregor8dcb29d2009-03-24 20:13:58 +0000852 else if (!Pointee->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +0000853 RequireCompleteType(StartLoc, Pointee,
Anders Carlssonb7906612009-08-26 23:45:07 +0000854 PDiag(diag::warn_delete_incomplete)
855 << Ex->getSourceRange()))
Douglas Gregor8dcb29d2009-03-24 20:13:58 +0000856 return ExprError();
Sebastian Redl28507842009-02-26 14:39:58 +0000857
Douglas Gregor1070c9f2009-09-29 21:38:53 +0000858 // C++ [expr.delete]p2:
859 // [Note: a pointer to a const type can be the operand of a
860 // delete-expression; it is not necessary to cast away the constness
861 // (5.2.11) of the pointer expression before it is used as the operand
862 // of the delete-expression. ]
863 ImpCastExprToType(Ex, Context.getPointerType(Context.VoidTy),
864 CastExpr::CK_NoOp);
865
866 // Update the operand.
867 Operand.take();
868 Operand = ExprArg(*this, Ex);
869
Anders Carlssond67c4c32009-08-16 20:29:29 +0000870 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
871 ArrayForm ? OO_Array_Delete : OO_Delete);
872
873 if (Pointee->isRecordType() && !UseGlobal) {
Mike Stump1eb44332009-09-09 15:08:12 +0000874 CXXRecordDecl *Record
Anders Carlssond67c4c32009-08-16 20:29:29 +0000875 = cast<CXXRecordDecl>(Pointee->getAs<RecordType>()->getDecl());
Douglas Gregor90916562009-09-29 18:16:17 +0000876
877 // Try to find operator delete/operator delete[] in class scope.
John McCallf36e02d2009-10-09 21:13:30 +0000878 LookupResult Found;
879 LookupQualifiedName(Found, Record, DeleteName, LookupOrdinaryName);
Douglas Gregor90916562009-09-29 18:16:17 +0000880 // FIXME: Diagnose ambiguity properly
881 assert(!Found.isAmbiguous() && "Ambiguous delete/delete[] not handled");
882 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
883 F != FEnd; ++F) {
884 if (CXXMethodDecl *Delete = dyn_cast<CXXMethodDecl>(*F))
885 if (Delete->isUsualDeallocationFunction()) {
886 OperatorDelete = Delete;
887 break;
888 }
889 }
890
Fariborz Jahanian34374e62009-09-03 23:18:17 +0000891 if (!Record->hasTrivialDestructor())
892 if (const CXXDestructorDecl *Dtor = Record->getDestructor(Context))
Mike Stump1eb44332009-09-09 15:08:12 +0000893 MarkDeclarationReferenced(StartLoc,
Fariborz Jahanian34374e62009-09-03 23:18:17 +0000894 const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssond67c4c32009-08-16 20:29:29 +0000895 }
Mike Stump1eb44332009-09-09 15:08:12 +0000896
Anders Carlssond67c4c32009-08-16 20:29:29 +0000897 if (!OperatorDelete) {
898 // Didn't find a member overload. Look for a global one.
899 DeclareGlobalNewDelete();
900 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000901 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
Douglas Gregor90916562009-09-29 18:16:17 +0000902 &Ex, 1, TUDecl, /*AllowMissing=*/false,
Anders Carlssond67c4c32009-08-16 20:29:29 +0000903 OperatorDelete))
904 return ExprError();
905 }
Mike Stump1eb44332009-09-09 15:08:12 +0000906
Sebastian Redl28507842009-02-26 14:39:58 +0000907 // FIXME: Check access and ambiguity of operator delete and destructor.
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000908 }
909
Sebastian Redlf53597f2009-03-15 17:47:39 +0000910 Operand.release();
911 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
Anders Carlssond67c4c32009-08-16 20:29:29 +0000912 OperatorDelete, Ex, StartLoc));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000913}
914
915
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000916/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
917/// C++ if/switch/while/for statement.
918/// e.g: "if (int x = f()) {...}"
Sebastian Redlf53597f2009-03-15 17:47:39 +0000919Action::OwningExprResult
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000920Sema::ActOnCXXConditionDeclarationExpr(Scope *S, SourceLocation StartLoc,
921 Declarator &D,
922 SourceLocation EqualLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000923 ExprArg AssignExprVal) {
924 assert(AssignExprVal.get() && "Null assignment expression");
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000925
926 // C++ 6.4p2:
927 // The declarator shall not specify a function or an array.
928 // The type-specifier-seq shall not contain typedef and shall not declare a
929 // new class or enumeration.
930
931 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
932 "Parser allowed 'typedef' as storage class of condition decl.");
933
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000934 // FIXME: Store DeclaratorInfo in the expression.
935 DeclaratorInfo *DInfo = 0;
Argyrios Kyrtzidise955e722009-08-11 05:20:41 +0000936 TagDecl *OwnedTag = 0;
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000937 QualType Ty = GetTypeForDeclarator(D, S, &DInfo, /*Skip=*/0, &OwnedTag);
Mike Stump1eb44332009-09-09 15:08:12 +0000938
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000939 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
940 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
941 // would be created and CXXConditionDeclExpr wants a VarDecl.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000942 return ExprError(Diag(StartLoc, diag::err_invalid_use_of_function_type)
943 << SourceRange(StartLoc, EqualLoc));
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000944 } else if (Ty->isArrayType()) { // ...or an array.
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000945 Diag(StartLoc, diag::err_invalid_use_of_array_type)
946 << SourceRange(StartLoc, EqualLoc);
Argyrios Kyrtzidise955e722009-08-11 05:20:41 +0000947 } else if (OwnedTag && OwnedTag->isDefinition()) {
948 // The type-specifier-seq shall not declare a new class or enumeration.
949 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000950 }
951
Douglas Gregor2e01cda2009-06-23 21:43:56 +0000952 DeclPtrTy Dcl = ActOnDeclarator(S, D);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000953 if (!Dcl)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000954 return ExprError();
Anders Carlssonf5dcd382009-05-30 21:37:25 +0000955 AddInitializerToDecl(Dcl, move(AssignExprVal), /*DirectInit=*/false);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000956
Douglas Gregorcaaf29a2008-12-10 23:01:14 +0000957 // Mark this variable as one that is declared within a conditional.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000958 // We know that the decl had to be a VarDecl because that is the only type of
959 // decl that can be assigned and the grammar requires an '='.
960 VarDecl *VD = cast<VarDecl>(Dcl.getAs<Decl>());
961 VD->setDeclaredInCondition(true);
962 return Owned(new (Context) CXXConditionDeclExpr(StartLoc, EqualLoc, VD));
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000963}
964
965/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
966bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
967 // C++ 6.4p4:
968 // The value of a condition that is an initialized declaration in a statement
969 // other than a switch statement is the value of the declared variable
970 // implicitly converted to type bool. If that conversion is ill-formed, the
971 // program is ill-formed.
972 // The value of a condition that is an expression is the value of the
973 // expression, implicitly converted to bool.
974 //
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000975 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000976}
Douglas Gregor77a52232008-09-12 00:47:35 +0000977
978/// Helper function to determine whether this is the (deprecated) C++
979/// conversion from a string literal to a pointer to non-const char or
980/// non-const wchar_t (for narrow and wide string literals,
981/// respectively).
Mike Stump1eb44332009-09-09 15:08:12 +0000982bool
Douglas Gregor77a52232008-09-12 00:47:35 +0000983Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
984 // Look inside the implicit cast, if it exists.
985 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
986 From = Cast->getSubExpr();
987
988 // A string literal (2.13.4) that is not a wide string literal can
989 // be converted to an rvalue of type "pointer to char"; a wide
990 // string literal can be converted to an rvalue of type "pointer
991 // to wchar_t" (C++ 4.2p2).
992 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From))
Ted Kremenek6217b802009-07-29 21:53:49 +0000993 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump1eb44332009-09-09 15:08:12 +0000994 if (const BuiltinType *ToPointeeType
John McCall183700f2009-09-21 23:43:11 +0000995 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregor77a52232008-09-12 00:47:35 +0000996 // This conversion is considered only when there is an
997 // explicit appropriate pointer target type (C++ 4.2p2).
John McCall0953e762009-09-24 19:53:00 +0000998 if (!ToPtrType->getPointeeType().hasQualifiers() &&
Douglas Gregor77a52232008-09-12 00:47:35 +0000999 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
1000 (!StrLit->isWide() &&
1001 (ToPointeeType->getKind() == BuiltinType::Char_U ||
1002 ToPointeeType->getKind() == BuiltinType::Char_S))))
1003 return true;
1004 }
1005
1006 return false;
1007}
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001008
1009/// PerformImplicitConversion - Perform an implicit conversion of the
1010/// expression From to the type ToType. Returns true if there was an
1011/// error, false otherwise. The expression From is replaced with the
Douglas Gregor45920e82008-12-19 17:40:08 +00001012/// converted expression. Flavor is the kind of conversion we're
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001013/// performing, used in the error message. If @p AllowExplicit,
Sebastian Redle2b68332009-04-12 17:16:29 +00001014/// explicit user-defined conversions are permitted. @p Elidable should be true
1015/// when called for copies which may be elided (C++ 12.8p15). C++0x overload
1016/// resolution works differently in that case.
1017bool
Douglas Gregor45920e82008-12-19 17:40:08 +00001018Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Sebastian Redle2b68332009-04-12 17:16:29 +00001019 const char *Flavor, bool AllowExplicit,
Mike Stump1eb44332009-09-09 15:08:12 +00001020 bool Elidable) {
Sebastian Redle2b68332009-04-12 17:16:29 +00001021 ImplicitConversionSequence ICS;
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00001022 return PerformImplicitConversion(From, ToType, Flavor, AllowExplicit,
1023 Elidable, ICS);
1024}
1025
1026bool
1027Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
1028 const char *Flavor, bool AllowExplicit,
1029 bool Elidable,
1030 ImplicitConversionSequence& ICS) {
Sebastian Redle2b68332009-04-12 17:16:29 +00001031 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1032 if (Elidable && getLangOptions().CPlusPlus0x) {
Mike Stump1eb44332009-09-09 15:08:12 +00001033 ICS = TryImplicitConversion(From, ToType,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001034 /*SuppressUserConversions=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +00001035 AllowExplicit,
Anders Carlsson08972922009-08-28 15:33:32 +00001036 /*ForceRValue=*/true,
1037 /*InOverloadResolution=*/false);
Sebastian Redle2b68332009-04-12 17:16:29 +00001038 }
1039 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion) {
Mike Stump1eb44332009-09-09 15:08:12 +00001040 ICS = TryImplicitConversion(From, ToType,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001041 /*SuppressUserConversions=*/false,
1042 AllowExplicit,
Anders Carlsson08972922009-08-28 15:33:32 +00001043 /*ForceRValue=*/false,
1044 /*InOverloadResolution=*/false);
Sebastian Redle2b68332009-04-12 17:16:29 +00001045 }
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001046 return PerformImplicitConversion(From, ToType, ICS, Flavor);
1047}
1048
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001049/// BuildCXXDerivedToBaseExpr - This routine generates the suitable AST
1050/// for the derived to base conversion of the expression 'From'. All
1051/// necessary information is passed in ICS.
1052bool
1053Sema::BuildCXXDerivedToBaseExpr(Expr *&From, CastExpr::CastKind CastKind,
1054 const ImplicitConversionSequence& ICS,
1055 const char *Flavor) {
1056 QualType BaseType =
1057 QualType::getFromOpaquePtr(ICS.UserDefined.After.ToTypePtr);
1058 // Must do additional defined to base conversion.
1059 QualType DerivedType =
1060 QualType::getFromOpaquePtr(ICS.UserDefined.After.FromTypePtr);
1061
1062 From = new (Context) ImplicitCastExpr(
1063 DerivedType.getNonReferenceType(),
1064 CastKind,
1065 From,
1066 DerivedType->isLValueReferenceType());
1067 From = new (Context) ImplicitCastExpr(BaseType.getNonReferenceType(),
1068 CastExpr::CK_DerivedToBase, From,
1069 BaseType->isLValueReferenceType());
1070 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1071 OwningExprResult FromResult =
1072 BuildCXXConstructExpr(
1073 ICS.UserDefined.After.CopyConstructor->getLocation(),
1074 BaseType,
1075 ICS.UserDefined.After.CopyConstructor,
1076 MultiExprArg(*this, (void **)&From, 1));
1077 if (FromResult.isInvalid())
1078 return true;
1079 From = FromResult.takeAs<Expr>();
1080 return false;
1081}
1082
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001083/// PerformImplicitConversion - Perform an implicit conversion of the
1084/// expression From to the type ToType using the pre-computed implicit
1085/// conversion sequence ICS. Returns true if there was an error, false
1086/// otherwise. The expression From is replaced with the converted
1087/// expression. Flavor is the kind of conversion we're performing,
1088/// used in the error message.
1089bool
1090Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
1091 const ImplicitConversionSequence &ICS,
1092 const char* Flavor) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001093 switch (ICS.ConversionKind) {
1094 case ImplicitConversionSequence::StandardConversion:
Douglas Gregor45920e82008-12-19 17:40:08 +00001095 if (PerformImplicitConversion(From, ToType, ICS.Standard, Flavor))
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001096 return true;
1097 break;
1098
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001099 case ImplicitConversionSequence::UserDefinedConversion: {
1100
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00001101 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
1102 CastExpr::CastKind CastKind = CastExpr::CK_Unknown;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001103 QualType BeforeToType;
1104 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00001105 CastKind = CastExpr::CK_UserDefinedConversion;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001106
1107 // If the user-defined conversion is specified by a conversion function,
1108 // the initial standard conversion sequence converts the source type to
1109 // the implicit object parameter of the conversion function.
1110 BeforeToType = Context.getTagDeclType(Conv->getParent());
1111 } else if (const CXXConstructorDecl *Ctor =
1112 dyn_cast<CXXConstructorDecl>(FD)) {
Anders Carlsson0aebc812009-09-09 21:33:21 +00001113 CastKind = CastExpr::CK_ConstructorConversion;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001114
1115 // If the user-defined conversion is specified by a constructor, the
1116 // initial standard conversion sequence converts the source type to the
1117 // type required by the argument of the constructor
1118 BeforeToType = Ctor->getParamDecl(0)->getType();
1119 }
Anders Carlsson0aebc812009-09-09 21:33:21 +00001120 else
1121 assert(0 && "Unknown conversion function kind!");
1122
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001123 if (PerformImplicitConversion(From, BeforeToType,
1124 ICS.UserDefined.Before, "converting"))
1125 return true;
1126
Anders Carlsson0aebc812009-09-09 21:33:21 +00001127 OwningExprResult CastArg
1128 = BuildCXXCastArgument(From->getLocStart(),
1129 ToType.getNonReferenceType(),
1130 CastKind, cast<CXXMethodDecl>(FD),
1131 Owned(From));
1132
1133 if (CastArg.isInvalid())
1134 return true;
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001135
1136 if (ICS.UserDefined.After.Second == ICK_Derived_To_Base &&
1137 ICS.UserDefined.After.CopyConstructor) {
1138 From = CastArg.takeAs<Expr>();
1139 return BuildCXXDerivedToBaseExpr(From, CastKind, ICS, Flavor);
1140 }
Anders Carlsson0aebc812009-09-09 21:33:21 +00001141
Anders Carlsson626c2d62009-09-15 05:49:31 +00001142 From = new (Context) ImplicitCastExpr(ToType.getNonReferenceType(),
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001143 CastKind, CastArg.takeAs<Expr>(),
Anders Carlsson626c2d62009-09-15 05:49:31 +00001144 ToType->isLValueReferenceType());
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00001145 return false;
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001146 }
1147
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001148 case ImplicitConversionSequence::EllipsisConversion:
1149 assert(false && "Cannot perform an ellipsis conversion");
Douglas Gregor60d62c22008-10-31 16:23:19 +00001150 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001151
1152 case ImplicitConversionSequence::BadConversion:
1153 return true;
1154 }
1155
1156 // Everything went well.
1157 return false;
1158}
1159
1160/// PerformImplicitConversion - Perform an implicit conversion of the
1161/// expression From to the type ToType by following the standard
1162/// conversion sequence SCS. Returns true if there was an error, false
1163/// otherwise. The expression From is replaced with the converted
Douglas Gregor45920e82008-12-19 17:40:08 +00001164/// expression. Flavor is the context in which we're performing this
1165/// conversion, for use in error messages.
Mike Stump1eb44332009-09-09 15:08:12 +00001166bool
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001167Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor45920e82008-12-19 17:40:08 +00001168 const StandardConversionSequence& SCS,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001169 const char *Flavor) {
Mike Stump390b4cc2009-05-16 07:39:55 +00001170 // Overall FIXME: we are recomputing too many types here and doing far too
1171 // much extra work. What this means is that we need to keep track of more
1172 // information that is computed when we try the implicit conversion initially,
1173 // so that we don't need to recompute anything here.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001174 QualType FromType = From->getType();
1175
Douglas Gregor225c41e2008-11-03 19:09:14 +00001176 if (SCS.CopyConstructor) {
Anders Carlsson7c3e8a12009-05-19 04:45:15 +00001177 // FIXME: When can ToType be a reference type?
1178 assert(!ToType->isReferenceType());
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00001179 if (SCS.Second == ICK_Derived_To_Base) {
1180 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1181 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
1182 MultiExprArg(*this, (void **)&From, 1),
1183 /*FIXME:ConstructLoc*/SourceLocation(),
1184 ConstructorArgs))
1185 return true;
1186 OwningExprResult FromResult =
1187 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1188 ToType, SCS.CopyConstructor,
1189 move_arg(ConstructorArgs));
1190 if (FromResult.isInvalid())
1191 return true;
1192 From = FromResult.takeAs<Expr>();
1193 return false;
1194 }
Mike Stump1eb44332009-09-09 15:08:12 +00001195 OwningExprResult FromResult =
1196 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1197 ToType, SCS.CopyConstructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00001198 MultiExprArg(*this, (void**)&From, 1));
Mike Stump1eb44332009-09-09 15:08:12 +00001199
Anders Carlssonda3f4e22009-08-25 05:12:04 +00001200 if (FromResult.isInvalid())
1201 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001202
Anders Carlssonda3f4e22009-08-25 05:12:04 +00001203 From = FromResult.takeAs<Expr>();
Douglas Gregor225c41e2008-11-03 19:09:14 +00001204 return false;
1205 }
1206
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001207 // Perform the first implicit conversion.
1208 switch (SCS.First) {
1209 case ICK_Identity:
1210 case ICK_Lvalue_To_Rvalue:
1211 // Nothing to do.
1212 break;
1213
1214 case ICK_Array_To_Pointer:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001215 FromType = Context.getArrayDecayedType(FromType);
Anders Carlsson82495762009-08-08 21:04:35 +00001216 ImpCastExprToType(From, FromType, CastExpr::CK_ArrayToPointerDecay);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001217 break;
1218
1219 case ICK_Function_To_Pointer:
Douglas Gregor063daf62009-03-13 18:40:31 +00001220 if (Context.getCanonicalType(FromType) == Context.OverloadTy) {
Douglas Gregor904eed32008-11-10 20:40:00 +00001221 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, true);
1222 if (!Fn)
1223 return true;
1224
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001225 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
1226 return true;
1227
Sebastian Redl759986e2009-10-17 20:50:27 +00001228 bool WasAddrOf = FixOverloadedFunctionReference(From, Fn);
Douglas Gregor904eed32008-11-10 20:40:00 +00001229 FromType = From->getType();
Sebastian Redl759986e2009-10-17 20:50:27 +00001230 // If there's already an address-of operator in the expression, we have
1231 // the right type already, and the code below would just introduce an
1232 // invalid additional pointer level.
1233 if (WasAddrOf)
1234 break;
Douglas Gregor904eed32008-11-10 20:40:00 +00001235 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001236 FromType = Context.getPointerType(FromType);
Anders Carlssonb633c4e2009-09-01 20:37:18 +00001237 ImpCastExprToType(From, FromType, CastExpr::CK_FunctionToPointerDecay);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001238 break;
1239
1240 default:
1241 assert(false && "Improper first standard conversion");
1242 break;
1243 }
1244
1245 // Perform the second implicit conversion
1246 switch (SCS.Second) {
1247 case ICK_Identity:
Sebastian Redl2c7588f2009-10-10 12:04:10 +00001248 // If both sides are functions (or pointers/references to them), there could
1249 // be incompatible exception declarations.
1250 if (CheckExceptionSpecCompatibility(From, ToType))
1251 return true;
1252 // Nothing else to do.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001253 break;
1254
1255 case ICK_Integral_Promotion:
1256 case ICK_Floating_Promotion:
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001257 case ICK_Complex_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001258 case ICK_Integral_Conversion:
1259 case ICK_Floating_Conversion:
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001260 case ICK_Complex_Conversion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001261 case ICK_Floating_Integral:
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001262 case ICK_Complex_Real:
Douglas Gregorf9201e02009-02-11 23:02:49 +00001263 case ICK_Compatible_Conversion:
1264 // FIXME: Go deeper to get the unqualified type!
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001265 FromType = ToType.getUnqualifiedType();
1266 ImpCastExprToType(From, FromType);
1267 break;
1268
Anders Carlsson61faec12009-09-12 04:46:44 +00001269 case ICK_Pointer_Conversion: {
Douglas Gregor45920e82008-12-19 17:40:08 +00001270 if (SCS.IncompatibleObjC) {
1271 // Diagnose incompatible Objective-C conversions
Mike Stump1eb44332009-09-09 15:08:12 +00001272 Diag(From->getSourceRange().getBegin(),
Douglas Gregor45920e82008-12-19 17:40:08 +00001273 diag::ext_typecheck_convert_incompatible_pointer)
1274 << From->getType() << ToType << Flavor
1275 << From->getSourceRange();
1276 }
1277
Anders Carlsson61faec12009-09-12 04:46:44 +00001278
1279 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
1280 if (CheckPointerConversion(From, ToType, Kind))
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001281 return true;
Anders Carlsson61faec12009-09-12 04:46:44 +00001282 ImpCastExprToType(From, ToType, Kind);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001283 break;
Anders Carlsson61faec12009-09-12 04:46:44 +00001284 }
1285
1286 case ICK_Pointer_Member: {
1287 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
1288 if (CheckMemberPointerConversion(From, ToType, Kind))
1289 return true;
Sebastian Redl2c7588f2009-10-10 12:04:10 +00001290 if (CheckExceptionSpecCompatibility(From, ToType))
1291 return true;
Anders Carlsson61faec12009-09-12 04:46:44 +00001292 ImpCastExprToType(From, ToType, Kind);
1293 break;
1294 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001295 case ICK_Boolean_Conversion:
1296 FromType = Context.BoolTy;
1297 ImpCastExprToType(From, FromType);
1298 break;
1299
1300 default:
1301 assert(false && "Improper second standard conversion");
1302 break;
1303 }
1304
1305 switch (SCS.Third) {
1306 case ICK_Identity:
1307 // Nothing to do.
1308 break;
1309
1310 case ICK_Qualification:
Mike Stump390b4cc2009-05-16 07:39:55 +00001311 // FIXME: Not sure about lvalue vs rvalue here in the presence of rvalue
1312 // references.
Mike Stump1eb44332009-09-09 15:08:12 +00001313 ImpCastExprToType(From, ToType.getNonReferenceType(),
Anders Carlsson3503d042009-07-31 01:23:52 +00001314 CastExpr::CK_Unknown,
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001315 ToType->isLValueReferenceType());
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001316 break;
1317
1318 default:
1319 assert(false && "Improper second standard conversion");
1320 break;
1321 }
1322
1323 return false;
1324}
1325
Sebastian Redl64b45f72009-01-05 20:52:13 +00001326Sema::OwningExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
1327 SourceLocation KWLoc,
1328 SourceLocation LParen,
1329 TypeTy *Ty,
1330 SourceLocation RParen) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00001331 QualType T = GetTypeFromParser(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00001332
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001333 // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
1334 // all traits except __is_class, __is_enum and __is_union require a the type
1335 // to be complete.
1336 if (OTT != UTT_IsClass && OTT != UTT_IsEnum && OTT != UTT_IsUnion) {
Mike Stump1eb44332009-09-09 15:08:12 +00001337 if (RequireCompleteType(KWLoc, T,
Anders Carlssond497ba72009-08-26 22:59:12 +00001338 diag::err_incomplete_type_used_in_type_trait_expr))
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001339 return ExprError();
1340 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00001341
1342 // There is no point in eagerly computing the value. The traits are designed
1343 // to be used from type trait templates, so Ty will be a template parameter
1344 // 99% of the time.
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001345 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT, T,
1346 RParen, Context.BoolTy));
Sebastian Redl64b45f72009-01-05 20:52:13 +00001347}
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001348
1349QualType Sema::CheckPointerToMemberOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00001350 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001351 const char *OpSpelling = isIndirect ? "->*" : ".*";
1352 // C++ 5.5p2
1353 // The binary operator .* [p3: ->*] binds its second operand, which shall
1354 // be of type "pointer to member of T" (where T is a completely-defined
1355 // class type) [...]
1356 QualType RType = rex->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001357 const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
Douglas Gregore7450f52009-03-24 19:52:54 +00001358 if (!MemPtr) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001359 Diag(Loc, diag::err_bad_memptr_rhs)
1360 << OpSpelling << RType << rex->getSourceRange();
1361 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00001362 }
Douglas Gregore7450f52009-03-24 19:52:54 +00001363
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001364 QualType Class(MemPtr->getClass(), 0);
1365
1366 // C++ 5.5p2
1367 // [...] to its first operand, which shall be of class T or of a class of
1368 // which T is an unambiguous and accessible base class. [p3: a pointer to
1369 // such a class]
1370 QualType LType = lex->getType();
1371 if (isIndirect) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001372 if (const PointerType *Ptr = LType->getAs<PointerType>())
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001373 LType = Ptr->getPointeeType().getNonReferenceType();
1374 else {
1375 Diag(Loc, diag::err_bad_memptr_lhs)
1376 << OpSpelling << 1 << LType << lex->getSourceRange();
1377 return QualType();
1378 }
1379 }
1380
1381 if (Context.getCanonicalType(Class).getUnqualifiedType() !=
1382 Context.getCanonicalType(LType).getUnqualifiedType()) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001383 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1384 /*DetectVirtual=*/false);
Mike Stump390b4cc2009-05-16 07:39:55 +00001385 // FIXME: Would it be useful to print full ambiguity paths, or is that
1386 // overkill?
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001387 if (!IsDerivedFrom(LType, Class, Paths) ||
1388 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
1389 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
1390 << (int)isIndirect << lex->getType() << lex->getSourceRange();
1391 return QualType();
1392 }
1393 }
1394
1395 // C++ 5.5p2
1396 // The result is an object or a function of the type specified by the
1397 // second operand.
1398 // The cv qualifiers are the union of those in the pointer and the left side,
1399 // in accordance with 5.5p5 and 5.2.5.
1400 // FIXME: This returns a dereferenced member function pointer as a normal
1401 // function type. However, the only operation valid on such functions is
Mike Stump390b4cc2009-05-16 07:39:55 +00001402 // calling them. There's also a GCC extension to get a function pointer to the
1403 // thing, which is another complication, because this type - unlike the type
1404 // that is the result of this expression - takes the class as the first
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001405 // argument.
1406 // We probably need a "MemberFunctionClosureType" or something like that.
1407 QualType Result = MemPtr->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00001408 Result = Context.getCVRQualifiedType(Result, LType.getCVRQualifiers());
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001409 return Result;
1410}
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001411
1412/// \brief Get the target type of a standard or user-defined conversion.
1413static QualType TargetType(const ImplicitConversionSequence &ICS) {
1414 assert((ICS.ConversionKind ==
1415 ImplicitConversionSequence::StandardConversion ||
1416 ICS.ConversionKind ==
1417 ImplicitConversionSequence::UserDefinedConversion) &&
1418 "function only valid for standard or user-defined conversions");
1419 if (ICS.ConversionKind == ImplicitConversionSequence::StandardConversion)
1420 return QualType::getFromOpaquePtr(ICS.Standard.ToTypePtr);
1421 return QualType::getFromOpaquePtr(ICS.UserDefined.After.ToTypePtr);
1422}
1423
1424/// \brief Try to convert a type to another according to C++0x 5.16p3.
1425///
1426/// This is part of the parameter validation for the ? operator. If either
1427/// value operand is a class type, the two operands are attempted to be
1428/// converted to each other. This function does the conversion in one direction.
1429/// It emits a diagnostic and returns true only if it finds an ambiguous
1430/// conversion.
1431static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
1432 SourceLocation QuestionLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00001433 ImplicitConversionSequence &ICS) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001434 // C++0x 5.16p3
1435 // The process for determining whether an operand expression E1 of type T1
1436 // can be converted to match an operand expression E2 of type T2 is defined
1437 // as follows:
1438 // -- If E2 is an lvalue:
1439 if (To->isLvalue(Self.Context) == Expr::LV_Valid) {
1440 // E1 can be converted to match E2 if E1 can be implicitly converted to
1441 // type "lvalue reference to T2", subject to the constraint that in the
1442 // conversion the reference must bind directly to E1.
1443 if (!Self.CheckReferenceInit(From,
1444 Self.Context.getLValueReferenceType(To->getType()),
Douglas Gregor739d8282009-09-23 23:04:10 +00001445 To->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001446 /*SuppressUserConversions=*/false,
1447 /*AllowExplicit=*/false,
1448 /*ForceRValue=*/false,
1449 &ICS))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001450 {
1451 assert((ICS.ConversionKind ==
1452 ImplicitConversionSequence::StandardConversion ||
1453 ICS.ConversionKind ==
1454 ImplicitConversionSequence::UserDefinedConversion) &&
1455 "expected a definite conversion");
1456 bool DirectBinding =
1457 ICS.ConversionKind == ImplicitConversionSequence::StandardConversion ?
1458 ICS.Standard.DirectBinding : ICS.UserDefined.After.DirectBinding;
1459 if (DirectBinding)
1460 return false;
1461 }
1462 }
1463 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1464 // -- If E2 is an rvalue, or if the conversion above cannot be done:
1465 // -- if E1 and E2 have class type, and the underlying class types are
1466 // the same or one is a base class of the other:
1467 QualType FTy = From->getType();
1468 QualType TTy = To->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001469 const RecordType *FRec = FTy->getAs<RecordType>();
1470 const RecordType *TRec = TTy->getAs<RecordType>();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001471 bool FDerivedFromT = FRec && TRec && Self.IsDerivedFrom(FTy, TTy);
1472 if (FRec && TRec && (FRec == TRec ||
1473 FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
1474 // E1 can be converted to match E2 if the class of T2 is the
1475 // same type as, or a base class of, the class of T1, and
1476 // [cv2 > cv1].
1477 if ((FRec == TRec || FDerivedFromT) && TTy.isAtLeastAsQualifiedAs(FTy)) {
1478 // Could still fail if there's no copy constructor.
1479 // FIXME: Is this a hard error then, or just a conversion failure? The
1480 // standard doesn't say.
Mike Stump1eb44332009-09-09 15:08:12 +00001481 ICS = Self.TryCopyInitialization(From, TTy,
Anders Carlssond28b4282009-08-27 17:18:13 +00001482 /*SuppressUserConversions=*/false,
Anders Carlsson7b361b52009-08-27 17:37:39 +00001483 /*ForceRValue=*/false,
1484 /*InOverloadResolution=*/false);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001485 }
1486 } else {
1487 // -- Otherwise: E1 can be converted to match E2 if E1 can be
1488 // implicitly converted to the type that expression E2 would have
1489 // if E2 were converted to an rvalue.
1490 // First find the decayed type.
1491 if (TTy->isFunctionType())
1492 TTy = Self.Context.getPointerType(TTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001493 else if (TTy->isArrayType())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001494 TTy = Self.Context.getArrayDecayedType(TTy);
1495
1496 // Now try the implicit conversion.
1497 // FIXME: This doesn't detect ambiguities.
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001498 ICS = Self.TryImplicitConversion(From, TTy,
1499 /*SuppressUserConversions=*/false,
1500 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00001501 /*ForceRValue=*/false,
1502 /*InOverloadResolution=*/false);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001503 }
1504 return false;
1505}
1506
1507/// \brief Try to find a common type for two according to C++0x 5.16p5.
1508///
1509/// This is part of the parameter validation for the ? operator. If either
1510/// value operand is a class type, overload resolution is used to find a
1511/// conversion to a common type.
1512static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
1513 SourceLocation Loc) {
1514 Expr *Args[2] = { LHS, RHS };
1515 OverloadCandidateSet CandidateSet;
1516 Self.AddBuiltinOperatorCandidates(OO_Conditional, Args, 2, CandidateSet);
1517
1518 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00001519 switch (Self.BestViableFunction(CandidateSet, Loc, Best)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001520 case Sema::OR_Success:
1521 // We found a match. Perform the conversions on the arguments and move on.
1522 if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
1523 Best->Conversions[0], "converting") ||
1524 Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
1525 Best->Conversions[1], "converting"))
1526 break;
1527 return false;
1528
1529 case Sema::OR_No_Viable_Function:
1530 Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
1531 << LHS->getType() << RHS->getType()
1532 << LHS->getSourceRange() << RHS->getSourceRange();
1533 return true;
1534
1535 case Sema::OR_Ambiguous:
1536 Self.Diag(Loc, diag::err_conditional_ambiguous_ovl)
1537 << LHS->getType() << RHS->getType()
1538 << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stump390b4cc2009-05-16 07:39:55 +00001539 // FIXME: Print the possible common types by printing the return types of
1540 // the viable candidates.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001541 break;
1542
1543 case Sema::OR_Deleted:
1544 assert(false && "Conditional operator has only built-in overloads");
1545 break;
1546 }
1547 return true;
1548}
1549
Sebastian Redl76458502009-04-17 16:30:52 +00001550/// \brief Perform an "extended" implicit conversion as returned by
1551/// TryClassUnification.
1552///
1553/// TryClassUnification generates ICSs that include reference bindings.
1554/// PerformImplicitConversion is not suitable for this; it chokes if the
1555/// second part of a standard conversion is ICK_DerivedToBase. This function
1556/// handles the reference binding specially.
1557static bool ConvertForConditional(Sema &Self, Expr *&E,
Mike Stump1eb44332009-09-09 15:08:12 +00001558 const ImplicitConversionSequence &ICS) {
Sebastian Redl76458502009-04-17 16:30:52 +00001559 if (ICS.ConversionKind == ImplicitConversionSequence::StandardConversion &&
1560 ICS.Standard.ReferenceBinding) {
1561 assert(ICS.Standard.DirectBinding &&
1562 "TryClassUnification should never generate indirect ref bindings");
Sebastian Redla5cd2cd2009-04-26 11:21:02 +00001563 // FIXME: CheckReferenceInit should be able to reuse the ICS instead of
1564 // redoing all the work.
1565 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001566 TargetType(ICS)),
Douglas Gregor739d8282009-09-23 23:04:10 +00001567 /*FIXME:*/E->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001568 /*SuppressUserConversions=*/false,
1569 /*AllowExplicit=*/false,
1570 /*ForceRValue=*/false);
Sebastian Redl76458502009-04-17 16:30:52 +00001571 }
1572 if (ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion &&
1573 ICS.UserDefined.After.ReferenceBinding) {
1574 assert(ICS.UserDefined.After.DirectBinding &&
1575 "TryClassUnification should never generate indirect ref bindings");
Sebastian Redla5cd2cd2009-04-26 11:21:02 +00001576 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001577 TargetType(ICS)),
Douglas Gregor739d8282009-09-23 23:04:10 +00001578 /*FIXME:*/E->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001579 /*SuppressUserConversions=*/false,
1580 /*AllowExplicit=*/false,
1581 /*ForceRValue=*/false);
Sebastian Redl76458502009-04-17 16:30:52 +00001582 }
1583 if (Self.PerformImplicitConversion(E, TargetType(ICS), ICS, "converting"))
1584 return true;
1585 return false;
1586}
1587
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001588/// \brief Check the operands of ?: under C++ semantics.
1589///
1590/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
1591/// extension. In this case, LHS == Cond. (But they're not aliases.)
1592QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
1593 SourceLocation QuestionLoc) {
Mike Stump390b4cc2009-05-16 07:39:55 +00001594 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
1595 // interface pointers.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001596
1597 // C++0x 5.16p1
1598 // The first expression is contextually converted to bool.
1599 if (!Cond->isTypeDependent()) {
1600 if (CheckCXXBooleanCondition(Cond))
1601 return QualType();
1602 }
1603
1604 // Either of the arguments dependent?
1605 if (LHS->isTypeDependent() || RHS->isTypeDependent())
1606 return Context.DependentTy;
1607
1608 // C++0x 5.16p2
1609 // If either the second or the third operand has type (cv) void, ...
1610 QualType LTy = LHS->getType();
1611 QualType RTy = RHS->getType();
1612 bool LVoid = LTy->isVoidType();
1613 bool RVoid = RTy->isVoidType();
1614 if (LVoid || RVoid) {
1615 // ... then the [l2r] conversions are performed on the second and third
1616 // operands ...
1617 DefaultFunctionArrayConversion(LHS);
1618 DefaultFunctionArrayConversion(RHS);
1619 LTy = LHS->getType();
1620 RTy = RHS->getType();
1621
1622 // ... and one of the following shall hold:
1623 // -- The second or the third operand (but not both) is a throw-
1624 // expression; the result is of the type of the other and is an rvalue.
1625 bool LThrow = isa<CXXThrowExpr>(LHS);
1626 bool RThrow = isa<CXXThrowExpr>(RHS);
1627 if (LThrow && !RThrow)
1628 return RTy;
1629 if (RThrow && !LThrow)
1630 return LTy;
1631
1632 // -- Both the second and third operands have type void; the result is of
1633 // type void and is an rvalue.
1634 if (LVoid && RVoid)
1635 return Context.VoidTy;
1636
1637 // Neither holds, error.
1638 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
1639 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
1640 << LHS->getSourceRange() << RHS->getSourceRange();
1641 return QualType();
1642 }
1643
1644 // Neither is void.
1645
1646 // C++0x 5.16p3
1647 // Otherwise, if the second and third operand have different types, and
1648 // either has (cv) class type, and attempt is made to convert each of those
1649 // operands to the other.
1650 if (Context.getCanonicalType(LTy) != Context.getCanonicalType(RTy) &&
1651 (LTy->isRecordType() || RTy->isRecordType())) {
1652 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
1653 // These return true if a single direction is already ambiguous.
1654 if (TryClassUnification(*this, LHS, RHS, QuestionLoc, ICSLeftToRight))
1655 return QualType();
1656 if (TryClassUnification(*this, RHS, LHS, QuestionLoc, ICSRightToLeft))
1657 return QualType();
1658
1659 bool HaveL2R = ICSLeftToRight.ConversionKind !=
1660 ImplicitConversionSequence::BadConversion;
1661 bool HaveR2L = ICSRightToLeft.ConversionKind !=
1662 ImplicitConversionSequence::BadConversion;
1663 // If both can be converted, [...] the program is ill-formed.
1664 if (HaveL2R && HaveR2L) {
1665 Diag(QuestionLoc, diag::err_conditional_ambiguous)
1666 << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
1667 return QualType();
1668 }
1669
1670 // If exactly one conversion is possible, that conversion is applied to
1671 // the chosen operand and the converted operands are used in place of the
1672 // original operands for the remainder of this section.
1673 if (HaveL2R) {
Sebastian Redl76458502009-04-17 16:30:52 +00001674 if (ConvertForConditional(*this, LHS, ICSLeftToRight))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001675 return QualType();
1676 LTy = LHS->getType();
1677 } else if (HaveR2L) {
Sebastian Redl76458502009-04-17 16:30:52 +00001678 if (ConvertForConditional(*this, RHS, ICSRightToLeft))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001679 return QualType();
1680 RTy = RHS->getType();
1681 }
1682 }
1683
1684 // C++0x 5.16p4
1685 // If the second and third operands are lvalues and have the same type,
1686 // the result is of that type [...]
1687 bool Same = Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy);
1688 if (Same && LHS->isLvalue(Context) == Expr::LV_Valid &&
1689 RHS->isLvalue(Context) == Expr::LV_Valid)
1690 return LTy;
1691
1692 // C++0x 5.16p5
1693 // Otherwise, the result is an rvalue. If the second and third operands
1694 // do not have the same type, and either has (cv) class type, ...
1695 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
1696 // ... overload resolution is used to determine the conversions (if any)
1697 // to be applied to the operands. If the overload resolution fails, the
1698 // program is ill-formed.
1699 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
1700 return QualType();
1701 }
1702
1703 // C++0x 5.16p6
1704 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
1705 // conversions are performed on the second and third operands.
1706 DefaultFunctionArrayConversion(LHS);
1707 DefaultFunctionArrayConversion(RHS);
1708 LTy = LHS->getType();
1709 RTy = RHS->getType();
1710
1711 // After those conversions, one of the following shall hold:
1712 // -- The second and third operands have the same type; the result
1713 // is of that type.
1714 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy))
1715 return LTy;
1716
1717 // -- The second and third operands have arithmetic or enumeration type;
1718 // the usual arithmetic conversions are performed to bring them to a
1719 // common type, and the result is of that type.
1720 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
1721 UsualArithmeticConversions(LHS, RHS);
1722 return LHS->getType();
1723 }
1724
1725 // -- The second and third operands have pointer type, or one has pointer
1726 // type and the other is a null pointer constant; pointer conversions
1727 // and qualification conversions are performed to bring them to their
1728 // composite pointer type. The result is of the composite pointer type.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001729 QualType Composite = FindCompositePointerType(LHS, RHS);
1730 if (!Composite.isNull())
1731 return Composite;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001732
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001733 // Fourth bullet is same for pointers-to-member. However, the possible
1734 // conversions are far more limited: we have null-to-pointer, upcast of
1735 // containing class, and second-level cv-ness.
1736 // cv-ness is not a union, but must match one of the two operands. (Which,
1737 // frankly, is stupid.)
Ted Kremenek6217b802009-07-29 21:53:49 +00001738 const MemberPointerType *LMemPtr = LTy->getAs<MemberPointerType>();
1739 const MemberPointerType *RMemPtr = RTy->getAs<MemberPointerType>();
Douglas Gregorce940492009-09-25 04:25:58 +00001740 if (LMemPtr &&
1741 RHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001742 ImpCastExprToType(RHS, LTy);
1743 return LTy;
1744 }
Douglas Gregorce940492009-09-25 04:25:58 +00001745 if (RMemPtr &&
1746 LHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001747 ImpCastExprToType(LHS, RTy);
1748 return RTy;
1749 }
1750 if (LMemPtr && RMemPtr) {
1751 QualType LPointee = LMemPtr->getPointeeType();
1752 QualType RPointee = RMemPtr->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00001753
1754 QualifierCollector LPQuals, RPQuals;
1755 const Type *LPCan = LPQuals.strip(Context.getCanonicalType(LPointee));
1756 const Type *RPCan = RPQuals.strip(Context.getCanonicalType(RPointee));
1757
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001758 // First, we check that the unqualified pointee type is the same. If it's
1759 // not, there's no conversion that will unify the two pointers.
John McCall0953e762009-09-24 19:53:00 +00001760 if (LPCan == RPCan) {
1761
1762 // Second, we take the greater of the two qualifications. If neither
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001763 // is greater than the other, the conversion is not possible.
John McCall0953e762009-09-24 19:53:00 +00001764
1765 Qualifiers MergedQuals = LPQuals + RPQuals;
1766
1767 bool CompatibleQuals = true;
1768 if (MergedQuals.getCVRQualifiers() != LPQuals.getCVRQualifiers() &&
1769 MergedQuals.getCVRQualifiers() != RPQuals.getCVRQualifiers())
1770 CompatibleQuals = false;
1771 else if (LPQuals.getAddressSpace() != RPQuals.getAddressSpace())
1772 // FIXME:
1773 // C99 6.5.15 as modified by TR 18037:
1774 // If the second and third operands are pointers into different
1775 // address spaces, the address spaces must overlap.
1776 CompatibleQuals = false;
1777 // FIXME: GC qualifiers?
1778
1779 if (CompatibleQuals) {
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001780 // Third, we check if either of the container classes is derived from
1781 // the other.
1782 QualType LContainer(LMemPtr->getClass(), 0);
1783 QualType RContainer(RMemPtr->getClass(), 0);
1784 QualType MoreDerived;
1785 if (Context.getCanonicalType(LContainer) ==
1786 Context.getCanonicalType(RContainer))
1787 MoreDerived = LContainer;
1788 else if (IsDerivedFrom(LContainer, RContainer))
1789 MoreDerived = LContainer;
1790 else if (IsDerivedFrom(RContainer, LContainer))
1791 MoreDerived = RContainer;
1792
1793 if (!MoreDerived.isNull()) {
1794 // The type 'Q Pointee (MoreDerived::*)' is the common type.
1795 // We don't use ImpCastExprToType here because this could still fail
1796 // for ambiguous or inaccessible conversions.
John McCall0953e762009-09-24 19:53:00 +00001797 LPointee = Context.getQualifiedType(LPointee, MergedQuals);
1798 QualType Common
1799 = Context.getMemberPointerType(LPointee, MoreDerived.getTypePtr());
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001800 if (PerformImplicitConversion(LHS, Common, "converting"))
1801 return QualType();
1802 if (PerformImplicitConversion(RHS, Common, "converting"))
1803 return QualType();
1804 return Common;
1805 }
1806 }
1807 }
1808 }
1809
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001810 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
1811 << LHS->getType() << RHS->getType()
1812 << LHS->getSourceRange() << RHS->getSourceRange();
1813 return QualType();
1814}
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001815
1816/// \brief Find a merged pointer type and convert the two expressions to it.
1817///
Douglas Gregor20b3e992009-08-24 17:42:35 +00001818/// This finds the composite pointer type (or member pointer type) for @p E1
1819/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
1820/// type and returns it.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001821/// It does not emit diagnostics.
1822QualType Sema::FindCompositePointerType(Expr *&E1, Expr *&E2) {
1823 assert(getLangOptions().CPlusPlus && "This function assumes C++");
1824 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001825
Douglas Gregor20b3e992009-08-24 17:42:35 +00001826 if (!T1->isPointerType() && !T1->isMemberPointerType() &&
1827 !T2->isPointerType() && !T2->isMemberPointerType())
1828 return QualType();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001829
Douglas Gregor20b3e992009-08-24 17:42:35 +00001830 // FIXME: Do we need to work on the canonical types?
Mike Stump1eb44332009-09-09 15:08:12 +00001831
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001832 // C++0x 5.9p2
1833 // Pointer conversions and qualification conversions are performed on
1834 // pointer operands to bring them to their composite pointer type. If
1835 // one operand is a null pointer constant, the composite pointer type is
1836 // the type of the other operand.
Douglas Gregorce940492009-09-25 04:25:58 +00001837 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001838 ImpCastExprToType(E1, T2);
1839 return T2;
1840 }
Douglas Gregorce940492009-09-25 04:25:58 +00001841 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001842 ImpCastExprToType(E2, T1);
1843 return T1;
1844 }
Mike Stump1eb44332009-09-09 15:08:12 +00001845
Douglas Gregor20b3e992009-08-24 17:42:35 +00001846 // Now both have to be pointers or member pointers.
1847 if (!T1->isPointerType() && !T1->isMemberPointerType() &&
1848 !T2->isPointerType() && !T2->isMemberPointerType())
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001849 return QualType();
1850
1851 // Otherwise, of one of the operands has type "pointer to cv1 void," then
1852 // the other has type "pointer to cv2 T" and the composite pointer type is
1853 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
1854 // Otherwise, the composite pointer type is a pointer type similar to the
1855 // type of one of the operands, with a cv-qualification signature that is
1856 // the union of the cv-qualification signatures of the operand types.
1857 // In practice, the first part here is redundant; it's subsumed by the second.
1858 // What we do here is, we build the two possible composite types, and try the
1859 // conversions in both directions. If only one works, or if the two composite
1860 // types are the same, we have succeeded.
John McCall0953e762009-09-24 19:53:00 +00001861 // FIXME: extended qualifiers?
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001862 llvm::SmallVector<unsigned, 4> QualifierUnion;
Douglas Gregor20b3e992009-08-24 17:42:35 +00001863 llvm::SmallVector<std::pair<const Type *, const Type *>, 4> MemberOfClass;
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001864 QualType Composite1 = T1, Composite2 = T2;
Douglas Gregor20b3e992009-08-24 17:42:35 +00001865 do {
1866 const PointerType *Ptr1, *Ptr2;
1867 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
1868 (Ptr2 = Composite2->getAs<PointerType>())) {
1869 Composite1 = Ptr1->getPointeeType();
1870 Composite2 = Ptr2->getPointeeType();
1871 QualifierUnion.push_back(
1872 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
1873 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
1874 continue;
1875 }
Mike Stump1eb44332009-09-09 15:08:12 +00001876
Douglas Gregor20b3e992009-08-24 17:42:35 +00001877 const MemberPointerType *MemPtr1, *MemPtr2;
1878 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
1879 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
1880 Composite1 = MemPtr1->getPointeeType();
1881 Composite2 = MemPtr2->getPointeeType();
1882 QualifierUnion.push_back(
1883 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
1884 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
1885 MemPtr2->getClass()));
1886 continue;
1887 }
Mike Stump1eb44332009-09-09 15:08:12 +00001888
Douglas Gregor20b3e992009-08-24 17:42:35 +00001889 // FIXME: block pointer types?
Mike Stump1eb44332009-09-09 15:08:12 +00001890
Douglas Gregor20b3e992009-08-24 17:42:35 +00001891 // Cannot unwrap any more types.
1892 break;
1893 } while (true);
Mike Stump1eb44332009-09-09 15:08:12 +00001894
Douglas Gregor20b3e992009-08-24 17:42:35 +00001895 // Rewrap the composites as pointers or member pointers with the union CVRs.
1896 llvm::SmallVector<std::pair<const Type *, const Type *>, 4>::iterator MOC
1897 = MemberOfClass.begin();
Mike Stump1eb44332009-09-09 15:08:12 +00001898 for (llvm::SmallVector<unsigned, 4>::iterator
Douglas Gregor20b3e992009-08-24 17:42:35 +00001899 I = QualifierUnion.begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00001900 E = QualifierUnion.end();
Douglas Gregor20b3e992009-08-24 17:42:35 +00001901 I != E; (void)++I, ++MOC) {
John McCall0953e762009-09-24 19:53:00 +00001902 Qualifiers Quals = Qualifiers::fromCVRMask(*I);
Douglas Gregor20b3e992009-08-24 17:42:35 +00001903 if (MOC->first && MOC->second) {
1904 // Rebuild member pointer type
John McCall0953e762009-09-24 19:53:00 +00001905 Composite1 = Context.getMemberPointerType(
1906 Context.getQualifiedType(Composite1, Quals),
1907 MOC->first);
1908 Composite2 = Context.getMemberPointerType(
1909 Context.getQualifiedType(Composite2, Quals),
1910 MOC->second);
Douglas Gregor20b3e992009-08-24 17:42:35 +00001911 } else {
1912 // Rebuild pointer type
John McCall0953e762009-09-24 19:53:00 +00001913 Composite1
1914 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
1915 Composite2
1916 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregor20b3e992009-08-24 17:42:35 +00001917 }
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001918 }
1919
Mike Stump1eb44332009-09-09 15:08:12 +00001920 ImplicitConversionSequence E1ToC1 =
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001921 TryImplicitConversion(E1, Composite1,
1922 /*SuppressUserConversions=*/false,
1923 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00001924 /*ForceRValue=*/false,
1925 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00001926 ImplicitConversionSequence E2ToC1 =
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001927 TryImplicitConversion(E2, Composite1,
1928 /*SuppressUserConversions=*/false,
1929 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00001930 /*ForceRValue=*/false,
1931 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00001932
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001933 ImplicitConversionSequence E1ToC2, E2ToC2;
1934 E1ToC2.ConversionKind = ImplicitConversionSequence::BadConversion;
1935 E2ToC2.ConversionKind = ImplicitConversionSequence::BadConversion;
1936 if (Context.getCanonicalType(Composite1) !=
1937 Context.getCanonicalType(Composite2)) {
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001938 E1ToC2 = TryImplicitConversion(E1, Composite2,
1939 /*SuppressUserConversions=*/false,
1940 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00001941 /*ForceRValue=*/false,
1942 /*InOverloadResolution=*/false);
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001943 E2ToC2 = TryImplicitConversion(E2, Composite2,
1944 /*SuppressUserConversions=*/false,
1945 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00001946 /*ForceRValue=*/false,
1947 /*InOverloadResolution=*/false);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001948 }
1949
1950 bool ToC1Viable = E1ToC1.ConversionKind !=
1951 ImplicitConversionSequence::BadConversion
1952 && E2ToC1.ConversionKind !=
1953 ImplicitConversionSequence::BadConversion;
1954 bool ToC2Viable = E1ToC2.ConversionKind !=
1955 ImplicitConversionSequence::BadConversion
1956 && E2ToC2.ConversionKind !=
1957 ImplicitConversionSequence::BadConversion;
1958 if (ToC1Viable && !ToC2Viable) {
1959 if (!PerformImplicitConversion(E1, Composite1, E1ToC1, "converting") &&
1960 !PerformImplicitConversion(E2, Composite1, E2ToC1, "converting"))
1961 return Composite1;
1962 }
1963 if (ToC2Viable && !ToC1Viable) {
1964 if (!PerformImplicitConversion(E1, Composite2, E1ToC2, "converting") &&
1965 !PerformImplicitConversion(E2, Composite2, E2ToC2, "converting"))
1966 return Composite2;
1967 }
1968 return QualType();
1969}
Anders Carlsson165a0a02009-05-17 18:41:29 +00001970
Anders Carlssondef11992009-05-30 20:36:53 +00001971Sema::OwningExprResult Sema::MaybeBindToTemporary(Expr *E) {
Anders Carlsson089c2602009-08-15 23:41:35 +00001972 if (!Context.getLangOptions().CPlusPlus)
1973 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001974
Ted Kremenek6217b802009-07-29 21:53:49 +00001975 const RecordType *RT = E->getType()->getAs<RecordType>();
Anders Carlssondef11992009-05-30 20:36:53 +00001976 if (!RT)
1977 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001978
Anders Carlssondef11992009-05-30 20:36:53 +00001979 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1980 if (RD->hasTrivialDestructor())
1981 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001982
Anders Carlsson283e4d52009-09-14 01:30:44 +00001983 if (CallExpr *CE = dyn_cast<CallExpr>(E)) {
1984 QualType Ty = CE->getCallee()->getType();
1985 if (const PointerType *PT = Ty->getAs<PointerType>())
1986 Ty = PT->getPointeeType();
1987
John McCall183700f2009-09-21 23:43:11 +00001988 const FunctionType *FTy = Ty->getAs<FunctionType>();
Anders Carlsson283e4d52009-09-14 01:30:44 +00001989 if (FTy->getResultType()->isReferenceType())
1990 return Owned(E);
1991 }
Mike Stump1eb44332009-09-09 15:08:12 +00001992 CXXTemporary *Temp = CXXTemporary::Create(Context,
Anders Carlssondef11992009-05-30 20:36:53 +00001993 RD->getDestructor(Context));
Anders Carlsson860306e2009-05-30 21:21:49 +00001994 ExprTemporaries.push_back(Temp);
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00001995 if (CXXDestructorDecl *Destructor =
1996 const_cast<CXXDestructorDecl*>(RD->getDestructor(Context)))
1997 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
Anders Carlssondef11992009-05-30 20:36:53 +00001998 // FIXME: Add the temporary to the temporaries vector.
1999 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
2000}
2001
Mike Stump1eb44332009-09-09 15:08:12 +00002002Expr *Sema::MaybeCreateCXXExprWithTemporaries(Expr *SubExpr,
Anders Carlssonf54741e2009-06-16 03:37:31 +00002003 bool ShouldDestroyTemps) {
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002004 assert(SubExpr && "sub expression can't be null!");
Mike Stump1eb44332009-09-09 15:08:12 +00002005
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002006 if (ExprTemporaries.empty())
2007 return SubExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00002008
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002009 Expr *E = CXXExprWithTemporaries::Create(Context, SubExpr,
Mike Stump1eb44332009-09-09 15:08:12 +00002010 &ExprTemporaries[0],
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002011 ExprTemporaries.size(),
Anders Carlssonf54741e2009-06-16 03:37:31 +00002012 ShouldDestroyTemps);
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002013 ExprTemporaries.clear();
Mike Stump1eb44332009-09-09 15:08:12 +00002014
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002015 return E;
2016}
2017
Mike Stump1eb44332009-09-09 15:08:12 +00002018Sema::OwningExprResult
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002019Sema::ActOnStartCXXMemberReference(Scope *S, ExprArg Base, SourceLocation OpLoc,
2020 tok::TokenKind OpKind, TypeTy *&ObjectType) {
2021 // Since this might be a postfix expression, get rid of ParenListExprs.
2022 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
Mike Stump1eb44332009-09-09 15:08:12 +00002023
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002024 Expr *BaseExpr = (Expr*)Base.get();
2025 assert(BaseExpr && "no record expansion");
Mike Stump1eb44332009-09-09 15:08:12 +00002026
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002027 QualType BaseType = BaseExpr->getType();
2028 if (BaseType->isDependentType()) {
2029 // FIXME: member of the current instantiation
2030 ObjectType = BaseType.getAsOpaquePtr();
2031 return move(Base);
2032 }
Mike Stump1eb44332009-09-09 15:08:12 +00002033
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002034 // C++ [over.match.oper]p8:
Mike Stump1eb44332009-09-09 15:08:12 +00002035 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002036 // returned, with the original second operand.
2037 if (OpKind == tok::arrow) {
John McCallc4e83212009-09-30 01:01:30 +00002038 // The set of types we've considered so far.
John McCall432887f2009-09-30 01:30:54 +00002039 llvm::SmallPtrSet<CanQualType,8> CTypes;
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002040 llvm::SmallVector<SourceLocation, 8> Locations;
John McCall432887f2009-09-30 01:30:54 +00002041 CTypes.insert(Context.getCanonicalType(BaseType));
John McCallc4e83212009-09-30 01:01:30 +00002042
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002043 while (BaseType->isRecordType()) {
Anders Carlsson15ea3782009-10-13 22:43:21 +00002044 Base = BuildOverloadedArrowExpr(S, move(Base), OpLoc);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002045 BaseExpr = (Expr*)Base.get();
2046 if (BaseExpr == NULL)
2047 return ExprError();
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002048 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(BaseExpr))
Anders Carlssonde699e52009-10-13 22:55:59 +00002049 Locations.push_back(OpCall->getDirectCallee()->getLocation());
John McCallc4e83212009-09-30 01:01:30 +00002050 BaseType = BaseExpr->getType();
2051 CanQualType CBaseType = Context.getCanonicalType(BaseType);
John McCall432887f2009-09-30 01:30:54 +00002052 if (!CTypes.insert(CBaseType)) {
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00002053 Diag(OpLoc, diag::err_operator_arrow_circular);
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002054 for (unsigned i = 0; i < Locations.size(); i++)
2055 Diag(Locations[i], diag::note_declared_at);
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00002056 return ExprError();
2057 }
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002058 }
2059 }
Mike Stump1eb44332009-09-09 15:08:12 +00002060
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002061 if (BaseType->isPointerType())
2062 BaseType = BaseType->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00002063
2064 // We could end up with various non-record types here, such as extended
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002065 // vector types or Objective-C interfaces. Just return early and let
2066 // ActOnMemberReferenceExpr do the work.
Douglas Gregorc68afe22009-09-03 21:38:09 +00002067 if (!BaseType->isRecordType()) {
2068 // C++ [basic.lookup.classref]p2:
2069 // [...] If the type of the object expression is of pointer to scalar
2070 // type, the unqualified-id is looked up in the context of the complete
2071 // postfix-expression.
2072 ObjectType = 0;
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002073 return move(Base);
Douglas Gregorc68afe22009-09-03 21:38:09 +00002074 }
Mike Stump1eb44332009-09-09 15:08:12 +00002075
Douglas Gregorc68afe22009-09-03 21:38:09 +00002076 // C++ [basic.lookup.classref]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00002077 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregorc68afe22009-09-03 21:38:09 +00002078 // unqualified-id, and the type of the object expres- sion is of a class
2079 // type C (or of pointer to a class type C), the unqualified-id is looked
2080 // up in the scope of class C. [...]
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002081 ObjectType = BaseType.getAsOpaquePtr();
Mike Stump1eb44332009-09-09 15:08:12 +00002082 return move(Base);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002083}
2084
Anders Carlssonec773872009-08-25 23:46:41 +00002085Sema::OwningExprResult
Anders Carlsson3aa4ca42009-08-26 17:36:19 +00002086Sema::ActOnDestructorReferenceExpr(Scope *S, ExprArg Base,
Anders Carlssonec773872009-08-25 23:46:41 +00002087 SourceLocation OpLoc,
2088 tok::TokenKind OpKind,
2089 SourceLocation ClassNameLoc,
2090 IdentifierInfo *ClassName,
Douglas Gregora78c5c32009-09-04 18:29:40 +00002091 const CXXScopeSpec &SS,
2092 bool HasTrailingLParen) {
2093 if (SS.isInvalid())
Anders Carlssonec773872009-08-25 23:46:41 +00002094 return ExprError();
Anders Carlsson2cf738f2009-08-26 19:22:42 +00002095
Douglas Gregora71d8192009-09-04 17:36:40 +00002096 QualType BaseType;
Douglas Gregora78c5c32009-09-04 18:29:40 +00002097 if (isUnknownSpecialization(SS))
2098 BaseType = Context.getTypenameType((NestedNameSpecifier *)SS.getScopeRep(),
Douglas Gregora71d8192009-09-04 17:36:40 +00002099 ClassName);
2100 else {
Douglas Gregora78c5c32009-09-04 18:29:40 +00002101 TypeTy *BaseTy = getTypeName(*ClassName, ClassNameLoc, S, &SS);
Douglas Gregora71d8192009-09-04 17:36:40 +00002102 if (!BaseTy) {
Mike Stump1eb44332009-09-09 15:08:12 +00002103 Diag(ClassNameLoc, diag::err_ident_in_pseudo_dtor_not_a_type)
Douglas Gregora71d8192009-09-04 17:36:40 +00002104 << ClassName;
2105 return ExprError();
2106 }
Mike Stump1eb44332009-09-09 15:08:12 +00002107
Douglas Gregora71d8192009-09-04 17:36:40 +00002108 BaseType = GetTypeFromParser(BaseTy);
Anders Carlsson2cf738f2009-08-26 19:22:42 +00002109 }
Mike Stump1eb44332009-09-09 15:08:12 +00002110
Anders Carlsson2cf738f2009-08-26 19:22:42 +00002111 CanQualType CanBaseType = Context.getCanonicalType(BaseType);
Mike Stump1eb44332009-09-09 15:08:12 +00002112 DeclarationName DtorName =
Anders Carlsson2cf738f2009-08-26 19:22:42 +00002113 Context.DeclarationNames.getCXXDestructorName(CanBaseType);
2114
Douglas Gregora78c5c32009-09-04 18:29:40 +00002115 OwningExprResult Result
2116 = BuildMemberReferenceExpr(S, move(Base), OpLoc, OpKind, ClassNameLoc,
2117 DtorName, DeclPtrTy(), &SS);
2118 if (Result.isInvalid() || HasTrailingLParen)
2119 return move(Result);
Mike Stump1eb44332009-09-09 15:08:12 +00002120
2121 // The only way a reference to a destructor can be used is to
Douglas Gregora78c5c32009-09-04 18:29:40 +00002122 // immediately call them. Since the next token is not a '(', produce a
2123 // diagnostic and build the call now.
2124 Expr *E = (Expr *)Result.get();
2125 SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(E->getLocEnd());
2126 Diag(E->getLocStart(), diag::err_dtor_expr_without_call)
2127 << isa<CXXPseudoDestructorExpr>(E)
2128 << CodeModificationHint::CreateInsertion(ExpectedLParenLoc, "()");
Mike Stump1eb44332009-09-09 15:08:12 +00002129
2130 return ActOnCallExpr(0, move(Result), ExpectedLParenLoc,
Douglas Gregora78c5c32009-09-04 18:29:40 +00002131 MultiExprArg(*this, 0, 0), 0, ExpectedLParenLoc);
Anders Carlssonec773872009-08-25 23:46:41 +00002132}
2133
Douglas Gregora6f0f9d2009-08-31 19:52:13 +00002134Sema::OwningExprResult
2135Sema::ActOnOverloadedOperatorReferenceExpr(Scope *S, ExprArg Base,
2136 SourceLocation OpLoc,
2137 tok::TokenKind OpKind,
2138 SourceLocation ClassNameLoc,
2139 OverloadedOperatorKind OverOpKind,
2140 const CXXScopeSpec *SS) {
2141 if (SS && SS->isInvalid())
2142 return ExprError();
2143
2144 DeclarationName Name =
2145 Context.DeclarationNames.getCXXOperatorName(OverOpKind);
2146
2147 return BuildMemberReferenceExpr(S, move(Base), OpLoc, OpKind, ClassNameLoc,
2148 Name, DeclPtrTy(), SS);
2149}
2150
2151Sema::OwningExprResult
2152Sema::ActOnConversionOperatorReferenceExpr(Scope *S, ExprArg Base,
2153 SourceLocation OpLoc,
2154 tok::TokenKind OpKind,
2155 SourceLocation ClassNameLoc,
2156 TypeTy *Ty,
2157 const CXXScopeSpec *SS) {
2158 if (SS && SS->isInvalid())
2159 return ExprError();
2160
2161 //FIXME: Preserve type source info.
2162 QualType ConvType = GetTypeFromParser(Ty);
2163 CanQualType ConvTypeCanon = Context.getCanonicalType(ConvType);
2164 DeclarationName ConvName =
2165 Context.DeclarationNames.getCXXConversionFunctionName(ConvTypeCanon);
2166
2167 return BuildMemberReferenceExpr(S, move(Base), OpLoc, OpKind, ClassNameLoc,
2168 ConvName, DeclPtrTy(), SS);
2169}
2170
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002171CXXMemberCallExpr *Sema::BuildCXXMemberCallExpr(Expr *Exp,
2172 CXXMethodDecl *Method) {
2173 MemberExpr *ME =
2174 new (Context) MemberExpr(Exp, /*IsArrow=*/false, Method,
2175 SourceLocation(), Method->getType());
2176 QualType ResultType;
2177 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(Method))
2178 ResultType = Conv->getConversionType().getNonReferenceType();
2179 else
2180 ResultType = Method->getResultType().getNonReferenceType();
2181
2182 CXXMemberCallExpr *CE =
2183 new (Context) CXXMemberCallExpr(Context, ME, 0, 0,
2184 ResultType,
2185 SourceLocation());
2186 return CE;
2187}
2188
Anders Carlsson0aebc812009-09-09 21:33:21 +00002189Sema::OwningExprResult Sema::BuildCXXCastArgument(SourceLocation CastLoc,
2190 QualType Ty,
2191 CastExpr::CastKind Kind,
2192 CXXMethodDecl *Method,
2193 ExprArg Arg) {
2194 Expr *From = Arg.takeAs<Expr>();
2195
2196 switch (Kind) {
2197 default: assert(0 && "Unhandled cast kind!");
2198 case CastExpr::CK_ConstructorConversion: {
Douglas Gregor39da0b82009-09-09 23:08:42 +00002199 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
2200
2201 if (CompleteConstructorCall(cast<CXXConstructorDecl>(Method),
2202 MultiExprArg(*this, (void **)&From, 1),
2203 CastLoc, ConstructorArgs))
2204 return ExprError();
Anders Carlsson4fa26842009-10-18 21:20:14 +00002205
2206 OwningExprResult Result =
2207 BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
2208 move_arg(ConstructorArgs));
2209 if (Result.isInvalid())
2210 return ExprError();
2211
2212 return MaybeBindToTemporary(Result.takeAs<Expr>());
Anders Carlsson0aebc812009-09-09 21:33:21 +00002213 }
2214
2215 case CastExpr::CK_UserDefinedConversion: {
Anders Carlssonaac6e3a2009-09-15 07:42:44 +00002216 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
2217
2218 // Cast to base if needed.
2219 if (PerformObjectArgumentInitialization(From, Method))
2220 return ExprError();
2221
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002222 // Create an implicit call expr that calls it.
2223 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(From, Method);
Anders Carlsson4fa26842009-10-18 21:20:14 +00002224 return MaybeBindToTemporary(CE);
Anders Carlsson0aebc812009-09-09 21:33:21 +00002225 }
Anders Carlsson0aebc812009-09-09 21:33:21 +00002226 }
2227}
2228
Anders Carlsson165a0a02009-05-17 18:41:29 +00002229Sema::OwningExprResult Sema::ActOnFinishFullExpr(ExprArg Arg) {
2230 Expr *FullExpr = Arg.takeAs<Expr>();
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002231 if (FullExpr)
Mike Stump1eb44332009-09-09 15:08:12 +00002232 FullExpr = MaybeCreateCXXExprWithTemporaries(FullExpr,
Anders Carlssonf54741e2009-06-16 03:37:31 +00002233 /*ShouldDestroyTemps=*/true);
Anders Carlsson165a0a02009-05-17 18:41:29 +00002234
Anders Carlssonec773872009-08-25 23:46:41 +00002235
Anders Carlsson165a0a02009-05-17 18:41:29 +00002236 return Owned(FullExpr);
2237}