blob: ec7b2c8e7f425c330ce0aecc01c3d5710a5f0cf1 [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
Douglas Gregor043cad22009-09-11 00:18:58 +0000329 // Every dimension shall be of constant size.
330 if (D.getNumTypeObjects() > 0 &&
331 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
332 for (unsigned I = 1, N = D.getNumTypeObjects(); I < N; ++I) {
333 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
334 break;
335
336 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
337 if (Expr *NumElts = (Expr *)Array.NumElts) {
338 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
339 !NumElts->isIntegerConstantExpr(Context)) {
340 Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst)
341 << NumElts->getSourceRange();
342 return ExprError();
343 }
344 }
345 }
346 }
347
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000348 //FIXME: Store DeclaratorInfo in CXXNew expression.
349 DeclaratorInfo *DInfo = 0;
350 QualType AllocType = GetTypeForDeclarator(D, /*Scope=*/0, &DInfo, Skip);
Chris Lattnereaaebc72009-04-25 08:06:05 +0000351 if (D.isInvalidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000352 return ExprError();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000353
Mike Stump1eb44332009-09-09 15:08:12 +0000354 return BuildCXXNew(StartLoc, UseGlobal,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000355 PlacementLParen,
Mike Stump1eb44332009-09-09 15:08:12 +0000356 move(PlacementArgs),
Douglas Gregor3433cf72009-05-21 00:00:09 +0000357 PlacementRParen,
358 ParenTypeId,
Mike Stump1eb44332009-09-09 15:08:12 +0000359 AllocType,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000360 D.getSourceRange().getBegin(),
361 D.getSourceRange(),
362 Owned(ArraySize),
363 ConstructorLParen,
364 move(ConstructorArgs),
365 ConstructorRParen);
366}
367
Mike Stump1eb44332009-09-09 15:08:12 +0000368Sema::OwningExprResult
Douglas Gregor3433cf72009-05-21 00:00:09 +0000369Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
370 SourceLocation PlacementLParen,
371 MultiExprArg PlacementArgs,
372 SourceLocation PlacementRParen,
Mike Stump1eb44332009-09-09 15:08:12 +0000373 bool ParenTypeId,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000374 QualType AllocType,
375 SourceLocation TypeLoc,
376 SourceRange TypeRange,
377 ExprArg ArraySizeE,
378 SourceLocation ConstructorLParen,
379 MultiExprArg ConstructorArgs,
380 SourceLocation ConstructorRParen) {
381 if (CheckAllocatedType(AllocType, TypeLoc, TypeRange))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000382 return ExprError();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000383
Douglas Gregor3433cf72009-05-21 00:00:09 +0000384 QualType ResultType = Context.getPointerType(AllocType);
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000385
386 // That every array dimension except the first is constant was already
387 // checked by the type check above.
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000388
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000389 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
390 // or enumeration type with a non-negative value."
Douglas Gregor3433cf72009-05-21 00:00:09 +0000391 Expr *ArraySize = (Expr *)ArraySizeE.get();
Sebastian Redl28507842009-02-26 14:39:58 +0000392 if (ArraySize && !ArraySize->isTypeDependent()) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000393 QualType SizeType = ArraySize->getType();
394 if (!SizeType->isIntegralType() && !SizeType->isEnumeralType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000395 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
396 diag::err_array_size_not_integral)
397 << SizeType << ArraySize->getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000398 // Let's see if this is a constant < 0. If so, we reject it out of hand.
399 // We don't care about special rules, so we tell the machinery it's not
400 // evaluated - it gives us a result in more cases.
Sebastian Redl28507842009-02-26 14:39:58 +0000401 if (!ArraySize->isValueDependent()) {
402 llvm::APSInt Value;
403 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
404 if (Value < llvm::APSInt(
405 llvm::APInt::getNullValue(Value.getBitWidth()), false))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000406 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
407 diag::err_typecheck_negative_array_size)
408 << ArraySize->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +0000409 }
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000410 }
411 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000412
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000413 FunctionDecl *OperatorNew = 0;
414 FunctionDecl *OperatorDelete = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000415 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
416 unsigned NumPlaceArgs = PlacementArgs.size();
Sebastian Redl28507842009-02-26 14:39:58 +0000417 if (!AllocType->isDependentType() &&
418 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
419 FindAllocationFunctions(StartLoc,
Sebastian Redl00e68e22009-02-09 18:24:27 +0000420 SourceRange(PlacementLParen, PlacementRParen),
421 UseGlobal, AllocType, ArraySize, PlaceArgs,
422 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000423 return ExprError();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000424
425 bool Init = ConstructorLParen.isValid();
426 // --- Choosing a constructor ---
427 // C++ 5.3.4p15
428 // 1) If T is a POD and there's no initializer (ConstructorLParen is invalid)
429 // the object is not initialized. If the object, or any part of it, is
430 // const-qualified, it's an error.
431 // 2) If T is a POD and there's an empty initializer, the object is value-
432 // initialized.
433 // 3) If T is a POD and there's one initializer argument, the object is copy-
434 // constructed.
435 // 4) If T is a POD and there's more initializer arguments, it's an error.
436 // 5) If T is not a POD, the initializer arguments are used as constructor
437 // arguments.
438 //
439 // Or by the C++0x formulation:
440 // 1) If there's no initializer, the object is default-initialized according
441 // to C++0x rules.
442 // 2) Otherwise, the object is direct-initialized.
443 CXXConstructorDecl *Constructor = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000444 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
Sebastian Redl4f149632009-05-07 16:14:23 +0000445 const RecordType *RT;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000446 unsigned NumConsArgs = ConstructorArgs.size();
Sebastian Redl28507842009-02-26 14:39:58 +0000447 if (AllocType->isDependentType()) {
448 // Skip all the checks.
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000449 } else if ((RT = AllocType->getAs<RecordType>()) &&
450 !AllocType->isAggregateType()) {
Douglas Gregor39da0b82009-09-09 23:08:42 +0000451 ASTOwningVector<&ActionBase::DeleteExpr> ConvertedConstructorArgs(*this);
452
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000453 Constructor = PerformInitializationByConstructor(
Douglas Gregor39da0b82009-09-09 23:08:42 +0000454 AllocType, move(ConstructorArgs),
Douglas Gregor3433cf72009-05-21 00:00:09 +0000455 TypeLoc,
456 SourceRange(TypeLoc, ConstructorRParen),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000457 RT->getDecl()->getDeclName(),
Douglas Gregor39da0b82009-09-09 23:08:42 +0000458 NumConsArgs != 0 ? IK_Direct : IK_Default,
459 ConvertedConstructorArgs);
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000460 if (!Constructor)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000461 return ExprError();
Douglas Gregor39da0b82009-09-09 23:08:42 +0000462
463 // Take the converted constructor arguments and use them for the new
464 // expression.
465 NumConsArgs = ConvertedConstructorArgs.size();
466 ConsArgs = (Expr **)ConvertedConstructorArgs.take();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000467 } else {
468 if (!Init) {
469 // FIXME: Check that no subpart is const.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000470 if (AllocType.isConstQualified())
471 return ExprError(Diag(StartLoc, diag::err_new_uninitialized_const)
Douglas Gregor3433cf72009-05-21 00:00:09 +0000472 << TypeRange);
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000473 } else if (NumConsArgs == 0) {
474 // Object is value-initialized. Do nothing.
475 } else if (NumConsArgs == 1) {
476 // Object is direct-initialized.
Sebastian Redl4f149632009-05-07 16:14:23 +0000477 // FIXME: What DeclarationName do we pass in here?
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000478 if (CheckInitializerTypes(ConsArgs[0], AllocType, StartLoc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000479 DeclarationName() /*AllocType.getAsString()*/,
480 /*DirectInit=*/true))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000481 return ExprError();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000482 } else {
Sebastian Redlf53597f2009-03-15 17:47:39 +0000483 return ExprError(Diag(StartLoc,
484 diag::err_builtin_direct_init_more_than_one_arg)
485 << SourceRange(ConstructorLParen, ConstructorRParen));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000486 }
487 }
488
489 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
490
Sebastian Redlf53597f2009-03-15 17:47:39 +0000491 PlacementArgs.release();
492 ConstructorArgs.release();
Douglas Gregor3433cf72009-05-21 00:00:09 +0000493 ArraySizeE.release();
Sebastian Redlf53597f2009-03-15 17:47:39 +0000494 return Owned(new (Context) CXXNewExpr(UseGlobal, OperatorNew, PlaceArgs,
Ted Kremenek8189cde2009-02-07 01:47:29 +0000495 NumPlaceArgs, ParenTypeId, ArraySize, Constructor, Init,
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000496 ConsArgs, NumConsArgs, OperatorDelete, ResultType,
Mike Stump1eb44332009-09-09 15:08:12 +0000497 StartLoc, Init ? ConstructorRParen : SourceLocation()));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000498}
499
500/// CheckAllocatedType - Checks that a type is suitable as the allocated type
501/// in a new-expression.
502/// dimension off and stores the size expression in ArraySize.
Douglas Gregor3433cf72009-05-21 00:00:09 +0000503bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +0000504 SourceRange R) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000505 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
506 // abstract class type or array thereof.
Douglas Gregore7450f52009-03-24 19:52:54 +0000507 if (AllocType->isFunctionType())
Douglas Gregor3433cf72009-05-21 00:00:09 +0000508 return Diag(Loc, diag::err_bad_new_type)
509 << AllocType << 0 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +0000510 else if (AllocType->isReferenceType())
Douglas Gregor3433cf72009-05-21 00:00:09 +0000511 return Diag(Loc, diag::err_bad_new_type)
512 << AllocType << 1 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +0000513 else if (!AllocType->isDependentType() &&
Douglas Gregor3433cf72009-05-21 00:00:09 +0000514 RequireCompleteType(Loc, AllocType,
Anders Carlssonb7906612009-08-26 23:45:07 +0000515 PDiag(diag::err_new_incomplete_type)
516 << R))
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000517 return true;
Douglas Gregor3433cf72009-05-21 00:00:09 +0000518 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregore7450f52009-03-24 19:52:54 +0000519 diag::err_allocation_of_abstract_type))
520 return true;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000521
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000522 return false;
523}
524
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000525/// FindAllocationFunctions - Finds the overloads of operator new and delete
526/// that are appropriate for the allocation.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000527bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
528 bool UseGlobal, QualType AllocType,
529 bool IsArray, Expr **PlaceArgs,
530 unsigned NumPlaceArgs,
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000531 FunctionDecl *&OperatorNew,
Mike Stump1eb44332009-09-09 15:08:12 +0000532 FunctionDecl *&OperatorDelete) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000533 // --- Choosing an allocation function ---
534 // C++ 5.3.4p8 - 14 & 18
535 // 1) If UseGlobal is true, only look in the global scope. Else, also look
536 // in the scope of the allocated class.
537 // 2) If an array size is given, look for operator new[], else look for
538 // operator new.
539 // 3) The first argument is always size_t. Append the arguments from the
540 // placement form.
541 // FIXME: Also find the appropriate delete operator.
542
543 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
544 // We don't care about the actual value of this argument.
545 // FIXME: Should the Sema create the expression and embed it in the syntax
546 // tree? Or should the consumer just recalculate the value?
Anders Carlssond67c4c32009-08-16 20:29:29 +0000547 IntegerLiteral Size(llvm::APInt::getNullValue(
548 Context.Target.getPointerWidth(0)),
549 Context.getSizeType(),
550 SourceLocation());
551 AllocArgs[0] = &Size;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000552 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
553
554 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
555 IsArray ? OO_Array_New : OO_New);
556 if (AllocType->isRecordType() && !UseGlobal) {
Mike Stump1eb44332009-09-09 15:08:12 +0000557 CXXRecordDecl *Record
Ted Kremenek6217b802009-07-29 21:53:49 +0000558 = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl());
Sebastian Redl7f662392008-12-04 22:20:51 +0000559 // FIXME: We fail to find inherited overloads.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000560 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000561 AllocArgs.size(), Record, /*AllowMissing=*/true,
562 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000563 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000564 }
565 if (!OperatorNew) {
566 // Didn't find a member overload. Look for a global one.
567 DeclareGlobalNewDelete();
Sebastian Redl7f662392008-12-04 22:20:51 +0000568 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl00e68e22009-02-09 18:24:27 +0000569 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000570 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
571 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000572 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000573 }
574
Anders Carlssond9583892009-05-31 20:26:12 +0000575 // FindAllocationOverload can change the passed in arguments, so we need to
576 // copy them back.
577 if (NumPlaceArgs > 0)
578 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
Mike Stump1eb44332009-09-09 15:08:12 +0000579
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000580 return false;
581}
582
Sebastian Redl7f662392008-12-04 22:20:51 +0000583/// FindAllocationOverload - Find an fitting overload for the allocation
584/// function in the specified scope.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000585bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
586 DeclarationName Name, Expr** Args,
587 unsigned NumArgs, DeclContext *Ctx,
Mike Stump1eb44332009-09-09 15:08:12 +0000588 bool AllowMissing, FunctionDecl *&Operator) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000589 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000590 llvm::tie(Alloc, AllocEnd) = Ctx->lookup(Name);
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000591 if (Alloc == AllocEnd) {
Sebastian Redl7f662392008-12-04 22:20:51 +0000592 if (AllowMissing)
593 return false;
Sebastian Redl7f662392008-12-04 22:20:51 +0000594 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +0000595 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +0000596 }
597
598 OverloadCandidateSet Candidates;
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000599 for (; Alloc != AllocEnd; ++Alloc) {
600 // Even member operator new/delete are implicitly treated as
601 // static, so don't use AddMemberCandidate.
602 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>(*Alloc))
603 AddOverloadCandidate(Fn, Args, NumArgs, Candidates,
604 /*SuppressUserConversions=*/false);
Sebastian Redl7f662392008-12-04 22:20:51 +0000605 }
606
607 // Do the resolution.
608 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +0000609 switch(BestViableFunction(Candidates, StartLoc, Best)) {
Sebastian Redl7f662392008-12-04 22:20:51 +0000610 case OR_Success: {
611 // Got one!
612 FunctionDecl *FnDecl = Best->Function;
613 // The first argument is size_t, and the first parameter must be size_t,
614 // too. This is checked on declaration and can be assumed. (It can't be
615 // asserted on, though, since invalid decls are left in there.)
616 for (unsigned i = 1; i < NumArgs; ++i) {
617 // FIXME: Passing word to diagnostic.
Anders Carlssonfc27d262009-05-31 19:49:47 +0000618 if (PerformCopyInitialization(Args[i],
Sebastian Redl7f662392008-12-04 22:20:51 +0000619 FnDecl->getParamDecl(i)->getType(),
620 "passing"))
621 return true;
622 }
623 Operator = FnDecl;
624 return false;
625 }
626
627 case OR_No_Viable_Function:
Sebastian Redl7f662392008-12-04 22:20:51 +0000628 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +0000629 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +0000630 PrintOverloadCandidates(Candidates, /*OnlyViable=*/false);
631 return true;
632
633 case OR_Ambiguous:
Sebastian Redl7f662392008-12-04 22:20:51 +0000634 Diag(StartLoc, diag::err_ovl_ambiguous_call)
Sebastian Redl00e68e22009-02-09 18:24:27 +0000635 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +0000636 PrintOverloadCandidates(Candidates, /*OnlyViable=*/true);
637 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000638
639 case OR_Deleted:
640 Diag(StartLoc, diag::err_ovl_deleted_call)
641 << Best->Function->isDeleted()
642 << Name << Range;
643 PrintOverloadCandidates(Candidates, /*OnlyViable=*/true);
644 return true;
Sebastian Redl7f662392008-12-04 22:20:51 +0000645 }
646 assert(false && "Unreachable, bad result from BestViableFunction");
647 return true;
648}
649
650
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000651/// DeclareGlobalNewDelete - Declare the global forms of operator new and
652/// delete. These are:
653/// @code
654/// void* operator new(std::size_t) throw(std::bad_alloc);
655/// void* operator new[](std::size_t) throw(std::bad_alloc);
656/// void operator delete(void *) throw();
657/// void operator delete[](void *) throw();
658/// @endcode
659/// Note that the placement and nothrow forms of new are *not* implicitly
660/// declared. Their use requires including \<new\>.
Mike Stump1eb44332009-09-09 15:08:12 +0000661void Sema::DeclareGlobalNewDelete() {
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000662 if (GlobalNewDeleteDeclared)
663 return;
664 GlobalNewDeleteDeclared = true;
665
666 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
667 QualType SizeT = Context.getSizeType();
668
669 // FIXME: Exception specifications are not added.
670 DeclareGlobalAllocationFunction(
671 Context.DeclarationNames.getCXXOperatorName(OO_New),
672 VoidPtr, SizeT);
673 DeclareGlobalAllocationFunction(
674 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
675 VoidPtr, SizeT);
676 DeclareGlobalAllocationFunction(
677 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
678 Context.VoidTy, VoidPtr);
679 DeclareGlobalAllocationFunction(
680 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
681 Context.VoidTy, VoidPtr);
682}
683
684/// DeclareGlobalAllocationFunction - Declares a single implicit global
685/// allocation function if it doesn't already exist.
686void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Mike Stump1eb44332009-09-09 15:08:12 +0000687 QualType Return, QualType Argument) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000688 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
689
690 // Check if this function is already declared.
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000691 {
Douglas Gregor5cc37092008-12-23 22:05:29 +0000692 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000693 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000694 Alloc != AllocEnd; ++Alloc) {
695 // FIXME: Do we need to check for default arguments here?
696 FunctionDecl *Func = cast<FunctionDecl>(*Alloc);
697 if (Func->getNumParams() == 1 &&
Ted Kremenek8189cde2009-02-07 01:47:29 +0000698 Context.getCanonicalType(Func->getParamDecl(0)->getType())==Argument)
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000699 return;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000700 }
701 }
702
703 QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0);
704 FunctionDecl *Alloc =
705 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +0000706 FnType, /*DInfo=*/0, FunctionDecl::None, false, true);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000707 Alloc->setImplicit();
708 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000709 0, Argument, /*DInfo=*/0,
710 VarDecl::None, 0);
Ted Kremenekfc767612009-01-14 00:42:25 +0000711 Alloc->setParams(Context, &Param, 1);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000712
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000713 // FIXME: Also add this declaration to the IdentifierResolver, but
714 // make sure it is at the end of the chain to coincide with the
715 // global scope.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000716 ((DeclContext *)TUScope->getEntity())->addDecl(Alloc);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000717}
718
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000719/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
720/// @code ::delete ptr; @endcode
721/// or
722/// @code delete [] ptr; @endcode
Sebastian Redlf53597f2009-03-15 17:47:39 +0000723Action::OwningExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000724Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
Mike Stump1eb44332009-09-09 15:08:12 +0000725 bool ArrayForm, ExprArg Operand) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000726 // C++ [expr.delete]p1:
727 // The operand shall have a pointer type, or a class type having a single
728 // conversion function to a pointer type. The result has type void.
729 //
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000730 // DR599 amends "pointer type" to "pointer to object type" in both cases.
731
Anders Carlssond67c4c32009-08-16 20:29:29 +0000732 FunctionDecl *OperatorDelete = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000733
Sebastian Redlf53597f2009-03-15 17:47:39 +0000734 Expr *Ex = (Expr *)Operand.get();
Sebastian Redl28507842009-02-26 14:39:58 +0000735 if (!Ex->isTypeDependent()) {
736 QualType Type = Ex->getType();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000737
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000738 if (const RecordType *Record = Type->getAs<RecordType>()) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000739 llvm::SmallVector<CXXConversionDecl *, 4> ObjectPtrConversions;
Fariborz Jahanian53462782009-09-11 21:44:33 +0000740 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
741 OverloadedFunctionDecl *Conversions =
Fariborz Jahanian62509212009-09-12 18:26:03 +0000742 RD->getVisibleConversionFunctions();
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000743
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000744 for (OverloadedFunctionDecl::function_iterator
745 Func = Conversions->function_begin(),
746 FuncEnd = Conversions->function_end();
747 Func != FuncEnd; ++Func) {
748 // Skip over templated conversion functions; they aren't considered.
749 if (isa<FunctionTemplateDecl>(*Func))
750 continue;
751
752 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
753
754 QualType ConvType = Conv->getConversionType().getNonReferenceType();
755 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
756 if (ConvPtrType->getPointeeType()->isObjectType())
757 ObjectPtrConversions.push_back(Conv);
758 }
759
760 if (ObjectPtrConversions.size() == 1) {
761 // We have a single conversion to a pointer-to-object type. Perform
762 // that conversion.
763 Operand.release();
764 if (PerformImplicitConversion(Ex,
765 ObjectPtrConversions.front()->getConversionType(),
766 "converting"))
767 return ExprError();
768
769 Operand = Owned(Ex);
770 Type = Ex->getType();
771 }
Sebastian Redl28507842009-02-26 14:39:58 +0000772 }
773
Sebastian Redlf53597f2009-03-15 17:47:39 +0000774 if (!Type->isPointerType())
775 return ExprError(Diag(StartLoc, diag::err_delete_operand)
776 << Type << Ex->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +0000777
Ted Kremenek6217b802009-07-29 21:53:49 +0000778 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Douglas Gregor8dcb29d2009-03-24 20:13:58 +0000779 if (Pointee->isFunctionType() || Pointee->isVoidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000780 return ExprError(Diag(StartLoc, diag::err_delete_operand)
781 << Type << Ex->getSourceRange());
Douglas Gregor8dcb29d2009-03-24 20:13:58 +0000782 else if (!Pointee->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +0000783 RequireCompleteType(StartLoc, Pointee,
Anders Carlssonb7906612009-08-26 23:45:07 +0000784 PDiag(diag::warn_delete_incomplete)
785 << Ex->getSourceRange()))
Douglas Gregor8dcb29d2009-03-24 20:13:58 +0000786 return ExprError();
Sebastian Redl28507842009-02-26 14:39:58 +0000787
Mike Stump1eb44332009-09-09 15:08:12 +0000788 // FIXME: This should be shared with the code for finding the delete
Anders Carlssond67c4c32009-08-16 20:29:29 +0000789 // operator in ActOnCXXNew.
790 IntegerLiteral Size(llvm::APInt::getNullValue(
791 Context.Target.getPointerWidth(0)),
792 Context.getSizeType(),
793 SourceLocation());
794 ImplicitCastExpr Cast(Context.getPointerType(Context.VoidTy),
795 CastExpr::CK_Unknown, &Size, false);
796 Expr *DeleteArg = &Cast;
Mike Stump1eb44332009-09-09 15:08:12 +0000797
Anders Carlssond67c4c32009-08-16 20:29:29 +0000798 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
799 ArrayForm ? OO_Array_Delete : OO_Delete);
800
801 if (Pointee->isRecordType() && !UseGlobal) {
Mike Stump1eb44332009-09-09 15:08:12 +0000802 CXXRecordDecl *Record
Anders Carlssond67c4c32009-08-16 20:29:29 +0000803 = cast<CXXRecordDecl>(Pointee->getAs<RecordType>()->getDecl());
804 // FIXME: We fail to find inherited overloads.
805 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
806 &DeleteArg, 1, Record, /*AllowMissing=*/true,
807 OperatorDelete))
808 return ExprError();
Fariborz Jahanian34374e62009-09-03 23:18:17 +0000809 if (!Record->hasTrivialDestructor())
810 if (const CXXDestructorDecl *Dtor = Record->getDestructor(Context))
Mike Stump1eb44332009-09-09 15:08:12 +0000811 MarkDeclarationReferenced(StartLoc,
Fariborz Jahanian34374e62009-09-03 23:18:17 +0000812 const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssond67c4c32009-08-16 20:29:29 +0000813 }
Mike Stump1eb44332009-09-09 15:08:12 +0000814
Anders Carlssond67c4c32009-08-16 20:29:29 +0000815 if (!OperatorDelete) {
816 // Didn't find a member overload. Look for a global one.
817 DeclareGlobalNewDelete();
818 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000819 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
Anders Carlssond67c4c32009-08-16 20:29:29 +0000820 &DeleteArg, 1, TUDecl, /*AllowMissing=*/false,
821 OperatorDelete))
822 return ExprError();
823 }
Mike Stump1eb44332009-09-09 15:08:12 +0000824
Sebastian Redl28507842009-02-26 14:39:58 +0000825 // FIXME: Check access and ambiguity of operator delete and destructor.
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000826 }
827
Sebastian Redlf53597f2009-03-15 17:47:39 +0000828 Operand.release();
829 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
Anders Carlssond67c4c32009-08-16 20:29:29 +0000830 OperatorDelete, Ex, StartLoc));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000831}
832
833
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000834/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
835/// C++ if/switch/while/for statement.
836/// e.g: "if (int x = f()) {...}"
Sebastian Redlf53597f2009-03-15 17:47:39 +0000837Action::OwningExprResult
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000838Sema::ActOnCXXConditionDeclarationExpr(Scope *S, SourceLocation StartLoc,
839 Declarator &D,
840 SourceLocation EqualLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000841 ExprArg AssignExprVal) {
842 assert(AssignExprVal.get() && "Null assignment expression");
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000843
844 // C++ 6.4p2:
845 // The declarator shall not specify a function or an array.
846 // The type-specifier-seq shall not contain typedef and shall not declare a
847 // new class or enumeration.
848
849 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
850 "Parser allowed 'typedef' as storage class of condition decl.");
851
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000852 // FIXME: Store DeclaratorInfo in the expression.
853 DeclaratorInfo *DInfo = 0;
Argyrios Kyrtzidise955e722009-08-11 05:20:41 +0000854 TagDecl *OwnedTag = 0;
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000855 QualType Ty = GetTypeForDeclarator(D, S, &DInfo, /*Skip=*/0, &OwnedTag);
Mike Stump1eb44332009-09-09 15:08:12 +0000856
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000857 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
858 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
859 // would be created and CXXConditionDeclExpr wants a VarDecl.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000860 return ExprError(Diag(StartLoc, diag::err_invalid_use_of_function_type)
861 << SourceRange(StartLoc, EqualLoc));
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000862 } else if (Ty->isArrayType()) { // ...or an array.
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000863 Diag(StartLoc, diag::err_invalid_use_of_array_type)
864 << SourceRange(StartLoc, EqualLoc);
Argyrios Kyrtzidise955e722009-08-11 05:20:41 +0000865 } else if (OwnedTag && OwnedTag->isDefinition()) {
866 // The type-specifier-seq shall not declare a new class or enumeration.
867 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000868 }
869
Douglas Gregor2e01cda2009-06-23 21:43:56 +0000870 DeclPtrTy Dcl = ActOnDeclarator(S, D);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000871 if (!Dcl)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000872 return ExprError();
Anders Carlssonf5dcd382009-05-30 21:37:25 +0000873 AddInitializerToDecl(Dcl, move(AssignExprVal), /*DirectInit=*/false);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000874
Douglas Gregorcaaf29a2008-12-10 23:01:14 +0000875 // Mark this variable as one that is declared within a conditional.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000876 // We know that the decl had to be a VarDecl because that is the only type of
877 // decl that can be assigned and the grammar requires an '='.
878 VarDecl *VD = cast<VarDecl>(Dcl.getAs<Decl>());
879 VD->setDeclaredInCondition(true);
880 return Owned(new (Context) CXXConditionDeclExpr(StartLoc, EqualLoc, VD));
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000881}
882
883/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
884bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
885 // C++ 6.4p4:
886 // The value of a condition that is an initialized declaration in a statement
887 // other than a switch statement is the value of the declared variable
888 // implicitly converted to type bool. If that conversion is ill-formed, the
889 // program is ill-formed.
890 // The value of a condition that is an expression is the value of the
891 // expression, implicitly converted to bool.
892 //
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000893 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000894}
Douglas Gregor77a52232008-09-12 00:47:35 +0000895
896/// Helper function to determine whether this is the (deprecated) C++
897/// conversion from a string literal to a pointer to non-const char or
898/// non-const wchar_t (for narrow and wide string literals,
899/// respectively).
Mike Stump1eb44332009-09-09 15:08:12 +0000900bool
Douglas Gregor77a52232008-09-12 00:47:35 +0000901Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
902 // Look inside the implicit cast, if it exists.
903 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
904 From = Cast->getSubExpr();
905
906 // A string literal (2.13.4) that is not a wide string literal can
907 // be converted to an rvalue of type "pointer to char"; a wide
908 // string literal can be converted to an rvalue of type "pointer
909 // to wchar_t" (C++ 4.2p2).
910 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From))
Ted Kremenek6217b802009-07-29 21:53:49 +0000911 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump1eb44332009-09-09 15:08:12 +0000912 if (const BuiltinType *ToPointeeType
Douglas Gregor77a52232008-09-12 00:47:35 +0000913 = ToPtrType->getPointeeType()->getAsBuiltinType()) {
914 // This conversion is considered only when there is an
915 // explicit appropriate pointer target type (C++ 4.2p2).
916 if (ToPtrType->getPointeeType().getCVRQualifiers() == 0 &&
917 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
918 (!StrLit->isWide() &&
919 (ToPointeeType->getKind() == BuiltinType::Char_U ||
920 ToPointeeType->getKind() == BuiltinType::Char_S))))
921 return true;
922 }
923
924 return false;
925}
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000926
927/// PerformImplicitConversion - Perform an implicit conversion of the
928/// expression From to the type ToType. Returns true if there was an
929/// error, false otherwise. The expression From is replaced with the
Douglas Gregor45920e82008-12-19 17:40:08 +0000930/// converted expression. Flavor is the kind of conversion we're
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000931/// performing, used in the error message. If @p AllowExplicit,
Sebastian Redle2b68332009-04-12 17:16:29 +0000932/// explicit user-defined conversions are permitted. @p Elidable should be true
933/// when called for copies which may be elided (C++ 12.8p15). C++0x overload
934/// resolution works differently in that case.
935bool
Douglas Gregor45920e82008-12-19 17:40:08 +0000936Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Sebastian Redle2b68332009-04-12 17:16:29 +0000937 const char *Flavor, bool AllowExplicit,
Mike Stump1eb44332009-09-09 15:08:12 +0000938 bool Elidable) {
Sebastian Redle2b68332009-04-12 17:16:29 +0000939 ImplicitConversionSequence ICS;
940 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
941 if (Elidable && getLangOptions().CPlusPlus0x) {
Mike Stump1eb44332009-09-09 15:08:12 +0000942 ICS = TryImplicitConversion(From, ToType,
Anders Carlssonda7a18b2009-08-27 17:24:15 +0000943 /*SuppressUserConversions=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +0000944 AllowExplicit,
Anders Carlsson08972922009-08-28 15:33:32 +0000945 /*ForceRValue=*/true,
946 /*InOverloadResolution=*/false);
Sebastian Redle2b68332009-04-12 17:16:29 +0000947 }
948 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion) {
Mike Stump1eb44332009-09-09 15:08:12 +0000949 ICS = TryImplicitConversion(From, ToType,
Anders Carlssonda7a18b2009-08-27 17:24:15 +0000950 /*SuppressUserConversions=*/false,
951 AllowExplicit,
Anders Carlsson08972922009-08-28 15:33:32 +0000952 /*ForceRValue=*/false,
953 /*InOverloadResolution=*/false);
Sebastian Redle2b68332009-04-12 17:16:29 +0000954 }
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000955 return PerformImplicitConversion(From, ToType, ICS, Flavor);
956}
957
958/// PerformImplicitConversion - Perform an implicit conversion of the
959/// expression From to the type ToType using the pre-computed implicit
960/// conversion sequence ICS. Returns true if there was an error, false
961/// otherwise. The expression From is replaced with the converted
962/// expression. Flavor is the kind of conversion we're performing,
963/// used in the error message.
964bool
965Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
966 const ImplicitConversionSequence &ICS,
967 const char* Flavor) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000968 switch (ICS.ConversionKind) {
969 case ImplicitConversionSequence::StandardConversion:
Douglas Gregor45920e82008-12-19 17:40:08 +0000970 if (PerformImplicitConversion(From, ToType, ICS.Standard, Flavor))
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000971 return true;
972 break;
973
Anders Carlssonf6c213a2009-09-15 06:28:28 +0000974 case ImplicitConversionSequence::UserDefinedConversion: {
975
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +0000976 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
977 CastExpr::CastKind CastKind = CastExpr::CK_Unknown;
Anders Carlssonf6c213a2009-09-15 06:28:28 +0000978 QualType BeforeToType;
979 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +0000980 CastKind = CastExpr::CK_UserDefinedConversion;
Anders Carlssonf6c213a2009-09-15 06:28:28 +0000981
982 // If the user-defined conversion is specified by a conversion function,
983 // the initial standard conversion sequence converts the source type to
984 // the implicit object parameter of the conversion function.
985 BeforeToType = Context.getTagDeclType(Conv->getParent());
986 } else if (const CXXConstructorDecl *Ctor =
987 dyn_cast<CXXConstructorDecl>(FD)) {
Anders Carlsson0aebc812009-09-09 21:33:21 +0000988 CastKind = CastExpr::CK_ConstructorConversion;
Anders Carlssonf6c213a2009-09-15 06:28:28 +0000989
990 // If the user-defined conversion is specified by a constructor, the
991 // initial standard conversion sequence converts the source type to the
992 // type required by the argument of the constructor
993 BeforeToType = Ctor->getParamDecl(0)->getType();
994 }
Anders Carlsson0aebc812009-09-09 21:33:21 +0000995 else
996 assert(0 && "Unknown conversion function kind!");
997
Anders Carlssonf6c213a2009-09-15 06:28:28 +0000998 if (PerformImplicitConversion(From, BeforeToType,
999 ICS.UserDefined.Before, "converting"))
1000 return true;
1001
Anders Carlsson0aebc812009-09-09 21:33:21 +00001002 OwningExprResult CastArg
1003 = BuildCXXCastArgument(From->getLocStart(),
1004 ToType.getNonReferenceType(),
1005 CastKind, cast<CXXMethodDecl>(FD),
1006 Owned(From));
1007
1008 if (CastArg.isInvalid())
1009 return true;
1010
Anders Carlsson626c2d62009-09-15 05:49:31 +00001011 From = new (Context) ImplicitCastExpr(ToType.getNonReferenceType(),
1012 CastKind, CastArg.takeAs<Expr>(),
1013 ToType->isLValueReferenceType());
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00001014 return false;
1015 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001016
1017 case ImplicitConversionSequence::EllipsisConversion:
1018 assert(false && "Cannot perform an ellipsis conversion");
Douglas Gregor60d62c22008-10-31 16:23:19 +00001019 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001020
1021 case ImplicitConversionSequence::BadConversion:
1022 return true;
1023 }
1024
1025 // Everything went well.
1026 return false;
1027}
1028
1029/// PerformImplicitConversion - Perform an implicit conversion of the
1030/// expression From to the type ToType by following the standard
1031/// conversion sequence SCS. Returns true if there was an error, false
1032/// otherwise. The expression From is replaced with the converted
Douglas Gregor45920e82008-12-19 17:40:08 +00001033/// expression. Flavor is the context in which we're performing this
1034/// conversion, for use in error messages.
Mike Stump1eb44332009-09-09 15:08:12 +00001035bool
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001036Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor45920e82008-12-19 17:40:08 +00001037 const StandardConversionSequence& SCS,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001038 const char *Flavor) {
Mike Stump390b4cc2009-05-16 07:39:55 +00001039 // Overall FIXME: we are recomputing too many types here and doing far too
1040 // much extra work. What this means is that we need to keep track of more
1041 // information that is computed when we try the implicit conversion initially,
1042 // so that we don't need to recompute anything here.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001043 QualType FromType = From->getType();
1044
Douglas Gregor225c41e2008-11-03 19:09:14 +00001045 if (SCS.CopyConstructor) {
Anders Carlsson7c3e8a12009-05-19 04:45:15 +00001046 // FIXME: When can ToType be a reference type?
1047 assert(!ToType->isReferenceType());
Mike Stump1eb44332009-09-09 15:08:12 +00001048
1049 OwningExprResult FromResult =
1050 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1051 ToType, SCS.CopyConstructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00001052 MultiExprArg(*this, (void**)&From, 1));
Mike Stump1eb44332009-09-09 15:08:12 +00001053
Anders Carlssonda3f4e22009-08-25 05:12:04 +00001054 if (FromResult.isInvalid())
1055 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001056
Anders Carlssonda3f4e22009-08-25 05:12:04 +00001057 From = FromResult.takeAs<Expr>();
Douglas Gregor225c41e2008-11-03 19:09:14 +00001058 return false;
1059 }
1060
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001061 // Perform the first implicit conversion.
1062 switch (SCS.First) {
1063 case ICK_Identity:
1064 case ICK_Lvalue_To_Rvalue:
1065 // Nothing to do.
1066 break;
1067
1068 case ICK_Array_To_Pointer:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001069 FromType = Context.getArrayDecayedType(FromType);
Anders Carlsson82495762009-08-08 21:04:35 +00001070 ImpCastExprToType(From, FromType, CastExpr::CK_ArrayToPointerDecay);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001071 break;
1072
1073 case ICK_Function_To_Pointer:
Douglas Gregor063daf62009-03-13 18:40:31 +00001074 if (Context.getCanonicalType(FromType) == Context.OverloadTy) {
Douglas Gregor904eed32008-11-10 20:40:00 +00001075 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, true);
1076 if (!Fn)
1077 return true;
1078
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001079 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
1080 return true;
1081
Douglas Gregor904eed32008-11-10 20:40:00 +00001082 FixOverloadedFunctionReference(From, Fn);
1083 FromType = From->getType();
Douglas Gregor904eed32008-11-10 20:40:00 +00001084 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001085 FromType = Context.getPointerType(FromType);
Anders Carlssonb633c4e2009-09-01 20:37:18 +00001086 ImpCastExprToType(From, FromType, CastExpr::CK_FunctionToPointerDecay);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001087 break;
1088
1089 default:
1090 assert(false && "Improper first standard conversion");
1091 break;
1092 }
1093
1094 // Perform the second implicit conversion
1095 switch (SCS.Second) {
1096 case ICK_Identity:
1097 // Nothing to do.
1098 break;
1099
1100 case ICK_Integral_Promotion:
1101 case ICK_Floating_Promotion:
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001102 case ICK_Complex_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001103 case ICK_Integral_Conversion:
1104 case ICK_Floating_Conversion:
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001105 case ICK_Complex_Conversion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001106 case ICK_Floating_Integral:
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001107 case ICK_Complex_Real:
Douglas Gregorf9201e02009-02-11 23:02:49 +00001108 case ICK_Compatible_Conversion:
1109 // FIXME: Go deeper to get the unqualified type!
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001110 FromType = ToType.getUnqualifiedType();
1111 ImpCastExprToType(From, FromType);
1112 break;
1113
Anders Carlsson61faec12009-09-12 04:46:44 +00001114 case ICK_Pointer_Conversion: {
Douglas Gregor45920e82008-12-19 17:40:08 +00001115 if (SCS.IncompatibleObjC) {
1116 // Diagnose incompatible Objective-C conversions
Mike Stump1eb44332009-09-09 15:08:12 +00001117 Diag(From->getSourceRange().getBegin(),
Douglas Gregor45920e82008-12-19 17:40:08 +00001118 diag::ext_typecheck_convert_incompatible_pointer)
1119 << From->getType() << ToType << Flavor
1120 << From->getSourceRange();
1121 }
1122
Anders Carlsson61faec12009-09-12 04:46:44 +00001123
1124 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
1125 if (CheckPointerConversion(From, ToType, Kind))
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001126 return true;
Anders Carlsson61faec12009-09-12 04:46:44 +00001127 ImpCastExprToType(From, ToType, Kind);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001128 break;
Anders Carlsson61faec12009-09-12 04:46:44 +00001129 }
1130
1131 case ICK_Pointer_Member: {
1132 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
1133 if (CheckMemberPointerConversion(From, ToType, Kind))
1134 return true;
1135 ImpCastExprToType(From, ToType, Kind);
1136 break;
1137 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001138 case ICK_Boolean_Conversion:
1139 FromType = Context.BoolTy;
1140 ImpCastExprToType(From, FromType);
1141 break;
1142
1143 default:
1144 assert(false && "Improper second standard conversion");
1145 break;
1146 }
1147
1148 switch (SCS.Third) {
1149 case ICK_Identity:
1150 // Nothing to do.
1151 break;
1152
1153 case ICK_Qualification:
Mike Stump390b4cc2009-05-16 07:39:55 +00001154 // FIXME: Not sure about lvalue vs rvalue here in the presence of rvalue
1155 // references.
Mike Stump1eb44332009-09-09 15:08:12 +00001156 ImpCastExprToType(From, ToType.getNonReferenceType(),
Anders Carlsson3503d042009-07-31 01:23:52 +00001157 CastExpr::CK_Unknown,
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001158 ToType->isLValueReferenceType());
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001159 break;
1160
1161 default:
1162 assert(false && "Improper second standard conversion");
1163 break;
1164 }
1165
1166 return false;
1167}
1168
Sebastian Redl64b45f72009-01-05 20:52:13 +00001169Sema::OwningExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
1170 SourceLocation KWLoc,
1171 SourceLocation LParen,
1172 TypeTy *Ty,
1173 SourceLocation RParen) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00001174 QualType T = GetTypeFromParser(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00001175
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001176 // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
1177 // all traits except __is_class, __is_enum and __is_union require a the type
1178 // to be complete.
1179 if (OTT != UTT_IsClass && OTT != UTT_IsEnum && OTT != UTT_IsUnion) {
Mike Stump1eb44332009-09-09 15:08:12 +00001180 if (RequireCompleteType(KWLoc, T,
Anders Carlssond497ba72009-08-26 22:59:12 +00001181 diag::err_incomplete_type_used_in_type_trait_expr))
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001182 return ExprError();
1183 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00001184
1185 // There is no point in eagerly computing the value. The traits are designed
1186 // to be used from type trait templates, so Ty will be a template parameter
1187 // 99% of the time.
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001188 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT, T,
1189 RParen, Context.BoolTy));
Sebastian Redl64b45f72009-01-05 20:52:13 +00001190}
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001191
1192QualType Sema::CheckPointerToMemberOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00001193 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001194 const char *OpSpelling = isIndirect ? "->*" : ".*";
1195 // C++ 5.5p2
1196 // The binary operator .* [p3: ->*] binds its second operand, which shall
1197 // be of type "pointer to member of T" (where T is a completely-defined
1198 // class type) [...]
1199 QualType RType = rex->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001200 const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
Douglas Gregore7450f52009-03-24 19:52:54 +00001201 if (!MemPtr) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001202 Diag(Loc, diag::err_bad_memptr_rhs)
1203 << OpSpelling << RType << rex->getSourceRange();
1204 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00001205 }
Douglas Gregore7450f52009-03-24 19:52:54 +00001206
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001207 QualType Class(MemPtr->getClass(), 0);
1208
1209 // C++ 5.5p2
1210 // [...] to its first operand, which shall be of class T or of a class of
1211 // which T is an unambiguous and accessible base class. [p3: a pointer to
1212 // such a class]
1213 QualType LType = lex->getType();
1214 if (isIndirect) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001215 if (const PointerType *Ptr = LType->getAs<PointerType>())
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001216 LType = Ptr->getPointeeType().getNonReferenceType();
1217 else {
1218 Diag(Loc, diag::err_bad_memptr_lhs)
1219 << OpSpelling << 1 << LType << lex->getSourceRange();
1220 return QualType();
1221 }
1222 }
1223
1224 if (Context.getCanonicalType(Class).getUnqualifiedType() !=
1225 Context.getCanonicalType(LType).getUnqualifiedType()) {
1226 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1227 /*DetectVirtual=*/false);
Mike Stump390b4cc2009-05-16 07:39:55 +00001228 // FIXME: Would it be useful to print full ambiguity paths, or is that
1229 // overkill?
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001230 if (!IsDerivedFrom(LType, Class, Paths) ||
1231 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
1232 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
1233 << (int)isIndirect << lex->getType() << lex->getSourceRange();
1234 return QualType();
1235 }
1236 }
1237
1238 // C++ 5.5p2
1239 // The result is an object or a function of the type specified by the
1240 // second operand.
1241 // The cv qualifiers are the union of those in the pointer and the left side,
1242 // in accordance with 5.5p5 and 5.2.5.
1243 // FIXME: This returns a dereferenced member function pointer as a normal
1244 // function type. However, the only operation valid on such functions is
Mike Stump390b4cc2009-05-16 07:39:55 +00001245 // calling them. There's also a GCC extension to get a function pointer to the
1246 // thing, which is another complication, because this type - unlike the type
1247 // that is the result of this expression - takes the class as the first
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001248 // argument.
1249 // We probably need a "MemberFunctionClosureType" or something like that.
1250 QualType Result = MemPtr->getPointeeType();
1251 if (LType.isConstQualified())
1252 Result.addConst();
1253 if (LType.isVolatileQualified())
1254 Result.addVolatile();
1255 return Result;
1256}
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001257
1258/// \brief Get the target type of a standard or user-defined conversion.
1259static QualType TargetType(const ImplicitConversionSequence &ICS) {
1260 assert((ICS.ConversionKind ==
1261 ImplicitConversionSequence::StandardConversion ||
1262 ICS.ConversionKind ==
1263 ImplicitConversionSequence::UserDefinedConversion) &&
1264 "function only valid for standard or user-defined conversions");
1265 if (ICS.ConversionKind == ImplicitConversionSequence::StandardConversion)
1266 return QualType::getFromOpaquePtr(ICS.Standard.ToTypePtr);
1267 return QualType::getFromOpaquePtr(ICS.UserDefined.After.ToTypePtr);
1268}
1269
1270/// \brief Try to convert a type to another according to C++0x 5.16p3.
1271///
1272/// This is part of the parameter validation for the ? operator. If either
1273/// value operand is a class type, the two operands are attempted to be
1274/// converted to each other. This function does the conversion in one direction.
1275/// It emits a diagnostic and returns true only if it finds an ambiguous
1276/// conversion.
1277static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
1278 SourceLocation QuestionLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00001279 ImplicitConversionSequence &ICS) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001280 // C++0x 5.16p3
1281 // The process for determining whether an operand expression E1 of type T1
1282 // can be converted to match an operand expression E2 of type T2 is defined
1283 // as follows:
1284 // -- If E2 is an lvalue:
1285 if (To->isLvalue(Self.Context) == Expr::LV_Valid) {
1286 // E1 can be converted to match E2 if E1 can be implicitly converted to
1287 // type "lvalue reference to T2", subject to the constraint that in the
1288 // conversion the reference must bind directly to E1.
1289 if (!Self.CheckReferenceInit(From,
1290 Self.Context.getLValueReferenceType(To->getType()),
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001291 /*SuppressUserConversions=*/false,
1292 /*AllowExplicit=*/false,
1293 /*ForceRValue=*/false,
1294 &ICS))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001295 {
1296 assert((ICS.ConversionKind ==
1297 ImplicitConversionSequence::StandardConversion ||
1298 ICS.ConversionKind ==
1299 ImplicitConversionSequence::UserDefinedConversion) &&
1300 "expected a definite conversion");
1301 bool DirectBinding =
1302 ICS.ConversionKind == ImplicitConversionSequence::StandardConversion ?
1303 ICS.Standard.DirectBinding : ICS.UserDefined.After.DirectBinding;
1304 if (DirectBinding)
1305 return false;
1306 }
1307 }
1308 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1309 // -- If E2 is an rvalue, or if the conversion above cannot be done:
1310 // -- if E1 and E2 have class type, and the underlying class types are
1311 // the same or one is a base class of the other:
1312 QualType FTy = From->getType();
1313 QualType TTy = To->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001314 const RecordType *FRec = FTy->getAs<RecordType>();
1315 const RecordType *TRec = TTy->getAs<RecordType>();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001316 bool FDerivedFromT = FRec && TRec && Self.IsDerivedFrom(FTy, TTy);
1317 if (FRec && TRec && (FRec == TRec ||
1318 FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
1319 // E1 can be converted to match E2 if the class of T2 is the
1320 // same type as, or a base class of, the class of T1, and
1321 // [cv2 > cv1].
1322 if ((FRec == TRec || FDerivedFromT) && TTy.isAtLeastAsQualifiedAs(FTy)) {
1323 // Could still fail if there's no copy constructor.
1324 // FIXME: Is this a hard error then, or just a conversion failure? The
1325 // standard doesn't say.
Mike Stump1eb44332009-09-09 15:08:12 +00001326 ICS = Self.TryCopyInitialization(From, TTy,
Anders Carlssond28b4282009-08-27 17:18:13 +00001327 /*SuppressUserConversions=*/false,
Anders Carlsson7b361b52009-08-27 17:37:39 +00001328 /*ForceRValue=*/false,
1329 /*InOverloadResolution=*/false);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001330 }
1331 } else {
1332 // -- Otherwise: E1 can be converted to match E2 if E1 can be
1333 // implicitly converted to the type that expression E2 would have
1334 // if E2 were converted to an rvalue.
1335 // First find the decayed type.
1336 if (TTy->isFunctionType())
1337 TTy = Self.Context.getPointerType(TTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001338 else if (TTy->isArrayType())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001339 TTy = Self.Context.getArrayDecayedType(TTy);
1340
1341 // Now try the implicit conversion.
1342 // FIXME: This doesn't detect ambiguities.
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001343 ICS = Self.TryImplicitConversion(From, TTy,
1344 /*SuppressUserConversions=*/false,
1345 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00001346 /*ForceRValue=*/false,
1347 /*InOverloadResolution=*/false);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001348 }
1349 return false;
1350}
1351
1352/// \brief Try to find a common type for two according to C++0x 5.16p5.
1353///
1354/// This is part of the parameter validation for the ? operator. If either
1355/// value operand is a class type, overload resolution is used to find a
1356/// conversion to a common type.
1357static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
1358 SourceLocation Loc) {
1359 Expr *Args[2] = { LHS, RHS };
1360 OverloadCandidateSet CandidateSet;
1361 Self.AddBuiltinOperatorCandidates(OO_Conditional, Args, 2, CandidateSet);
1362
1363 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00001364 switch (Self.BestViableFunction(CandidateSet, Loc, Best)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001365 case Sema::OR_Success:
1366 // We found a match. Perform the conversions on the arguments and move on.
1367 if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
1368 Best->Conversions[0], "converting") ||
1369 Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
1370 Best->Conversions[1], "converting"))
1371 break;
1372 return false;
1373
1374 case Sema::OR_No_Viable_Function:
1375 Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
1376 << LHS->getType() << RHS->getType()
1377 << LHS->getSourceRange() << RHS->getSourceRange();
1378 return true;
1379
1380 case Sema::OR_Ambiguous:
1381 Self.Diag(Loc, diag::err_conditional_ambiguous_ovl)
1382 << LHS->getType() << RHS->getType()
1383 << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stump390b4cc2009-05-16 07:39:55 +00001384 // FIXME: Print the possible common types by printing the return types of
1385 // the viable candidates.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001386 break;
1387
1388 case Sema::OR_Deleted:
1389 assert(false && "Conditional operator has only built-in overloads");
1390 break;
1391 }
1392 return true;
1393}
1394
Sebastian Redl76458502009-04-17 16:30:52 +00001395/// \brief Perform an "extended" implicit conversion as returned by
1396/// TryClassUnification.
1397///
1398/// TryClassUnification generates ICSs that include reference bindings.
1399/// PerformImplicitConversion is not suitable for this; it chokes if the
1400/// second part of a standard conversion is ICK_DerivedToBase. This function
1401/// handles the reference binding specially.
1402static bool ConvertForConditional(Sema &Self, Expr *&E,
Mike Stump1eb44332009-09-09 15:08:12 +00001403 const ImplicitConversionSequence &ICS) {
Sebastian Redl76458502009-04-17 16:30:52 +00001404 if (ICS.ConversionKind == ImplicitConversionSequence::StandardConversion &&
1405 ICS.Standard.ReferenceBinding) {
1406 assert(ICS.Standard.DirectBinding &&
1407 "TryClassUnification should never generate indirect ref bindings");
Sebastian Redla5cd2cd2009-04-26 11:21:02 +00001408 // FIXME: CheckReferenceInit should be able to reuse the ICS instead of
1409 // redoing all the work.
1410 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001411 TargetType(ICS)),
1412 /*SuppressUserConversions=*/false,
1413 /*AllowExplicit=*/false,
1414 /*ForceRValue=*/false);
Sebastian Redl76458502009-04-17 16:30:52 +00001415 }
1416 if (ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion &&
1417 ICS.UserDefined.After.ReferenceBinding) {
1418 assert(ICS.UserDefined.After.DirectBinding &&
1419 "TryClassUnification should never generate indirect ref bindings");
Sebastian Redla5cd2cd2009-04-26 11:21:02 +00001420 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001421 TargetType(ICS)),
1422 /*SuppressUserConversions=*/false,
1423 /*AllowExplicit=*/false,
1424 /*ForceRValue=*/false);
Sebastian Redl76458502009-04-17 16:30:52 +00001425 }
1426 if (Self.PerformImplicitConversion(E, TargetType(ICS), ICS, "converting"))
1427 return true;
1428 return false;
1429}
1430
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001431/// \brief Check the operands of ?: under C++ semantics.
1432///
1433/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
1434/// extension. In this case, LHS == Cond. (But they're not aliases.)
1435QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
1436 SourceLocation QuestionLoc) {
Mike Stump390b4cc2009-05-16 07:39:55 +00001437 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
1438 // interface pointers.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001439
1440 // C++0x 5.16p1
1441 // The first expression is contextually converted to bool.
1442 if (!Cond->isTypeDependent()) {
1443 if (CheckCXXBooleanCondition(Cond))
1444 return QualType();
1445 }
1446
1447 // Either of the arguments dependent?
1448 if (LHS->isTypeDependent() || RHS->isTypeDependent())
1449 return Context.DependentTy;
1450
1451 // C++0x 5.16p2
1452 // If either the second or the third operand has type (cv) void, ...
1453 QualType LTy = LHS->getType();
1454 QualType RTy = RHS->getType();
1455 bool LVoid = LTy->isVoidType();
1456 bool RVoid = RTy->isVoidType();
1457 if (LVoid || RVoid) {
1458 // ... then the [l2r] conversions are performed on the second and third
1459 // operands ...
1460 DefaultFunctionArrayConversion(LHS);
1461 DefaultFunctionArrayConversion(RHS);
1462 LTy = LHS->getType();
1463 RTy = RHS->getType();
1464
1465 // ... and one of the following shall hold:
1466 // -- The second or the third operand (but not both) is a throw-
1467 // expression; the result is of the type of the other and is an rvalue.
1468 bool LThrow = isa<CXXThrowExpr>(LHS);
1469 bool RThrow = isa<CXXThrowExpr>(RHS);
1470 if (LThrow && !RThrow)
1471 return RTy;
1472 if (RThrow && !LThrow)
1473 return LTy;
1474
1475 // -- Both the second and third operands have type void; the result is of
1476 // type void and is an rvalue.
1477 if (LVoid && RVoid)
1478 return Context.VoidTy;
1479
1480 // Neither holds, error.
1481 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
1482 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
1483 << LHS->getSourceRange() << RHS->getSourceRange();
1484 return QualType();
1485 }
1486
1487 // Neither is void.
1488
1489 // C++0x 5.16p3
1490 // Otherwise, if the second and third operand have different types, and
1491 // either has (cv) class type, and attempt is made to convert each of those
1492 // operands to the other.
1493 if (Context.getCanonicalType(LTy) != Context.getCanonicalType(RTy) &&
1494 (LTy->isRecordType() || RTy->isRecordType())) {
1495 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
1496 // These return true if a single direction is already ambiguous.
1497 if (TryClassUnification(*this, LHS, RHS, QuestionLoc, ICSLeftToRight))
1498 return QualType();
1499 if (TryClassUnification(*this, RHS, LHS, QuestionLoc, ICSRightToLeft))
1500 return QualType();
1501
1502 bool HaveL2R = ICSLeftToRight.ConversionKind !=
1503 ImplicitConversionSequence::BadConversion;
1504 bool HaveR2L = ICSRightToLeft.ConversionKind !=
1505 ImplicitConversionSequence::BadConversion;
1506 // If both can be converted, [...] the program is ill-formed.
1507 if (HaveL2R && HaveR2L) {
1508 Diag(QuestionLoc, diag::err_conditional_ambiguous)
1509 << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
1510 return QualType();
1511 }
1512
1513 // If exactly one conversion is possible, that conversion is applied to
1514 // the chosen operand and the converted operands are used in place of the
1515 // original operands for the remainder of this section.
1516 if (HaveL2R) {
Sebastian Redl76458502009-04-17 16:30:52 +00001517 if (ConvertForConditional(*this, LHS, ICSLeftToRight))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001518 return QualType();
1519 LTy = LHS->getType();
1520 } else if (HaveR2L) {
Sebastian Redl76458502009-04-17 16:30:52 +00001521 if (ConvertForConditional(*this, RHS, ICSRightToLeft))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001522 return QualType();
1523 RTy = RHS->getType();
1524 }
1525 }
1526
1527 // C++0x 5.16p4
1528 // If the second and third operands are lvalues and have the same type,
1529 // the result is of that type [...]
1530 bool Same = Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy);
1531 if (Same && LHS->isLvalue(Context) == Expr::LV_Valid &&
1532 RHS->isLvalue(Context) == Expr::LV_Valid)
1533 return LTy;
1534
1535 // C++0x 5.16p5
1536 // Otherwise, the result is an rvalue. If the second and third operands
1537 // do not have the same type, and either has (cv) class type, ...
1538 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
1539 // ... overload resolution is used to determine the conversions (if any)
1540 // to be applied to the operands. If the overload resolution fails, the
1541 // program is ill-formed.
1542 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
1543 return QualType();
1544 }
1545
1546 // C++0x 5.16p6
1547 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
1548 // conversions are performed on the second and third operands.
1549 DefaultFunctionArrayConversion(LHS);
1550 DefaultFunctionArrayConversion(RHS);
1551 LTy = LHS->getType();
1552 RTy = RHS->getType();
1553
1554 // After those conversions, one of the following shall hold:
1555 // -- The second and third operands have the same type; the result
1556 // is of that type.
1557 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy))
1558 return LTy;
1559
1560 // -- The second and third operands have arithmetic or enumeration type;
1561 // the usual arithmetic conversions are performed to bring them to a
1562 // common type, and the result is of that type.
1563 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
1564 UsualArithmeticConversions(LHS, RHS);
1565 return LHS->getType();
1566 }
1567
1568 // -- The second and third operands have pointer type, or one has pointer
1569 // type and the other is a null pointer constant; pointer conversions
1570 // and qualification conversions are performed to bring them to their
1571 // composite pointer type. The result is of the composite pointer type.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001572 QualType Composite = FindCompositePointerType(LHS, RHS);
1573 if (!Composite.isNull())
1574 return Composite;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001575
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001576 // Fourth bullet is same for pointers-to-member. However, the possible
1577 // conversions are far more limited: we have null-to-pointer, upcast of
1578 // containing class, and second-level cv-ness.
1579 // cv-ness is not a union, but must match one of the two operands. (Which,
1580 // frankly, is stupid.)
Ted Kremenek6217b802009-07-29 21:53:49 +00001581 const MemberPointerType *LMemPtr = LTy->getAs<MemberPointerType>();
1582 const MemberPointerType *RMemPtr = RTy->getAs<MemberPointerType>();
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001583 if (LMemPtr && RHS->isNullPointerConstant(Context)) {
1584 ImpCastExprToType(RHS, LTy);
1585 return LTy;
1586 }
1587 if (RMemPtr && LHS->isNullPointerConstant(Context)) {
1588 ImpCastExprToType(LHS, RTy);
1589 return RTy;
1590 }
1591 if (LMemPtr && RMemPtr) {
1592 QualType LPointee = LMemPtr->getPointeeType();
1593 QualType RPointee = RMemPtr->getPointeeType();
1594 // First, we check that the unqualified pointee type is the same. If it's
1595 // not, there's no conversion that will unify the two pointers.
1596 if (Context.getCanonicalType(LPointee).getUnqualifiedType() ==
1597 Context.getCanonicalType(RPointee).getUnqualifiedType()) {
1598 // Second, we take the greater of the two cv qualifications. If neither
1599 // is greater than the other, the conversion is not possible.
1600 unsigned Q = LPointee.getCVRQualifiers() | RPointee.getCVRQualifiers();
1601 if (Q == LPointee.getCVRQualifiers() || Q == RPointee.getCVRQualifiers()){
1602 // Third, we check if either of the container classes is derived from
1603 // the other.
1604 QualType LContainer(LMemPtr->getClass(), 0);
1605 QualType RContainer(RMemPtr->getClass(), 0);
1606 QualType MoreDerived;
1607 if (Context.getCanonicalType(LContainer) ==
1608 Context.getCanonicalType(RContainer))
1609 MoreDerived = LContainer;
1610 else if (IsDerivedFrom(LContainer, RContainer))
1611 MoreDerived = LContainer;
1612 else if (IsDerivedFrom(RContainer, LContainer))
1613 MoreDerived = RContainer;
1614
1615 if (!MoreDerived.isNull()) {
1616 // The type 'Q Pointee (MoreDerived::*)' is the common type.
1617 // We don't use ImpCastExprToType here because this could still fail
1618 // for ambiguous or inaccessible conversions.
1619 QualType Common = Context.getMemberPointerType(
1620 LPointee.getQualifiedType(Q), MoreDerived.getTypePtr());
1621 if (PerformImplicitConversion(LHS, Common, "converting"))
1622 return QualType();
1623 if (PerformImplicitConversion(RHS, Common, "converting"))
1624 return QualType();
1625 return Common;
1626 }
1627 }
1628 }
1629 }
1630
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001631 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
1632 << LHS->getType() << RHS->getType()
1633 << LHS->getSourceRange() << RHS->getSourceRange();
1634 return QualType();
1635}
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001636
1637/// \brief Find a merged pointer type and convert the two expressions to it.
1638///
Douglas Gregor20b3e992009-08-24 17:42:35 +00001639/// This finds the composite pointer type (or member pointer type) for @p E1
1640/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
1641/// type and returns it.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001642/// It does not emit diagnostics.
1643QualType Sema::FindCompositePointerType(Expr *&E1, Expr *&E2) {
1644 assert(getLangOptions().CPlusPlus && "This function assumes C++");
1645 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001646
Douglas Gregor20b3e992009-08-24 17:42:35 +00001647 if (!T1->isPointerType() && !T1->isMemberPointerType() &&
1648 !T2->isPointerType() && !T2->isMemberPointerType())
1649 return QualType();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001650
Douglas Gregor20b3e992009-08-24 17:42:35 +00001651 // FIXME: Do we need to work on the canonical types?
Mike Stump1eb44332009-09-09 15:08:12 +00001652
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001653 // C++0x 5.9p2
1654 // Pointer conversions and qualification conversions are performed on
1655 // pointer operands to bring them to their composite pointer type. If
1656 // one operand is a null pointer constant, the composite pointer type is
1657 // the type of the other operand.
1658 if (E1->isNullPointerConstant(Context)) {
1659 ImpCastExprToType(E1, T2);
1660 return T2;
1661 }
1662 if (E2->isNullPointerConstant(Context)) {
1663 ImpCastExprToType(E2, T1);
1664 return T1;
1665 }
Mike Stump1eb44332009-09-09 15:08:12 +00001666
Douglas Gregor20b3e992009-08-24 17:42:35 +00001667 // Now both have to be pointers or member pointers.
1668 if (!T1->isPointerType() && !T1->isMemberPointerType() &&
1669 !T2->isPointerType() && !T2->isMemberPointerType())
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001670 return QualType();
1671
1672 // Otherwise, of one of the operands has type "pointer to cv1 void," then
1673 // the other has type "pointer to cv2 T" and the composite pointer type is
1674 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
1675 // Otherwise, the composite pointer type is a pointer type similar to the
1676 // type of one of the operands, with a cv-qualification signature that is
1677 // the union of the cv-qualification signatures of the operand types.
1678 // In practice, the first part here is redundant; it's subsumed by the second.
1679 // What we do here is, we build the two possible composite types, and try the
1680 // conversions in both directions. If only one works, or if the two composite
1681 // types are the same, we have succeeded.
1682 llvm::SmallVector<unsigned, 4> QualifierUnion;
Douglas Gregor20b3e992009-08-24 17:42:35 +00001683 llvm::SmallVector<std::pair<const Type *, const Type *>, 4> MemberOfClass;
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001684 QualType Composite1 = T1, Composite2 = T2;
Douglas Gregor20b3e992009-08-24 17:42:35 +00001685 do {
1686 const PointerType *Ptr1, *Ptr2;
1687 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
1688 (Ptr2 = Composite2->getAs<PointerType>())) {
1689 Composite1 = Ptr1->getPointeeType();
1690 Composite2 = Ptr2->getPointeeType();
1691 QualifierUnion.push_back(
1692 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
1693 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
1694 continue;
1695 }
Mike Stump1eb44332009-09-09 15:08:12 +00001696
Douglas Gregor20b3e992009-08-24 17:42:35 +00001697 const MemberPointerType *MemPtr1, *MemPtr2;
1698 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
1699 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
1700 Composite1 = MemPtr1->getPointeeType();
1701 Composite2 = MemPtr2->getPointeeType();
1702 QualifierUnion.push_back(
1703 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
1704 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
1705 MemPtr2->getClass()));
1706 continue;
1707 }
Mike Stump1eb44332009-09-09 15:08:12 +00001708
Douglas Gregor20b3e992009-08-24 17:42:35 +00001709 // FIXME: block pointer types?
Mike Stump1eb44332009-09-09 15:08:12 +00001710
Douglas Gregor20b3e992009-08-24 17:42:35 +00001711 // Cannot unwrap any more types.
1712 break;
1713 } while (true);
Mike Stump1eb44332009-09-09 15:08:12 +00001714
Douglas Gregor20b3e992009-08-24 17:42:35 +00001715 // Rewrap the composites as pointers or member pointers with the union CVRs.
1716 llvm::SmallVector<std::pair<const Type *, const Type *>, 4>::iterator MOC
1717 = MemberOfClass.begin();
Mike Stump1eb44332009-09-09 15:08:12 +00001718 for (llvm::SmallVector<unsigned, 4>::iterator
Douglas Gregor20b3e992009-08-24 17:42:35 +00001719 I = QualifierUnion.begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00001720 E = QualifierUnion.end();
Douglas Gregor20b3e992009-08-24 17:42:35 +00001721 I != E; (void)++I, ++MOC) {
1722 if (MOC->first && MOC->second) {
1723 // Rebuild member pointer type
1724 Composite1 = Context.getMemberPointerType(Composite1.getQualifiedType(*I),
1725 MOC->first);
1726 Composite2 = Context.getMemberPointerType(Composite2.getQualifiedType(*I),
1727 MOC->second);
1728 } else {
1729 // Rebuild pointer type
1730 Composite1 = Context.getPointerType(Composite1.getQualifiedType(*I));
1731 Composite2 = Context.getPointerType(Composite2.getQualifiedType(*I));
1732 }
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001733 }
1734
Mike Stump1eb44332009-09-09 15:08:12 +00001735 ImplicitConversionSequence E1ToC1 =
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001736 TryImplicitConversion(E1, Composite1,
1737 /*SuppressUserConversions=*/false,
1738 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00001739 /*ForceRValue=*/false,
1740 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00001741 ImplicitConversionSequence E2ToC1 =
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001742 TryImplicitConversion(E2, Composite1,
1743 /*SuppressUserConversions=*/false,
1744 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00001745 /*ForceRValue=*/false,
1746 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00001747
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001748 ImplicitConversionSequence E1ToC2, E2ToC2;
1749 E1ToC2.ConversionKind = ImplicitConversionSequence::BadConversion;
1750 E2ToC2.ConversionKind = ImplicitConversionSequence::BadConversion;
1751 if (Context.getCanonicalType(Composite1) !=
1752 Context.getCanonicalType(Composite2)) {
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001753 E1ToC2 = TryImplicitConversion(E1, Composite2,
1754 /*SuppressUserConversions=*/false,
1755 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00001756 /*ForceRValue=*/false,
1757 /*InOverloadResolution=*/false);
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001758 E2ToC2 = TryImplicitConversion(E2, Composite2,
1759 /*SuppressUserConversions=*/false,
1760 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00001761 /*ForceRValue=*/false,
1762 /*InOverloadResolution=*/false);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001763 }
1764
1765 bool ToC1Viable = E1ToC1.ConversionKind !=
1766 ImplicitConversionSequence::BadConversion
1767 && E2ToC1.ConversionKind !=
1768 ImplicitConversionSequence::BadConversion;
1769 bool ToC2Viable = E1ToC2.ConversionKind !=
1770 ImplicitConversionSequence::BadConversion
1771 && E2ToC2.ConversionKind !=
1772 ImplicitConversionSequence::BadConversion;
1773 if (ToC1Viable && !ToC2Viable) {
1774 if (!PerformImplicitConversion(E1, Composite1, E1ToC1, "converting") &&
1775 !PerformImplicitConversion(E2, Composite1, E2ToC1, "converting"))
1776 return Composite1;
1777 }
1778 if (ToC2Viable && !ToC1Viable) {
1779 if (!PerformImplicitConversion(E1, Composite2, E1ToC2, "converting") &&
1780 !PerformImplicitConversion(E2, Composite2, E2ToC2, "converting"))
1781 return Composite2;
1782 }
1783 return QualType();
1784}
Anders Carlsson165a0a02009-05-17 18:41:29 +00001785
Anders Carlssondef11992009-05-30 20:36:53 +00001786Sema::OwningExprResult Sema::MaybeBindToTemporary(Expr *E) {
Anders Carlsson089c2602009-08-15 23:41:35 +00001787 if (!Context.getLangOptions().CPlusPlus)
1788 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001789
Ted Kremenek6217b802009-07-29 21:53:49 +00001790 const RecordType *RT = E->getType()->getAs<RecordType>();
Anders Carlssondef11992009-05-30 20:36:53 +00001791 if (!RT)
1792 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001793
Anders Carlssondef11992009-05-30 20:36:53 +00001794 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1795 if (RD->hasTrivialDestructor())
1796 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001797
Anders Carlsson283e4d52009-09-14 01:30:44 +00001798 if (CallExpr *CE = dyn_cast<CallExpr>(E)) {
1799 QualType Ty = CE->getCallee()->getType();
1800 if (const PointerType *PT = Ty->getAs<PointerType>())
1801 Ty = PT->getPointeeType();
1802
1803 const FunctionType *FTy = Ty->getAsFunctionType();
1804 if (FTy->getResultType()->isReferenceType())
1805 return Owned(E);
1806 }
Mike Stump1eb44332009-09-09 15:08:12 +00001807 CXXTemporary *Temp = CXXTemporary::Create(Context,
Anders Carlssondef11992009-05-30 20:36:53 +00001808 RD->getDestructor(Context));
Anders Carlsson860306e2009-05-30 21:21:49 +00001809 ExprTemporaries.push_back(Temp);
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00001810 if (CXXDestructorDecl *Destructor =
1811 const_cast<CXXDestructorDecl*>(RD->getDestructor(Context)))
1812 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
Anders Carlssondef11992009-05-30 20:36:53 +00001813 // FIXME: Add the temporary to the temporaries vector.
1814 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
1815}
1816
Mike Stump1eb44332009-09-09 15:08:12 +00001817Expr *Sema::MaybeCreateCXXExprWithTemporaries(Expr *SubExpr,
Anders Carlssonf54741e2009-06-16 03:37:31 +00001818 bool ShouldDestroyTemps) {
Anders Carlsson99ba36d2009-06-05 15:38:08 +00001819 assert(SubExpr && "sub expression can't be null!");
Mike Stump1eb44332009-09-09 15:08:12 +00001820
Anders Carlsson99ba36d2009-06-05 15:38:08 +00001821 if (ExprTemporaries.empty())
1822 return SubExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00001823
Anders Carlsson99ba36d2009-06-05 15:38:08 +00001824 Expr *E = CXXExprWithTemporaries::Create(Context, SubExpr,
Mike Stump1eb44332009-09-09 15:08:12 +00001825 &ExprTemporaries[0],
Anders Carlsson99ba36d2009-06-05 15:38:08 +00001826 ExprTemporaries.size(),
Anders Carlssonf54741e2009-06-16 03:37:31 +00001827 ShouldDestroyTemps);
Anders Carlsson99ba36d2009-06-05 15:38:08 +00001828 ExprTemporaries.clear();
Mike Stump1eb44332009-09-09 15:08:12 +00001829
Anders Carlsson99ba36d2009-06-05 15:38:08 +00001830 return E;
1831}
1832
Mike Stump1eb44332009-09-09 15:08:12 +00001833Sema::OwningExprResult
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001834Sema::ActOnStartCXXMemberReference(Scope *S, ExprArg Base, SourceLocation OpLoc,
1835 tok::TokenKind OpKind, TypeTy *&ObjectType) {
1836 // Since this might be a postfix expression, get rid of ParenListExprs.
1837 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
Mike Stump1eb44332009-09-09 15:08:12 +00001838
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001839 Expr *BaseExpr = (Expr*)Base.get();
1840 assert(BaseExpr && "no record expansion");
Mike Stump1eb44332009-09-09 15:08:12 +00001841
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001842 QualType BaseType = BaseExpr->getType();
1843 if (BaseType->isDependentType()) {
1844 // FIXME: member of the current instantiation
1845 ObjectType = BaseType.getAsOpaquePtr();
1846 return move(Base);
1847 }
Mike Stump1eb44332009-09-09 15:08:12 +00001848
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001849 // C++ [over.match.oper]p8:
Mike Stump1eb44332009-09-09 15:08:12 +00001850 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001851 // returned, with the original second operand.
1852 if (OpKind == tok::arrow) {
1853 while (BaseType->isRecordType()) {
1854 Base = BuildOverloadedArrowExpr(S, move(Base), BaseExpr->getExprLoc());
1855 BaseExpr = (Expr*)Base.get();
1856 if (BaseExpr == NULL)
1857 return ExprError();
1858 BaseType = BaseExpr->getType();
1859 }
1860 }
Mike Stump1eb44332009-09-09 15:08:12 +00001861
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001862 if (BaseType->isPointerType())
1863 BaseType = BaseType->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00001864
1865 // We could end up with various non-record types here, such as extended
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001866 // vector types or Objective-C interfaces. Just return early and let
1867 // ActOnMemberReferenceExpr do the work.
Douglas Gregorc68afe22009-09-03 21:38:09 +00001868 if (!BaseType->isRecordType()) {
1869 // C++ [basic.lookup.classref]p2:
1870 // [...] If the type of the object expression is of pointer to scalar
1871 // type, the unqualified-id is looked up in the context of the complete
1872 // postfix-expression.
1873 ObjectType = 0;
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001874 return move(Base);
Douglas Gregorc68afe22009-09-03 21:38:09 +00001875 }
Mike Stump1eb44332009-09-09 15:08:12 +00001876
Douglas Gregorc68afe22009-09-03 21:38:09 +00001877 // C++ [basic.lookup.classref]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00001878 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregorc68afe22009-09-03 21:38:09 +00001879 // unqualified-id, and the type of the object expres- sion is of a class
1880 // type C (or of pointer to a class type C), the unqualified-id is looked
1881 // up in the scope of class C. [...]
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001882 ObjectType = BaseType.getAsOpaquePtr();
Mike Stump1eb44332009-09-09 15:08:12 +00001883 return move(Base);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001884}
1885
Anders Carlssonec773872009-08-25 23:46:41 +00001886Sema::OwningExprResult
Anders Carlsson3aa4ca42009-08-26 17:36:19 +00001887Sema::ActOnDestructorReferenceExpr(Scope *S, ExprArg Base,
Anders Carlssonec773872009-08-25 23:46:41 +00001888 SourceLocation OpLoc,
1889 tok::TokenKind OpKind,
1890 SourceLocation ClassNameLoc,
1891 IdentifierInfo *ClassName,
Douglas Gregora78c5c32009-09-04 18:29:40 +00001892 const CXXScopeSpec &SS,
1893 bool HasTrailingLParen) {
1894 if (SS.isInvalid())
Anders Carlssonec773872009-08-25 23:46:41 +00001895 return ExprError();
Anders Carlsson2cf738f2009-08-26 19:22:42 +00001896
Douglas Gregora71d8192009-09-04 17:36:40 +00001897 QualType BaseType;
Douglas Gregora78c5c32009-09-04 18:29:40 +00001898 if (isUnknownSpecialization(SS))
1899 BaseType = Context.getTypenameType((NestedNameSpecifier *)SS.getScopeRep(),
Douglas Gregora71d8192009-09-04 17:36:40 +00001900 ClassName);
1901 else {
Douglas Gregora78c5c32009-09-04 18:29:40 +00001902 TypeTy *BaseTy = getTypeName(*ClassName, ClassNameLoc, S, &SS);
Douglas Gregora71d8192009-09-04 17:36:40 +00001903 if (!BaseTy) {
Mike Stump1eb44332009-09-09 15:08:12 +00001904 Diag(ClassNameLoc, diag::err_ident_in_pseudo_dtor_not_a_type)
Douglas Gregora71d8192009-09-04 17:36:40 +00001905 << ClassName;
1906 return ExprError();
1907 }
Mike Stump1eb44332009-09-09 15:08:12 +00001908
Douglas Gregora71d8192009-09-04 17:36:40 +00001909 BaseType = GetTypeFromParser(BaseTy);
Anders Carlsson2cf738f2009-08-26 19:22:42 +00001910 }
Mike Stump1eb44332009-09-09 15:08:12 +00001911
Anders Carlsson2cf738f2009-08-26 19:22:42 +00001912 CanQualType CanBaseType = Context.getCanonicalType(BaseType);
Mike Stump1eb44332009-09-09 15:08:12 +00001913 DeclarationName DtorName =
Anders Carlsson2cf738f2009-08-26 19:22:42 +00001914 Context.DeclarationNames.getCXXDestructorName(CanBaseType);
1915
Douglas Gregora78c5c32009-09-04 18:29:40 +00001916 OwningExprResult Result
1917 = BuildMemberReferenceExpr(S, move(Base), OpLoc, OpKind, ClassNameLoc,
1918 DtorName, DeclPtrTy(), &SS);
1919 if (Result.isInvalid() || HasTrailingLParen)
1920 return move(Result);
Mike Stump1eb44332009-09-09 15:08:12 +00001921
1922 // The only way a reference to a destructor can be used is to
Douglas Gregora78c5c32009-09-04 18:29:40 +00001923 // immediately call them. Since the next token is not a '(', produce a
1924 // diagnostic and build the call now.
1925 Expr *E = (Expr *)Result.get();
1926 SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(E->getLocEnd());
1927 Diag(E->getLocStart(), diag::err_dtor_expr_without_call)
1928 << isa<CXXPseudoDestructorExpr>(E)
1929 << CodeModificationHint::CreateInsertion(ExpectedLParenLoc, "()");
Mike Stump1eb44332009-09-09 15:08:12 +00001930
1931 return ActOnCallExpr(0, move(Result), ExpectedLParenLoc,
Douglas Gregora78c5c32009-09-04 18:29:40 +00001932 MultiExprArg(*this, 0, 0), 0, ExpectedLParenLoc);
Anders Carlssonec773872009-08-25 23:46:41 +00001933}
1934
Douglas Gregora6f0f9d2009-08-31 19:52:13 +00001935Sema::OwningExprResult
1936Sema::ActOnOverloadedOperatorReferenceExpr(Scope *S, ExprArg Base,
1937 SourceLocation OpLoc,
1938 tok::TokenKind OpKind,
1939 SourceLocation ClassNameLoc,
1940 OverloadedOperatorKind OverOpKind,
1941 const CXXScopeSpec *SS) {
1942 if (SS && SS->isInvalid())
1943 return ExprError();
1944
1945 DeclarationName Name =
1946 Context.DeclarationNames.getCXXOperatorName(OverOpKind);
1947
1948 return BuildMemberReferenceExpr(S, move(Base), OpLoc, OpKind, ClassNameLoc,
1949 Name, DeclPtrTy(), SS);
1950}
1951
1952Sema::OwningExprResult
1953Sema::ActOnConversionOperatorReferenceExpr(Scope *S, ExprArg Base,
1954 SourceLocation OpLoc,
1955 tok::TokenKind OpKind,
1956 SourceLocation ClassNameLoc,
1957 TypeTy *Ty,
1958 const CXXScopeSpec *SS) {
1959 if (SS && SS->isInvalid())
1960 return ExprError();
1961
1962 //FIXME: Preserve type source info.
1963 QualType ConvType = GetTypeFromParser(Ty);
1964 CanQualType ConvTypeCanon = Context.getCanonicalType(ConvType);
1965 DeclarationName ConvName =
1966 Context.DeclarationNames.getCXXConversionFunctionName(ConvTypeCanon);
1967
1968 return BuildMemberReferenceExpr(S, move(Base), OpLoc, OpKind, ClassNameLoc,
1969 ConvName, DeclPtrTy(), SS);
1970}
1971
Anders Carlsson0aebc812009-09-09 21:33:21 +00001972Sema::OwningExprResult Sema::BuildCXXCastArgument(SourceLocation CastLoc,
1973 QualType Ty,
1974 CastExpr::CastKind Kind,
1975 CXXMethodDecl *Method,
1976 ExprArg Arg) {
1977 Expr *From = Arg.takeAs<Expr>();
1978
1979 switch (Kind) {
1980 default: assert(0 && "Unhandled cast kind!");
1981 case CastExpr::CK_ConstructorConversion: {
Douglas Gregor39da0b82009-09-09 23:08:42 +00001982 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1983
1984 if (CompleteConstructorCall(cast<CXXConstructorDecl>(Method),
1985 MultiExprArg(*this, (void **)&From, 1),
1986 CastLoc, ConstructorArgs))
1987 return ExprError();
1988
Anders Carlsson0aebc812009-09-09 21:33:21 +00001989 return BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
Douglas Gregor39da0b82009-09-09 23:08:42 +00001990 move_arg(ConstructorArgs));
Anders Carlsson0aebc812009-09-09 21:33:21 +00001991 }
1992
1993 case CastExpr::CK_UserDefinedConversion: {
Anders Carlssonaac6e3a2009-09-15 07:42:44 +00001994 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
1995
1996 // Cast to base if needed.
1997 if (PerformObjectArgumentInitialization(From, Method))
1998 return ExprError();
1999
Anders Carlsson0aebc812009-09-09 21:33:21 +00002000 // Create an implicit member expr to refer to the conversion operator.
2001 MemberExpr *ME =
Anders Carlssonaac6e3a2009-09-15 07:42:44 +00002002 new (Context) MemberExpr(From, /*IsArrow=*/false, Method,
Anders Carlsson0aebc812009-09-09 21:33:21 +00002003 SourceLocation(), Method->getType());
2004
2005
2006 // And an implicit call expr that calls it.
2007 QualType ResultType = Method->getResultType().getNonReferenceType();
2008 CXXMemberCallExpr *CE =
2009 new (Context) CXXMemberCallExpr(Context, ME, 0, 0,
2010 ResultType,
2011 SourceLocation());
2012
2013 return Owned(CE);
2014 }
2015
2016 }
2017}
2018
Anders Carlsson165a0a02009-05-17 18:41:29 +00002019Sema::OwningExprResult Sema::ActOnFinishFullExpr(ExprArg Arg) {
2020 Expr *FullExpr = Arg.takeAs<Expr>();
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002021 if (FullExpr)
Mike Stump1eb44332009-09-09 15:08:12 +00002022 FullExpr = MaybeCreateCXXExprWithTemporaries(FullExpr,
Anders Carlssonf54741e2009-06-16 03:37:31 +00002023 /*ShouldDestroyTemps=*/true);
Anders Carlsson165a0a02009-05-17 18:41:29 +00002024
Anders Carlssonec773872009-08-25 23:46:41 +00002025
Anders Carlsson165a0a02009-05-17 18:41:29 +00002026 return Owned(FullExpr);
2027}