blob: 4aa928a4369611a312d333adac10b273863ea64e [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
John McCall7d384dd2009-11-18 07:57:50 +000015#include "Lookup.h"
Steve Naroff210679c2007-08-25 14:02:58 +000016#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000017#include "clang/AST/CXXInheritance.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000018#include "clang/AST/ExprCXX.h"
19#include "clang/Basic/PartialDiagnostic.h"
Sebastian Redlb5a57a62008-12-03 20:26:15 +000020#include "clang/Basic/TargetInfo.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000021#include "clang/Lex/Preprocessor.h"
22#include "clang/Parse/DeclSpec.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000023#include "llvm/ADT/STLExtras.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000024using namespace clang;
25
Sebastian Redlc42e1182008-11-11 11:37:55 +000026/// ActOnCXXTypeidOfType - Parse typeid( type-id ).
Sebastian Redlf53597f2009-03-15 17:47:39 +000027Action::OwningExprResult
Sebastian Redlc42e1182008-11-11 11:37:55 +000028Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
29 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +000030 if (!StdNamespace)
Sebastian Redlf53597f2009-03-15 17:47:39 +000031 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +000032
33 if (isType)
34 // FIXME: Preserve type source info.
35 TyOrExpr = GetTypeFromParser(TyOrExpr).getAsOpaquePtr();
36
Chris Lattner572af492008-11-20 05:51:55 +000037 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
John McCalla24dc2e2009-11-17 02:14:36 +000038 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
39 LookupQualifiedName(R, StdNamespace);
John McCallf36e02d2009-10-09 21:13:30 +000040 Decl *TypeInfoDecl = R.getAsSingleDecl(Context);
Sebastian Redlc42e1182008-11-11 11:37:55 +000041 RecordDecl *TypeInfoRecordDecl = dyn_cast_or_null<RecordDecl>(TypeInfoDecl);
Chris Lattner572af492008-11-20 05:51:55 +000042 if (!TypeInfoRecordDecl)
Sebastian Redlf53597f2009-03-15 17:47:39 +000043 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Sebastian Redlc42e1182008-11-11 11:37:55 +000044
45 QualType TypeInfoType = Context.getTypeDeclType(TypeInfoRecordDecl);
46
Douglas Gregorac7610d2009-06-22 20:57:11 +000047 if (!isType) {
48 // C++0x [expr.typeid]p3:
Mike Stump1eb44332009-09-09 15:08:12 +000049 // When typeid is applied to an expression other than an lvalue of a
50 // polymorphic class type [...] [the] expression is an unevaluated
Douglas Gregorac7610d2009-06-22 20:57:11 +000051 // operand.
Mike Stump1eb44332009-09-09 15:08:12 +000052
Douglas Gregorac7610d2009-06-22 20:57:11 +000053 // FIXME: if the type of the expression is a class type, the class
54 // shall be completely defined.
55 bool isUnevaluatedOperand = true;
56 Expr *E = static_cast<Expr *>(TyOrExpr);
57 if (E && !E->isTypeDependent() && E->isLvalue(Context) == Expr::LV_Valid) {
58 QualType T = E->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +000059 if (const RecordType *RecordT = T->getAs<RecordType>()) {
Douglas Gregorac7610d2009-06-22 20:57:11 +000060 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
61 if (RecordD->isPolymorphic())
62 isUnevaluatedOperand = false;
63 }
64 }
Mike Stump1eb44332009-09-09 15:08:12 +000065
Douglas Gregorac7610d2009-06-22 20:57:11 +000066 // If this is an unevaluated operand, clear out the set of declaration
67 // references we have been computing.
68 if (isUnevaluatedOperand)
69 PotentiallyReferencedDeclStack.back().clear();
70 }
Mike Stump1eb44332009-09-09 15:08:12 +000071
Sebastian Redlf53597f2009-03-15 17:47:39 +000072 return Owned(new (Context) CXXTypeidExpr(isType, TyOrExpr,
73 TypeInfoType.withConst(),
74 SourceRange(OpLoc, RParenLoc)));
Sebastian Redlc42e1182008-11-11 11:37:55 +000075}
76
Steve Naroff1b273c42007-09-16 14:56:35 +000077/// ActOnCXXBoolLiteral - Parse {true,false} literals.
Sebastian Redlf53597f2009-03-15 17:47:39 +000078Action::OwningExprResult
Steve Naroff1b273c42007-09-16 14:56:35 +000079Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor2f639b92008-10-24 15:36:09 +000080 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Reid Spencer5f016e22007-07-11 17:01:13 +000081 "Unknown C++ Boolean value!");
Sebastian Redlf53597f2009-03-15 17:47:39 +000082 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
83 Context.BoolTy, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +000084}
Chris Lattner50dd2892008-02-26 00:51:44 +000085
Sebastian Redl6e8ed162009-05-10 18:38:11 +000086/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
87Action::OwningExprResult
88Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
89 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
90}
91
Chris Lattner50dd2892008-02-26 00:51:44 +000092/// ActOnCXXThrow - Parse throw expressions.
Sebastian Redlf53597f2009-03-15 17:47:39 +000093Action::OwningExprResult
94Sema::ActOnCXXThrow(SourceLocation OpLoc, ExprArg E) {
Sebastian Redl972041f2009-04-27 20:27:31 +000095 Expr *Ex = E.takeAs<Expr>();
96 if (Ex && !Ex->isTypeDependent() && CheckCXXThrowOperand(OpLoc, Ex))
97 return ExprError();
98 return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc));
99}
100
101/// CheckCXXThrowOperand - Validate the operand of a throw.
102bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *&E) {
103 // C++ [except.throw]p3:
104 // [...] adjusting the type from "array of T" or "function returning T"
105 // to "pointer to T" or "pointer to function returning T", [...]
106 DefaultFunctionArrayConversion(E);
107
108 // If the type of the exception would be an incomplete type or a pointer
109 // to an incomplete type other than (cv) void the program is ill-formed.
110 QualType Ty = E->getType();
111 int isPointer = 0;
Ted Kremenek6217b802009-07-29 21:53:49 +0000112 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000113 Ty = Ptr->getPointeeType();
114 isPointer = 1;
115 }
116 if (!isPointer || !Ty->isVoidType()) {
117 if (RequireCompleteType(ThrowLoc, Ty,
Anders Carlssond497ba72009-08-26 22:59:12 +0000118 PDiag(isPointer ? diag::err_throw_incomplete_ptr
119 : diag::err_throw_incomplete)
120 << E->getSourceRange()))
Sebastian Redl972041f2009-04-27 20:27:31 +0000121 return true;
122 }
123
124 // FIXME: Construct a temporary here.
125 return false;
Chris Lattner50dd2892008-02-26 00:51:44 +0000126}
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000127
Sebastian Redlf53597f2009-03-15 17:47:39 +0000128Action::OwningExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000129 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
130 /// is a non-lvalue expression whose value is the address of the object for
131 /// which the function is called.
132
Sebastian Redlf53597f2009-03-15 17:47:39 +0000133 if (!isa<FunctionDecl>(CurContext))
134 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000135
136 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext))
137 if (MD->isInstance())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000138 return Owned(new (Context) CXXThisExpr(ThisLoc,
139 MD->getThisType(Context)));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000140
Sebastian Redlf53597f2009-03-15 17:47:39 +0000141 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000142}
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000143
144/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
145/// Can be interpreted either as function-style casting ("int(x)")
146/// or class type construction ("ClassType(x,y,z)")
147/// or creation of a value-initialized type ("int()").
Sebastian Redlf53597f2009-03-15 17:47:39 +0000148Action::OwningExprResult
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000149Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep,
150 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000151 MultiExprArg exprs,
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000152 SourceLocation *CommaLocs,
153 SourceLocation RParenLoc) {
154 assert(TypeRep && "Missing type!");
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000155 // FIXME: Preserve type source info.
156 QualType Ty = GetTypeFromParser(TypeRep);
Sebastian Redlf53597f2009-03-15 17:47:39 +0000157 unsigned NumExprs = exprs.size();
158 Expr **Exprs = (Expr**)exprs.get();
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000159 SourceLocation TyBeginLoc = TypeRange.getBegin();
160 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
161
Sebastian Redlf53597f2009-03-15 17:47:39 +0000162 if (Ty->isDependentType() ||
Douglas Gregorba498172009-03-13 21:01:28 +0000163 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
Sebastian Redlf53597f2009-03-15 17:47:39 +0000164 exprs.release();
Mike Stump1eb44332009-09-09 15:08:12 +0000165
166 return Owned(CXXUnresolvedConstructExpr::Create(Context,
167 TypeRange.getBegin(), Ty,
Douglas Gregord81e6ca2009-05-20 18:46:25 +0000168 LParenLoc,
169 Exprs, NumExprs,
170 RParenLoc));
Douglas Gregorba498172009-03-13 21:01:28 +0000171 }
172
Anders Carlssonbb60a502009-08-27 03:53:50 +0000173 if (Ty->isArrayType())
174 return ExprError(Diag(TyBeginLoc,
175 diag::err_value_init_for_array_type) << FullRange);
176 if (!Ty->isVoidType() &&
177 RequireCompleteType(TyBeginLoc, Ty,
178 PDiag(diag::err_invalid_incomplete_type_use)
179 << FullRange))
180 return ExprError();
Fariborz Jahanianf071e9b2009-10-23 21:01:39 +0000181
Anders Carlssonbb60a502009-08-27 03:53:50 +0000182 if (RequireNonAbstractType(TyBeginLoc, Ty,
183 diag::err_allocation_of_abstract_type))
184 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000185
186
Douglas Gregor506ae412009-01-16 18:33:17 +0000187 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000188 // If the expression list is a single expression, the type conversion
189 // expression is equivalent (in definedness, and if defined in meaning) to the
190 // corresponding cast expression.
191 //
192 if (NumExprs == 1) {
Anders Carlssoncdb61972009-08-07 22:21:05 +0000193 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Anders Carlsson0aebc812009-09-09 21:33:21 +0000194 CXXMethodDecl *Method = 0;
195 if (CheckCastTypes(TypeRange, Ty, Exprs[0], Kind, Method,
196 /*FunctionalStyle=*/true))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000197 return ExprError();
Anders Carlsson0aebc812009-09-09 21:33:21 +0000198
199 exprs.release();
200 if (Method) {
201 OwningExprResult CastArg
202 = BuildCXXCastArgument(TypeRange.getBegin(), Ty.getNonReferenceType(),
203 Kind, Method, Owned(Exprs[0]));
204 if (CastArg.isInvalid())
205 return ExprError();
206
207 Exprs[0] = CastArg.takeAs<Expr>();
Fariborz Jahanian4fc7ab32009-08-28 15:11:24 +0000208 }
Anders Carlsson0aebc812009-09-09 21:33:21 +0000209
210 return Owned(new (Context) CXXFunctionalCastExpr(Ty.getNonReferenceType(),
211 Ty, TyBeginLoc, Kind,
212 Exprs[0], RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000213 }
214
Ted Kremenek6217b802009-07-29 21:53:49 +0000215 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Douglas Gregor506ae412009-01-16 18:33:17 +0000216 CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
Sebastian Redlf53597f2009-03-15 17:47:39 +0000217
Mike Stump1eb44332009-09-09 15:08:12 +0000218 if (NumExprs > 1 || !Record->hasTrivialConstructor() ||
Anders Carlssone7624a72009-08-27 05:08:22 +0000219 !Record->hasTrivialDestructor()) {
Douglas Gregor39da0b82009-09-09 23:08:42 +0000220 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
221
Douglas Gregor506ae412009-01-16 18:33:17 +0000222 CXXConstructorDecl *Constructor
Douglas Gregor39da0b82009-09-09 23:08:42 +0000223 = PerformInitializationByConstructor(Ty, move(exprs),
Douglas Gregor506ae412009-01-16 18:33:17 +0000224 TypeRange.getBegin(),
225 SourceRange(TypeRange.getBegin(),
226 RParenLoc),
227 DeclarationName(),
Douglas Gregor39da0b82009-09-09 23:08:42 +0000228 IK_Direct,
229 ConstructorArgs);
Douglas Gregor506ae412009-01-16 18:33:17 +0000230
Sebastian Redlf53597f2009-03-15 17:47:39 +0000231 if (!Constructor)
232 return ExprError();
233
Mike Stump1eb44332009-09-09 15:08:12 +0000234 OwningExprResult Result =
235 BuildCXXTemporaryObjectExpr(Constructor, Ty, TyBeginLoc,
Douglas Gregor39da0b82009-09-09 23:08:42 +0000236 move_arg(ConstructorArgs), RParenLoc);
Anders Carlssone7624a72009-08-27 05:08:22 +0000237 if (Result.isInvalid())
238 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000239
Anders Carlssone7624a72009-08-27 05:08:22 +0000240 return MaybeBindToTemporary(Result.takeAs<Expr>());
Douglas Gregor506ae412009-01-16 18:33:17 +0000241 }
242
243 // Fall through to value-initialize an object of class type that
244 // doesn't have a user-declared default constructor.
245 }
246
247 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000248 // If the expression list specifies more than a single value, the type shall
249 // be a class with a suitably declared constructor.
250 //
251 if (NumExprs > 1)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000252 return ExprError(Diag(CommaLocs[0],
253 diag::err_builtin_func_cast_more_than_one_arg)
254 << FullRange);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000255
256 assert(NumExprs == 0 && "Expected 0 expressions");
Douglas Gregor506ae412009-01-16 18:33:17 +0000257 // C++ [expr.type.conv]p2:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000258 // The expression T(), where T is a simple-type-specifier for a non-array
259 // complete object type or the (possibly cv-qualified) void type, creates an
260 // rvalue of the specified type, which is value-initialized.
261 //
Sebastian Redlf53597f2009-03-15 17:47:39 +0000262 exprs.release();
263 return Owned(new (Context) CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000264}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000265
266
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000267/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
268/// @code new (memory) int[size][4] @endcode
269/// or
270/// @code ::new Foo(23, "hello") @endcode
271/// For the interpretation of this heap of arguments, consult the base version.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000272Action::OwningExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000273Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000274 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000275 SourceLocation PlacementRParen, bool ParenTypeId,
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000276 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000277 MultiExprArg ConstructorArgs,
Mike Stump1eb44332009-09-09 15:08:12 +0000278 SourceLocation ConstructorRParen) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000279 Expr *ArraySize = 0;
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000280 // If the specified type is an array, unwrap it and save the expression.
281 if (D.getNumTypeObjects() > 0 &&
282 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
283 DeclaratorChunk &Chunk = D.getTypeObject(0);
284 if (Chunk.Arr.hasStatic)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000285 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
286 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000287 if (!Chunk.Arr.NumElts)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000288 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
289 << D.getSourceRange());
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000290
291 if (ParenTypeId) {
292 // Can't have dynamic array size when the type-id is in parentheses.
293 Expr *NumElts = (Expr *)Chunk.Arr.NumElts;
294 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
295 !NumElts->isIntegerConstantExpr(Context)) {
296 Diag(D.getTypeObject(0).Loc, diag::err_new_paren_array_nonconst)
297 << NumElts->getSourceRange();
298 return ExprError();
299 }
300 }
301
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000302 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000303 D.DropFirstTypeObject();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000304 }
305
Douglas Gregor043cad22009-09-11 00:18:58 +0000306 // Every dimension shall be of constant size.
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000307 if (ArraySize) {
308 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor043cad22009-09-11 00:18:58 +0000309 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
310 break;
311
312 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
313 if (Expr *NumElts = (Expr *)Array.NumElts) {
314 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
315 !NumElts->isIntegerConstantExpr(Context)) {
316 Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst)
317 << NumElts->getSourceRange();
318 return ExprError();
319 }
320 }
321 }
322 }
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000323
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000324 //FIXME: Store DeclaratorInfo in CXXNew expression.
325 DeclaratorInfo *DInfo = 0;
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000326 QualType AllocType = GetTypeForDeclarator(D, /*Scope=*/0, &DInfo);
Chris Lattnereaaebc72009-04-25 08:06:05 +0000327 if (D.isInvalidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000328 return ExprError();
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000329
Mike Stump1eb44332009-09-09 15:08:12 +0000330 return BuildCXXNew(StartLoc, UseGlobal,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000331 PlacementLParen,
Mike Stump1eb44332009-09-09 15:08:12 +0000332 move(PlacementArgs),
Douglas Gregor3433cf72009-05-21 00:00:09 +0000333 PlacementRParen,
334 ParenTypeId,
Mike Stump1eb44332009-09-09 15:08:12 +0000335 AllocType,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000336 D.getSourceRange().getBegin(),
337 D.getSourceRange(),
338 Owned(ArraySize),
339 ConstructorLParen,
340 move(ConstructorArgs),
341 ConstructorRParen);
342}
343
Mike Stump1eb44332009-09-09 15:08:12 +0000344Sema::OwningExprResult
Douglas Gregor3433cf72009-05-21 00:00:09 +0000345Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
346 SourceLocation PlacementLParen,
347 MultiExprArg PlacementArgs,
348 SourceLocation PlacementRParen,
Mike Stump1eb44332009-09-09 15:08:12 +0000349 bool ParenTypeId,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000350 QualType AllocType,
351 SourceLocation TypeLoc,
352 SourceRange TypeRange,
353 ExprArg ArraySizeE,
354 SourceLocation ConstructorLParen,
355 MultiExprArg ConstructorArgs,
356 SourceLocation ConstructorRParen) {
357 if (CheckAllocatedType(AllocType, TypeLoc, TypeRange))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000358 return ExprError();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000359
Douglas Gregor3433cf72009-05-21 00:00:09 +0000360 QualType ResultType = Context.getPointerType(AllocType);
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000361
362 // That every array dimension except the first is constant was already
363 // checked by the type check above.
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000364
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000365 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
366 // or enumeration type with a non-negative value."
Douglas Gregor3433cf72009-05-21 00:00:09 +0000367 Expr *ArraySize = (Expr *)ArraySizeE.get();
Sebastian Redl28507842009-02-26 14:39:58 +0000368 if (ArraySize && !ArraySize->isTypeDependent()) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000369 QualType SizeType = ArraySize->getType();
370 if (!SizeType->isIntegralType() && !SizeType->isEnumeralType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000371 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
372 diag::err_array_size_not_integral)
373 << SizeType << ArraySize->getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000374 // Let's see if this is a constant < 0. If so, we reject it out of hand.
375 // We don't care about special rules, so we tell the machinery it's not
376 // evaluated - it gives us a result in more cases.
Sebastian Redl28507842009-02-26 14:39:58 +0000377 if (!ArraySize->isValueDependent()) {
378 llvm::APSInt Value;
379 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
380 if (Value < llvm::APSInt(
Anders Carlssonac18b2e2009-09-23 00:37:25 +0000381 llvm::APInt::getNullValue(Value.getBitWidth()),
382 Value.isUnsigned()))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000383 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
384 diag::err_typecheck_negative_array_size)
385 << ArraySize->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +0000386 }
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000387 }
Anders Carlssonac18b2e2009-09-23 00:37:25 +0000388
Eli Friedman73c39ab2009-10-20 08:27:19 +0000389 ImpCastExprToType(ArraySize, Context.getSizeType(),
390 CastExpr::CK_IntegralCast);
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000391 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000392
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000393 FunctionDecl *OperatorNew = 0;
394 FunctionDecl *OperatorDelete = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000395 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
396 unsigned NumPlaceArgs = PlacementArgs.size();
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000397
Sebastian Redl28507842009-02-26 14:39:58 +0000398 if (!AllocType->isDependentType() &&
399 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
400 FindAllocationFunctions(StartLoc,
Sebastian Redl00e68e22009-02-09 18:24:27 +0000401 SourceRange(PlacementLParen, PlacementRParen),
402 UseGlobal, AllocType, ArraySize, PlaceArgs,
403 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000404 return ExprError();
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000405 llvm::SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000406 if (OperatorNew) {
407 // Add default arguments, if any.
408 const FunctionProtoType *Proto =
409 OperatorNew->getType()->getAs<FunctionProtoType>();
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000410 bool Invalid = GatherArgumentsForCall(PlacementLParen, OperatorNew,
411 Proto, 1, PlaceArgs, NumPlaceArgs,
412 AllPlaceArgs);
413 if (Invalid)
414 return ExprError();
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000415
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000416 NumPlaceArgs = AllPlaceArgs.size();
417 if (NumPlaceArgs > 0)
418 PlaceArgs = &AllPlaceArgs[0];
419 }
420
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000421 bool Init = ConstructorLParen.isValid();
422 // --- Choosing a constructor ---
423 // C++ 5.3.4p15
424 // 1) If T is a POD and there's no initializer (ConstructorLParen is invalid)
425 // the object is not initialized. If the object, or any part of it, is
426 // const-qualified, it's an error.
427 // 2) If T is a POD and there's an empty initializer, the object is value-
428 // initialized.
429 // 3) If T is a POD and there's one initializer argument, the object is copy-
430 // constructed.
431 // 4) If T is a POD and there's more initializer arguments, it's an error.
432 // 5) If T is not a POD, the initializer arguments are used as constructor
433 // arguments.
434 //
435 // Or by the C++0x formulation:
436 // 1) If there's no initializer, the object is default-initialized according
437 // to C++0x rules.
438 // 2) Otherwise, the object is direct-initialized.
439 CXXConstructorDecl *Constructor = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000440 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
Sebastian Redl4f149632009-05-07 16:14:23 +0000441 const RecordType *RT;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000442 unsigned NumConsArgs = ConstructorArgs.size();
Eli Friedmana8ce9ec2009-11-08 22:15:39 +0000443 ASTOwningVector<&ActionBase::DeleteExpr> ConvertedConstructorArgs(*this);
444
Douglas Gregor089407b2009-10-17 21:40:42 +0000445 if (AllocType->isDependentType() ||
446 Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) {
Sebastian Redl28507842009-02-26 14:39:58 +0000447 // Skip all the checks.
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000448 } else if ((RT = AllocType->getAs<RecordType>()) &&
449 !AllocType->isAggregateType()) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000450 Constructor = PerformInitializationByConstructor(
Douglas Gregor39da0b82009-09-09 23:08:42 +0000451 AllocType, move(ConstructorArgs),
Douglas Gregor3433cf72009-05-21 00:00:09 +0000452 TypeLoc,
453 SourceRange(TypeLoc, ConstructorRParen),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000454 RT->getDecl()->getDeclName(),
Douglas Gregor39da0b82009-09-09 23:08:42 +0000455 NumConsArgs != 0 ? IK_Direct : IK_Default,
456 ConvertedConstructorArgs);
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000457 if (!Constructor)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000458 return ExprError();
Douglas Gregor39da0b82009-09-09 23:08:42 +0000459
460 // Take the converted constructor arguments and use them for the new
461 // expression.
462 NumConsArgs = ConvertedConstructorArgs.size();
463 ConsArgs = (Expr **)ConvertedConstructorArgs.take();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000464 } else {
465 if (!Init) {
466 // FIXME: Check that no subpart is const.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000467 if (AllocType.isConstQualified())
468 return ExprError(Diag(StartLoc, diag::err_new_uninitialized_const)
Douglas Gregor3433cf72009-05-21 00:00:09 +0000469 << TypeRange);
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000470 } else if (NumConsArgs == 0) {
Fariborz Jahanian6f269202009-11-03 20:38:53 +0000471 // Object is value-initialized. Do nothing.
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000472 } else if (NumConsArgs == 1) {
473 // Object is direct-initialized.
Sebastian Redl4f149632009-05-07 16:14:23 +0000474 // FIXME: What DeclarationName do we pass in here?
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000475 if (CheckInitializerTypes(ConsArgs[0], AllocType, StartLoc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000476 DeclarationName() /*AllocType.getAsString()*/,
477 /*DirectInit=*/true))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000478 return ExprError();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000479 } else {
Sebastian Redlf53597f2009-03-15 17:47:39 +0000480 return ExprError(Diag(StartLoc,
481 diag::err_builtin_direct_init_more_than_one_arg)
482 << SourceRange(ConstructorLParen, ConstructorRParen));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000483 }
484 }
485
486 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
Douglas Gregor089407b2009-10-17 21:40:42 +0000487
Sebastian Redlf53597f2009-03-15 17:47:39 +0000488 PlacementArgs.release();
489 ConstructorArgs.release();
Douglas Gregor3433cf72009-05-21 00:00:09 +0000490 ArraySizeE.release();
Sebastian Redlf53597f2009-03-15 17:47:39 +0000491 return Owned(new (Context) CXXNewExpr(UseGlobal, OperatorNew, PlaceArgs,
Ted Kremenek8189cde2009-02-07 01:47:29 +0000492 NumPlaceArgs, ParenTypeId, ArraySize, Constructor, Init,
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000493 ConsArgs, NumConsArgs, OperatorDelete, ResultType,
Mike Stump1eb44332009-09-09 15:08:12 +0000494 StartLoc, Init ? ConstructorRParen : SourceLocation()));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000495}
496
497/// CheckAllocatedType - Checks that a type is suitable as the allocated type
498/// in a new-expression.
499/// dimension off and stores the size expression in ArraySize.
Douglas Gregor3433cf72009-05-21 00:00:09 +0000500bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +0000501 SourceRange R) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000502 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
503 // abstract class type or array thereof.
Douglas Gregore7450f52009-03-24 19:52:54 +0000504 if (AllocType->isFunctionType())
Douglas Gregor3433cf72009-05-21 00:00:09 +0000505 return Diag(Loc, diag::err_bad_new_type)
506 << AllocType << 0 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +0000507 else if (AllocType->isReferenceType())
Douglas Gregor3433cf72009-05-21 00:00:09 +0000508 return Diag(Loc, diag::err_bad_new_type)
509 << AllocType << 1 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +0000510 else if (!AllocType->isDependentType() &&
Douglas Gregor3433cf72009-05-21 00:00:09 +0000511 RequireCompleteType(Loc, AllocType,
Anders Carlssonb7906612009-08-26 23:45:07 +0000512 PDiag(diag::err_new_incomplete_type)
513 << R))
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000514 return true;
Douglas Gregor3433cf72009-05-21 00:00:09 +0000515 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregore7450f52009-03-24 19:52:54 +0000516 diag::err_allocation_of_abstract_type))
517 return true;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000518
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000519 return false;
520}
521
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000522/// FindAllocationFunctions - Finds the overloads of operator new and delete
523/// that are appropriate for the allocation.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000524bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
525 bool UseGlobal, QualType AllocType,
526 bool IsArray, Expr **PlaceArgs,
527 unsigned NumPlaceArgs,
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000528 FunctionDecl *&OperatorNew,
Mike Stump1eb44332009-09-09 15:08:12 +0000529 FunctionDecl *&OperatorDelete) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000530 // --- Choosing an allocation function ---
531 // C++ 5.3.4p8 - 14 & 18
532 // 1) If UseGlobal is true, only look in the global scope. Else, also look
533 // in the scope of the allocated class.
534 // 2) If an array size is given, look for operator new[], else look for
535 // operator new.
536 // 3) The first argument is always size_t. Append the arguments from the
537 // placement form.
538 // FIXME: Also find the appropriate delete operator.
539
540 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
541 // We don't care about the actual value of this argument.
542 // FIXME: Should the Sema create the expression and embed it in the syntax
543 // tree? Or should the consumer just recalculate the value?
Anders Carlssond67c4c32009-08-16 20:29:29 +0000544 IntegerLiteral Size(llvm::APInt::getNullValue(
545 Context.Target.getPointerWidth(0)),
546 Context.getSizeType(),
547 SourceLocation());
548 AllocArgs[0] = &Size;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000549 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
550
551 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
552 IsArray ? OO_Array_New : OO_New);
553 if (AllocType->isRecordType() && !UseGlobal) {
Mike Stump1eb44332009-09-09 15:08:12 +0000554 CXXRecordDecl *Record
Ted Kremenek6217b802009-07-29 21:53:49 +0000555 = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl());
Sebastian Redl7f662392008-12-04 22:20:51 +0000556 // FIXME: We fail to find inherited overloads.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000557 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000558 AllocArgs.size(), Record, /*AllowMissing=*/true,
559 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000560 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000561 }
562 if (!OperatorNew) {
563 // Didn't find a member overload. Look for a global one.
564 DeclareGlobalNewDelete();
Sebastian Redl7f662392008-12-04 22:20:51 +0000565 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl00e68e22009-02-09 18:24:27 +0000566 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000567 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
568 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000569 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000570 }
571
Anders Carlssond9583892009-05-31 20:26:12 +0000572 // FindAllocationOverload can change the passed in arguments, so we need to
573 // copy them back.
574 if (NumPlaceArgs > 0)
575 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
Mike Stump1eb44332009-09-09 15:08:12 +0000576
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000577 return false;
578}
579
Sebastian Redl7f662392008-12-04 22:20:51 +0000580/// FindAllocationOverload - Find an fitting overload for the allocation
581/// function in the specified scope.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000582bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
583 DeclarationName Name, Expr** Args,
584 unsigned NumArgs, DeclContext *Ctx,
Mike Stump1eb44332009-09-09 15:08:12 +0000585 bool AllowMissing, FunctionDecl *&Operator) {
John McCalla24dc2e2009-11-17 02:14:36 +0000586 LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
587 LookupQualifiedName(R, Ctx);
John McCallf36e02d2009-10-09 21:13:30 +0000588 if (R.empty()) {
Sebastian Redl7f662392008-12-04 22:20:51 +0000589 if (AllowMissing)
590 return false;
Sebastian Redl7f662392008-12-04 22:20:51 +0000591 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +0000592 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +0000593 }
594
John McCallf36e02d2009-10-09 21:13:30 +0000595 // FIXME: handle ambiguity
596
Sebastian Redl7f662392008-12-04 22:20:51 +0000597 OverloadCandidateSet Candidates;
Douglas Gregor5d64e5b2009-09-30 00:03:47 +0000598 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
599 Alloc != AllocEnd; ++Alloc) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000600 // Even member operator new/delete are implicitly treated as
601 // static, so don't use AddMemberCandidate.
Douglas Gregor90916562009-09-29 18:16:17 +0000602 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>(*Alloc)) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000603 AddOverloadCandidate(Fn, Args, NumArgs, Candidates,
604 /*SuppressUserConversions=*/false);
Douglas Gregor90916562009-09-29 18:16:17 +0000605 continue;
606 }
607
608 // FIXME: Handle function templates
Sebastian Redl7f662392008-12-04 22:20:51 +0000609 }
610
611 // Do the resolution.
612 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +0000613 switch(BestViableFunction(Candidates, StartLoc, Best)) {
Sebastian Redl7f662392008-12-04 22:20:51 +0000614 case OR_Success: {
615 // Got one!
616 FunctionDecl *FnDecl = Best->Function;
617 // The first argument is size_t, and the first parameter must be size_t,
618 // too. This is checked on declaration and can be assumed. (It can't be
619 // asserted on, though, since invalid decls are left in there.)
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000620 // Whatch out for variadic allocator function.
621 unsigned NumArgsInFnDecl = FnDecl->getNumParams();
622 for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) {
Sebastian Redl7f662392008-12-04 22:20:51 +0000623 // FIXME: Passing word to diagnostic.
Anders Carlssonfc27d262009-05-31 19:49:47 +0000624 if (PerformCopyInitialization(Args[i],
Sebastian Redl7f662392008-12-04 22:20:51 +0000625 FnDecl->getParamDecl(i)->getType(),
626 "passing"))
627 return true;
628 }
629 Operator = FnDecl;
630 return false;
631 }
632
633 case OR_No_Viable_Function:
Sebastian Redl7f662392008-12-04 22:20:51 +0000634 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +0000635 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +0000636 PrintOverloadCandidates(Candidates, /*OnlyViable=*/false);
637 return true;
638
639 case OR_Ambiguous:
Sebastian Redl7f662392008-12-04 22:20:51 +0000640 Diag(StartLoc, diag::err_ovl_ambiguous_call)
Sebastian Redl00e68e22009-02-09 18:24:27 +0000641 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +0000642 PrintOverloadCandidates(Candidates, /*OnlyViable=*/true);
643 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000644
645 case OR_Deleted:
646 Diag(StartLoc, diag::err_ovl_deleted_call)
647 << Best->Function->isDeleted()
648 << Name << Range;
649 PrintOverloadCandidates(Candidates, /*OnlyViable=*/true);
650 return true;
Sebastian Redl7f662392008-12-04 22:20:51 +0000651 }
652 assert(false && "Unreachable, bad result from BestViableFunction");
653 return true;
654}
655
656
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000657/// DeclareGlobalNewDelete - Declare the global forms of operator new and
658/// delete. These are:
659/// @code
660/// void* operator new(std::size_t) throw(std::bad_alloc);
661/// void* operator new[](std::size_t) throw(std::bad_alloc);
662/// void operator delete(void *) throw();
663/// void operator delete[](void *) throw();
664/// @endcode
665/// Note that the placement and nothrow forms of new are *not* implicitly
666/// declared. Their use requires including \<new\>.
Mike Stump1eb44332009-09-09 15:08:12 +0000667void Sema::DeclareGlobalNewDelete() {
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000668 if (GlobalNewDeleteDeclared)
669 return;
Douglas Gregor7adb10f2009-09-15 22:30:29 +0000670
671 // C++ [basic.std.dynamic]p2:
672 // [...] The following allocation and deallocation functions (18.4) are
673 // implicitly declared in global scope in each translation unit of a
674 // program
675 //
676 // void* operator new(std::size_t) throw(std::bad_alloc);
677 // void* operator new[](std::size_t) throw(std::bad_alloc);
678 // void operator delete(void*) throw();
679 // void operator delete[](void*) throw();
680 //
681 // These implicit declarations introduce only the function names operator
682 // new, operator new[], operator delete, operator delete[].
683 //
684 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
685 // "std" or "bad_alloc" as necessary to form the exception specification.
686 // However, we do not make these implicit declarations visible to name
687 // lookup.
688 if (!StdNamespace) {
689 // The "std" namespace has not yet been defined, so build one implicitly.
690 StdNamespace = NamespaceDecl::Create(Context,
691 Context.getTranslationUnitDecl(),
692 SourceLocation(),
693 &PP.getIdentifierTable().get("std"));
694 StdNamespace->setImplicit(true);
695 }
696
697 if (!StdBadAlloc) {
698 // The "std::bad_alloc" class has not yet been declared, so build it
699 // implicitly.
700 StdBadAlloc = CXXRecordDecl::Create(Context, TagDecl::TK_class,
701 StdNamespace,
702 SourceLocation(),
703 &PP.getIdentifierTable().get("bad_alloc"),
704 SourceLocation(), 0);
705 StdBadAlloc->setImplicit(true);
706 }
707
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000708 GlobalNewDeleteDeclared = true;
709
710 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
711 QualType SizeT = Context.getSizeType();
712
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000713 DeclareGlobalAllocationFunction(
714 Context.DeclarationNames.getCXXOperatorName(OO_New),
715 VoidPtr, SizeT);
716 DeclareGlobalAllocationFunction(
717 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
718 VoidPtr, SizeT);
719 DeclareGlobalAllocationFunction(
720 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
721 Context.VoidTy, VoidPtr);
722 DeclareGlobalAllocationFunction(
723 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
724 Context.VoidTy, VoidPtr);
725}
726
727/// DeclareGlobalAllocationFunction - Declares a single implicit global
728/// allocation function if it doesn't already exist.
729void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Mike Stump1eb44332009-09-09 15:08:12 +0000730 QualType Return, QualType Argument) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000731 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
732
733 // Check if this function is already declared.
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000734 {
Douglas Gregor5cc37092008-12-23 22:05:29 +0000735 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000736 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000737 Alloc != AllocEnd; ++Alloc) {
738 // FIXME: Do we need to check for default arguments here?
739 FunctionDecl *Func = cast<FunctionDecl>(*Alloc);
740 if (Func->getNumParams() == 1 &&
Ted Kremenek8189cde2009-02-07 01:47:29 +0000741 Context.getCanonicalType(Func->getParamDecl(0)->getType())==Argument)
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000742 return;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000743 }
744 }
745
Douglas Gregor7adb10f2009-09-15 22:30:29 +0000746 QualType BadAllocType;
747 bool HasBadAllocExceptionSpec
748 = (Name.getCXXOverloadedOperator() == OO_New ||
749 Name.getCXXOverloadedOperator() == OO_Array_New);
750 if (HasBadAllocExceptionSpec) {
751 assert(StdBadAlloc && "Must have std::bad_alloc declared");
752 BadAllocType = Context.getTypeDeclType(StdBadAlloc);
753 }
754
755 QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0,
756 true, false,
757 HasBadAllocExceptionSpec? 1 : 0,
758 &BadAllocType);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000759 FunctionDecl *Alloc =
760 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +0000761 FnType, /*DInfo=*/0, FunctionDecl::None, false, true);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000762 Alloc->setImplicit();
763 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000764 0, Argument, /*DInfo=*/0,
765 VarDecl::None, 0);
Ted Kremenekfc767612009-01-14 00:42:25 +0000766 Alloc->setParams(Context, &Param, 1);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000767
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000768 // FIXME: Also add this declaration to the IdentifierResolver, but
769 // make sure it is at the end of the chain to coincide with the
770 // global scope.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000771 ((DeclContext *)TUScope->getEntity())->addDecl(Alloc);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000772}
773
Anders Carlsson78f74552009-11-15 18:45:20 +0000774bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
775 DeclarationName Name,
776 FunctionDecl* &Operator) {
John McCalla24dc2e2009-11-17 02:14:36 +0000777 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlsson78f74552009-11-15 18:45:20 +0000778 // Try to find operator delete/operator delete[] in class scope.
John McCalla24dc2e2009-11-17 02:14:36 +0000779 LookupQualifiedName(Found, RD);
Anders Carlsson78f74552009-11-15 18:45:20 +0000780
John McCalla24dc2e2009-11-17 02:14:36 +0000781 if (Found.isAmbiguous())
Anders Carlsson78f74552009-11-15 18:45:20 +0000782 return true;
Anders Carlsson78f74552009-11-15 18:45:20 +0000783
784 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
785 F != FEnd; ++F) {
786 if (CXXMethodDecl *Delete = dyn_cast<CXXMethodDecl>(*F))
787 if (Delete->isUsualDeallocationFunction()) {
788 Operator = Delete;
789 return false;
790 }
791 }
792
793 // We did find operator delete/operator delete[] declarations, but
794 // none of them were suitable.
795 if (!Found.empty()) {
796 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
797 << Name << RD;
798
799 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
800 F != FEnd; ++F) {
801 Diag((*F)->getLocation(),
802 diag::note_delete_member_function_declared_here)
803 << Name;
804 }
805
806 return true;
807 }
808
809 // Look for a global declaration.
810 DeclareGlobalNewDelete();
811 DeclContext *TUDecl = Context.getTranslationUnitDecl();
812
813 CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation());
814 Expr* DeallocArgs[1];
815 DeallocArgs[0] = &Null;
816 if (FindAllocationOverload(StartLoc, SourceRange(), Name,
817 DeallocArgs, 1, TUDecl, /*AllowMissing=*/false,
818 Operator))
819 return true;
820
821 assert(Operator && "Did not find a deallocation function!");
822 return false;
823}
824
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000825/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
826/// @code ::delete ptr; @endcode
827/// or
828/// @code delete [] ptr; @endcode
Sebastian Redlf53597f2009-03-15 17:47:39 +0000829Action::OwningExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000830Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
Mike Stump1eb44332009-09-09 15:08:12 +0000831 bool ArrayForm, ExprArg Operand) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000832 // C++ [expr.delete]p1:
833 // The operand shall have a pointer type, or a class type having a single
834 // conversion function to a pointer type. The result has type void.
835 //
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000836 // DR599 amends "pointer type" to "pointer to object type" in both cases.
837
Anders Carlssond67c4c32009-08-16 20:29:29 +0000838 FunctionDecl *OperatorDelete = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000839
Sebastian Redlf53597f2009-03-15 17:47:39 +0000840 Expr *Ex = (Expr *)Operand.get();
Sebastian Redl28507842009-02-26 14:39:58 +0000841 if (!Ex->isTypeDependent()) {
842 QualType Type = Ex->getType();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000843
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000844 if (const RecordType *Record = Type->getAs<RecordType>()) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000845 llvm::SmallVector<CXXConversionDecl *, 4> ObjectPtrConversions;
Fariborz Jahanian53462782009-09-11 21:44:33 +0000846 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
John McCallba135432009-11-21 08:51:07 +0000847 const UnresolvedSet *Conversions = RD->getVisibleConversionFunctions();
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000848
John McCallba135432009-11-21 08:51:07 +0000849 for (UnresolvedSet::iterator I = Conversions->begin(),
850 E = Conversions->end(); I != E; ++I) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000851 // Skip over templated conversion functions; they aren't considered.
John McCallba135432009-11-21 08:51:07 +0000852 if (isa<FunctionTemplateDecl>(*I))
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000853 continue;
854
John McCallba135432009-11-21 08:51:07 +0000855 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*I);
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000856
857 QualType ConvType = Conv->getConversionType().getNonReferenceType();
858 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
859 if (ConvPtrType->getPointeeType()->isObjectType())
Fariborz Jahanian8b915e72009-09-15 22:15:23 +0000860 ObjectPtrConversions.push_back(Conv);
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000861 }
Fariborz Jahanian8b915e72009-09-15 22:15:23 +0000862 if (ObjectPtrConversions.size() == 1) {
863 // We have a single conversion to a pointer-to-object type. Perform
864 // that conversion.
865 Operand.release();
866 if (!PerformImplicitConversion(Ex,
867 ObjectPtrConversions.front()->getConversionType(),
868 "converting")) {
869 Operand = Owned(Ex);
870 Type = Ex->getType();
871 }
872 }
873 else if (ObjectPtrConversions.size() > 1) {
874 Diag(StartLoc, diag::err_ambiguous_delete_operand)
875 << Type << Ex->getSourceRange();
876 for (unsigned i= 0; i < ObjectPtrConversions.size(); i++) {
877 CXXConversionDecl *Conv = ObjectPtrConversions[i];
878 Diag(Conv->getLocation(), diag::err_ovl_candidate);
879 }
880 return ExprError();
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000881 }
Sebastian Redl28507842009-02-26 14:39:58 +0000882 }
883
Sebastian Redlf53597f2009-03-15 17:47:39 +0000884 if (!Type->isPointerType())
885 return ExprError(Diag(StartLoc, diag::err_delete_operand)
886 << Type << Ex->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +0000887
Ted Kremenek6217b802009-07-29 21:53:49 +0000888 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Douglas Gregor8dcb29d2009-03-24 20:13:58 +0000889 if (Pointee->isFunctionType() || Pointee->isVoidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000890 return ExprError(Diag(StartLoc, diag::err_delete_operand)
891 << Type << Ex->getSourceRange());
Douglas Gregor8dcb29d2009-03-24 20:13:58 +0000892 else if (!Pointee->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +0000893 RequireCompleteType(StartLoc, Pointee,
Anders Carlssonb7906612009-08-26 23:45:07 +0000894 PDiag(diag::warn_delete_incomplete)
895 << Ex->getSourceRange()))
Douglas Gregor8dcb29d2009-03-24 20:13:58 +0000896 return ExprError();
Sebastian Redl28507842009-02-26 14:39:58 +0000897
Douglas Gregor1070c9f2009-09-29 21:38:53 +0000898 // C++ [expr.delete]p2:
899 // [Note: a pointer to a const type can be the operand of a
900 // delete-expression; it is not necessary to cast away the constness
901 // (5.2.11) of the pointer expression before it is used as the operand
902 // of the delete-expression. ]
903 ImpCastExprToType(Ex, Context.getPointerType(Context.VoidTy),
904 CastExpr::CK_NoOp);
905
906 // Update the operand.
907 Operand.take();
908 Operand = ExprArg(*this, Ex);
909
Anders Carlssond67c4c32009-08-16 20:29:29 +0000910 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
911 ArrayForm ? OO_Array_Delete : OO_Delete);
912
Anders Carlsson78f74552009-11-15 18:45:20 +0000913 if (const RecordType *RT = Pointee->getAs<RecordType>()) {
914 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
915
916 if (!UseGlobal &&
917 FindDeallocationFunction(StartLoc, RD, DeleteName, OperatorDelete))
Anders Carlsson0ba63ea2009-11-14 03:17:38 +0000918 return ExprError();
Anders Carlsson0ba63ea2009-11-14 03:17:38 +0000919
Anders Carlsson78f74552009-11-15 18:45:20 +0000920 if (!RD->hasTrivialDestructor())
921 if (const CXXDestructorDecl *Dtor = RD->getDestructor(Context))
Mike Stump1eb44332009-09-09 15:08:12 +0000922 MarkDeclarationReferenced(StartLoc,
Fariborz Jahanian34374e62009-09-03 23:18:17 +0000923 const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssond67c4c32009-08-16 20:29:29 +0000924 }
Anders Carlsson78f74552009-11-15 18:45:20 +0000925
Anders Carlssond67c4c32009-08-16 20:29:29 +0000926 if (!OperatorDelete) {
Anders Carlsson78f74552009-11-15 18:45:20 +0000927 // Look for a global declaration.
Anders Carlssond67c4c32009-08-16 20:29:29 +0000928 DeclareGlobalNewDelete();
929 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000930 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
Douglas Gregor90916562009-09-29 18:16:17 +0000931 &Ex, 1, TUDecl, /*AllowMissing=*/false,
Anders Carlssond67c4c32009-08-16 20:29:29 +0000932 OperatorDelete))
933 return ExprError();
934 }
Mike Stump1eb44332009-09-09 15:08:12 +0000935
Sebastian Redl28507842009-02-26 14:39:58 +0000936 // FIXME: Check access and ambiguity of operator delete and destructor.
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000937 }
938
Sebastian Redlf53597f2009-03-15 17:47:39 +0000939 Operand.release();
940 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
Anders Carlssond67c4c32009-08-16 20:29:29 +0000941 OperatorDelete, Ex, StartLoc));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000942}
943
944
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000945/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
946/// C++ if/switch/while/for statement.
947/// e.g: "if (int x = f()) {...}"
Sebastian Redlf53597f2009-03-15 17:47:39 +0000948Action::OwningExprResult
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000949Sema::ActOnCXXConditionDeclarationExpr(Scope *S, SourceLocation StartLoc,
950 Declarator &D,
951 SourceLocation EqualLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000952 ExprArg AssignExprVal) {
953 assert(AssignExprVal.get() && "Null assignment expression");
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000954
955 // C++ 6.4p2:
956 // The declarator shall not specify a function or an array.
957 // The type-specifier-seq shall not contain typedef and shall not declare a
958 // new class or enumeration.
959
960 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
961 "Parser allowed 'typedef' as storage class of condition decl.");
962
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000963 // FIXME: Store DeclaratorInfo in the expression.
964 DeclaratorInfo *DInfo = 0;
Argyrios Kyrtzidise955e722009-08-11 05:20:41 +0000965 TagDecl *OwnedTag = 0;
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000966 QualType Ty = GetTypeForDeclarator(D, S, &DInfo, &OwnedTag);
Mike Stump1eb44332009-09-09 15:08:12 +0000967
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000968 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
969 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
970 // would be created and CXXConditionDeclExpr wants a VarDecl.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000971 return ExprError(Diag(StartLoc, diag::err_invalid_use_of_function_type)
972 << SourceRange(StartLoc, EqualLoc));
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000973 } else if (Ty->isArrayType()) { // ...or an array.
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000974 Diag(StartLoc, diag::err_invalid_use_of_array_type)
975 << SourceRange(StartLoc, EqualLoc);
Argyrios Kyrtzidise955e722009-08-11 05:20:41 +0000976 } else if (OwnedTag && OwnedTag->isDefinition()) {
977 // The type-specifier-seq shall not declare a new class or enumeration.
978 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000979 }
980
Douglas Gregor2e01cda2009-06-23 21:43:56 +0000981 DeclPtrTy Dcl = ActOnDeclarator(S, D);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000982 if (!Dcl)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000983 return ExprError();
Anders Carlssonf5dcd382009-05-30 21:37:25 +0000984 AddInitializerToDecl(Dcl, move(AssignExprVal), /*DirectInit=*/false);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000985
Douglas Gregorcaaf29a2008-12-10 23:01:14 +0000986 // Mark this variable as one that is declared within a conditional.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000987 // We know that the decl had to be a VarDecl because that is the only type of
988 // decl that can be assigned and the grammar requires an '='.
989 VarDecl *VD = cast<VarDecl>(Dcl.getAs<Decl>());
990 VD->setDeclaredInCondition(true);
991 return Owned(new (Context) CXXConditionDeclExpr(StartLoc, EqualLoc, VD));
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000992}
993
Douglas Gregor8cfe5a72009-11-23 23:44:04 +0000994/// \brief Check the use of the given variable as a C++ condition in an if,
995/// while, do-while, or switch statement.
996Action::OwningExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar) {
997 QualType T = ConditionVar->getType();
998
999 // C++ [stmt.select]p2:
1000 // The declarator shall not specify a function or an array.
1001 if (T->isFunctionType())
1002 return ExprError(Diag(ConditionVar->getLocation(),
1003 diag::err_invalid_use_of_function_type)
1004 << ConditionVar->getSourceRange());
1005 else if (T->isArrayType())
1006 return ExprError(Diag(ConditionVar->getLocation(),
1007 diag::err_invalid_use_of_array_type)
1008 << ConditionVar->getSourceRange());
Douglas Gregora7605db2009-11-24 16:07:02 +00001009
1010 // FIXME: Switch to building a DeclRefExpr, once we've eliminated the
1011 // need for CXXConditionDeclExpr.
1012#if 0
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001013 return Owned(DeclRefExpr::Create(Context, 0, SourceRange(), ConditionVar,
1014 ConditionVar->getLocation(),
1015 ConditionVar->getType().getNonReferenceType()));
Douglas Gregora7605db2009-11-24 16:07:02 +00001016#else
1017 return Owned(new (Context) CXXConditionDeclExpr(
1018 ConditionVar->getSourceRange().getBegin(),
1019 ConditionVar->getSourceRange().getEnd(),
1020 ConditionVar));
1021#endif
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001022}
1023
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001024/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
1025bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
1026 // C++ 6.4p4:
1027 // The value of a condition that is an initialized declaration in a statement
1028 // other than a switch statement is the value of the declared variable
1029 // implicitly converted to type bool. If that conversion is ill-formed, the
1030 // program is ill-formed.
1031 // The value of a condition that is an expression is the value of the
1032 // expression, implicitly converted to bool.
1033 //
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001034 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001035}
Douglas Gregor77a52232008-09-12 00:47:35 +00001036
1037/// Helper function to determine whether this is the (deprecated) C++
1038/// conversion from a string literal to a pointer to non-const char or
1039/// non-const wchar_t (for narrow and wide string literals,
1040/// respectively).
Mike Stump1eb44332009-09-09 15:08:12 +00001041bool
Douglas Gregor77a52232008-09-12 00:47:35 +00001042Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
1043 // Look inside the implicit cast, if it exists.
1044 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
1045 From = Cast->getSubExpr();
1046
1047 // A string literal (2.13.4) that is not a wide string literal can
1048 // be converted to an rvalue of type "pointer to char"; a wide
1049 // string literal can be converted to an rvalue of type "pointer
1050 // to wchar_t" (C++ 4.2p2).
1051 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From))
Ted Kremenek6217b802009-07-29 21:53:49 +00001052 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump1eb44332009-09-09 15:08:12 +00001053 if (const BuiltinType *ToPointeeType
John McCall183700f2009-09-21 23:43:11 +00001054 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregor77a52232008-09-12 00:47:35 +00001055 // This conversion is considered only when there is an
1056 // explicit appropriate pointer target type (C++ 4.2p2).
John McCall0953e762009-09-24 19:53:00 +00001057 if (!ToPtrType->getPointeeType().hasQualifiers() &&
Douglas Gregor77a52232008-09-12 00:47:35 +00001058 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
1059 (!StrLit->isWide() &&
1060 (ToPointeeType->getKind() == BuiltinType::Char_U ||
1061 ToPointeeType->getKind() == BuiltinType::Char_S))))
1062 return true;
1063 }
1064
1065 return false;
1066}
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001067
1068/// PerformImplicitConversion - Perform an implicit conversion of the
1069/// expression From to the type ToType. Returns true if there was an
1070/// error, false otherwise. The expression From is replaced with the
Douglas Gregor45920e82008-12-19 17:40:08 +00001071/// converted expression. Flavor is the kind of conversion we're
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001072/// performing, used in the error message. If @p AllowExplicit,
Sebastian Redle2b68332009-04-12 17:16:29 +00001073/// explicit user-defined conversions are permitted. @p Elidable should be true
1074/// when called for copies which may be elided (C++ 12.8p15). C++0x overload
1075/// resolution works differently in that case.
1076bool
Douglas Gregor45920e82008-12-19 17:40:08 +00001077Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Sebastian Redle2b68332009-04-12 17:16:29 +00001078 const char *Flavor, bool AllowExplicit,
Mike Stump1eb44332009-09-09 15:08:12 +00001079 bool Elidable) {
Sebastian Redle2b68332009-04-12 17:16:29 +00001080 ImplicitConversionSequence ICS;
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00001081 return PerformImplicitConversion(From, ToType, Flavor, AllowExplicit,
1082 Elidable, ICS);
1083}
1084
1085bool
1086Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
1087 const char *Flavor, bool AllowExplicit,
1088 bool Elidable,
1089 ImplicitConversionSequence& ICS) {
Sebastian Redle2b68332009-04-12 17:16:29 +00001090 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1091 if (Elidable && getLangOptions().CPlusPlus0x) {
Mike Stump1eb44332009-09-09 15:08:12 +00001092 ICS = TryImplicitConversion(From, ToType,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001093 /*SuppressUserConversions=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +00001094 AllowExplicit,
Anders Carlsson08972922009-08-28 15:33:32 +00001095 /*ForceRValue=*/true,
1096 /*InOverloadResolution=*/false);
Sebastian Redle2b68332009-04-12 17:16:29 +00001097 }
1098 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion) {
Mike Stump1eb44332009-09-09 15:08:12 +00001099 ICS = TryImplicitConversion(From, ToType,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001100 /*SuppressUserConversions=*/false,
1101 AllowExplicit,
Anders Carlsson08972922009-08-28 15:33:32 +00001102 /*ForceRValue=*/false,
1103 /*InOverloadResolution=*/false);
Sebastian Redle2b68332009-04-12 17:16:29 +00001104 }
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001105 return PerformImplicitConversion(From, ToType, ICS, Flavor);
1106}
1107
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001108/// BuildCXXDerivedToBaseExpr - This routine generates the suitable AST
1109/// for the derived to base conversion of the expression 'From'. All
1110/// necessary information is passed in ICS.
1111bool
1112Sema::BuildCXXDerivedToBaseExpr(Expr *&From, CastExpr::CastKind CastKind,
1113 const ImplicitConversionSequence& ICS,
1114 const char *Flavor) {
1115 QualType BaseType =
1116 QualType::getFromOpaquePtr(ICS.UserDefined.After.ToTypePtr);
1117 // Must do additional defined to base conversion.
1118 QualType DerivedType =
1119 QualType::getFromOpaquePtr(ICS.UserDefined.After.FromTypePtr);
1120
1121 From = new (Context) ImplicitCastExpr(
1122 DerivedType.getNonReferenceType(),
1123 CastKind,
1124 From,
1125 DerivedType->isLValueReferenceType());
1126 From = new (Context) ImplicitCastExpr(BaseType.getNonReferenceType(),
1127 CastExpr::CK_DerivedToBase, From,
1128 BaseType->isLValueReferenceType());
1129 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1130 OwningExprResult FromResult =
1131 BuildCXXConstructExpr(
1132 ICS.UserDefined.After.CopyConstructor->getLocation(),
1133 BaseType,
1134 ICS.UserDefined.After.CopyConstructor,
1135 MultiExprArg(*this, (void **)&From, 1));
1136 if (FromResult.isInvalid())
1137 return true;
1138 From = FromResult.takeAs<Expr>();
1139 return false;
1140}
1141
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001142/// PerformImplicitConversion - Perform an implicit conversion of the
1143/// expression From to the type ToType using the pre-computed implicit
1144/// conversion sequence ICS. Returns true if there was an error, false
1145/// otherwise. The expression From is replaced with the converted
1146/// expression. Flavor is the kind of conversion we're performing,
1147/// used in the error message.
1148bool
1149Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
1150 const ImplicitConversionSequence &ICS,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001151 const char* Flavor, bool IgnoreBaseAccess) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001152 switch (ICS.ConversionKind) {
1153 case ImplicitConversionSequence::StandardConversion:
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001154 if (PerformImplicitConversion(From, ToType, ICS.Standard, Flavor,
1155 IgnoreBaseAccess))
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001156 return true;
1157 break;
1158
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001159 case ImplicitConversionSequence::UserDefinedConversion: {
1160
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00001161 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
1162 CastExpr::CastKind CastKind = CastExpr::CK_Unknown;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001163 QualType BeforeToType;
1164 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00001165 CastKind = CastExpr::CK_UserDefinedConversion;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001166
1167 // If the user-defined conversion is specified by a conversion function,
1168 // the initial standard conversion sequence converts the source type to
1169 // the implicit object parameter of the conversion function.
1170 BeforeToType = Context.getTagDeclType(Conv->getParent());
1171 } else if (const CXXConstructorDecl *Ctor =
1172 dyn_cast<CXXConstructorDecl>(FD)) {
Anders Carlsson0aebc812009-09-09 21:33:21 +00001173 CastKind = CastExpr::CK_ConstructorConversion;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001174 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregore44201a2009-11-20 02:31:03 +00001175 if (!ICS.UserDefined.EllipsisConversion) {
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001176 // If the user-defined conversion is specified by a constructor, the
1177 // initial standard conversion sequence converts the source type to the
1178 // type required by the argument of the constructor
Douglas Gregore44201a2009-11-20 02:31:03 +00001179 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
1180 }
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001181 }
Anders Carlsson0aebc812009-09-09 21:33:21 +00001182 else
1183 assert(0 && "Unknown conversion function kind!");
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001184 // Whatch out for elipsis conversion.
Fariborz Jahanian4c0cea22009-11-06 00:55:14 +00001185 if (!ICS.UserDefined.EllipsisConversion) {
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001186 if (PerformImplicitConversion(From, BeforeToType,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001187 ICS.UserDefined.Before, "converting",
1188 IgnoreBaseAccess))
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001189 return true;
1190 }
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001191
Anders Carlsson0aebc812009-09-09 21:33:21 +00001192 OwningExprResult CastArg
1193 = BuildCXXCastArgument(From->getLocStart(),
1194 ToType.getNonReferenceType(),
1195 CastKind, cast<CXXMethodDecl>(FD),
1196 Owned(From));
1197
1198 if (CastArg.isInvalid())
1199 return true;
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001200
1201 if (ICS.UserDefined.After.Second == ICK_Derived_To_Base &&
1202 ICS.UserDefined.After.CopyConstructor) {
1203 From = CastArg.takeAs<Expr>();
1204 return BuildCXXDerivedToBaseExpr(From, CastKind, ICS, Flavor);
1205 }
Fariborz Jahanian7a1f4cc2009-10-23 18:08:22 +00001206
1207 if (ICS.UserDefined.After.Second == ICK_Pointer_Member &&
1208 ToType.getNonReferenceType()->isMemberFunctionPointerType())
1209 CastKind = CastExpr::CK_BaseToDerivedMemberPointer;
Anders Carlsson0aebc812009-09-09 21:33:21 +00001210
Anders Carlsson626c2d62009-09-15 05:49:31 +00001211 From = new (Context) ImplicitCastExpr(ToType.getNonReferenceType(),
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001212 CastKind, CastArg.takeAs<Expr>(),
Anders Carlsson626c2d62009-09-15 05:49:31 +00001213 ToType->isLValueReferenceType());
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00001214 return false;
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001215 }
1216
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001217 case ImplicitConversionSequence::EllipsisConversion:
1218 assert(false && "Cannot perform an ellipsis conversion");
Douglas Gregor60d62c22008-10-31 16:23:19 +00001219 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001220
1221 case ImplicitConversionSequence::BadConversion:
1222 return true;
1223 }
1224
1225 // Everything went well.
1226 return false;
1227}
1228
1229/// PerformImplicitConversion - Perform an implicit conversion of the
1230/// expression From to the type ToType by following the standard
1231/// conversion sequence SCS. Returns true if there was an error, false
1232/// otherwise. The expression From is replaced with the converted
Douglas Gregor45920e82008-12-19 17:40:08 +00001233/// expression. Flavor is the context in which we're performing this
1234/// conversion, for use in error messages.
Mike Stump1eb44332009-09-09 15:08:12 +00001235bool
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001236Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor45920e82008-12-19 17:40:08 +00001237 const StandardConversionSequence& SCS,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001238 const char *Flavor, bool IgnoreBaseAccess) {
Mike Stump390b4cc2009-05-16 07:39:55 +00001239 // Overall FIXME: we are recomputing too many types here and doing far too
1240 // much extra work. What this means is that we need to keep track of more
1241 // information that is computed when we try the implicit conversion initially,
1242 // so that we don't need to recompute anything here.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001243 QualType FromType = From->getType();
1244
Douglas Gregor225c41e2008-11-03 19:09:14 +00001245 if (SCS.CopyConstructor) {
Anders Carlsson7c3e8a12009-05-19 04:45:15 +00001246 // FIXME: When can ToType be a reference type?
1247 assert(!ToType->isReferenceType());
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00001248 if (SCS.Second == ICK_Derived_To_Base) {
1249 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1250 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
1251 MultiExprArg(*this, (void **)&From, 1),
1252 /*FIXME:ConstructLoc*/SourceLocation(),
1253 ConstructorArgs))
1254 return true;
1255 OwningExprResult FromResult =
1256 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1257 ToType, SCS.CopyConstructor,
1258 move_arg(ConstructorArgs));
1259 if (FromResult.isInvalid())
1260 return true;
1261 From = FromResult.takeAs<Expr>();
1262 return false;
1263 }
Mike Stump1eb44332009-09-09 15:08:12 +00001264 OwningExprResult FromResult =
1265 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1266 ToType, SCS.CopyConstructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00001267 MultiExprArg(*this, (void**)&From, 1));
Mike Stump1eb44332009-09-09 15:08:12 +00001268
Anders Carlssonda3f4e22009-08-25 05:12:04 +00001269 if (FromResult.isInvalid())
1270 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001271
Anders Carlssonda3f4e22009-08-25 05:12:04 +00001272 From = FromResult.takeAs<Expr>();
Douglas Gregor225c41e2008-11-03 19:09:14 +00001273 return false;
1274 }
1275
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001276 // Perform the first implicit conversion.
1277 switch (SCS.First) {
1278 case ICK_Identity:
1279 case ICK_Lvalue_To_Rvalue:
1280 // Nothing to do.
1281 break;
1282
1283 case ICK_Array_To_Pointer:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001284 FromType = Context.getArrayDecayedType(FromType);
Anders Carlsson82495762009-08-08 21:04:35 +00001285 ImpCastExprToType(From, FromType, CastExpr::CK_ArrayToPointerDecay);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001286 break;
1287
1288 case ICK_Function_To_Pointer:
Douglas Gregor063daf62009-03-13 18:40:31 +00001289 if (Context.getCanonicalType(FromType) == Context.OverloadTy) {
Douglas Gregor904eed32008-11-10 20:40:00 +00001290 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, true);
1291 if (!Fn)
1292 return true;
1293
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001294 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
1295 return true;
1296
Anders Carlsson96ad5332009-10-21 17:16:23 +00001297 From = FixOverloadedFunctionReference(From, Fn);
Douglas Gregor904eed32008-11-10 20:40:00 +00001298 FromType = From->getType();
Anders Carlsson96ad5332009-10-21 17:16:23 +00001299
Sebastian Redl759986e2009-10-17 20:50:27 +00001300 // If there's already an address-of operator in the expression, we have
1301 // the right type already, and the code below would just introduce an
1302 // invalid additional pointer level.
Anders Carlsson96ad5332009-10-21 17:16:23 +00001303 if (FromType->isPointerType() || FromType->isMemberFunctionPointerType())
Sebastian Redl759986e2009-10-17 20:50:27 +00001304 break;
Douglas Gregor904eed32008-11-10 20:40:00 +00001305 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001306 FromType = Context.getPointerType(FromType);
Anders Carlssonb633c4e2009-09-01 20:37:18 +00001307 ImpCastExprToType(From, FromType, CastExpr::CK_FunctionToPointerDecay);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001308 break;
1309
1310 default:
1311 assert(false && "Improper first standard conversion");
1312 break;
1313 }
1314
1315 // Perform the second implicit conversion
1316 switch (SCS.Second) {
1317 case ICK_Identity:
Sebastian Redl2c7588f2009-10-10 12:04:10 +00001318 // If both sides are functions (or pointers/references to them), there could
1319 // be incompatible exception declarations.
1320 if (CheckExceptionSpecCompatibility(From, ToType))
1321 return true;
1322 // Nothing else to do.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001323 break;
1324
1325 case ICK_Integral_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001326 case ICK_Integral_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001327 ImpCastExprToType(From, ToType, CastExpr::CK_IntegralCast);
1328 break;
1329
1330 case ICK_Floating_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001331 case ICK_Floating_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001332 ImpCastExprToType(From, ToType, CastExpr::CK_FloatingCast);
1333 break;
1334
1335 case ICK_Complex_Promotion:
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001336 case ICK_Complex_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001337 ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1338 break;
1339
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001340 case ICK_Floating_Integral:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001341 if (ToType->isFloatingType())
1342 ImpCastExprToType(From, ToType, CastExpr::CK_IntegralToFloating);
1343 else
1344 ImpCastExprToType(From, ToType, CastExpr::CK_FloatingToIntegral);
1345 break;
1346
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001347 case ICK_Complex_Real:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001348 ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1349 break;
1350
Douglas Gregorf9201e02009-02-11 23:02:49 +00001351 case ICK_Compatible_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001352 ImpCastExprToType(From, ToType, CastExpr::CK_NoOp);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001353 break;
1354
Anders Carlsson61faec12009-09-12 04:46:44 +00001355 case ICK_Pointer_Conversion: {
Douglas Gregor45920e82008-12-19 17:40:08 +00001356 if (SCS.IncompatibleObjC) {
1357 // Diagnose incompatible Objective-C conversions
Mike Stump1eb44332009-09-09 15:08:12 +00001358 Diag(From->getSourceRange().getBegin(),
Douglas Gregor45920e82008-12-19 17:40:08 +00001359 diag::ext_typecheck_convert_incompatible_pointer)
1360 << From->getType() << ToType << Flavor
1361 << From->getSourceRange();
1362 }
1363
Anders Carlsson61faec12009-09-12 04:46:44 +00001364
1365 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001366 if (CheckPointerConversion(From, ToType, Kind, IgnoreBaseAccess))
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001367 return true;
Anders Carlsson61faec12009-09-12 04:46:44 +00001368 ImpCastExprToType(From, ToType, Kind);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001369 break;
Anders Carlsson61faec12009-09-12 04:46:44 +00001370 }
1371
1372 case ICK_Pointer_Member: {
1373 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001374 if (CheckMemberPointerConversion(From, ToType, Kind, IgnoreBaseAccess))
Anders Carlsson61faec12009-09-12 04:46:44 +00001375 return true;
Sebastian Redl2c7588f2009-10-10 12:04:10 +00001376 if (CheckExceptionSpecCompatibility(From, ToType))
1377 return true;
Anders Carlsson61faec12009-09-12 04:46:44 +00001378 ImpCastExprToType(From, ToType, Kind);
1379 break;
1380 }
Anders Carlssonbc0e0782009-11-23 20:04:44 +00001381 case ICK_Boolean_Conversion: {
1382 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
1383 if (FromType->isMemberPointerType())
1384 Kind = CastExpr::CK_MemberPointerToBoolean;
1385
1386 ImpCastExprToType(From, Context.BoolTy, Kind);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001387 break;
Anders Carlssonbc0e0782009-11-23 20:04:44 +00001388 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001389
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001390 case ICK_Derived_To_Base:
1391 if (CheckDerivedToBaseConversion(From->getType(),
1392 ToType.getNonReferenceType(),
1393 From->getLocStart(),
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001394 From->getSourceRange(),
1395 IgnoreBaseAccess))
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001396 return true;
1397 ImpCastExprToType(From, ToType.getNonReferenceType(),
1398 CastExpr::CK_DerivedToBase);
1399 break;
1400
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001401 default:
1402 assert(false && "Improper second standard conversion");
1403 break;
1404 }
1405
1406 switch (SCS.Third) {
1407 case ICK_Identity:
1408 // Nothing to do.
1409 break;
1410
1411 case ICK_Qualification:
Mike Stump390b4cc2009-05-16 07:39:55 +00001412 // FIXME: Not sure about lvalue vs rvalue here in the presence of rvalue
1413 // references.
Mike Stump1eb44332009-09-09 15:08:12 +00001414 ImpCastExprToType(From, ToType.getNonReferenceType(),
Eli Friedman73c39ab2009-10-20 08:27:19 +00001415 CastExpr::CK_NoOp,
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001416 ToType->isLValueReferenceType());
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001417 break;
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001418
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001419 default:
1420 assert(false && "Improper second standard conversion");
1421 break;
1422 }
1423
1424 return false;
1425}
1426
Sebastian Redl64b45f72009-01-05 20:52:13 +00001427Sema::OwningExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
1428 SourceLocation KWLoc,
1429 SourceLocation LParen,
1430 TypeTy *Ty,
1431 SourceLocation RParen) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00001432 QualType T = GetTypeFromParser(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00001433
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001434 // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
1435 // all traits except __is_class, __is_enum and __is_union require a the type
1436 // to be complete.
1437 if (OTT != UTT_IsClass && OTT != UTT_IsEnum && OTT != UTT_IsUnion) {
Mike Stump1eb44332009-09-09 15:08:12 +00001438 if (RequireCompleteType(KWLoc, T,
Anders Carlssond497ba72009-08-26 22:59:12 +00001439 diag::err_incomplete_type_used_in_type_trait_expr))
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001440 return ExprError();
1441 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00001442
1443 // There is no point in eagerly computing the value. The traits are designed
1444 // to be used from type trait templates, so Ty will be a template parameter
1445 // 99% of the time.
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001446 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT, T,
1447 RParen, Context.BoolTy));
Sebastian Redl64b45f72009-01-05 20:52:13 +00001448}
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001449
1450QualType Sema::CheckPointerToMemberOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00001451 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001452 const char *OpSpelling = isIndirect ? "->*" : ".*";
1453 // C++ 5.5p2
1454 // The binary operator .* [p3: ->*] binds its second operand, which shall
1455 // be of type "pointer to member of T" (where T is a completely-defined
1456 // class type) [...]
1457 QualType RType = rex->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001458 const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
Douglas Gregore7450f52009-03-24 19:52:54 +00001459 if (!MemPtr) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001460 Diag(Loc, diag::err_bad_memptr_rhs)
1461 << OpSpelling << RType << rex->getSourceRange();
1462 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00001463 }
Douglas Gregore7450f52009-03-24 19:52:54 +00001464
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001465 QualType Class(MemPtr->getClass(), 0);
1466
1467 // C++ 5.5p2
1468 // [...] to its first operand, which shall be of class T or of a class of
1469 // which T is an unambiguous and accessible base class. [p3: a pointer to
1470 // such a class]
1471 QualType LType = lex->getType();
1472 if (isIndirect) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001473 if (const PointerType *Ptr = LType->getAs<PointerType>())
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001474 LType = Ptr->getPointeeType().getNonReferenceType();
1475 else {
1476 Diag(Loc, diag::err_bad_memptr_lhs)
Fariborz Jahanianef78ac62009-10-26 20:45:27 +00001477 << OpSpelling << 1 << LType
1478 << CodeModificationHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001479 return QualType();
1480 }
1481 }
1482
Douglas Gregora4923eb2009-11-16 21:35:15 +00001483 if (!Context.hasSameUnqualifiedType(Class, LType)) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001484 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1485 /*DetectVirtual=*/false);
Mike Stump390b4cc2009-05-16 07:39:55 +00001486 // FIXME: Would it be useful to print full ambiguity paths, or is that
1487 // overkill?
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001488 if (!IsDerivedFrom(LType, Class, Paths) ||
1489 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
Fariborz Jahanianef78ac62009-10-26 20:45:27 +00001490 const char *ReplaceStr = isIndirect ? ".*" : "->*";
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001491 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Fariborz Jahanianef78ac62009-10-26 20:45:27 +00001492 << (int)isIndirect << lex->getType() <<
1493 CodeModificationHint::CreateReplacement(SourceRange(Loc), ReplaceStr);
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001494 return QualType();
1495 }
1496 }
1497
Fariborz Jahanian19d70732009-11-18 22:16:17 +00001498 if (isa<CXXZeroInitValueExpr>(rex->IgnoreParens())) {
Fariborz Jahanian05ebda92009-11-18 21:54:48 +00001499 // Diagnose use of pointer-to-member type which when used as
1500 // the functional cast in a pointer-to-member expression.
1501 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
1502 return QualType();
1503 }
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001504 // C++ 5.5p2
1505 // The result is an object or a function of the type specified by the
1506 // second operand.
1507 // The cv qualifiers are the union of those in the pointer and the left side,
1508 // in accordance with 5.5p5 and 5.2.5.
1509 // FIXME: This returns a dereferenced member function pointer as a normal
1510 // function type. However, the only operation valid on such functions is
Mike Stump390b4cc2009-05-16 07:39:55 +00001511 // calling them. There's also a GCC extension to get a function pointer to the
1512 // thing, which is another complication, because this type - unlike the type
1513 // that is the result of this expression - takes the class as the first
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001514 // argument.
1515 // We probably need a "MemberFunctionClosureType" or something like that.
1516 QualType Result = MemPtr->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00001517 Result = Context.getCVRQualifiedType(Result, LType.getCVRQualifiers());
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001518 return Result;
1519}
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001520
1521/// \brief Get the target type of a standard or user-defined conversion.
1522static QualType TargetType(const ImplicitConversionSequence &ICS) {
1523 assert((ICS.ConversionKind ==
1524 ImplicitConversionSequence::StandardConversion ||
1525 ICS.ConversionKind ==
1526 ImplicitConversionSequence::UserDefinedConversion) &&
1527 "function only valid for standard or user-defined conversions");
1528 if (ICS.ConversionKind == ImplicitConversionSequence::StandardConversion)
1529 return QualType::getFromOpaquePtr(ICS.Standard.ToTypePtr);
1530 return QualType::getFromOpaquePtr(ICS.UserDefined.After.ToTypePtr);
1531}
1532
1533/// \brief Try to convert a type to another according to C++0x 5.16p3.
1534///
1535/// This is part of the parameter validation for the ? operator. If either
1536/// value operand is a class type, the two operands are attempted to be
1537/// converted to each other. This function does the conversion in one direction.
1538/// It emits a diagnostic and returns true only if it finds an ambiguous
1539/// conversion.
1540static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
1541 SourceLocation QuestionLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00001542 ImplicitConversionSequence &ICS) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001543 // C++0x 5.16p3
1544 // The process for determining whether an operand expression E1 of type T1
1545 // can be converted to match an operand expression E2 of type T2 is defined
1546 // as follows:
1547 // -- If E2 is an lvalue:
1548 if (To->isLvalue(Self.Context) == Expr::LV_Valid) {
1549 // E1 can be converted to match E2 if E1 can be implicitly converted to
1550 // type "lvalue reference to T2", subject to the constraint that in the
1551 // conversion the reference must bind directly to E1.
1552 if (!Self.CheckReferenceInit(From,
1553 Self.Context.getLValueReferenceType(To->getType()),
Douglas Gregor739d8282009-09-23 23:04:10 +00001554 To->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001555 /*SuppressUserConversions=*/false,
1556 /*AllowExplicit=*/false,
1557 /*ForceRValue=*/false,
1558 &ICS))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001559 {
1560 assert((ICS.ConversionKind ==
1561 ImplicitConversionSequence::StandardConversion ||
1562 ICS.ConversionKind ==
1563 ImplicitConversionSequence::UserDefinedConversion) &&
1564 "expected a definite conversion");
1565 bool DirectBinding =
1566 ICS.ConversionKind == ImplicitConversionSequence::StandardConversion ?
1567 ICS.Standard.DirectBinding : ICS.UserDefined.After.DirectBinding;
1568 if (DirectBinding)
1569 return false;
1570 }
1571 }
1572 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1573 // -- If E2 is an rvalue, or if the conversion above cannot be done:
1574 // -- if E1 and E2 have class type, and the underlying class types are
1575 // the same or one is a base class of the other:
1576 QualType FTy = From->getType();
1577 QualType TTy = To->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001578 const RecordType *FRec = FTy->getAs<RecordType>();
1579 const RecordType *TRec = TTy->getAs<RecordType>();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001580 bool FDerivedFromT = FRec && TRec && Self.IsDerivedFrom(FTy, TTy);
1581 if (FRec && TRec && (FRec == TRec ||
1582 FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
1583 // E1 can be converted to match E2 if the class of T2 is the
1584 // same type as, or a base class of, the class of T1, and
1585 // [cv2 > cv1].
1586 if ((FRec == TRec || FDerivedFromT) && TTy.isAtLeastAsQualifiedAs(FTy)) {
1587 // Could still fail if there's no copy constructor.
1588 // FIXME: Is this a hard error then, or just a conversion failure? The
1589 // standard doesn't say.
Mike Stump1eb44332009-09-09 15:08:12 +00001590 ICS = Self.TryCopyInitialization(From, TTy,
Anders Carlssond28b4282009-08-27 17:18:13 +00001591 /*SuppressUserConversions=*/false,
Anders Carlsson7b361b52009-08-27 17:37:39 +00001592 /*ForceRValue=*/false,
1593 /*InOverloadResolution=*/false);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001594 }
1595 } else {
1596 // -- Otherwise: E1 can be converted to match E2 if E1 can be
1597 // implicitly converted to the type that expression E2 would have
1598 // if E2 were converted to an rvalue.
1599 // First find the decayed type.
1600 if (TTy->isFunctionType())
1601 TTy = Self.Context.getPointerType(TTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001602 else if (TTy->isArrayType())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001603 TTy = Self.Context.getArrayDecayedType(TTy);
1604
1605 // Now try the implicit conversion.
1606 // FIXME: This doesn't detect ambiguities.
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001607 ICS = Self.TryImplicitConversion(From, TTy,
1608 /*SuppressUserConversions=*/false,
1609 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00001610 /*ForceRValue=*/false,
1611 /*InOverloadResolution=*/false);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001612 }
1613 return false;
1614}
1615
1616/// \brief Try to find a common type for two according to C++0x 5.16p5.
1617///
1618/// This is part of the parameter validation for the ? operator. If either
1619/// value operand is a class type, overload resolution is used to find a
1620/// conversion to a common type.
1621static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
1622 SourceLocation Loc) {
1623 Expr *Args[2] = { LHS, RHS };
1624 OverloadCandidateSet CandidateSet;
Douglas Gregor573d9c32009-10-21 23:19:44 +00001625 Self.AddBuiltinOperatorCandidates(OO_Conditional, Loc, Args, 2, CandidateSet);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001626
1627 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00001628 switch (Self.BestViableFunction(CandidateSet, Loc, Best)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001629 case Sema::OR_Success:
1630 // We found a match. Perform the conversions on the arguments and move on.
1631 if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
1632 Best->Conversions[0], "converting") ||
1633 Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
1634 Best->Conversions[1], "converting"))
1635 break;
1636 return false;
1637
1638 case Sema::OR_No_Viable_Function:
1639 Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
1640 << LHS->getType() << RHS->getType()
1641 << LHS->getSourceRange() << RHS->getSourceRange();
1642 return true;
1643
1644 case Sema::OR_Ambiguous:
1645 Self.Diag(Loc, diag::err_conditional_ambiguous_ovl)
1646 << LHS->getType() << RHS->getType()
1647 << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stump390b4cc2009-05-16 07:39:55 +00001648 // FIXME: Print the possible common types by printing the return types of
1649 // the viable candidates.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001650 break;
1651
1652 case Sema::OR_Deleted:
1653 assert(false && "Conditional operator has only built-in overloads");
1654 break;
1655 }
1656 return true;
1657}
1658
Sebastian Redl76458502009-04-17 16:30:52 +00001659/// \brief Perform an "extended" implicit conversion as returned by
1660/// TryClassUnification.
1661///
1662/// TryClassUnification generates ICSs that include reference bindings.
1663/// PerformImplicitConversion is not suitable for this; it chokes if the
1664/// second part of a standard conversion is ICK_DerivedToBase. This function
1665/// handles the reference binding specially.
1666static bool ConvertForConditional(Sema &Self, Expr *&E,
Mike Stump1eb44332009-09-09 15:08:12 +00001667 const ImplicitConversionSequence &ICS) {
Sebastian Redl76458502009-04-17 16:30:52 +00001668 if (ICS.ConversionKind == ImplicitConversionSequence::StandardConversion &&
1669 ICS.Standard.ReferenceBinding) {
1670 assert(ICS.Standard.DirectBinding &&
1671 "TryClassUnification should never generate indirect ref bindings");
Sebastian Redla5cd2cd2009-04-26 11:21:02 +00001672 // FIXME: CheckReferenceInit should be able to reuse the ICS instead of
1673 // redoing all the work.
1674 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001675 TargetType(ICS)),
Douglas Gregor739d8282009-09-23 23:04:10 +00001676 /*FIXME:*/E->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001677 /*SuppressUserConversions=*/false,
1678 /*AllowExplicit=*/false,
1679 /*ForceRValue=*/false);
Sebastian Redl76458502009-04-17 16:30:52 +00001680 }
1681 if (ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion &&
1682 ICS.UserDefined.After.ReferenceBinding) {
1683 assert(ICS.UserDefined.After.DirectBinding &&
1684 "TryClassUnification should never generate indirect ref bindings");
Sebastian Redla5cd2cd2009-04-26 11:21:02 +00001685 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001686 TargetType(ICS)),
Douglas Gregor739d8282009-09-23 23:04:10 +00001687 /*FIXME:*/E->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001688 /*SuppressUserConversions=*/false,
1689 /*AllowExplicit=*/false,
1690 /*ForceRValue=*/false);
Sebastian Redl76458502009-04-17 16:30:52 +00001691 }
1692 if (Self.PerformImplicitConversion(E, TargetType(ICS), ICS, "converting"))
1693 return true;
1694 return false;
1695}
1696
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001697/// \brief Check the operands of ?: under C++ semantics.
1698///
1699/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
1700/// extension. In this case, LHS == Cond. (But they're not aliases.)
1701QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
1702 SourceLocation QuestionLoc) {
Mike Stump390b4cc2009-05-16 07:39:55 +00001703 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
1704 // interface pointers.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001705
1706 // C++0x 5.16p1
1707 // The first expression is contextually converted to bool.
1708 if (!Cond->isTypeDependent()) {
1709 if (CheckCXXBooleanCondition(Cond))
1710 return QualType();
1711 }
1712
1713 // Either of the arguments dependent?
1714 if (LHS->isTypeDependent() || RHS->isTypeDependent())
1715 return Context.DependentTy;
1716
John McCallb13c87f2009-11-05 09:23:39 +00001717 CheckSignCompare(LHS, RHS, QuestionLoc, diag::warn_mixed_sign_conditional);
1718
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001719 // C++0x 5.16p2
1720 // If either the second or the third operand has type (cv) void, ...
1721 QualType LTy = LHS->getType();
1722 QualType RTy = RHS->getType();
1723 bool LVoid = LTy->isVoidType();
1724 bool RVoid = RTy->isVoidType();
1725 if (LVoid || RVoid) {
1726 // ... then the [l2r] conversions are performed on the second and third
1727 // operands ...
1728 DefaultFunctionArrayConversion(LHS);
1729 DefaultFunctionArrayConversion(RHS);
1730 LTy = LHS->getType();
1731 RTy = RHS->getType();
1732
1733 // ... and one of the following shall hold:
1734 // -- The second or the third operand (but not both) is a throw-
1735 // expression; the result is of the type of the other and is an rvalue.
1736 bool LThrow = isa<CXXThrowExpr>(LHS);
1737 bool RThrow = isa<CXXThrowExpr>(RHS);
1738 if (LThrow && !RThrow)
1739 return RTy;
1740 if (RThrow && !LThrow)
1741 return LTy;
1742
1743 // -- Both the second and third operands have type void; the result is of
1744 // type void and is an rvalue.
1745 if (LVoid && RVoid)
1746 return Context.VoidTy;
1747
1748 // Neither holds, error.
1749 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
1750 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
1751 << LHS->getSourceRange() << RHS->getSourceRange();
1752 return QualType();
1753 }
1754
1755 // Neither is void.
1756
1757 // C++0x 5.16p3
1758 // Otherwise, if the second and third operand have different types, and
1759 // either has (cv) class type, and attempt is made to convert each of those
1760 // operands to the other.
1761 if (Context.getCanonicalType(LTy) != Context.getCanonicalType(RTy) &&
1762 (LTy->isRecordType() || RTy->isRecordType())) {
1763 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
1764 // These return true if a single direction is already ambiguous.
1765 if (TryClassUnification(*this, LHS, RHS, QuestionLoc, ICSLeftToRight))
1766 return QualType();
1767 if (TryClassUnification(*this, RHS, LHS, QuestionLoc, ICSRightToLeft))
1768 return QualType();
1769
1770 bool HaveL2R = ICSLeftToRight.ConversionKind !=
1771 ImplicitConversionSequence::BadConversion;
1772 bool HaveR2L = ICSRightToLeft.ConversionKind !=
1773 ImplicitConversionSequence::BadConversion;
1774 // If both can be converted, [...] the program is ill-formed.
1775 if (HaveL2R && HaveR2L) {
1776 Diag(QuestionLoc, diag::err_conditional_ambiguous)
1777 << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
1778 return QualType();
1779 }
1780
1781 // If exactly one conversion is possible, that conversion is applied to
1782 // the chosen operand and the converted operands are used in place of the
1783 // original operands for the remainder of this section.
1784 if (HaveL2R) {
Sebastian Redl76458502009-04-17 16:30:52 +00001785 if (ConvertForConditional(*this, LHS, ICSLeftToRight))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001786 return QualType();
1787 LTy = LHS->getType();
1788 } else if (HaveR2L) {
Sebastian Redl76458502009-04-17 16:30:52 +00001789 if (ConvertForConditional(*this, RHS, ICSRightToLeft))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001790 return QualType();
1791 RTy = RHS->getType();
1792 }
1793 }
1794
1795 // C++0x 5.16p4
1796 // If the second and third operands are lvalues and have the same type,
1797 // the result is of that type [...]
1798 bool Same = Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy);
1799 if (Same && LHS->isLvalue(Context) == Expr::LV_Valid &&
1800 RHS->isLvalue(Context) == Expr::LV_Valid)
1801 return LTy;
1802
1803 // C++0x 5.16p5
1804 // Otherwise, the result is an rvalue. If the second and third operands
1805 // do not have the same type, and either has (cv) class type, ...
1806 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
1807 // ... overload resolution is used to determine the conversions (if any)
1808 // to be applied to the operands. If the overload resolution fails, the
1809 // program is ill-formed.
1810 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
1811 return QualType();
1812 }
1813
1814 // C++0x 5.16p6
1815 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
1816 // conversions are performed on the second and third operands.
1817 DefaultFunctionArrayConversion(LHS);
1818 DefaultFunctionArrayConversion(RHS);
1819 LTy = LHS->getType();
1820 RTy = RHS->getType();
1821
1822 // After those conversions, one of the following shall hold:
1823 // -- The second and third operands have the same type; the result
1824 // is of that type.
1825 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy))
1826 return LTy;
1827
1828 // -- The second and third operands have arithmetic or enumeration type;
1829 // the usual arithmetic conversions are performed to bring them to a
1830 // common type, and the result is of that type.
1831 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
1832 UsualArithmeticConversions(LHS, RHS);
1833 return LHS->getType();
1834 }
1835
1836 // -- The second and third operands have pointer type, or one has pointer
1837 // type and the other is a null pointer constant; pointer conversions
1838 // and qualification conversions are performed to bring them to their
1839 // composite pointer type. The result is of the composite pointer type.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001840 QualType Composite = FindCompositePointerType(LHS, RHS);
1841 if (!Composite.isNull())
1842 return Composite;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001843
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001844 // Fourth bullet is same for pointers-to-member. However, the possible
1845 // conversions are far more limited: we have null-to-pointer, upcast of
1846 // containing class, and second-level cv-ness.
1847 // cv-ness is not a union, but must match one of the two operands. (Which,
1848 // frankly, is stupid.)
Ted Kremenek6217b802009-07-29 21:53:49 +00001849 const MemberPointerType *LMemPtr = LTy->getAs<MemberPointerType>();
1850 const MemberPointerType *RMemPtr = RTy->getAs<MemberPointerType>();
Douglas Gregorce940492009-09-25 04:25:58 +00001851 if (LMemPtr &&
1852 RHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00001853 ImpCastExprToType(RHS, LTy, CastExpr::CK_NullToMemberPointer);
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001854 return LTy;
1855 }
Douglas Gregorce940492009-09-25 04:25:58 +00001856 if (RMemPtr &&
1857 LHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00001858 ImpCastExprToType(LHS, RTy, CastExpr::CK_NullToMemberPointer);
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001859 return RTy;
1860 }
1861 if (LMemPtr && RMemPtr) {
1862 QualType LPointee = LMemPtr->getPointeeType();
1863 QualType RPointee = RMemPtr->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00001864
1865 QualifierCollector LPQuals, RPQuals;
1866 const Type *LPCan = LPQuals.strip(Context.getCanonicalType(LPointee));
1867 const Type *RPCan = RPQuals.strip(Context.getCanonicalType(RPointee));
1868
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001869 // First, we check that the unqualified pointee type is the same. If it's
1870 // not, there's no conversion that will unify the two pointers.
John McCall0953e762009-09-24 19:53:00 +00001871 if (LPCan == RPCan) {
1872
1873 // Second, we take the greater of the two qualifications. If neither
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001874 // is greater than the other, the conversion is not possible.
John McCall0953e762009-09-24 19:53:00 +00001875
1876 Qualifiers MergedQuals = LPQuals + RPQuals;
1877
1878 bool CompatibleQuals = true;
1879 if (MergedQuals.getCVRQualifiers() != LPQuals.getCVRQualifiers() &&
1880 MergedQuals.getCVRQualifiers() != RPQuals.getCVRQualifiers())
1881 CompatibleQuals = false;
1882 else if (LPQuals.getAddressSpace() != RPQuals.getAddressSpace())
1883 // FIXME:
1884 // C99 6.5.15 as modified by TR 18037:
1885 // If the second and third operands are pointers into different
1886 // address spaces, the address spaces must overlap.
1887 CompatibleQuals = false;
1888 // FIXME: GC qualifiers?
1889
1890 if (CompatibleQuals) {
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001891 // Third, we check if either of the container classes is derived from
1892 // the other.
1893 QualType LContainer(LMemPtr->getClass(), 0);
1894 QualType RContainer(RMemPtr->getClass(), 0);
1895 QualType MoreDerived;
1896 if (Context.getCanonicalType(LContainer) ==
1897 Context.getCanonicalType(RContainer))
1898 MoreDerived = LContainer;
1899 else if (IsDerivedFrom(LContainer, RContainer))
1900 MoreDerived = LContainer;
1901 else if (IsDerivedFrom(RContainer, LContainer))
1902 MoreDerived = RContainer;
1903
1904 if (!MoreDerived.isNull()) {
1905 // The type 'Q Pointee (MoreDerived::*)' is the common type.
1906 // We don't use ImpCastExprToType here because this could still fail
1907 // for ambiguous or inaccessible conversions.
John McCall0953e762009-09-24 19:53:00 +00001908 LPointee = Context.getQualifiedType(LPointee, MergedQuals);
1909 QualType Common
1910 = Context.getMemberPointerType(LPointee, MoreDerived.getTypePtr());
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001911 if (PerformImplicitConversion(LHS, Common, "converting"))
1912 return QualType();
1913 if (PerformImplicitConversion(RHS, Common, "converting"))
1914 return QualType();
1915 return Common;
1916 }
1917 }
1918 }
1919 }
1920
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001921 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
1922 << LHS->getType() << RHS->getType()
1923 << LHS->getSourceRange() << RHS->getSourceRange();
1924 return QualType();
1925}
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001926
1927/// \brief Find a merged pointer type and convert the two expressions to it.
1928///
Douglas Gregor20b3e992009-08-24 17:42:35 +00001929/// This finds the composite pointer type (or member pointer type) for @p E1
1930/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
1931/// type and returns it.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001932/// It does not emit diagnostics.
1933QualType Sema::FindCompositePointerType(Expr *&E1, Expr *&E2) {
1934 assert(getLangOptions().CPlusPlus && "This function assumes C++");
1935 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001936
Douglas Gregor20b3e992009-08-24 17:42:35 +00001937 if (!T1->isPointerType() && !T1->isMemberPointerType() &&
1938 !T2->isPointerType() && !T2->isMemberPointerType())
1939 return QualType();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001940
1941 // C++0x 5.9p2
1942 // Pointer conversions and qualification conversions are performed on
1943 // pointer operands to bring them to their composite pointer type. If
1944 // one operand is a null pointer constant, the composite pointer type is
1945 // the type of the other operand.
Douglas Gregorce940492009-09-25 04:25:58 +00001946 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00001947 if (T2->isMemberPointerType())
1948 ImpCastExprToType(E1, T2, CastExpr::CK_NullToMemberPointer);
1949 else
1950 ImpCastExprToType(E1, T2, CastExpr::CK_IntegralToPointer);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001951 return T2;
1952 }
Douglas Gregorce940492009-09-25 04:25:58 +00001953 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00001954 if (T1->isMemberPointerType())
1955 ImpCastExprToType(E2, T1, CastExpr::CK_NullToMemberPointer);
1956 else
1957 ImpCastExprToType(E2, T1, CastExpr::CK_IntegralToPointer);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001958 return T1;
1959 }
Mike Stump1eb44332009-09-09 15:08:12 +00001960
Douglas Gregor20b3e992009-08-24 17:42:35 +00001961 // Now both have to be pointers or member pointers.
Sebastian Redla439e6f2009-11-16 21:03:45 +00001962 if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
1963 (!T2->isPointerType() && !T2->isMemberPointerType()))
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001964 return QualType();
1965
1966 // Otherwise, of one of the operands has type "pointer to cv1 void," then
1967 // the other has type "pointer to cv2 T" and the composite pointer type is
1968 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
1969 // Otherwise, the composite pointer type is a pointer type similar to the
1970 // type of one of the operands, with a cv-qualification signature that is
1971 // the union of the cv-qualification signatures of the operand types.
1972 // In practice, the first part here is redundant; it's subsumed by the second.
1973 // What we do here is, we build the two possible composite types, and try the
1974 // conversions in both directions. If only one works, or if the two composite
1975 // types are the same, we have succeeded.
John McCall0953e762009-09-24 19:53:00 +00001976 // FIXME: extended qualifiers?
Sebastian Redla439e6f2009-11-16 21:03:45 +00001977 typedef llvm::SmallVector<unsigned, 4> QualifierVector;
1978 QualifierVector QualifierUnion;
1979 typedef llvm::SmallVector<std::pair<const Type *, const Type *>, 4>
1980 ContainingClassVector;
1981 ContainingClassVector MemberOfClass;
1982 QualType Composite1 = Context.getCanonicalType(T1),
1983 Composite2 = Context.getCanonicalType(T2);
Douglas Gregor20b3e992009-08-24 17:42:35 +00001984 do {
1985 const PointerType *Ptr1, *Ptr2;
1986 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
1987 (Ptr2 = Composite2->getAs<PointerType>())) {
1988 Composite1 = Ptr1->getPointeeType();
1989 Composite2 = Ptr2->getPointeeType();
1990 QualifierUnion.push_back(
1991 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
1992 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
1993 continue;
1994 }
Mike Stump1eb44332009-09-09 15:08:12 +00001995
Douglas Gregor20b3e992009-08-24 17:42:35 +00001996 const MemberPointerType *MemPtr1, *MemPtr2;
1997 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
1998 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
1999 Composite1 = MemPtr1->getPointeeType();
2000 Composite2 = MemPtr2->getPointeeType();
2001 QualifierUnion.push_back(
2002 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
2003 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
2004 MemPtr2->getClass()));
2005 continue;
2006 }
Mike Stump1eb44332009-09-09 15:08:12 +00002007
Douglas Gregor20b3e992009-08-24 17:42:35 +00002008 // FIXME: block pointer types?
Mike Stump1eb44332009-09-09 15:08:12 +00002009
Douglas Gregor20b3e992009-08-24 17:42:35 +00002010 // Cannot unwrap any more types.
2011 break;
2012 } while (true);
Mike Stump1eb44332009-09-09 15:08:12 +00002013
Douglas Gregor20b3e992009-08-24 17:42:35 +00002014 // Rewrap the composites as pointers or member pointers with the union CVRs.
Sebastian Redla439e6f2009-11-16 21:03:45 +00002015 ContainingClassVector::reverse_iterator MOC
2016 = MemberOfClass.rbegin();
2017 for (QualifierVector::reverse_iterator
2018 I = QualifierUnion.rbegin(),
2019 E = QualifierUnion.rend();
Douglas Gregor20b3e992009-08-24 17:42:35 +00002020 I != E; (void)++I, ++MOC) {
John McCall0953e762009-09-24 19:53:00 +00002021 Qualifiers Quals = Qualifiers::fromCVRMask(*I);
Douglas Gregor20b3e992009-08-24 17:42:35 +00002022 if (MOC->first && MOC->second) {
2023 // Rebuild member pointer type
John McCall0953e762009-09-24 19:53:00 +00002024 Composite1 = Context.getMemberPointerType(
2025 Context.getQualifiedType(Composite1, Quals),
2026 MOC->first);
2027 Composite2 = Context.getMemberPointerType(
2028 Context.getQualifiedType(Composite2, Quals),
2029 MOC->second);
Douglas Gregor20b3e992009-08-24 17:42:35 +00002030 } else {
2031 // Rebuild pointer type
John McCall0953e762009-09-24 19:53:00 +00002032 Composite1
2033 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
2034 Composite2
2035 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregor20b3e992009-08-24 17:42:35 +00002036 }
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002037 }
2038
Mike Stump1eb44332009-09-09 15:08:12 +00002039 ImplicitConversionSequence E1ToC1 =
Anders Carlssonda7a18b2009-08-27 17:24:15 +00002040 TryImplicitConversion(E1, Composite1,
2041 /*SuppressUserConversions=*/false,
2042 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00002043 /*ForceRValue=*/false,
2044 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00002045 ImplicitConversionSequence E2ToC1 =
Anders Carlssonda7a18b2009-08-27 17:24:15 +00002046 TryImplicitConversion(E2, Composite1,
2047 /*SuppressUserConversions=*/false,
2048 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00002049 /*ForceRValue=*/false,
2050 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00002051
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002052 ImplicitConversionSequence E1ToC2, E2ToC2;
2053 E1ToC2.ConversionKind = ImplicitConversionSequence::BadConversion;
2054 E2ToC2.ConversionKind = ImplicitConversionSequence::BadConversion;
2055 if (Context.getCanonicalType(Composite1) !=
2056 Context.getCanonicalType(Composite2)) {
Anders Carlssonda7a18b2009-08-27 17:24:15 +00002057 E1ToC2 = TryImplicitConversion(E1, Composite2,
2058 /*SuppressUserConversions=*/false,
2059 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00002060 /*ForceRValue=*/false,
2061 /*InOverloadResolution=*/false);
Anders Carlssonda7a18b2009-08-27 17:24:15 +00002062 E2ToC2 = TryImplicitConversion(E2, Composite2,
2063 /*SuppressUserConversions=*/false,
2064 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00002065 /*ForceRValue=*/false,
2066 /*InOverloadResolution=*/false);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002067 }
2068
2069 bool ToC1Viable = E1ToC1.ConversionKind !=
2070 ImplicitConversionSequence::BadConversion
2071 && E2ToC1.ConversionKind !=
2072 ImplicitConversionSequence::BadConversion;
2073 bool ToC2Viable = E1ToC2.ConversionKind !=
2074 ImplicitConversionSequence::BadConversion
2075 && E2ToC2.ConversionKind !=
2076 ImplicitConversionSequence::BadConversion;
2077 if (ToC1Viable && !ToC2Viable) {
2078 if (!PerformImplicitConversion(E1, Composite1, E1ToC1, "converting") &&
2079 !PerformImplicitConversion(E2, Composite1, E2ToC1, "converting"))
2080 return Composite1;
2081 }
2082 if (ToC2Viable && !ToC1Viable) {
2083 if (!PerformImplicitConversion(E1, Composite2, E1ToC2, "converting") &&
2084 !PerformImplicitConversion(E2, Composite2, E2ToC2, "converting"))
2085 return Composite2;
2086 }
2087 return QualType();
2088}
Anders Carlsson165a0a02009-05-17 18:41:29 +00002089
Anders Carlssondef11992009-05-30 20:36:53 +00002090Sema::OwningExprResult Sema::MaybeBindToTemporary(Expr *E) {
Anders Carlsson089c2602009-08-15 23:41:35 +00002091 if (!Context.getLangOptions().CPlusPlus)
2092 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002093
Ted Kremenek6217b802009-07-29 21:53:49 +00002094 const RecordType *RT = E->getType()->getAs<RecordType>();
Anders Carlssondef11992009-05-30 20:36:53 +00002095 if (!RT)
2096 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002097
Anders Carlssondef11992009-05-30 20:36:53 +00002098 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2099 if (RD->hasTrivialDestructor())
2100 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002101
Anders Carlsson283e4d52009-09-14 01:30:44 +00002102 if (CallExpr *CE = dyn_cast<CallExpr>(E)) {
2103 QualType Ty = CE->getCallee()->getType();
2104 if (const PointerType *PT = Ty->getAs<PointerType>())
2105 Ty = PT->getPointeeType();
2106
John McCall183700f2009-09-21 23:43:11 +00002107 const FunctionType *FTy = Ty->getAs<FunctionType>();
Anders Carlsson283e4d52009-09-14 01:30:44 +00002108 if (FTy->getResultType()->isReferenceType())
2109 return Owned(E);
2110 }
Mike Stump1eb44332009-09-09 15:08:12 +00002111 CXXTemporary *Temp = CXXTemporary::Create(Context,
Anders Carlssondef11992009-05-30 20:36:53 +00002112 RD->getDestructor(Context));
Anders Carlsson860306e2009-05-30 21:21:49 +00002113 ExprTemporaries.push_back(Temp);
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00002114 if (CXXDestructorDecl *Destructor =
2115 const_cast<CXXDestructorDecl*>(RD->getDestructor(Context)))
2116 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
Anders Carlssondef11992009-05-30 20:36:53 +00002117 // FIXME: Add the temporary to the temporaries vector.
2118 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
2119}
2120
Mike Stump1eb44332009-09-09 15:08:12 +00002121Expr *Sema::MaybeCreateCXXExprWithTemporaries(Expr *SubExpr,
Anders Carlssonf54741e2009-06-16 03:37:31 +00002122 bool ShouldDestroyTemps) {
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002123 assert(SubExpr && "sub expression can't be null!");
Mike Stump1eb44332009-09-09 15:08:12 +00002124
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002125 if (ExprTemporaries.empty())
2126 return SubExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00002127
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002128 Expr *E = CXXExprWithTemporaries::Create(Context, SubExpr,
Mike Stump1eb44332009-09-09 15:08:12 +00002129 &ExprTemporaries[0],
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002130 ExprTemporaries.size(),
Anders Carlssonf54741e2009-06-16 03:37:31 +00002131 ShouldDestroyTemps);
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002132 ExprTemporaries.clear();
Mike Stump1eb44332009-09-09 15:08:12 +00002133
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002134 return E;
2135}
2136
Mike Stump1eb44332009-09-09 15:08:12 +00002137Sema::OwningExprResult
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002138Sema::ActOnStartCXXMemberReference(Scope *S, ExprArg Base, SourceLocation OpLoc,
2139 tok::TokenKind OpKind, TypeTy *&ObjectType) {
2140 // Since this might be a postfix expression, get rid of ParenListExprs.
2141 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
Mike Stump1eb44332009-09-09 15:08:12 +00002142
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002143 Expr *BaseExpr = (Expr*)Base.get();
2144 assert(BaseExpr && "no record expansion");
Mike Stump1eb44332009-09-09 15:08:12 +00002145
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002146 QualType BaseType = BaseExpr->getType();
2147 if (BaseType->isDependentType()) {
Douglas Gregor43d88632009-11-04 22:49:18 +00002148 // If we have a pointer to a dependent type and are using the -> operator,
2149 // the object type is the type that the pointer points to. We might still
2150 // have enough information about that type to do something useful.
2151 if (OpKind == tok::arrow)
2152 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
2153 BaseType = Ptr->getPointeeType();
2154
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002155 ObjectType = BaseType.getAsOpaquePtr();
2156 return move(Base);
2157 }
Mike Stump1eb44332009-09-09 15:08:12 +00002158
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002159 // C++ [over.match.oper]p8:
Mike Stump1eb44332009-09-09 15:08:12 +00002160 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002161 // returned, with the original second operand.
2162 if (OpKind == tok::arrow) {
John McCallc4e83212009-09-30 01:01:30 +00002163 // The set of types we've considered so far.
John McCall432887f2009-09-30 01:30:54 +00002164 llvm::SmallPtrSet<CanQualType,8> CTypes;
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002165 llvm::SmallVector<SourceLocation, 8> Locations;
John McCall432887f2009-09-30 01:30:54 +00002166 CTypes.insert(Context.getCanonicalType(BaseType));
John McCallc4e83212009-09-30 01:01:30 +00002167
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002168 while (BaseType->isRecordType()) {
Anders Carlsson15ea3782009-10-13 22:43:21 +00002169 Base = BuildOverloadedArrowExpr(S, move(Base), OpLoc);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002170 BaseExpr = (Expr*)Base.get();
2171 if (BaseExpr == NULL)
2172 return ExprError();
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002173 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(BaseExpr))
Anders Carlssonde699e52009-10-13 22:55:59 +00002174 Locations.push_back(OpCall->getDirectCallee()->getLocation());
John McCallc4e83212009-09-30 01:01:30 +00002175 BaseType = BaseExpr->getType();
2176 CanQualType CBaseType = Context.getCanonicalType(BaseType);
John McCall432887f2009-09-30 01:30:54 +00002177 if (!CTypes.insert(CBaseType)) {
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00002178 Diag(OpLoc, diag::err_operator_arrow_circular);
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002179 for (unsigned i = 0; i < Locations.size(); i++)
2180 Diag(Locations[i], diag::note_declared_at);
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00002181 return ExprError();
2182 }
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002183 }
Mike Stump1eb44332009-09-09 15:08:12 +00002184
Douglas Gregor31658df2009-11-20 19:58:21 +00002185 if (BaseType->isPointerType())
2186 BaseType = BaseType->getPointeeType();
2187 }
Mike Stump1eb44332009-09-09 15:08:12 +00002188
2189 // We could end up with various non-record types here, such as extended
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002190 // vector types or Objective-C interfaces. Just return early and let
2191 // ActOnMemberReferenceExpr do the work.
Douglas Gregorc68afe22009-09-03 21:38:09 +00002192 if (!BaseType->isRecordType()) {
2193 // C++ [basic.lookup.classref]p2:
2194 // [...] If the type of the object expression is of pointer to scalar
2195 // type, the unqualified-id is looked up in the context of the complete
2196 // postfix-expression.
2197 ObjectType = 0;
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002198 return move(Base);
Douglas Gregorc68afe22009-09-03 21:38:09 +00002199 }
Mike Stump1eb44332009-09-09 15:08:12 +00002200
Douglas Gregor03c57052009-11-17 05:17:33 +00002201 // The object type must be complete (or dependent).
2202 if (!BaseType->isDependentType() &&
2203 RequireCompleteType(OpLoc, BaseType,
2204 PDiag(diag::err_incomplete_member_access)))
2205 return ExprError();
2206
Douglas Gregorc68afe22009-09-03 21:38:09 +00002207 // C++ [basic.lookup.classref]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00002208 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor03c57052009-11-17 05:17:33 +00002209 // unqualified-id, and the type of the object expression is of a class
Douglas Gregorc68afe22009-09-03 21:38:09 +00002210 // type C (or of pointer to a class type C), the unqualified-id is looked
2211 // up in the scope of class C. [...]
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002212 ObjectType = BaseType.getAsOpaquePtr();
Douglas Gregor03c57052009-11-17 05:17:33 +00002213
Mike Stump1eb44332009-09-09 15:08:12 +00002214 return move(Base);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002215}
2216
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002217CXXMemberCallExpr *Sema::BuildCXXMemberCallExpr(Expr *Exp,
2218 CXXMethodDecl *Method) {
2219 MemberExpr *ME =
2220 new (Context) MemberExpr(Exp, /*IsArrow=*/false, Method,
2221 SourceLocation(), Method->getType());
2222 QualType ResultType;
2223 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(Method))
2224 ResultType = Conv->getConversionType().getNonReferenceType();
2225 else
2226 ResultType = Method->getResultType().getNonReferenceType();
2227
Douglas Gregor7edfb692009-11-23 12:27:39 +00002228 MarkDeclarationReferenced(Exp->getLocStart(), Method);
2229 CXXMemberCallExpr *CE =
2230 new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType,
2231 Exp->getLocEnd());
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002232 return CE;
2233}
2234
Anders Carlsson0aebc812009-09-09 21:33:21 +00002235Sema::OwningExprResult Sema::BuildCXXCastArgument(SourceLocation CastLoc,
2236 QualType Ty,
2237 CastExpr::CastKind Kind,
2238 CXXMethodDecl *Method,
2239 ExprArg Arg) {
2240 Expr *From = Arg.takeAs<Expr>();
2241
2242 switch (Kind) {
2243 default: assert(0 && "Unhandled cast kind!");
2244 case CastExpr::CK_ConstructorConversion: {
Douglas Gregor39da0b82009-09-09 23:08:42 +00002245 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
2246
2247 if (CompleteConstructorCall(cast<CXXConstructorDecl>(Method),
2248 MultiExprArg(*this, (void **)&From, 1),
2249 CastLoc, ConstructorArgs))
2250 return ExprError();
Anders Carlsson4fa26842009-10-18 21:20:14 +00002251
2252 OwningExprResult Result =
2253 BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
2254 move_arg(ConstructorArgs));
2255 if (Result.isInvalid())
2256 return ExprError();
2257
2258 return MaybeBindToTemporary(Result.takeAs<Expr>());
Anders Carlsson0aebc812009-09-09 21:33:21 +00002259 }
2260
2261 case CastExpr::CK_UserDefinedConversion: {
Anders Carlssonaac6e3a2009-09-15 07:42:44 +00002262 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
2263
2264 // Cast to base if needed.
2265 if (PerformObjectArgumentInitialization(From, Method))
2266 return ExprError();
2267
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002268 // Create an implicit call expr that calls it.
2269 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(From, Method);
Anders Carlsson4fa26842009-10-18 21:20:14 +00002270 return MaybeBindToTemporary(CE);
Anders Carlsson0aebc812009-09-09 21:33:21 +00002271 }
Anders Carlsson0aebc812009-09-09 21:33:21 +00002272 }
2273}
2274
Anders Carlsson165a0a02009-05-17 18:41:29 +00002275Sema::OwningExprResult Sema::ActOnFinishFullExpr(ExprArg Arg) {
2276 Expr *FullExpr = Arg.takeAs<Expr>();
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002277 if (FullExpr)
Mike Stump1eb44332009-09-09 15:08:12 +00002278 FullExpr = MaybeCreateCXXExprWithTemporaries(FullExpr,
Anders Carlssonf54741e2009-06-16 03:37:31 +00002279 /*ShouldDestroyTemps=*/true);
Anders Carlsson165a0a02009-05-17 18:41:29 +00002280
Anders Carlssonec773872009-08-25 23:46:41 +00002281
Anders Carlsson165a0a02009-05-17 18:41:29 +00002282 return Owned(FullExpr);
2283}
Douglas Gregore961afb2009-10-22 07:08:30 +00002284
2285/// \brief Determine whether a reference to the given declaration in the
2286/// current context is an implicit member access
2287/// (C++ [class.mfct.non-static]p2).
2288///
2289/// FIXME: Should Objective-C also use this approach?
2290///
2291/// \param SS if non-NULL, the C++ nested-name-specifier that precedes the
2292/// name of the declaration referenced.
2293///
2294/// \param D the declaration being referenced from the current scope.
2295///
2296/// \param NameLoc the location of the name in the source.
2297///
2298/// \param ThisType if the reference to this declaration is an implicit member
2299/// access, will be set to the type of the "this" pointer to be used when
2300/// building that implicit member access.
2301///
2302/// \param MemberType if the reference to this declaration is an implicit
2303/// member access, will be set to the type of the member being referenced
2304/// (for use at the type of the resulting member access expression).
2305///
2306/// \returns true if this is an implicit member reference (in which case
2307/// \p ThisType and \p MemberType will be set), or false if it is not an
2308/// implicit member reference.
2309bool Sema::isImplicitMemberReference(const CXXScopeSpec *SS, NamedDecl *D,
2310 SourceLocation NameLoc, QualType &ThisType,
2311 QualType &MemberType) {
2312 // If this isn't a C++ method, then it isn't an implicit member reference.
2313 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext);
2314 if (!MD || MD->isStatic())
2315 return false;
2316
2317 // C++ [class.mfct.nonstatic]p2:
2318 // [...] if name lookup (3.4.1) resolves the name in the
2319 // id-expression to a nonstatic nontype member of class X or of
2320 // a base class of X, the id-expression is transformed into a
2321 // class member access expression (5.2.5) using (*this) (9.3.2)
2322 // as the postfix-expression to the left of the '.' operator.
2323 DeclContext *Ctx = 0;
2324 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
2325 Ctx = FD->getDeclContext();
2326 MemberType = FD->getType();
2327
2328 if (const ReferenceType *RefType = MemberType->getAs<ReferenceType>())
2329 MemberType = RefType->getPointeeType();
2330 else if (!FD->isMutable())
2331 MemberType
2332 = Context.getQualifiedType(MemberType,
2333 Qualifiers::fromCVRMask(MD->getTypeQualifiers()));
John McCallba135432009-11-21 08:51:07 +00002334 } else if (isa<UnresolvedUsingValueDecl>(D)) {
2335 Ctx = D->getDeclContext();
2336 MemberType = Context.DependentTy;
Douglas Gregore961afb2009-10-22 07:08:30 +00002337 } else {
2338 for (OverloadIterator Ovl(D), OvlEnd; Ovl != OvlEnd; ++Ovl) {
2339 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*Ovl);
2340 FunctionTemplateDecl *FunTmpl = 0;
2341 if (!Method && (FunTmpl = dyn_cast<FunctionTemplateDecl>(*Ovl)))
2342 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
2343
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00002344 // FIXME: Do we have to know if there are explicit template arguments?
Douglas Gregore961afb2009-10-22 07:08:30 +00002345 if (Method && !Method->isStatic()) {
2346 Ctx = Method->getParent();
2347 if (isa<CXXMethodDecl>(D) && !FunTmpl)
2348 MemberType = Method->getType();
2349 else
2350 MemberType = Context.OverloadTy;
2351 break;
2352 }
2353 }
2354 }
2355
2356 if (!Ctx || !Ctx->isRecord())
2357 return false;
2358
2359 // Determine whether the declaration(s) we found are actually in a base
2360 // class. If not, this isn't an implicit member reference.
2361 ThisType = MD->getThisType(Context);
Douglas Gregor7a343142009-11-01 17:08:18 +00002362
Douglas Gregore961afb2009-10-22 07:08:30 +00002363 QualType CtxType = Context.getTypeDeclType(cast<CXXRecordDecl>(Ctx));
2364 QualType ClassType
2365 = Context.getTypeDeclType(cast<CXXRecordDecl>(MD->getParent()));
2366 return Context.hasSameType(CtxType, ClassType) ||
2367 IsDerivedFrom(ClassType, CtxType);
2368}
2369