blob: d08d445911f5d63342a105610acdf93003156722 [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
Sebastian Redl7c8bd602009-02-07 20:10:22 +000014#include "SemaInherit.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000015#include "Sema.h"
Steve Naroff210679c2007-08-25 14:02:58 +000016#include "clang/AST/ASTContext.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 Gregor4c921ae2009-01-30 01:04:22 +000064 NamespaceDecl *StdNs = GetStdNamespace();
Chris Lattner572af492008-11-20 05:51:55 +000065 if (!StdNs)
Sebastian Redlf53597f2009-03-15 17:47:39 +000066 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +000067
68 if (isType)
69 // FIXME: Preserve type source info.
70 TyOrExpr = GetTypeFromParser(TyOrExpr).getAsOpaquePtr();
71
Chris Lattner572af492008-11-20 05:51:55 +000072 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
Douglas Gregor4c921ae2009-01-30 01:04:22 +000073 Decl *TypeInfoDecl = LookupQualifiedName(StdNs, TypeInfoII, LookupTagName);
Sebastian Redlc42e1182008-11-11 11:37:55 +000074 RecordDecl *TypeInfoRecordDecl = dyn_cast_or_null<RecordDecl>(TypeInfoDecl);
Chris Lattner572af492008-11-20 05:51:55 +000075 if (!TypeInfoRecordDecl)
Sebastian Redlf53597f2009-03-15 17:47:39 +000076 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Sebastian Redlc42e1182008-11-11 11:37:55 +000077
78 QualType TypeInfoType = Context.getTypeDeclType(TypeInfoRecordDecl);
79
Douglas Gregorac7610d2009-06-22 20:57:11 +000080 if (!isType) {
81 // C++0x [expr.typeid]p3:
Mike Stump1eb44332009-09-09 15:08:12 +000082 // When typeid is applied to an expression other than an lvalue of a
83 // polymorphic class type [...] [the] expression is an unevaluated
Douglas Gregorac7610d2009-06-22 20:57:11 +000084 // operand.
Mike Stump1eb44332009-09-09 15:08:12 +000085
Douglas Gregorac7610d2009-06-22 20:57:11 +000086 // FIXME: if the type of the expression is a class type, the class
87 // shall be completely defined.
88 bool isUnevaluatedOperand = true;
89 Expr *E = static_cast<Expr *>(TyOrExpr);
90 if (E && !E->isTypeDependent() && E->isLvalue(Context) == Expr::LV_Valid) {
91 QualType T = E->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +000092 if (const RecordType *RecordT = T->getAs<RecordType>()) {
Douglas Gregorac7610d2009-06-22 20:57:11 +000093 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
94 if (RecordD->isPolymorphic())
95 isUnevaluatedOperand = false;
96 }
97 }
Mike Stump1eb44332009-09-09 15:08:12 +000098
Douglas Gregorac7610d2009-06-22 20:57:11 +000099 // If this is an unevaluated operand, clear out the set of declaration
100 // references we have been computing.
101 if (isUnevaluatedOperand)
102 PotentiallyReferencedDeclStack.back().clear();
103 }
Mike Stump1eb44332009-09-09 15:08:12 +0000104
Sebastian Redlf53597f2009-03-15 17:47:39 +0000105 return Owned(new (Context) CXXTypeidExpr(isType, TyOrExpr,
106 TypeInfoType.withConst(),
107 SourceRange(OpLoc, RParenLoc)));
Sebastian Redlc42e1182008-11-11 11:37:55 +0000108}
109
Steve Naroff1b273c42007-09-16 14:56:35 +0000110/// ActOnCXXBoolLiteral - Parse {true,false} literals.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000111Action::OwningExprResult
Steve Naroff1b273c42007-09-16 14:56:35 +0000112Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor2f639b92008-10-24 15:36:09 +0000113 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000114 "Unknown C++ Boolean value!");
Sebastian Redlf53597f2009-03-15 17:47:39 +0000115 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
116 Context.BoolTy, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000117}
Chris Lattner50dd2892008-02-26 00:51:44 +0000118
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000119/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
120Action::OwningExprResult
121Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
122 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
123}
124
Chris Lattner50dd2892008-02-26 00:51:44 +0000125/// ActOnCXXThrow - Parse throw expressions.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000126Action::OwningExprResult
127Sema::ActOnCXXThrow(SourceLocation OpLoc, ExprArg E) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000128 Expr *Ex = E.takeAs<Expr>();
129 if (Ex && !Ex->isTypeDependent() && CheckCXXThrowOperand(OpLoc, Ex))
130 return ExprError();
131 return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc));
132}
133
134/// CheckCXXThrowOperand - Validate the operand of a throw.
135bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *&E) {
136 // C++ [except.throw]p3:
137 // [...] adjusting the type from "array of T" or "function returning T"
138 // to "pointer to T" or "pointer to function returning T", [...]
139 DefaultFunctionArrayConversion(E);
140
141 // If the type of the exception would be an incomplete type or a pointer
142 // to an incomplete type other than (cv) void the program is ill-formed.
143 QualType Ty = E->getType();
144 int isPointer = 0;
Ted Kremenek6217b802009-07-29 21:53:49 +0000145 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000146 Ty = Ptr->getPointeeType();
147 isPointer = 1;
148 }
149 if (!isPointer || !Ty->isVoidType()) {
150 if (RequireCompleteType(ThrowLoc, Ty,
Anders Carlssond497ba72009-08-26 22:59:12 +0000151 PDiag(isPointer ? diag::err_throw_incomplete_ptr
152 : diag::err_throw_incomplete)
153 << E->getSourceRange()))
Sebastian Redl972041f2009-04-27 20:27:31 +0000154 return true;
155 }
156
157 // FIXME: Construct a temporary here.
158 return false;
Chris Lattner50dd2892008-02-26 00:51:44 +0000159}
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000160
Sebastian Redlf53597f2009-03-15 17:47:39 +0000161Action::OwningExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000162 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
163 /// is a non-lvalue expression whose value is the address of the object for
164 /// which the function is called.
165
Sebastian Redlf53597f2009-03-15 17:47:39 +0000166 if (!isa<FunctionDecl>(CurContext))
167 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000168
169 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext))
170 if (MD->isInstance())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000171 return Owned(new (Context) CXXThisExpr(ThisLoc,
172 MD->getThisType(Context)));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000173
Sebastian Redlf53597f2009-03-15 17:47:39 +0000174 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000175}
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000176
177/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
178/// Can be interpreted either as function-style casting ("int(x)")
179/// or class type construction ("ClassType(x,y,z)")
180/// or creation of a value-initialized type ("int()").
Sebastian Redlf53597f2009-03-15 17:47:39 +0000181Action::OwningExprResult
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000182Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep,
183 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000184 MultiExprArg exprs,
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000185 SourceLocation *CommaLocs,
186 SourceLocation RParenLoc) {
187 assert(TypeRep && "Missing type!");
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000188 // FIXME: Preserve type source info.
189 QualType Ty = GetTypeFromParser(TypeRep);
Sebastian Redlf53597f2009-03-15 17:47:39 +0000190 unsigned NumExprs = exprs.size();
191 Expr **Exprs = (Expr**)exprs.get();
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000192 SourceLocation TyBeginLoc = TypeRange.getBegin();
193 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
194
Sebastian Redlf53597f2009-03-15 17:47:39 +0000195 if (Ty->isDependentType() ||
Douglas Gregorba498172009-03-13 21:01:28 +0000196 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
Sebastian Redlf53597f2009-03-15 17:47:39 +0000197 exprs.release();
Mike Stump1eb44332009-09-09 15:08:12 +0000198
199 return Owned(CXXUnresolvedConstructExpr::Create(Context,
200 TypeRange.getBegin(), Ty,
Douglas Gregord81e6ca2009-05-20 18:46:25 +0000201 LParenLoc,
202 Exprs, NumExprs,
203 RParenLoc));
Douglas Gregorba498172009-03-13 21:01:28 +0000204 }
205
Anders Carlssonbb60a502009-08-27 03:53:50 +0000206 if (Ty->isArrayType())
207 return ExprError(Diag(TyBeginLoc,
208 diag::err_value_init_for_array_type) << FullRange);
209 if (!Ty->isVoidType() &&
210 RequireCompleteType(TyBeginLoc, Ty,
211 PDiag(diag::err_invalid_incomplete_type_use)
212 << FullRange))
213 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000214
Anders Carlssonbb60a502009-08-27 03:53:50 +0000215 if (RequireNonAbstractType(TyBeginLoc, Ty,
216 diag::err_allocation_of_abstract_type))
217 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000218
219
Douglas Gregor506ae412009-01-16 18:33:17 +0000220 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000221 // If the expression list is a single expression, the type conversion
222 // expression is equivalent (in definedness, and if defined in meaning) to the
223 // corresponding cast expression.
224 //
225 if (NumExprs == 1) {
Anders Carlssoncdb61972009-08-07 22:21:05 +0000226 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Anders Carlsson0aebc812009-09-09 21:33:21 +0000227 CXXMethodDecl *Method = 0;
228 if (CheckCastTypes(TypeRange, Ty, Exprs[0], Kind, Method,
229 /*FunctionalStyle=*/true))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000230 return ExprError();
Anders Carlsson0aebc812009-09-09 21:33:21 +0000231
232 exprs.release();
233 if (Method) {
234 OwningExprResult CastArg
235 = BuildCXXCastArgument(TypeRange.getBegin(), Ty.getNonReferenceType(),
236 Kind, Method, Owned(Exprs[0]));
237 if (CastArg.isInvalid())
238 return ExprError();
239
240 Exprs[0] = CastArg.takeAs<Expr>();
Fariborz Jahanian4fc7ab32009-08-28 15:11:24 +0000241 }
Anders Carlsson0aebc812009-09-09 21:33:21 +0000242
243 return Owned(new (Context) CXXFunctionalCastExpr(Ty.getNonReferenceType(),
244 Ty, TyBeginLoc, Kind,
245 Exprs[0], RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000246 }
247
Ted Kremenek6217b802009-07-29 21:53:49 +0000248 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Douglas Gregor506ae412009-01-16 18:33:17 +0000249 CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
Sebastian Redlf53597f2009-03-15 17:47:39 +0000250
Mike Stump1eb44332009-09-09 15:08:12 +0000251 if (NumExprs > 1 || !Record->hasTrivialConstructor() ||
Anders Carlssone7624a72009-08-27 05:08:22 +0000252 !Record->hasTrivialDestructor()) {
Douglas Gregor39da0b82009-09-09 23:08:42 +0000253 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
254
Douglas Gregor506ae412009-01-16 18:33:17 +0000255 CXXConstructorDecl *Constructor
Douglas Gregor39da0b82009-09-09 23:08:42 +0000256 = PerformInitializationByConstructor(Ty, move(exprs),
Douglas Gregor506ae412009-01-16 18:33:17 +0000257 TypeRange.getBegin(),
258 SourceRange(TypeRange.getBegin(),
259 RParenLoc),
260 DeclarationName(),
Douglas Gregor39da0b82009-09-09 23:08:42 +0000261 IK_Direct,
262 ConstructorArgs);
Douglas Gregor506ae412009-01-16 18:33:17 +0000263
Sebastian Redlf53597f2009-03-15 17:47:39 +0000264 if (!Constructor)
265 return ExprError();
266
Mike Stump1eb44332009-09-09 15:08:12 +0000267 OwningExprResult Result =
268 BuildCXXTemporaryObjectExpr(Constructor, Ty, TyBeginLoc,
Douglas Gregor39da0b82009-09-09 23:08:42 +0000269 move_arg(ConstructorArgs), RParenLoc);
Anders Carlssone7624a72009-08-27 05:08:22 +0000270 if (Result.isInvalid())
271 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000272
Anders Carlssone7624a72009-08-27 05:08:22 +0000273 return MaybeBindToTemporary(Result.takeAs<Expr>());
Douglas Gregor506ae412009-01-16 18:33:17 +0000274 }
275
276 // Fall through to value-initialize an object of class type that
277 // doesn't have a user-declared default constructor.
278 }
279
280 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000281 // If the expression list specifies more than a single value, the type shall
282 // be a class with a suitably declared constructor.
283 //
284 if (NumExprs > 1)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000285 return ExprError(Diag(CommaLocs[0],
286 diag::err_builtin_func_cast_more_than_one_arg)
287 << FullRange);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000288
289 assert(NumExprs == 0 && "Expected 0 expressions");
290
Douglas Gregor506ae412009-01-16 18:33:17 +0000291 // C++ [expr.type.conv]p2:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000292 // The expression T(), where T is a simple-type-specifier for a non-array
293 // complete object type or the (possibly cv-qualified) void type, creates an
294 // rvalue of the specified type, which is value-initialized.
295 //
Sebastian Redlf53597f2009-03-15 17:47:39 +0000296 exprs.release();
297 return Owned(new (Context) CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000298}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000299
300
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000301/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
302/// @code new (memory) int[size][4] @endcode
303/// or
304/// @code ::new Foo(23, "hello") @endcode
305/// For the interpretation of this heap of arguments, consult the base version.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000306Action::OwningExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000307Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000308 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000309 SourceLocation PlacementRParen, bool ParenTypeId,
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000310 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000311 MultiExprArg ConstructorArgs,
Mike Stump1eb44332009-09-09 15:08:12 +0000312 SourceLocation ConstructorRParen) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000313 Expr *ArraySize = 0;
314 unsigned Skip = 0;
315 // If the specified type is an array, unwrap it and save the expression.
316 if (D.getNumTypeObjects() > 0 &&
317 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
318 DeclaratorChunk &Chunk = D.getTypeObject(0);
319 if (Chunk.Arr.hasStatic)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000320 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
321 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000322 if (!Chunk.Arr.NumElts)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000323 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
324 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000325 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
326 Skip = 1;
327 }
328
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000329 //FIXME: Store DeclaratorInfo in CXXNew expression.
330 DeclaratorInfo *DInfo = 0;
331 QualType AllocType = GetTypeForDeclarator(D, /*Scope=*/0, &DInfo, Skip);
Chris Lattnereaaebc72009-04-25 08:06:05 +0000332 if (D.isInvalidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000333 return ExprError();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000334
Douglas Gregor3433cf72009-05-21 00:00:09 +0000335 // Every dimension shall be of constant size.
336 unsigned i = 1;
337 QualType ElementType = AllocType;
338 while (const ArrayType *Array = Context.getAsArrayType(ElementType)) {
339 if (!Array->isConstantArrayType()) {
340 Diag(D.getTypeObject(i).Loc, diag::err_new_array_nonconst)
341 << static_cast<Expr*>(D.getTypeObject(i).Arr.NumElts)->getSourceRange();
342 return ExprError();
343 }
344 ElementType = Array->getElementType();
345 ++i;
346 }
347
Mike Stump1eb44332009-09-09 15:08:12 +0000348 return BuildCXXNew(StartLoc, UseGlobal,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000349 PlacementLParen,
Mike Stump1eb44332009-09-09 15:08:12 +0000350 move(PlacementArgs),
Douglas Gregor3433cf72009-05-21 00:00:09 +0000351 PlacementRParen,
352 ParenTypeId,
Mike Stump1eb44332009-09-09 15:08:12 +0000353 AllocType,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000354 D.getSourceRange().getBegin(),
355 D.getSourceRange(),
356 Owned(ArraySize),
357 ConstructorLParen,
358 move(ConstructorArgs),
359 ConstructorRParen);
360}
361
Mike Stump1eb44332009-09-09 15:08:12 +0000362Sema::OwningExprResult
Douglas Gregor3433cf72009-05-21 00:00:09 +0000363Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
364 SourceLocation PlacementLParen,
365 MultiExprArg PlacementArgs,
366 SourceLocation PlacementRParen,
Mike Stump1eb44332009-09-09 15:08:12 +0000367 bool ParenTypeId,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000368 QualType AllocType,
369 SourceLocation TypeLoc,
370 SourceRange TypeRange,
371 ExprArg ArraySizeE,
372 SourceLocation ConstructorLParen,
373 MultiExprArg ConstructorArgs,
374 SourceLocation ConstructorRParen) {
375 if (CheckAllocatedType(AllocType, TypeLoc, TypeRange))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000376 return ExprError();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000377
Douglas Gregor3433cf72009-05-21 00:00:09 +0000378 QualType ResultType = Context.getPointerType(AllocType);
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000379
380 // That every array dimension except the first is constant was already
381 // checked by the type check above.
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000382
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000383 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
384 // or enumeration type with a non-negative value."
Douglas Gregor3433cf72009-05-21 00:00:09 +0000385 Expr *ArraySize = (Expr *)ArraySizeE.get();
Sebastian Redl28507842009-02-26 14:39:58 +0000386 if (ArraySize && !ArraySize->isTypeDependent()) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000387 QualType SizeType = ArraySize->getType();
388 if (!SizeType->isIntegralType() && !SizeType->isEnumeralType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000389 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
390 diag::err_array_size_not_integral)
391 << SizeType << ArraySize->getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000392 // Let's see if this is a constant < 0. If so, we reject it out of hand.
393 // We don't care about special rules, so we tell the machinery it's not
394 // evaluated - it gives us a result in more cases.
Sebastian Redl28507842009-02-26 14:39:58 +0000395 if (!ArraySize->isValueDependent()) {
396 llvm::APSInt Value;
397 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
398 if (Value < llvm::APSInt(
399 llvm::APInt::getNullValue(Value.getBitWidth()), false))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000400 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
401 diag::err_typecheck_negative_array_size)
402 << ArraySize->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +0000403 }
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000404 }
405 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000406
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000407 FunctionDecl *OperatorNew = 0;
408 FunctionDecl *OperatorDelete = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000409 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
410 unsigned NumPlaceArgs = PlacementArgs.size();
Sebastian Redl28507842009-02-26 14:39:58 +0000411 if (!AllocType->isDependentType() &&
412 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
413 FindAllocationFunctions(StartLoc,
Sebastian Redl00e68e22009-02-09 18:24:27 +0000414 SourceRange(PlacementLParen, PlacementRParen),
415 UseGlobal, AllocType, ArraySize, PlaceArgs,
416 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000417 return ExprError();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000418
419 bool Init = ConstructorLParen.isValid();
420 // --- Choosing a constructor ---
421 // C++ 5.3.4p15
422 // 1) If T is a POD and there's no initializer (ConstructorLParen is invalid)
423 // the object is not initialized. If the object, or any part of it, is
424 // const-qualified, it's an error.
425 // 2) If T is a POD and there's an empty initializer, the object is value-
426 // initialized.
427 // 3) If T is a POD and there's one initializer argument, the object is copy-
428 // constructed.
429 // 4) If T is a POD and there's more initializer arguments, it's an error.
430 // 5) If T is not a POD, the initializer arguments are used as constructor
431 // arguments.
432 //
433 // Or by the C++0x formulation:
434 // 1) If there's no initializer, the object is default-initialized according
435 // to C++0x rules.
436 // 2) Otherwise, the object is direct-initialized.
437 CXXConstructorDecl *Constructor = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000438 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
Sebastian Redl4f149632009-05-07 16:14:23 +0000439 const RecordType *RT;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000440 unsigned NumConsArgs = ConstructorArgs.size();
Sebastian Redl28507842009-02-26 14:39:58 +0000441 if (AllocType->isDependentType()) {
442 // Skip all the checks.
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000443 } else if ((RT = AllocType->getAs<RecordType>()) &&
444 !AllocType->isAggregateType()) {
Douglas Gregor39da0b82009-09-09 23:08:42 +0000445 ASTOwningVector<&ActionBase::DeleteExpr> ConvertedConstructorArgs(*this);
446
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000447 Constructor = PerformInitializationByConstructor(
Douglas Gregor39da0b82009-09-09 23:08:42 +0000448 AllocType, move(ConstructorArgs),
Douglas Gregor3433cf72009-05-21 00:00:09 +0000449 TypeLoc,
450 SourceRange(TypeLoc, ConstructorRParen),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000451 RT->getDecl()->getDeclName(),
Douglas Gregor39da0b82009-09-09 23:08:42 +0000452 NumConsArgs != 0 ? IK_Direct : IK_Default,
453 ConvertedConstructorArgs);
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000454 if (!Constructor)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000455 return ExprError();
Douglas Gregor39da0b82009-09-09 23:08:42 +0000456
457 // Take the converted constructor arguments and use them for the new
458 // expression.
459 NumConsArgs = ConvertedConstructorArgs.size();
460 ConsArgs = (Expr **)ConvertedConstructorArgs.take();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000461 } else {
462 if (!Init) {
463 // FIXME: Check that no subpart is const.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000464 if (AllocType.isConstQualified())
465 return ExprError(Diag(StartLoc, diag::err_new_uninitialized_const)
Douglas Gregor3433cf72009-05-21 00:00:09 +0000466 << TypeRange);
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000467 } else if (NumConsArgs == 0) {
468 // Object is value-initialized. Do nothing.
469 } else if (NumConsArgs == 1) {
470 // Object is direct-initialized.
Sebastian Redl4f149632009-05-07 16:14:23 +0000471 // FIXME: What DeclarationName do we pass in here?
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000472 if (CheckInitializerTypes(ConsArgs[0], AllocType, StartLoc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000473 DeclarationName() /*AllocType.getAsString()*/,
474 /*DirectInit=*/true))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000475 return ExprError();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000476 } else {
Sebastian Redlf53597f2009-03-15 17:47:39 +0000477 return ExprError(Diag(StartLoc,
478 diag::err_builtin_direct_init_more_than_one_arg)
479 << SourceRange(ConstructorLParen, ConstructorRParen));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000480 }
481 }
482
483 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
484
Sebastian Redlf53597f2009-03-15 17:47:39 +0000485 PlacementArgs.release();
486 ConstructorArgs.release();
Douglas Gregor3433cf72009-05-21 00:00:09 +0000487 ArraySizeE.release();
Sebastian Redlf53597f2009-03-15 17:47:39 +0000488 return Owned(new (Context) CXXNewExpr(UseGlobal, OperatorNew, PlaceArgs,
Ted Kremenek8189cde2009-02-07 01:47:29 +0000489 NumPlaceArgs, ParenTypeId, ArraySize, Constructor, Init,
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000490 ConsArgs, NumConsArgs, OperatorDelete, ResultType,
Mike Stump1eb44332009-09-09 15:08:12 +0000491 StartLoc, Init ? ConstructorRParen : SourceLocation()));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000492}
493
494/// CheckAllocatedType - Checks that a type is suitable as the allocated type
495/// in a new-expression.
496/// dimension off and stores the size expression in ArraySize.
Douglas Gregor3433cf72009-05-21 00:00:09 +0000497bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +0000498 SourceRange R) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000499 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
500 // abstract class type or array thereof.
Douglas Gregore7450f52009-03-24 19:52:54 +0000501 if (AllocType->isFunctionType())
Douglas Gregor3433cf72009-05-21 00:00:09 +0000502 return Diag(Loc, diag::err_bad_new_type)
503 << AllocType << 0 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +0000504 else if (AllocType->isReferenceType())
Douglas Gregor3433cf72009-05-21 00:00:09 +0000505 return Diag(Loc, diag::err_bad_new_type)
506 << AllocType << 1 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +0000507 else if (!AllocType->isDependentType() &&
Douglas Gregor3433cf72009-05-21 00:00:09 +0000508 RequireCompleteType(Loc, AllocType,
Anders Carlssonb7906612009-08-26 23:45:07 +0000509 PDiag(diag::err_new_incomplete_type)
510 << R))
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000511 return true;
Douglas Gregor3433cf72009-05-21 00:00:09 +0000512 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregore7450f52009-03-24 19:52:54 +0000513 diag::err_allocation_of_abstract_type))
514 return true;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000515
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000516 return false;
517}
518
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000519/// FindAllocationFunctions - Finds the overloads of operator new and delete
520/// that are appropriate for the allocation.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000521bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
522 bool UseGlobal, QualType AllocType,
523 bool IsArray, Expr **PlaceArgs,
524 unsigned NumPlaceArgs,
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000525 FunctionDecl *&OperatorNew,
Mike Stump1eb44332009-09-09 15:08:12 +0000526 FunctionDecl *&OperatorDelete) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000527 // --- Choosing an allocation function ---
528 // C++ 5.3.4p8 - 14 & 18
529 // 1) If UseGlobal is true, only look in the global scope. Else, also look
530 // in the scope of the allocated class.
531 // 2) If an array size is given, look for operator new[], else look for
532 // operator new.
533 // 3) The first argument is always size_t. Append the arguments from the
534 // placement form.
535 // FIXME: Also find the appropriate delete operator.
536
537 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
538 // We don't care about the actual value of this argument.
539 // FIXME: Should the Sema create the expression and embed it in the syntax
540 // tree? Or should the consumer just recalculate the value?
Anders Carlssond67c4c32009-08-16 20:29:29 +0000541 IntegerLiteral Size(llvm::APInt::getNullValue(
542 Context.Target.getPointerWidth(0)),
543 Context.getSizeType(),
544 SourceLocation());
545 AllocArgs[0] = &Size;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000546 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
547
548 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
549 IsArray ? OO_Array_New : OO_New);
550 if (AllocType->isRecordType() && !UseGlobal) {
Mike Stump1eb44332009-09-09 15:08:12 +0000551 CXXRecordDecl *Record
Ted Kremenek6217b802009-07-29 21:53:49 +0000552 = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl());
Sebastian Redl7f662392008-12-04 22:20:51 +0000553 // FIXME: We fail to find inherited overloads.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000554 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000555 AllocArgs.size(), Record, /*AllowMissing=*/true,
556 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000557 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000558 }
559 if (!OperatorNew) {
560 // Didn't find a member overload. Look for a global one.
561 DeclareGlobalNewDelete();
Sebastian Redl7f662392008-12-04 22:20:51 +0000562 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl00e68e22009-02-09 18:24:27 +0000563 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000564 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
565 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000566 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000567 }
568
Anders Carlssond9583892009-05-31 20:26:12 +0000569 // FindAllocationOverload can change the passed in arguments, so we need to
570 // copy them back.
571 if (NumPlaceArgs > 0)
572 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
Mike Stump1eb44332009-09-09 15:08:12 +0000573
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000574 return false;
575}
576
Sebastian Redl7f662392008-12-04 22:20:51 +0000577/// FindAllocationOverload - Find an fitting overload for the allocation
578/// function in the specified scope.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000579bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
580 DeclarationName Name, Expr** Args,
581 unsigned NumArgs, DeclContext *Ctx,
Mike Stump1eb44332009-09-09 15:08:12 +0000582 bool AllowMissing, FunctionDecl *&Operator) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000583 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000584 llvm::tie(Alloc, AllocEnd) = Ctx->lookup(Name);
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000585 if (Alloc == AllocEnd) {
Sebastian Redl7f662392008-12-04 22:20:51 +0000586 if (AllowMissing)
587 return false;
Sebastian Redl7f662392008-12-04 22:20:51 +0000588 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +0000589 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +0000590 }
591
592 OverloadCandidateSet Candidates;
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000593 for (; Alloc != AllocEnd; ++Alloc) {
594 // Even member operator new/delete are implicitly treated as
595 // static, so don't use AddMemberCandidate.
596 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>(*Alloc))
597 AddOverloadCandidate(Fn, Args, NumArgs, Candidates,
598 /*SuppressUserConversions=*/false);
Sebastian Redl7f662392008-12-04 22:20:51 +0000599 }
600
601 // Do the resolution.
602 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +0000603 switch(BestViableFunction(Candidates, StartLoc, Best)) {
Sebastian Redl7f662392008-12-04 22:20:51 +0000604 case OR_Success: {
605 // Got one!
606 FunctionDecl *FnDecl = Best->Function;
607 // The first argument is size_t, and the first parameter must be size_t,
608 // too. This is checked on declaration and can be assumed. (It can't be
609 // asserted on, though, since invalid decls are left in there.)
610 for (unsigned i = 1; i < NumArgs; ++i) {
611 // FIXME: Passing word to diagnostic.
Anders Carlssonfc27d262009-05-31 19:49:47 +0000612 if (PerformCopyInitialization(Args[i],
Sebastian Redl7f662392008-12-04 22:20:51 +0000613 FnDecl->getParamDecl(i)->getType(),
614 "passing"))
615 return true;
616 }
617 Operator = FnDecl;
618 return false;
619 }
620
621 case OR_No_Viable_Function:
Sebastian Redl7f662392008-12-04 22:20:51 +0000622 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +0000623 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +0000624 PrintOverloadCandidates(Candidates, /*OnlyViable=*/false);
625 return true;
626
627 case OR_Ambiguous:
Sebastian Redl7f662392008-12-04 22:20:51 +0000628 Diag(StartLoc, diag::err_ovl_ambiguous_call)
Sebastian Redl00e68e22009-02-09 18:24:27 +0000629 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +0000630 PrintOverloadCandidates(Candidates, /*OnlyViable=*/true);
631 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000632
633 case OR_Deleted:
634 Diag(StartLoc, diag::err_ovl_deleted_call)
635 << Best->Function->isDeleted()
636 << Name << Range;
637 PrintOverloadCandidates(Candidates, /*OnlyViable=*/true);
638 return true;
Sebastian Redl7f662392008-12-04 22:20:51 +0000639 }
640 assert(false && "Unreachable, bad result from BestViableFunction");
641 return true;
642}
643
644
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000645/// DeclareGlobalNewDelete - Declare the global forms of operator new and
646/// delete. These are:
647/// @code
648/// void* operator new(std::size_t) throw(std::bad_alloc);
649/// void* operator new[](std::size_t) throw(std::bad_alloc);
650/// void operator delete(void *) throw();
651/// void operator delete[](void *) throw();
652/// @endcode
653/// Note that the placement and nothrow forms of new are *not* implicitly
654/// declared. Their use requires including \<new\>.
Mike Stump1eb44332009-09-09 15:08:12 +0000655void Sema::DeclareGlobalNewDelete() {
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000656 if (GlobalNewDeleteDeclared)
657 return;
658 GlobalNewDeleteDeclared = true;
659
660 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
661 QualType SizeT = Context.getSizeType();
662
663 // FIXME: Exception specifications are not added.
664 DeclareGlobalAllocationFunction(
665 Context.DeclarationNames.getCXXOperatorName(OO_New),
666 VoidPtr, SizeT);
667 DeclareGlobalAllocationFunction(
668 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
669 VoidPtr, SizeT);
670 DeclareGlobalAllocationFunction(
671 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
672 Context.VoidTy, VoidPtr);
673 DeclareGlobalAllocationFunction(
674 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
675 Context.VoidTy, VoidPtr);
676}
677
678/// DeclareGlobalAllocationFunction - Declares a single implicit global
679/// allocation function if it doesn't already exist.
680void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Mike Stump1eb44332009-09-09 15:08:12 +0000681 QualType Return, QualType Argument) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000682 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
683
684 // Check if this function is already declared.
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000685 {
Douglas Gregor5cc37092008-12-23 22:05:29 +0000686 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000687 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000688 Alloc != AllocEnd; ++Alloc) {
689 // FIXME: Do we need to check for default arguments here?
690 FunctionDecl *Func = cast<FunctionDecl>(*Alloc);
691 if (Func->getNumParams() == 1 &&
Ted Kremenek8189cde2009-02-07 01:47:29 +0000692 Context.getCanonicalType(Func->getParamDecl(0)->getType())==Argument)
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000693 return;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000694 }
695 }
696
697 QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0);
698 FunctionDecl *Alloc =
699 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +0000700 FnType, /*DInfo=*/0, FunctionDecl::None, false, true);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000701 Alloc->setImplicit();
702 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000703 0, Argument, /*DInfo=*/0,
704 VarDecl::None, 0);
Ted Kremenekfc767612009-01-14 00:42:25 +0000705 Alloc->setParams(Context, &Param, 1);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000706
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000707 // FIXME: Also add this declaration to the IdentifierResolver, but
708 // make sure it is at the end of the chain to coincide with the
709 // global scope.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000710 ((DeclContext *)TUScope->getEntity())->addDecl(Alloc);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000711}
712
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000713/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
714/// @code ::delete ptr; @endcode
715/// or
716/// @code delete [] ptr; @endcode
Sebastian Redlf53597f2009-03-15 17:47:39 +0000717Action::OwningExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000718Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
Mike Stump1eb44332009-09-09 15:08:12 +0000719 bool ArrayForm, ExprArg Operand) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000720 // C++ [expr.delete]p1:
721 // The operand shall have a pointer type, or a class type having a single
722 // conversion function to a pointer type. The result has type void.
723 //
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000724 // DR599 amends "pointer type" to "pointer to object type" in both cases.
725
Anders Carlssond67c4c32009-08-16 20:29:29 +0000726 FunctionDecl *OperatorDelete = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000727
Sebastian Redlf53597f2009-03-15 17:47:39 +0000728 Expr *Ex = (Expr *)Operand.get();
Sebastian Redl28507842009-02-26 14:39:58 +0000729 if (!Ex->isTypeDependent()) {
730 QualType Type = Ex->getType();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000731
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000732 if (const RecordType *Record = Type->getAs<RecordType>()) {
733 // FIXME: Inherited conversion functions!
734 llvm::SmallVector<CXXConversionDecl *, 4> ObjectPtrConversions;
735
736 OverloadedFunctionDecl *Conversions
737 = cast<CXXRecordDecl>(Record->getDecl())->getConversionFunctions();
738 for (OverloadedFunctionDecl::function_iterator
739 Func = Conversions->function_begin(),
740 FuncEnd = Conversions->function_end();
741 Func != FuncEnd; ++Func) {
742 // Skip over templated conversion functions; they aren't considered.
743 if (isa<FunctionTemplateDecl>(*Func))
744 continue;
745
746 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
747
748 QualType ConvType = Conv->getConversionType().getNonReferenceType();
749 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
750 if (ConvPtrType->getPointeeType()->isObjectType())
751 ObjectPtrConversions.push_back(Conv);
752 }
753
754 if (ObjectPtrConversions.size() == 1) {
755 // We have a single conversion to a pointer-to-object type. Perform
756 // that conversion.
757 Operand.release();
758 if (PerformImplicitConversion(Ex,
759 ObjectPtrConversions.front()->getConversionType(),
760 "converting"))
761 return ExprError();
762
763 Operand = Owned(Ex);
764 Type = Ex->getType();
765 }
Sebastian Redl28507842009-02-26 14:39:58 +0000766 }
767
Sebastian Redlf53597f2009-03-15 17:47:39 +0000768 if (!Type->isPointerType())
769 return ExprError(Diag(StartLoc, diag::err_delete_operand)
770 << Type << Ex->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +0000771
Ted Kremenek6217b802009-07-29 21:53:49 +0000772 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Douglas Gregor8dcb29d2009-03-24 20:13:58 +0000773 if (Pointee->isFunctionType() || Pointee->isVoidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000774 return ExprError(Diag(StartLoc, diag::err_delete_operand)
775 << Type << Ex->getSourceRange());
Douglas Gregor8dcb29d2009-03-24 20:13:58 +0000776 else if (!Pointee->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +0000777 RequireCompleteType(StartLoc, Pointee,
Anders Carlssonb7906612009-08-26 23:45:07 +0000778 PDiag(diag::warn_delete_incomplete)
779 << Ex->getSourceRange()))
Douglas Gregor8dcb29d2009-03-24 20:13:58 +0000780 return ExprError();
Sebastian Redl28507842009-02-26 14:39:58 +0000781
Mike Stump1eb44332009-09-09 15:08:12 +0000782 // FIXME: This should be shared with the code for finding the delete
Anders Carlssond67c4c32009-08-16 20:29:29 +0000783 // operator in ActOnCXXNew.
784 IntegerLiteral Size(llvm::APInt::getNullValue(
785 Context.Target.getPointerWidth(0)),
786 Context.getSizeType(),
787 SourceLocation());
788 ImplicitCastExpr Cast(Context.getPointerType(Context.VoidTy),
789 CastExpr::CK_Unknown, &Size, false);
790 Expr *DeleteArg = &Cast;
Mike Stump1eb44332009-09-09 15:08:12 +0000791
Anders Carlssond67c4c32009-08-16 20:29:29 +0000792 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
793 ArrayForm ? OO_Array_Delete : OO_Delete);
794
795 if (Pointee->isRecordType() && !UseGlobal) {
Mike Stump1eb44332009-09-09 15:08:12 +0000796 CXXRecordDecl *Record
Anders Carlssond67c4c32009-08-16 20:29:29 +0000797 = cast<CXXRecordDecl>(Pointee->getAs<RecordType>()->getDecl());
798 // FIXME: We fail to find inherited overloads.
799 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
800 &DeleteArg, 1, Record, /*AllowMissing=*/true,
801 OperatorDelete))
802 return ExprError();
Fariborz Jahanian34374e62009-09-03 23:18:17 +0000803 if (!Record->hasTrivialDestructor())
804 if (const CXXDestructorDecl *Dtor = Record->getDestructor(Context))
Mike Stump1eb44332009-09-09 15:08:12 +0000805 MarkDeclarationReferenced(StartLoc,
Fariborz Jahanian34374e62009-09-03 23:18:17 +0000806 const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssond67c4c32009-08-16 20:29:29 +0000807 }
Mike Stump1eb44332009-09-09 15:08:12 +0000808
Anders Carlssond67c4c32009-08-16 20:29:29 +0000809 if (!OperatorDelete) {
810 // Didn't find a member overload. Look for a global one.
811 DeclareGlobalNewDelete();
812 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000813 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
Anders Carlssond67c4c32009-08-16 20:29:29 +0000814 &DeleteArg, 1, TUDecl, /*AllowMissing=*/false,
815 OperatorDelete))
816 return ExprError();
817 }
Mike Stump1eb44332009-09-09 15:08:12 +0000818
Sebastian Redl28507842009-02-26 14:39:58 +0000819 // FIXME: Check access and ambiguity of operator delete and destructor.
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000820 }
821
Sebastian Redlf53597f2009-03-15 17:47:39 +0000822 Operand.release();
823 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
Anders Carlssond67c4c32009-08-16 20:29:29 +0000824 OperatorDelete, Ex, StartLoc));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000825}
826
827
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000828/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
829/// C++ if/switch/while/for statement.
830/// e.g: "if (int x = f()) {...}"
Sebastian Redlf53597f2009-03-15 17:47:39 +0000831Action::OwningExprResult
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000832Sema::ActOnCXXConditionDeclarationExpr(Scope *S, SourceLocation StartLoc,
833 Declarator &D,
834 SourceLocation EqualLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000835 ExprArg AssignExprVal) {
836 assert(AssignExprVal.get() && "Null assignment expression");
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000837
838 // C++ 6.4p2:
839 // The declarator shall not specify a function or an array.
840 // The type-specifier-seq shall not contain typedef and shall not declare a
841 // new class or enumeration.
842
843 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
844 "Parser allowed 'typedef' as storage class of condition decl.");
845
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000846 // FIXME: Store DeclaratorInfo in the expression.
847 DeclaratorInfo *DInfo = 0;
Argyrios Kyrtzidise955e722009-08-11 05:20:41 +0000848 TagDecl *OwnedTag = 0;
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000849 QualType Ty = GetTypeForDeclarator(D, S, &DInfo, /*Skip=*/0, &OwnedTag);
Mike Stump1eb44332009-09-09 15:08:12 +0000850
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000851 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
852 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
853 // would be created and CXXConditionDeclExpr wants a VarDecl.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000854 return ExprError(Diag(StartLoc, diag::err_invalid_use_of_function_type)
855 << SourceRange(StartLoc, EqualLoc));
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000856 } else if (Ty->isArrayType()) { // ...or an array.
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000857 Diag(StartLoc, diag::err_invalid_use_of_array_type)
858 << SourceRange(StartLoc, EqualLoc);
Argyrios Kyrtzidise955e722009-08-11 05:20:41 +0000859 } else if (OwnedTag && OwnedTag->isDefinition()) {
860 // The type-specifier-seq shall not declare a new class or enumeration.
861 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000862 }
863
Douglas Gregor2e01cda2009-06-23 21:43:56 +0000864 DeclPtrTy Dcl = ActOnDeclarator(S, D);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000865 if (!Dcl)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000866 return ExprError();
Anders Carlssonf5dcd382009-05-30 21:37:25 +0000867 AddInitializerToDecl(Dcl, move(AssignExprVal), /*DirectInit=*/false);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000868
Douglas Gregorcaaf29a2008-12-10 23:01:14 +0000869 // Mark this variable as one that is declared within a conditional.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000870 // We know that the decl had to be a VarDecl because that is the only type of
871 // decl that can be assigned and the grammar requires an '='.
872 VarDecl *VD = cast<VarDecl>(Dcl.getAs<Decl>());
873 VD->setDeclaredInCondition(true);
874 return Owned(new (Context) CXXConditionDeclExpr(StartLoc, EqualLoc, VD));
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000875}
876
877/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
878bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
879 // C++ 6.4p4:
880 // The value of a condition that is an initialized declaration in a statement
881 // other than a switch statement is the value of the declared variable
882 // implicitly converted to type bool. If that conversion is ill-formed, the
883 // program is ill-formed.
884 // The value of a condition that is an expression is the value of the
885 // expression, implicitly converted to bool.
886 //
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000887 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000888}
Douglas Gregor77a52232008-09-12 00:47:35 +0000889
890/// Helper function to determine whether this is the (deprecated) C++
891/// conversion from a string literal to a pointer to non-const char or
892/// non-const wchar_t (for narrow and wide string literals,
893/// respectively).
Mike Stump1eb44332009-09-09 15:08:12 +0000894bool
Douglas Gregor77a52232008-09-12 00:47:35 +0000895Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
896 // Look inside the implicit cast, if it exists.
897 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
898 From = Cast->getSubExpr();
899
900 // A string literal (2.13.4) that is not a wide string literal can
901 // be converted to an rvalue of type "pointer to char"; a wide
902 // string literal can be converted to an rvalue of type "pointer
903 // to wchar_t" (C++ 4.2p2).
904 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From))
Ted Kremenek6217b802009-07-29 21:53:49 +0000905 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump1eb44332009-09-09 15:08:12 +0000906 if (const BuiltinType *ToPointeeType
Douglas Gregor77a52232008-09-12 00:47:35 +0000907 = ToPtrType->getPointeeType()->getAsBuiltinType()) {
908 // This conversion is considered only when there is an
909 // explicit appropriate pointer target type (C++ 4.2p2).
910 if (ToPtrType->getPointeeType().getCVRQualifiers() == 0 &&
911 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
912 (!StrLit->isWide() &&
913 (ToPointeeType->getKind() == BuiltinType::Char_U ||
914 ToPointeeType->getKind() == BuiltinType::Char_S))))
915 return true;
916 }
917
918 return false;
919}
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000920
921/// PerformImplicitConversion - Perform an implicit conversion of the
922/// expression From to the type ToType. Returns true if there was an
923/// error, false otherwise. The expression From is replaced with the
Douglas Gregor45920e82008-12-19 17:40:08 +0000924/// converted expression. Flavor is the kind of conversion we're
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000925/// performing, used in the error message. If @p AllowExplicit,
Sebastian Redle2b68332009-04-12 17:16:29 +0000926/// explicit user-defined conversions are permitted. @p Elidable should be true
927/// when called for copies which may be elided (C++ 12.8p15). C++0x overload
928/// resolution works differently in that case.
929bool
Douglas Gregor45920e82008-12-19 17:40:08 +0000930Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Sebastian Redle2b68332009-04-12 17:16:29 +0000931 const char *Flavor, bool AllowExplicit,
Mike Stump1eb44332009-09-09 15:08:12 +0000932 bool Elidable) {
Sebastian Redle2b68332009-04-12 17:16:29 +0000933 ImplicitConversionSequence ICS;
934 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
935 if (Elidable && getLangOptions().CPlusPlus0x) {
Mike Stump1eb44332009-09-09 15:08:12 +0000936 ICS = TryImplicitConversion(From, ToType,
Anders Carlssonda7a18b2009-08-27 17:24:15 +0000937 /*SuppressUserConversions=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +0000938 AllowExplicit,
Anders Carlsson08972922009-08-28 15:33:32 +0000939 /*ForceRValue=*/true,
940 /*InOverloadResolution=*/false);
Sebastian Redle2b68332009-04-12 17:16:29 +0000941 }
942 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion) {
Mike Stump1eb44332009-09-09 15:08:12 +0000943 ICS = TryImplicitConversion(From, ToType,
Anders Carlssonda7a18b2009-08-27 17:24:15 +0000944 /*SuppressUserConversions=*/false,
945 AllowExplicit,
Anders Carlsson08972922009-08-28 15:33:32 +0000946 /*ForceRValue=*/false,
947 /*InOverloadResolution=*/false);
Sebastian Redle2b68332009-04-12 17:16:29 +0000948 }
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000949 return PerformImplicitConversion(From, ToType, ICS, Flavor);
950}
951
952/// PerformImplicitConversion - Perform an implicit conversion of the
953/// expression From to the type ToType using the pre-computed implicit
954/// conversion sequence ICS. Returns true if there was an error, false
955/// otherwise. The expression From is replaced with the converted
956/// expression. Flavor is the kind of conversion we're performing,
957/// used in the error message.
958bool
959Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
960 const ImplicitConversionSequence &ICS,
961 const char* Flavor) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000962 switch (ICS.ConversionKind) {
963 case ImplicitConversionSequence::StandardConversion:
Douglas Gregor45920e82008-12-19 17:40:08 +0000964 if (PerformImplicitConversion(From, ToType, ICS.Standard, Flavor))
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000965 return true;
966 break;
967
968 case ImplicitConversionSequence::UserDefinedConversion:
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +0000969 {
970 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
971 CastExpr::CastKind CastKind = CastExpr::CK_Unknown;
Anders Carlsson0aebc812009-09-09 21:33:21 +0000972 if (isa<CXXConversionDecl>(FD))
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +0000973 CastKind = CastExpr::CK_UserDefinedConversion;
Anders Carlsson0aebc812009-09-09 21:33:21 +0000974 else if (isa<CXXConstructorDecl>(FD))
975 CastKind = CastExpr::CK_ConstructorConversion;
976 else
977 assert(0 && "Unknown conversion function kind!");
978
979 OwningExprResult CastArg
980 = BuildCXXCastArgument(From->getLocStart(),
981 ToType.getNonReferenceType(),
982 CastKind, cast<CXXMethodDecl>(FD),
983 Owned(From));
984
985 if (CastArg.isInvalid())
986 return true;
987
988 From = new (Context) ImplicitCastExpr(ToType.getNonReferenceType(),
989 CastKind, CastArg.takeAs<Expr>(),
990 ToType->isLValueReferenceType());
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +0000991 return false;
992 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000993
994 case ImplicitConversionSequence::EllipsisConversion:
995 assert(false && "Cannot perform an ellipsis conversion");
Douglas Gregor60d62c22008-10-31 16:23:19 +0000996 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000997
998 case ImplicitConversionSequence::BadConversion:
999 return true;
1000 }
1001
1002 // Everything went well.
1003 return false;
1004}
1005
1006/// PerformImplicitConversion - Perform an implicit conversion of the
1007/// expression From to the type ToType by following the standard
1008/// conversion sequence SCS. Returns true if there was an error, false
1009/// otherwise. The expression From is replaced with the converted
Douglas Gregor45920e82008-12-19 17:40:08 +00001010/// expression. Flavor is the context in which we're performing this
1011/// conversion, for use in error messages.
Mike Stump1eb44332009-09-09 15:08:12 +00001012bool
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001013Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor45920e82008-12-19 17:40:08 +00001014 const StandardConversionSequence& SCS,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001015 const char *Flavor) {
Mike Stump390b4cc2009-05-16 07:39:55 +00001016 // Overall FIXME: we are recomputing too many types here and doing far too
1017 // much extra work. What this means is that we need to keep track of more
1018 // information that is computed when we try the implicit conversion initially,
1019 // so that we don't need to recompute anything here.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001020 QualType FromType = From->getType();
1021
Douglas Gregor225c41e2008-11-03 19:09:14 +00001022 if (SCS.CopyConstructor) {
Anders Carlsson7c3e8a12009-05-19 04:45:15 +00001023 // FIXME: When can ToType be a reference type?
1024 assert(!ToType->isReferenceType());
Mike Stump1eb44332009-09-09 15:08:12 +00001025
1026 OwningExprResult FromResult =
1027 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1028 ToType, SCS.CopyConstructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00001029 MultiExprArg(*this, (void**)&From, 1));
Mike Stump1eb44332009-09-09 15:08:12 +00001030
Anders Carlssonda3f4e22009-08-25 05:12:04 +00001031 if (FromResult.isInvalid())
1032 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001033
Anders Carlssonda3f4e22009-08-25 05:12:04 +00001034 From = FromResult.takeAs<Expr>();
Douglas Gregor225c41e2008-11-03 19:09:14 +00001035 return false;
1036 }
1037
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001038 // Perform the first implicit conversion.
1039 switch (SCS.First) {
1040 case ICK_Identity:
1041 case ICK_Lvalue_To_Rvalue:
1042 // Nothing to do.
1043 break;
1044
1045 case ICK_Array_To_Pointer:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001046 FromType = Context.getArrayDecayedType(FromType);
Anders Carlsson82495762009-08-08 21:04:35 +00001047 ImpCastExprToType(From, FromType, CastExpr::CK_ArrayToPointerDecay);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001048 break;
1049
1050 case ICK_Function_To_Pointer:
Douglas Gregor063daf62009-03-13 18:40:31 +00001051 if (Context.getCanonicalType(FromType) == Context.OverloadTy) {
Douglas Gregor904eed32008-11-10 20:40:00 +00001052 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, true);
1053 if (!Fn)
1054 return true;
1055
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001056 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
1057 return true;
1058
Douglas Gregor904eed32008-11-10 20:40:00 +00001059 FixOverloadedFunctionReference(From, Fn);
1060 FromType = From->getType();
Douglas Gregor904eed32008-11-10 20:40:00 +00001061 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001062 FromType = Context.getPointerType(FromType);
Anders Carlssonb633c4e2009-09-01 20:37:18 +00001063 ImpCastExprToType(From, FromType, CastExpr::CK_FunctionToPointerDecay);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001064 break;
1065
1066 default:
1067 assert(false && "Improper first standard conversion");
1068 break;
1069 }
1070
1071 // Perform the second implicit conversion
1072 switch (SCS.Second) {
1073 case ICK_Identity:
1074 // Nothing to do.
1075 break;
1076
1077 case ICK_Integral_Promotion:
1078 case ICK_Floating_Promotion:
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001079 case ICK_Complex_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001080 case ICK_Integral_Conversion:
1081 case ICK_Floating_Conversion:
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001082 case ICK_Complex_Conversion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001083 case ICK_Floating_Integral:
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001084 case ICK_Complex_Real:
Douglas Gregorf9201e02009-02-11 23:02:49 +00001085 case ICK_Compatible_Conversion:
1086 // FIXME: Go deeper to get the unqualified type!
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001087 FromType = ToType.getUnqualifiedType();
1088 ImpCastExprToType(From, FromType);
1089 break;
1090
1091 case ICK_Pointer_Conversion:
Douglas Gregor45920e82008-12-19 17:40:08 +00001092 if (SCS.IncompatibleObjC) {
1093 // Diagnose incompatible Objective-C conversions
Mike Stump1eb44332009-09-09 15:08:12 +00001094 Diag(From->getSourceRange().getBegin(),
Douglas Gregor45920e82008-12-19 17:40:08 +00001095 diag::ext_typecheck_convert_incompatible_pointer)
1096 << From->getType() << ToType << Flavor
1097 << From->getSourceRange();
1098 }
1099
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001100 if (CheckPointerConversion(From, ToType))
1101 return true;
1102 ImpCastExprToType(From, ToType);
1103 break;
1104
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001105 case ICK_Pointer_Member: {
1106 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
1107 if (CheckMemberPointerConversion(From, ToType, Kind))
1108 return true;
1109 ImpCastExprToType(From, ToType, Kind);
1110 break;
1111 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001112 case ICK_Boolean_Conversion:
1113 FromType = Context.BoolTy;
1114 ImpCastExprToType(From, FromType);
1115 break;
1116
1117 default:
1118 assert(false && "Improper second standard conversion");
1119 break;
1120 }
1121
1122 switch (SCS.Third) {
1123 case ICK_Identity:
1124 // Nothing to do.
1125 break;
1126
1127 case ICK_Qualification:
Mike Stump390b4cc2009-05-16 07:39:55 +00001128 // FIXME: Not sure about lvalue vs rvalue here in the presence of rvalue
1129 // references.
Mike Stump1eb44332009-09-09 15:08:12 +00001130 ImpCastExprToType(From, ToType.getNonReferenceType(),
Anders Carlsson3503d042009-07-31 01:23:52 +00001131 CastExpr::CK_Unknown,
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001132 ToType->isLValueReferenceType());
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001133 break;
1134
1135 default:
1136 assert(false && "Improper second standard conversion");
1137 break;
1138 }
1139
1140 return false;
1141}
1142
Sebastian Redl64b45f72009-01-05 20:52:13 +00001143Sema::OwningExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
1144 SourceLocation KWLoc,
1145 SourceLocation LParen,
1146 TypeTy *Ty,
1147 SourceLocation RParen) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00001148 QualType T = GetTypeFromParser(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00001149
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001150 // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
1151 // all traits except __is_class, __is_enum and __is_union require a the type
1152 // to be complete.
1153 if (OTT != UTT_IsClass && OTT != UTT_IsEnum && OTT != UTT_IsUnion) {
Mike Stump1eb44332009-09-09 15:08:12 +00001154 if (RequireCompleteType(KWLoc, T,
Anders Carlssond497ba72009-08-26 22:59:12 +00001155 diag::err_incomplete_type_used_in_type_trait_expr))
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001156 return ExprError();
1157 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00001158
1159 // There is no point in eagerly computing the value. The traits are designed
1160 // to be used from type trait templates, so Ty will be a template parameter
1161 // 99% of the time.
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001162 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT, T,
1163 RParen, Context.BoolTy));
Sebastian Redl64b45f72009-01-05 20:52:13 +00001164}
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001165
1166QualType Sema::CheckPointerToMemberOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00001167 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001168 const char *OpSpelling = isIndirect ? "->*" : ".*";
1169 // C++ 5.5p2
1170 // The binary operator .* [p3: ->*] binds its second operand, which shall
1171 // be of type "pointer to member of T" (where T is a completely-defined
1172 // class type) [...]
1173 QualType RType = rex->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001174 const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
Douglas Gregore7450f52009-03-24 19:52:54 +00001175 if (!MemPtr) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001176 Diag(Loc, diag::err_bad_memptr_rhs)
1177 << OpSpelling << RType << rex->getSourceRange();
1178 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00001179 }
Douglas Gregore7450f52009-03-24 19:52:54 +00001180
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001181 QualType Class(MemPtr->getClass(), 0);
1182
1183 // C++ 5.5p2
1184 // [...] to its first operand, which shall be of class T or of a class of
1185 // which T is an unambiguous and accessible base class. [p3: a pointer to
1186 // such a class]
1187 QualType LType = lex->getType();
1188 if (isIndirect) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001189 if (const PointerType *Ptr = LType->getAs<PointerType>())
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001190 LType = Ptr->getPointeeType().getNonReferenceType();
1191 else {
1192 Diag(Loc, diag::err_bad_memptr_lhs)
1193 << OpSpelling << 1 << LType << lex->getSourceRange();
1194 return QualType();
1195 }
1196 }
1197
1198 if (Context.getCanonicalType(Class).getUnqualifiedType() !=
1199 Context.getCanonicalType(LType).getUnqualifiedType()) {
1200 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1201 /*DetectVirtual=*/false);
Mike Stump390b4cc2009-05-16 07:39:55 +00001202 // FIXME: Would it be useful to print full ambiguity paths, or is that
1203 // overkill?
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001204 if (!IsDerivedFrom(LType, Class, Paths) ||
1205 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
1206 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
1207 << (int)isIndirect << lex->getType() << lex->getSourceRange();
1208 return QualType();
1209 }
1210 }
1211
1212 // C++ 5.5p2
1213 // The result is an object or a function of the type specified by the
1214 // second operand.
1215 // The cv qualifiers are the union of those in the pointer and the left side,
1216 // in accordance with 5.5p5 and 5.2.5.
1217 // FIXME: This returns a dereferenced member function pointer as a normal
1218 // function type. However, the only operation valid on such functions is
Mike Stump390b4cc2009-05-16 07:39:55 +00001219 // calling them. There's also a GCC extension to get a function pointer to the
1220 // thing, which is another complication, because this type - unlike the type
1221 // that is the result of this expression - takes the class as the first
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001222 // argument.
1223 // We probably need a "MemberFunctionClosureType" or something like that.
1224 QualType Result = MemPtr->getPointeeType();
1225 if (LType.isConstQualified())
1226 Result.addConst();
1227 if (LType.isVolatileQualified())
1228 Result.addVolatile();
1229 return Result;
1230}
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001231
1232/// \brief Get the target type of a standard or user-defined conversion.
1233static QualType TargetType(const ImplicitConversionSequence &ICS) {
1234 assert((ICS.ConversionKind ==
1235 ImplicitConversionSequence::StandardConversion ||
1236 ICS.ConversionKind ==
1237 ImplicitConversionSequence::UserDefinedConversion) &&
1238 "function only valid for standard or user-defined conversions");
1239 if (ICS.ConversionKind == ImplicitConversionSequence::StandardConversion)
1240 return QualType::getFromOpaquePtr(ICS.Standard.ToTypePtr);
1241 return QualType::getFromOpaquePtr(ICS.UserDefined.After.ToTypePtr);
1242}
1243
1244/// \brief Try to convert a type to another according to C++0x 5.16p3.
1245///
1246/// This is part of the parameter validation for the ? operator. If either
1247/// value operand is a class type, the two operands are attempted to be
1248/// converted to each other. This function does the conversion in one direction.
1249/// It emits a diagnostic and returns true only if it finds an ambiguous
1250/// conversion.
1251static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
1252 SourceLocation QuestionLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00001253 ImplicitConversionSequence &ICS) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001254 // C++0x 5.16p3
1255 // The process for determining whether an operand expression E1 of type T1
1256 // can be converted to match an operand expression E2 of type T2 is defined
1257 // as follows:
1258 // -- If E2 is an lvalue:
1259 if (To->isLvalue(Self.Context) == Expr::LV_Valid) {
1260 // E1 can be converted to match E2 if E1 can be implicitly converted to
1261 // type "lvalue reference to T2", subject to the constraint that in the
1262 // conversion the reference must bind directly to E1.
1263 if (!Self.CheckReferenceInit(From,
1264 Self.Context.getLValueReferenceType(To->getType()),
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001265 /*SuppressUserConversions=*/false,
1266 /*AllowExplicit=*/false,
1267 /*ForceRValue=*/false,
1268 &ICS))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001269 {
1270 assert((ICS.ConversionKind ==
1271 ImplicitConversionSequence::StandardConversion ||
1272 ICS.ConversionKind ==
1273 ImplicitConversionSequence::UserDefinedConversion) &&
1274 "expected a definite conversion");
1275 bool DirectBinding =
1276 ICS.ConversionKind == ImplicitConversionSequence::StandardConversion ?
1277 ICS.Standard.DirectBinding : ICS.UserDefined.After.DirectBinding;
1278 if (DirectBinding)
1279 return false;
1280 }
1281 }
1282 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1283 // -- If E2 is an rvalue, or if the conversion above cannot be done:
1284 // -- if E1 and E2 have class type, and the underlying class types are
1285 // the same or one is a base class of the other:
1286 QualType FTy = From->getType();
1287 QualType TTy = To->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001288 const RecordType *FRec = FTy->getAs<RecordType>();
1289 const RecordType *TRec = TTy->getAs<RecordType>();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001290 bool FDerivedFromT = FRec && TRec && Self.IsDerivedFrom(FTy, TTy);
1291 if (FRec && TRec && (FRec == TRec ||
1292 FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
1293 // E1 can be converted to match E2 if the class of T2 is the
1294 // same type as, or a base class of, the class of T1, and
1295 // [cv2 > cv1].
1296 if ((FRec == TRec || FDerivedFromT) && TTy.isAtLeastAsQualifiedAs(FTy)) {
1297 // Could still fail if there's no copy constructor.
1298 // FIXME: Is this a hard error then, or just a conversion failure? The
1299 // standard doesn't say.
Mike Stump1eb44332009-09-09 15:08:12 +00001300 ICS = Self.TryCopyInitialization(From, TTy,
Anders Carlssond28b4282009-08-27 17:18:13 +00001301 /*SuppressUserConversions=*/false,
Anders Carlsson7b361b52009-08-27 17:37:39 +00001302 /*ForceRValue=*/false,
1303 /*InOverloadResolution=*/false);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001304 }
1305 } else {
1306 // -- Otherwise: E1 can be converted to match E2 if E1 can be
1307 // implicitly converted to the type that expression E2 would have
1308 // if E2 were converted to an rvalue.
1309 // First find the decayed type.
1310 if (TTy->isFunctionType())
1311 TTy = Self.Context.getPointerType(TTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001312 else if (TTy->isArrayType())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001313 TTy = Self.Context.getArrayDecayedType(TTy);
1314
1315 // Now try the implicit conversion.
1316 // FIXME: This doesn't detect ambiguities.
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001317 ICS = Self.TryImplicitConversion(From, TTy,
1318 /*SuppressUserConversions=*/false,
1319 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00001320 /*ForceRValue=*/false,
1321 /*InOverloadResolution=*/false);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001322 }
1323 return false;
1324}
1325
1326/// \brief Try to find a common type for two according to C++0x 5.16p5.
1327///
1328/// This is part of the parameter validation for the ? operator. If either
1329/// value operand is a class type, overload resolution is used to find a
1330/// conversion to a common type.
1331static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
1332 SourceLocation Loc) {
1333 Expr *Args[2] = { LHS, RHS };
1334 OverloadCandidateSet CandidateSet;
1335 Self.AddBuiltinOperatorCandidates(OO_Conditional, Args, 2, CandidateSet);
1336
1337 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00001338 switch (Self.BestViableFunction(CandidateSet, Loc, Best)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001339 case Sema::OR_Success:
1340 // We found a match. Perform the conversions on the arguments and move on.
1341 if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
1342 Best->Conversions[0], "converting") ||
1343 Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
1344 Best->Conversions[1], "converting"))
1345 break;
1346 return false;
1347
1348 case Sema::OR_No_Viable_Function:
1349 Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
1350 << LHS->getType() << RHS->getType()
1351 << LHS->getSourceRange() << RHS->getSourceRange();
1352 return true;
1353
1354 case Sema::OR_Ambiguous:
1355 Self.Diag(Loc, diag::err_conditional_ambiguous_ovl)
1356 << LHS->getType() << RHS->getType()
1357 << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stump390b4cc2009-05-16 07:39:55 +00001358 // FIXME: Print the possible common types by printing the return types of
1359 // the viable candidates.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001360 break;
1361
1362 case Sema::OR_Deleted:
1363 assert(false && "Conditional operator has only built-in overloads");
1364 break;
1365 }
1366 return true;
1367}
1368
Sebastian Redl76458502009-04-17 16:30:52 +00001369/// \brief Perform an "extended" implicit conversion as returned by
1370/// TryClassUnification.
1371///
1372/// TryClassUnification generates ICSs that include reference bindings.
1373/// PerformImplicitConversion is not suitable for this; it chokes if the
1374/// second part of a standard conversion is ICK_DerivedToBase. This function
1375/// handles the reference binding specially.
1376static bool ConvertForConditional(Sema &Self, Expr *&E,
Mike Stump1eb44332009-09-09 15:08:12 +00001377 const ImplicitConversionSequence &ICS) {
Sebastian Redl76458502009-04-17 16:30:52 +00001378 if (ICS.ConversionKind == ImplicitConversionSequence::StandardConversion &&
1379 ICS.Standard.ReferenceBinding) {
1380 assert(ICS.Standard.DirectBinding &&
1381 "TryClassUnification should never generate indirect ref bindings");
Sebastian Redla5cd2cd2009-04-26 11:21:02 +00001382 // FIXME: CheckReferenceInit should be able to reuse the ICS instead of
1383 // redoing all the work.
1384 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001385 TargetType(ICS)),
1386 /*SuppressUserConversions=*/false,
1387 /*AllowExplicit=*/false,
1388 /*ForceRValue=*/false);
Sebastian Redl76458502009-04-17 16:30:52 +00001389 }
1390 if (ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion &&
1391 ICS.UserDefined.After.ReferenceBinding) {
1392 assert(ICS.UserDefined.After.DirectBinding &&
1393 "TryClassUnification should never generate indirect ref bindings");
Sebastian Redla5cd2cd2009-04-26 11:21:02 +00001394 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001395 TargetType(ICS)),
1396 /*SuppressUserConversions=*/false,
1397 /*AllowExplicit=*/false,
1398 /*ForceRValue=*/false);
Sebastian Redl76458502009-04-17 16:30:52 +00001399 }
1400 if (Self.PerformImplicitConversion(E, TargetType(ICS), ICS, "converting"))
1401 return true;
1402 return false;
1403}
1404
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001405/// \brief Check the operands of ?: under C++ semantics.
1406///
1407/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
1408/// extension. In this case, LHS == Cond. (But they're not aliases.)
1409QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
1410 SourceLocation QuestionLoc) {
Mike Stump390b4cc2009-05-16 07:39:55 +00001411 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
1412 // interface pointers.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001413
1414 // C++0x 5.16p1
1415 // The first expression is contextually converted to bool.
1416 if (!Cond->isTypeDependent()) {
1417 if (CheckCXXBooleanCondition(Cond))
1418 return QualType();
1419 }
1420
1421 // Either of the arguments dependent?
1422 if (LHS->isTypeDependent() || RHS->isTypeDependent())
1423 return Context.DependentTy;
1424
1425 // C++0x 5.16p2
1426 // If either the second or the third operand has type (cv) void, ...
1427 QualType LTy = LHS->getType();
1428 QualType RTy = RHS->getType();
1429 bool LVoid = LTy->isVoidType();
1430 bool RVoid = RTy->isVoidType();
1431 if (LVoid || RVoid) {
1432 // ... then the [l2r] conversions are performed on the second and third
1433 // operands ...
1434 DefaultFunctionArrayConversion(LHS);
1435 DefaultFunctionArrayConversion(RHS);
1436 LTy = LHS->getType();
1437 RTy = RHS->getType();
1438
1439 // ... and one of the following shall hold:
1440 // -- The second or the third operand (but not both) is a throw-
1441 // expression; the result is of the type of the other and is an rvalue.
1442 bool LThrow = isa<CXXThrowExpr>(LHS);
1443 bool RThrow = isa<CXXThrowExpr>(RHS);
1444 if (LThrow && !RThrow)
1445 return RTy;
1446 if (RThrow && !LThrow)
1447 return LTy;
1448
1449 // -- Both the second and third operands have type void; the result is of
1450 // type void and is an rvalue.
1451 if (LVoid && RVoid)
1452 return Context.VoidTy;
1453
1454 // Neither holds, error.
1455 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
1456 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
1457 << LHS->getSourceRange() << RHS->getSourceRange();
1458 return QualType();
1459 }
1460
1461 // Neither is void.
1462
1463 // C++0x 5.16p3
1464 // Otherwise, if the second and third operand have different types, and
1465 // either has (cv) class type, and attempt is made to convert each of those
1466 // operands to the other.
1467 if (Context.getCanonicalType(LTy) != Context.getCanonicalType(RTy) &&
1468 (LTy->isRecordType() || RTy->isRecordType())) {
1469 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
1470 // These return true if a single direction is already ambiguous.
1471 if (TryClassUnification(*this, LHS, RHS, QuestionLoc, ICSLeftToRight))
1472 return QualType();
1473 if (TryClassUnification(*this, RHS, LHS, QuestionLoc, ICSRightToLeft))
1474 return QualType();
1475
1476 bool HaveL2R = ICSLeftToRight.ConversionKind !=
1477 ImplicitConversionSequence::BadConversion;
1478 bool HaveR2L = ICSRightToLeft.ConversionKind !=
1479 ImplicitConversionSequence::BadConversion;
1480 // If both can be converted, [...] the program is ill-formed.
1481 if (HaveL2R && HaveR2L) {
1482 Diag(QuestionLoc, diag::err_conditional_ambiguous)
1483 << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
1484 return QualType();
1485 }
1486
1487 // If exactly one conversion is possible, that conversion is applied to
1488 // the chosen operand and the converted operands are used in place of the
1489 // original operands for the remainder of this section.
1490 if (HaveL2R) {
Sebastian Redl76458502009-04-17 16:30:52 +00001491 if (ConvertForConditional(*this, LHS, ICSLeftToRight))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001492 return QualType();
1493 LTy = LHS->getType();
1494 } else if (HaveR2L) {
Sebastian Redl76458502009-04-17 16:30:52 +00001495 if (ConvertForConditional(*this, RHS, ICSRightToLeft))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001496 return QualType();
1497 RTy = RHS->getType();
1498 }
1499 }
1500
1501 // C++0x 5.16p4
1502 // If the second and third operands are lvalues and have the same type,
1503 // the result is of that type [...]
1504 bool Same = Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy);
1505 if (Same && LHS->isLvalue(Context) == Expr::LV_Valid &&
1506 RHS->isLvalue(Context) == Expr::LV_Valid)
1507 return LTy;
1508
1509 // C++0x 5.16p5
1510 // Otherwise, the result is an rvalue. If the second and third operands
1511 // do not have the same type, and either has (cv) class type, ...
1512 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
1513 // ... overload resolution is used to determine the conversions (if any)
1514 // to be applied to the operands. If the overload resolution fails, the
1515 // program is ill-formed.
1516 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
1517 return QualType();
1518 }
1519
1520 // C++0x 5.16p6
1521 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
1522 // conversions are performed on the second and third operands.
1523 DefaultFunctionArrayConversion(LHS);
1524 DefaultFunctionArrayConversion(RHS);
1525 LTy = LHS->getType();
1526 RTy = RHS->getType();
1527
1528 // After those conversions, one of the following shall hold:
1529 // -- The second and third operands have the same type; the result
1530 // is of that type.
1531 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy))
1532 return LTy;
1533
1534 // -- The second and third operands have arithmetic or enumeration type;
1535 // the usual arithmetic conversions are performed to bring them to a
1536 // common type, and the result is of that type.
1537 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
1538 UsualArithmeticConversions(LHS, RHS);
1539 return LHS->getType();
1540 }
1541
1542 // -- The second and third operands have pointer type, or one has pointer
1543 // type and the other is a null pointer constant; pointer conversions
1544 // and qualification conversions are performed to bring them to their
1545 // composite pointer type. The result is of the composite pointer type.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001546 QualType Composite = FindCompositePointerType(LHS, RHS);
1547 if (!Composite.isNull())
1548 return Composite;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001549
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001550 // Fourth bullet is same for pointers-to-member. However, the possible
1551 // conversions are far more limited: we have null-to-pointer, upcast of
1552 // containing class, and second-level cv-ness.
1553 // cv-ness is not a union, but must match one of the two operands. (Which,
1554 // frankly, is stupid.)
Ted Kremenek6217b802009-07-29 21:53:49 +00001555 const MemberPointerType *LMemPtr = LTy->getAs<MemberPointerType>();
1556 const MemberPointerType *RMemPtr = RTy->getAs<MemberPointerType>();
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001557 if (LMemPtr && RHS->isNullPointerConstant(Context)) {
1558 ImpCastExprToType(RHS, LTy);
1559 return LTy;
1560 }
1561 if (RMemPtr && LHS->isNullPointerConstant(Context)) {
1562 ImpCastExprToType(LHS, RTy);
1563 return RTy;
1564 }
1565 if (LMemPtr && RMemPtr) {
1566 QualType LPointee = LMemPtr->getPointeeType();
1567 QualType RPointee = RMemPtr->getPointeeType();
1568 // First, we check that the unqualified pointee type is the same. If it's
1569 // not, there's no conversion that will unify the two pointers.
1570 if (Context.getCanonicalType(LPointee).getUnqualifiedType() ==
1571 Context.getCanonicalType(RPointee).getUnqualifiedType()) {
1572 // Second, we take the greater of the two cv qualifications. If neither
1573 // is greater than the other, the conversion is not possible.
1574 unsigned Q = LPointee.getCVRQualifiers() | RPointee.getCVRQualifiers();
1575 if (Q == LPointee.getCVRQualifiers() || Q == RPointee.getCVRQualifiers()){
1576 // Third, we check if either of the container classes is derived from
1577 // the other.
1578 QualType LContainer(LMemPtr->getClass(), 0);
1579 QualType RContainer(RMemPtr->getClass(), 0);
1580 QualType MoreDerived;
1581 if (Context.getCanonicalType(LContainer) ==
1582 Context.getCanonicalType(RContainer))
1583 MoreDerived = LContainer;
1584 else if (IsDerivedFrom(LContainer, RContainer))
1585 MoreDerived = LContainer;
1586 else if (IsDerivedFrom(RContainer, LContainer))
1587 MoreDerived = RContainer;
1588
1589 if (!MoreDerived.isNull()) {
1590 // The type 'Q Pointee (MoreDerived::*)' is the common type.
1591 // We don't use ImpCastExprToType here because this could still fail
1592 // for ambiguous or inaccessible conversions.
1593 QualType Common = Context.getMemberPointerType(
1594 LPointee.getQualifiedType(Q), MoreDerived.getTypePtr());
1595 if (PerformImplicitConversion(LHS, Common, "converting"))
1596 return QualType();
1597 if (PerformImplicitConversion(RHS, Common, "converting"))
1598 return QualType();
1599 return Common;
1600 }
1601 }
1602 }
1603 }
1604
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001605 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
1606 << LHS->getType() << RHS->getType()
1607 << LHS->getSourceRange() << RHS->getSourceRange();
1608 return QualType();
1609}
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001610
1611/// \brief Find a merged pointer type and convert the two expressions to it.
1612///
Douglas Gregor20b3e992009-08-24 17:42:35 +00001613/// This finds the composite pointer type (or member pointer type) for @p E1
1614/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
1615/// type and returns it.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001616/// It does not emit diagnostics.
1617QualType Sema::FindCompositePointerType(Expr *&E1, Expr *&E2) {
1618 assert(getLangOptions().CPlusPlus && "This function assumes C++");
1619 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001620
Douglas Gregor20b3e992009-08-24 17:42:35 +00001621 if (!T1->isPointerType() && !T1->isMemberPointerType() &&
1622 !T2->isPointerType() && !T2->isMemberPointerType())
1623 return QualType();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001624
Douglas Gregor20b3e992009-08-24 17:42:35 +00001625 // FIXME: Do we need to work on the canonical types?
Mike Stump1eb44332009-09-09 15:08:12 +00001626
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001627 // C++0x 5.9p2
1628 // Pointer conversions and qualification conversions are performed on
1629 // pointer operands to bring them to their composite pointer type. If
1630 // one operand is a null pointer constant, the composite pointer type is
1631 // the type of the other operand.
1632 if (E1->isNullPointerConstant(Context)) {
1633 ImpCastExprToType(E1, T2);
1634 return T2;
1635 }
1636 if (E2->isNullPointerConstant(Context)) {
1637 ImpCastExprToType(E2, T1);
1638 return T1;
1639 }
Mike Stump1eb44332009-09-09 15:08:12 +00001640
Douglas Gregor20b3e992009-08-24 17:42:35 +00001641 // Now both have to be pointers or member pointers.
1642 if (!T1->isPointerType() && !T1->isMemberPointerType() &&
1643 !T2->isPointerType() && !T2->isMemberPointerType())
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001644 return QualType();
1645
1646 // Otherwise, of one of the operands has type "pointer to cv1 void," then
1647 // the other has type "pointer to cv2 T" and the composite pointer type is
1648 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
1649 // Otherwise, the composite pointer type is a pointer type similar to the
1650 // type of one of the operands, with a cv-qualification signature that is
1651 // the union of the cv-qualification signatures of the operand types.
1652 // In practice, the first part here is redundant; it's subsumed by the second.
1653 // What we do here is, we build the two possible composite types, and try the
1654 // conversions in both directions. If only one works, or if the two composite
1655 // types are the same, we have succeeded.
1656 llvm::SmallVector<unsigned, 4> QualifierUnion;
Douglas Gregor20b3e992009-08-24 17:42:35 +00001657 llvm::SmallVector<std::pair<const Type *, const Type *>, 4> MemberOfClass;
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001658 QualType Composite1 = T1, Composite2 = T2;
Douglas Gregor20b3e992009-08-24 17:42:35 +00001659 do {
1660 const PointerType *Ptr1, *Ptr2;
1661 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
1662 (Ptr2 = Composite2->getAs<PointerType>())) {
1663 Composite1 = Ptr1->getPointeeType();
1664 Composite2 = Ptr2->getPointeeType();
1665 QualifierUnion.push_back(
1666 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
1667 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
1668 continue;
1669 }
Mike Stump1eb44332009-09-09 15:08:12 +00001670
Douglas Gregor20b3e992009-08-24 17:42:35 +00001671 const MemberPointerType *MemPtr1, *MemPtr2;
1672 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
1673 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
1674 Composite1 = MemPtr1->getPointeeType();
1675 Composite2 = MemPtr2->getPointeeType();
1676 QualifierUnion.push_back(
1677 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
1678 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
1679 MemPtr2->getClass()));
1680 continue;
1681 }
Mike Stump1eb44332009-09-09 15:08:12 +00001682
Douglas Gregor20b3e992009-08-24 17:42:35 +00001683 // FIXME: block pointer types?
Mike Stump1eb44332009-09-09 15:08:12 +00001684
Douglas Gregor20b3e992009-08-24 17:42:35 +00001685 // Cannot unwrap any more types.
1686 break;
1687 } while (true);
Mike Stump1eb44332009-09-09 15:08:12 +00001688
Douglas Gregor20b3e992009-08-24 17:42:35 +00001689 // Rewrap the composites as pointers or member pointers with the union CVRs.
1690 llvm::SmallVector<std::pair<const Type *, const Type *>, 4>::iterator MOC
1691 = MemberOfClass.begin();
Mike Stump1eb44332009-09-09 15:08:12 +00001692 for (llvm::SmallVector<unsigned, 4>::iterator
Douglas Gregor20b3e992009-08-24 17:42:35 +00001693 I = QualifierUnion.begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00001694 E = QualifierUnion.end();
Douglas Gregor20b3e992009-08-24 17:42:35 +00001695 I != E; (void)++I, ++MOC) {
1696 if (MOC->first && MOC->second) {
1697 // Rebuild member pointer type
1698 Composite1 = Context.getMemberPointerType(Composite1.getQualifiedType(*I),
1699 MOC->first);
1700 Composite2 = Context.getMemberPointerType(Composite2.getQualifiedType(*I),
1701 MOC->second);
1702 } else {
1703 // Rebuild pointer type
1704 Composite1 = Context.getPointerType(Composite1.getQualifiedType(*I));
1705 Composite2 = Context.getPointerType(Composite2.getQualifiedType(*I));
1706 }
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001707 }
1708
Mike Stump1eb44332009-09-09 15:08:12 +00001709 ImplicitConversionSequence E1ToC1 =
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001710 TryImplicitConversion(E1, Composite1,
1711 /*SuppressUserConversions=*/false,
1712 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00001713 /*ForceRValue=*/false,
1714 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00001715 ImplicitConversionSequence E2ToC1 =
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001716 TryImplicitConversion(E2, Composite1,
1717 /*SuppressUserConversions=*/false,
1718 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00001719 /*ForceRValue=*/false,
1720 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00001721
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001722 ImplicitConversionSequence E1ToC2, E2ToC2;
1723 E1ToC2.ConversionKind = ImplicitConversionSequence::BadConversion;
1724 E2ToC2.ConversionKind = ImplicitConversionSequence::BadConversion;
1725 if (Context.getCanonicalType(Composite1) !=
1726 Context.getCanonicalType(Composite2)) {
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001727 E1ToC2 = TryImplicitConversion(E1, Composite2,
1728 /*SuppressUserConversions=*/false,
1729 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00001730 /*ForceRValue=*/false,
1731 /*InOverloadResolution=*/false);
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001732 E2ToC2 = TryImplicitConversion(E2, Composite2,
1733 /*SuppressUserConversions=*/false,
1734 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00001735 /*ForceRValue=*/false,
1736 /*InOverloadResolution=*/false);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001737 }
1738
1739 bool ToC1Viable = E1ToC1.ConversionKind !=
1740 ImplicitConversionSequence::BadConversion
1741 && E2ToC1.ConversionKind !=
1742 ImplicitConversionSequence::BadConversion;
1743 bool ToC2Viable = E1ToC2.ConversionKind !=
1744 ImplicitConversionSequence::BadConversion
1745 && E2ToC2.ConversionKind !=
1746 ImplicitConversionSequence::BadConversion;
1747 if (ToC1Viable && !ToC2Viable) {
1748 if (!PerformImplicitConversion(E1, Composite1, E1ToC1, "converting") &&
1749 !PerformImplicitConversion(E2, Composite1, E2ToC1, "converting"))
1750 return Composite1;
1751 }
1752 if (ToC2Viable && !ToC1Viable) {
1753 if (!PerformImplicitConversion(E1, Composite2, E1ToC2, "converting") &&
1754 !PerformImplicitConversion(E2, Composite2, E2ToC2, "converting"))
1755 return Composite2;
1756 }
1757 return QualType();
1758}
Anders Carlsson165a0a02009-05-17 18:41:29 +00001759
Anders Carlssondef11992009-05-30 20:36:53 +00001760Sema::OwningExprResult Sema::MaybeBindToTemporary(Expr *E) {
Anders Carlsson089c2602009-08-15 23:41:35 +00001761 if (!Context.getLangOptions().CPlusPlus)
1762 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001763
Ted Kremenek6217b802009-07-29 21:53:49 +00001764 const RecordType *RT = E->getType()->getAs<RecordType>();
Anders Carlssondef11992009-05-30 20:36:53 +00001765 if (!RT)
1766 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001767
Anders Carlssondef11992009-05-30 20:36:53 +00001768 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1769 if (RD->hasTrivialDestructor())
1770 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001771
1772 CXXTemporary *Temp = CXXTemporary::Create(Context,
Anders Carlssondef11992009-05-30 20:36:53 +00001773 RD->getDestructor(Context));
Anders Carlsson860306e2009-05-30 21:21:49 +00001774 ExprTemporaries.push_back(Temp);
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00001775 if (CXXDestructorDecl *Destructor =
1776 const_cast<CXXDestructorDecl*>(RD->getDestructor(Context)))
1777 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
Anders Carlssondef11992009-05-30 20:36:53 +00001778 // FIXME: Add the temporary to the temporaries vector.
1779 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
1780}
1781
Mike Stump1eb44332009-09-09 15:08:12 +00001782Expr *Sema::MaybeCreateCXXExprWithTemporaries(Expr *SubExpr,
Anders Carlssonf54741e2009-06-16 03:37:31 +00001783 bool ShouldDestroyTemps) {
Anders Carlsson99ba36d2009-06-05 15:38:08 +00001784 assert(SubExpr && "sub expression can't be null!");
Mike Stump1eb44332009-09-09 15:08:12 +00001785
Anders Carlsson99ba36d2009-06-05 15:38:08 +00001786 if (ExprTemporaries.empty())
1787 return SubExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00001788
Anders Carlsson99ba36d2009-06-05 15:38:08 +00001789 Expr *E = CXXExprWithTemporaries::Create(Context, SubExpr,
Mike Stump1eb44332009-09-09 15:08:12 +00001790 &ExprTemporaries[0],
Anders Carlsson99ba36d2009-06-05 15:38:08 +00001791 ExprTemporaries.size(),
Anders Carlssonf54741e2009-06-16 03:37:31 +00001792 ShouldDestroyTemps);
Anders Carlsson99ba36d2009-06-05 15:38:08 +00001793 ExprTemporaries.clear();
Mike Stump1eb44332009-09-09 15:08:12 +00001794
Anders Carlsson99ba36d2009-06-05 15:38:08 +00001795 return E;
1796}
1797
Mike Stump1eb44332009-09-09 15:08:12 +00001798Sema::OwningExprResult
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001799Sema::ActOnStartCXXMemberReference(Scope *S, ExprArg Base, SourceLocation OpLoc,
1800 tok::TokenKind OpKind, TypeTy *&ObjectType) {
1801 // Since this might be a postfix expression, get rid of ParenListExprs.
1802 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
Mike Stump1eb44332009-09-09 15:08:12 +00001803
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001804 Expr *BaseExpr = (Expr*)Base.get();
1805 assert(BaseExpr && "no record expansion");
Mike Stump1eb44332009-09-09 15:08:12 +00001806
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001807 QualType BaseType = BaseExpr->getType();
1808 if (BaseType->isDependentType()) {
1809 // FIXME: member of the current instantiation
1810 ObjectType = BaseType.getAsOpaquePtr();
1811 return move(Base);
1812 }
Mike Stump1eb44332009-09-09 15:08:12 +00001813
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001814 // C++ [over.match.oper]p8:
Mike Stump1eb44332009-09-09 15:08:12 +00001815 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001816 // returned, with the original second operand.
1817 if (OpKind == tok::arrow) {
1818 while (BaseType->isRecordType()) {
1819 Base = BuildOverloadedArrowExpr(S, move(Base), BaseExpr->getExprLoc());
1820 BaseExpr = (Expr*)Base.get();
1821 if (BaseExpr == NULL)
1822 return ExprError();
1823 BaseType = BaseExpr->getType();
1824 }
1825 }
Mike Stump1eb44332009-09-09 15:08:12 +00001826
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001827 if (BaseType->isPointerType())
1828 BaseType = BaseType->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00001829
1830 // We could end up with various non-record types here, such as extended
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001831 // vector types or Objective-C interfaces. Just return early and let
1832 // ActOnMemberReferenceExpr do the work.
Douglas Gregorc68afe22009-09-03 21:38:09 +00001833 if (!BaseType->isRecordType()) {
1834 // C++ [basic.lookup.classref]p2:
1835 // [...] If the type of the object expression is of pointer to scalar
1836 // type, the unqualified-id is looked up in the context of the complete
1837 // postfix-expression.
1838 ObjectType = 0;
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001839 return move(Base);
Douglas Gregorc68afe22009-09-03 21:38:09 +00001840 }
Mike Stump1eb44332009-09-09 15:08:12 +00001841
Douglas Gregorc68afe22009-09-03 21:38:09 +00001842 // C++ [basic.lookup.classref]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00001843 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregorc68afe22009-09-03 21:38:09 +00001844 // unqualified-id, and the type of the object expres- sion is of a class
1845 // type C (or of pointer to a class type C), the unqualified-id is looked
1846 // up in the scope of class C. [...]
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001847 ObjectType = BaseType.getAsOpaquePtr();
Mike Stump1eb44332009-09-09 15:08:12 +00001848 return move(Base);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001849}
1850
Anders Carlssonec773872009-08-25 23:46:41 +00001851Sema::OwningExprResult
Anders Carlsson3aa4ca42009-08-26 17:36:19 +00001852Sema::ActOnDestructorReferenceExpr(Scope *S, ExprArg Base,
Anders Carlssonec773872009-08-25 23:46:41 +00001853 SourceLocation OpLoc,
1854 tok::TokenKind OpKind,
1855 SourceLocation ClassNameLoc,
1856 IdentifierInfo *ClassName,
Douglas Gregora78c5c32009-09-04 18:29:40 +00001857 const CXXScopeSpec &SS,
1858 bool HasTrailingLParen) {
1859 if (SS.isInvalid())
Anders Carlssonec773872009-08-25 23:46:41 +00001860 return ExprError();
Anders Carlsson2cf738f2009-08-26 19:22:42 +00001861
Douglas Gregora71d8192009-09-04 17:36:40 +00001862 QualType BaseType;
Douglas Gregora78c5c32009-09-04 18:29:40 +00001863 if (isUnknownSpecialization(SS))
1864 BaseType = Context.getTypenameType((NestedNameSpecifier *)SS.getScopeRep(),
Douglas Gregora71d8192009-09-04 17:36:40 +00001865 ClassName);
1866 else {
Douglas Gregora78c5c32009-09-04 18:29:40 +00001867 TypeTy *BaseTy = getTypeName(*ClassName, ClassNameLoc, S, &SS);
Douglas Gregora71d8192009-09-04 17:36:40 +00001868 if (!BaseTy) {
Mike Stump1eb44332009-09-09 15:08:12 +00001869 Diag(ClassNameLoc, diag::err_ident_in_pseudo_dtor_not_a_type)
Douglas Gregora71d8192009-09-04 17:36:40 +00001870 << ClassName;
1871 return ExprError();
1872 }
Mike Stump1eb44332009-09-09 15:08:12 +00001873
Douglas Gregora71d8192009-09-04 17:36:40 +00001874 BaseType = GetTypeFromParser(BaseTy);
Anders Carlsson2cf738f2009-08-26 19:22:42 +00001875 }
Mike Stump1eb44332009-09-09 15:08:12 +00001876
Anders Carlsson2cf738f2009-08-26 19:22:42 +00001877 CanQualType CanBaseType = Context.getCanonicalType(BaseType);
Mike Stump1eb44332009-09-09 15:08:12 +00001878 DeclarationName DtorName =
Anders Carlsson2cf738f2009-08-26 19:22:42 +00001879 Context.DeclarationNames.getCXXDestructorName(CanBaseType);
1880
Douglas Gregora78c5c32009-09-04 18:29:40 +00001881 OwningExprResult Result
1882 = BuildMemberReferenceExpr(S, move(Base), OpLoc, OpKind, ClassNameLoc,
1883 DtorName, DeclPtrTy(), &SS);
1884 if (Result.isInvalid() || HasTrailingLParen)
1885 return move(Result);
Mike Stump1eb44332009-09-09 15:08:12 +00001886
1887 // The only way a reference to a destructor can be used is to
Douglas Gregora78c5c32009-09-04 18:29:40 +00001888 // immediately call them. Since the next token is not a '(', produce a
1889 // diagnostic and build the call now.
1890 Expr *E = (Expr *)Result.get();
1891 SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(E->getLocEnd());
1892 Diag(E->getLocStart(), diag::err_dtor_expr_without_call)
1893 << isa<CXXPseudoDestructorExpr>(E)
1894 << CodeModificationHint::CreateInsertion(ExpectedLParenLoc, "()");
Mike Stump1eb44332009-09-09 15:08:12 +00001895
1896 return ActOnCallExpr(0, move(Result), ExpectedLParenLoc,
Douglas Gregora78c5c32009-09-04 18:29:40 +00001897 MultiExprArg(*this, 0, 0), 0, ExpectedLParenLoc);
Anders Carlssonec773872009-08-25 23:46:41 +00001898}
1899
Douglas Gregora6f0f9d2009-08-31 19:52:13 +00001900Sema::OwningExprResult
1901Sema::ActOnOverloadedOperatorReferenceExpr(Scope *S, ExprArg Base,
1902 SourceLocation OpLoc,
1903 tok::TokenKind OpKind,
1904 SourceLocation ClassNameLoc,
1905 OverloadedOperatorKind OverOpKind,
1906 const CXXScopeSpec *SS) {
1907 if (SS && SS->isInvalid())
1908 return ExprError();
1909
1910 DeclarationName Name =
1911 Context.DeclarationNames.getCXXOperatorName(OverOpKind);
1912
1913 return BuildMemberReferenceExpr(S, move(Base), OpLoc, OpKind, ClassNameLoc,
1914 Name, DeclPtrTy(), SS);
1915}
1916
1917Sema::OwningExprResult
1918Sema::ActOnConversionOperatorReferenceExpr(Scope *S, ExprArg Base,
1919 SourceLocation OpLoc,
1920 tok::TokenKind OpKind,
1921 SourceLocation ClassNameLoc,
1922 TypeTy *Ty,
1923 const CXXScopeSpec *SS) {
1924 if (SS && SS->isInvalid())
1925 return ExprError();
1926
1927 //FIXME: Preserve type source info.
1928 QualType ConvType = GetTypeFromParser(Ty);
1929 CanQualType ConvTypeCanon = Context.getCanonicalType(ConvType);
1930 DeclarationName ConvName =
1931 Context.DeclarationNames.getCXXConversionFunctionName(ConvTypeCanon);
1932
1933 return BuildMemberReferenceExpr(S, move(Base), OpLoc, OpKind, ClassNameLoc,
1934 ConvName, DeclPtrTy(), SS);
1935}
1936
Anders Carlsson0aebc812009-09-09 21:33:21 +00001937Sema::OwningExprResult Sema::BuildCXXCastArgument(SourceLocation CastLoc,
1938 QualType Ty,
1939 CastExpr::CastKind Kind,
1940 CXXMethodDecl *Method,
1941 ExprArg Arg) {
1942 Expr *From = Arg.takeAs<Expr>();
1943
1944 switch (Kind) {
1945 default: assert(0 && "Unhandled cast kind!");
1946 case CastExpr::CK_ConstructorConversion: {
Douglas Gregor39da0b82009-09-09 23:08:42 +00001947 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1948
1949 if (CompleteConstructorCall(cast<CXXConstructorDecl>(Method),
1950 MultiExprArg(*this, (void **)&From, 1),
1951 CastLoc, ConstructorArgs))
1952 return ExprError();
1953
Anders Carlsson0aebc812009-09-09 21:33:21 +00001954 return BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
Douglas Gregor39da0b82009-09-09 23:08:42 +00001955 move_arg(ConstructorArgs));
Anders Carlsson0aebc812009-09-09 21:33:21 +00001956 }
1957
1958 case CastExpr::CK_UserDefinedConversion: {
1959 // Create an implicit member expr to refer to the conversion operator.
1960 MemberExpr *ME =
1961 new (Context) MemberExpr(From, From->getType()->isPointerType(), Method,
1962 SourceLocation(), Method->getType());
1963
1964
1965 // And an implicit call expr that calls it.
1966 QualType ResultType = Method->getResultType().getNonReferenceType();
1967 CXXMemberCallExpr *CE =
1968 new (Context) CXXMemberCallExpr(Context, ME, 0, 0,
1969 ResultType,
1970 SourceLocation());
1971
1972 return Owned(CE);
1973 }
1974
1975 }
1976}
1977
Anders Carlsson165a0a02009-05-17 18:41:29 +00001978Sema::OwningExprResult Sema::ActOnFinishFullExpr(ExprArg Arg) {
1979 Expr *FullExpr = Arg.takeAs<Expr>();
Anders Carlsson99ba36d2009-06-05 15:38:08 +00001980 if (FullExpr)
Mike Stump1eb44332009-09-09 15:08:12 +00001981 FullExpr = MaybeCreateCXXExprWithTemporaries(FullExpr,
Anders Carlssonf54741e2009-06-16 03:37:31 +00001982 /*ShouldDestroyTemps=*/true);
Anders Carlsson165a0a02009-05-17 18:41:29 +00001983
Anders Carlssonec773872009-08-25 23:46:41 +00001984
Anders Carlsson165a0a02009-05-17 18:41:29 +00001985 return Owned(FullExpr);
1986}