blob: 8870a59d136e6b99a696c84fd377254b5e98cf8a [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Douglas Gregor20093b42009-12-09 23:02:17 +000015#include "SemaInit.h"
John McCall7d384dd2009-11-18 07:57:50 +000016#include "Lookup.h"
Steve Naroff210679c2007-08-25 14:02:58 +000017#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000018#include "clang/AST/CXXInheritance.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000019#include "clang/AST/ExprCXX.h"
20#include "clang/Basic/PartialDiagnostic.h"
Sebastian Redlb5a57a62008-12-03 20:26:15 +000021#include "clang/Basic/TargetInfo.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000022#include "clang/Lex/Preprocessor.h"
23#include "clang/Parse/DeclSpec.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000024#include "llvm/ADT/STLExtras.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000025using namespace clang;
26
Sebastian Redlc42e1182008-11-11 11:37:55 +000027/// ActOnCXXTypeidOfType - Parse typeid( type-id ).
Sebastian Redlf53597f2009-03-15 17:47:39 +000028Action::OwningExprResult
Sebastian Redlc42e1182008-11-11 11:37:55 +000029Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
30 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +000031 if (!StdNamespace)
Sebastian Redlf53597f2009-03-15 17:47:39 +000032 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +000033
34 if (isType)
35 // FIXME: Preserve type source info.
36 TyOrExpr = GetTypeFromParser(TyOrExpr).getAsOpaquePtr();
37
Chris Lattner572af492008-11-20 05:51:55 +000038 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
John McCalla24dc2e2009-11-17 02:14:36 +000039 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
40 LookupQualifiedName(R, StdNamespace);
John McCall1bcee0a2009-12-02 08:25:40 +000041 RecordDecl *TypeInfoRecordDecl = R.getAsSingle<RecordDecl>();
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 Gregor2afce722009-11-26 00:44:06 +000066 // If this is an unevaluated operand, clear out the set of
67 // declaration references we have been computing and eliminate any
68 // temporaries introduced in its computation.
Douglas Gregorac7610d2009-06-22 20:57:11 +000069 if (isUnevaluatedOperand)
Douglas Gregor2afce722009-11-26 00:44:06 +000070 ExprEvalContexts.back().Context = Unevaluated;
Douglas Gregorac7610d2009-06-22 20:57:11 +000071 }
Mike Stump1eb44332009-09-09 15:08:12 +000072
Sebastian Redlf53597f2009-03-15 17:47:39 +000073 return Owned(new (Context) CXXTypeidExpr(isType, TyOrExpr,
74 TypeInfoType.withConst(),
75 SourceRange(OpLoc, RParenLoc)));
Sebastian Redlc42e1182008-11-11 11:37:55 +000076}
77
Steve Naroff1b273c42007-09-16 14:56:35 +000078/// ActOnCXXBoolLiteral - Parse {true,false} literals.
Sebastian Redlf53597f2009-03-15 17:47:39 +000079Action::OwningExprResult
Steve Naroff1b273c42007-09-16 14:56:35 +000080Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor2f639b92008-10-24 15:36:09 +000081 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Reid Spencer5f016e22007-07-11 17:01:13 +000082 "Unknown C++ Boolean value!");
Sebastian Redlf53597f2009-03-15 17:47:39 +000083 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
84 Context.BoolTy, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +000085}
Chris Lattner50dd2892008-02-26 00:51:44 +000086
Sebastian Redl6e8ed162009-05-10 18:38:11 +000087/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
88Action::OwningExprResult
89Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
90 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
91}
92
Chris Lattner50dd2892008-02-26 00:51:44 +000093/// ActOnCXXThrow - Parse throw expressions.
Sebastian Redlf53597f2009-03-15 17:47:39 +000094Action::OwningExprResult
95Sema::ActOnCXXThrow(SourceLocation OpLoc, ExprArg E) {
Sebastian Redl972041f2009-04-27 20:27:31 +000096 Expr *Ex = E.takeAs<Expr>();
97 if (Ex && !Ex->isTypeDependent() && CheckCXXThrowOperand(OpLoc, Ex))
98 return ExprError();
99 return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc));
100}
101
102/// CheckCXXThrowOperand - Validate the operand of a throw.
103bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *&E) {
104 // C++ [except.throw]p3:
105 // [...] adjusting the type from "array of T" or "function returning T"
106 // to "pointer to T" or "pointer to function returning T", [...]
107 DefaultFunctionArrayConversion(E);
108
109 // If the type of the exception would be an incomplete type or a pointer
110 // to an incomplete type other than (cv) void the program is ill-formed.
111 QualType Ty = E->getType();
112 int isPointer = 0;
Ted Kremenek6217b802009-07-29 21:53:49 +0000113 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000114 Ty = Ptr->getPointeeType();
115 isPointer = 1;
116 }
117 if (!isPointer || !Ty->isVoidType()) {
118 if (RequireCompleteType(ThrowLoc, Ty,
Anders Carlssond497ba72009-08-26 22:59:12 +0000119 PDiag(isPointer ? diag::err_throw_incomplete_ptr
120 : diag::err_throw_incomplete)
121 << E->getSourceRange()))
Sebastian Redl972041f2009-04-27 20:27:31 +0000122 return true;
123 }
124
125 // FIXME: Construct a temporary here.
126 return false;
Chris Lattner50dd2892008-02-26 00:51:44 +0000127}
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000128
Sebastian Redlf53597f2009-03-15 17:47:39 +0000129Action::OwningExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000130 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
131 /// is a non-lvalue expression whose value is the address of the object for
132 /// which the function is called.
133
Sebastian Redlf53597f2009-03-15 17:47:39 +0000134 if (!isa<FunctionDecl>(CurContext))
135 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000136
137 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext))
138 if (MD->isInstance())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000139 return Owned(new (Context) CXXThisExpr(ThisLoc,
140 MD->getThisType(Context)));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000141
Sebastian Redlf53597f2009-03-15 17:47:39 +0000142 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000143}
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000144
145/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
146/// Can be interpreted either as function-style casting ("int(x)")
147/// or class type construction ("ClassType(x,y,z)")
148/// or creation of a value-initialized type ("int()").
Sebastian Redlf53597f2009-03-15 17:47:39 +0000149Action::OwningExprResult
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000150Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep,
151 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000152 MultiExprArg exprs,
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000153 SourceLocation *CommaLocs,
154 SourceLocation RParenLoc) {
155 assert(TypeRep && "Missing type!");
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000156 // FIXME: Preserve type source info.
157 QualType Ty = GetTypeFromParser(TypeRep);
Sebastian Redlf53597f2009-03-15 17:47:39 +0000158 unsigned NumExprs = exprs.size();
159 Expr **Exprs = (Expr**)exprs.get();
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000160 SourceLocation TyBeginLoc = TypeRange.getBegin();
161 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
162
Sebastian Redlf53597f2009-03-15 17:47:39 +0000163 if (Ty->isDependentType() ||
Douglas Gregorba498172009-03-13 21:01:28 +0000164 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
Sebastian Redlf53597f2009-03-15 17:47:39 +0000165 exprs.release();
Mike Stump1eb44332009-09-09 15:08:12 +0000166
167 return Owned(CXXUnresolvedConstructExpr::Create(Context,
168 TypeRange.getBegin(), Ty,
Douglas Gregord81e6ca2009-05-20 18:46:25 +0000169 LParenLoc,
170 Exprs, NumExprs,
171 RParenLoc));
Douglas Gregorba498172009-03-13 21:01:28 +0000172 }
173
Anders Carlssonbb60a502009-08-27 03:53:50 +0000174 if (Ty->isArrayType())
175 return ExprError(Diag(TyBeginLoc,
176 diag::err_value_init_for_array_type) << FullRange);
177 if (!Ty->isVoidType() &&
178 RequireCompleteType(TyBeginLoc, Ty,
179 PDiag(diag::err_invalid_incomplete_type_use)
180 << FullRange))
181 return ExprError();
Fariborz Jahanianf071e9b2009-10-23 21:01:39 +0000182
Anders Carlssonbb60a502009-08-27 03:53:50 +0000183 if (RequireNonAbstractType(TyBeginLoc, Ty,
184 diag::err_allocation_of_abstract_type))
185 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000186
187
Douglas Gregor506ae412009-01-16 18:33:17 +0000188 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000189 // If the expression list is a single expression, the type conversion
190 // expression is equivalent (in definedness, and if defined in meaning) to the
191 // corresponding cast expression.
192 //
193 if (NumExprs == 1) {
Anders Carlssoncdb61972009-08-07 22:21:05 +0000194 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Anders Carlsson0aebc812009-09-09 21:33:21 +0000195 CXXMethodDecl *Method = 0;
196 if (CheckCastTypes(TypeRange, Ty, Exprs[0], Kind, Method,
197 /*FunctionalStyle=*/true))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000198 return ExprError();
Anders Carlsson0aebc812009-09-09 21:33:21 +0000199
200 exprs.release();
201 if (Method) {
202 OwningExprResult CastArg
203 = BuildCXXCastArgument(TypeRange.getBegin(), Ty.getNonReferenceType(),
204 Kind, Method, Owned(Exprs[0]));
205 if (CastArg.isInvalid())
206 return ExprError();
207
208 Exprs[0] = CastArg.takeAs<Expr>();
Fariborz Jahanian4fc7ab32009-08-28 15:11:24 +0000209 }
Anders Carlsson0aebc812009-09-09 21:33:21 +0000210
211 return Owned(new (Context) CXXFunctionalCastExpr(Ty.getNonReferenceType(),
212 Ty, TyBeginLoc, Kind,
213 Exprs[0], RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000214 }
215
Ted Kremenek6217b802009-07-29 21:53:49 +0000216 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Douglas Gregor506ae412009-01-16 18:33:17 +0000217 CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
Sebastian Redlf53597f2009-03-15 17:47:39 +0000218
Mike Stump1eb44332009-09-09 15:08:12 +0000219 if (NumExprs > 1 || !Record->hasTrivialConstructor() ||
Anders Carlssone7624a72009-08-27 05:08:22 +0000220 !Record->hasTrivialDestructor()) {
Douglas Gregor39da0b82009-09-09 23:08:42 +0000221 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
222
Douglas Gregor506ae412009-01-16 18:33:17 +0000223 CXXConstructorDecl *Constructor
Douglas Gregor39da0b82009-09-09 23:08:42 +0000224 = PerformInitializationByConstructor(Ty, move(exprs),
Douglas Gregor506ae412009-01-16 18:33:17 +0000225 TypeRange.getBegin(),
226 SourceRange(TypeRange.getBegin(),
227 RParenLoc),
228 DeclarationName(),
Douglas Gregor20093b42009-12-09 23:02:17 +0000229 InitializationKind::CreateDirect(TypeRange.getBegin(),
230 LParenLoc,
231 RParenLoc),
Douglas Gregor39da0b82009-09-09 23:08:42 +0000232 ConstructorArgs);
Douglas Gregor506ae412009-01-16 18:33:17 +0000233
Sebastian Redlf53597f2009-03-15 17:47:39 +0000234 if (!Constructor)
235 return ExprError();
236
Mike Stump1eb44332009-09-09 15:08:12 +0000237 OwningExprResult Result =
238 BuildCXXTemporaryObjectExpr(Constructor, Ty, TyBeginLoc,
Douglas Gregor39da0b82009-09-09 23:08:42 +0000239 move_arg(ConstructorArgs), RParenLoc);
Anders Carlssone7624a72009-08-27 05:08:22 +0000240 if (Result.isInvalid())
241 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000242
Anders Carlssone7624a72009-08-27 05:08:22 +0000243 return MaybeBindToTemporary(Result.takeAs<Expr>());
Douglas Gregor506ae412009-01-16 18:33:17 +0000244 }
245
246 // Fall through to value-initialize an object of class type that
247 // doesn't have a user-declared default constructor.
248 }
249
250 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000251 // If the expression list specifies more than a single value, the type shall
252 // be a class with a suitably declared constructor.
253 //
254 if (NumExprs > 1)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000255 return ExprError(Diag(CommaLocs[0],
256 diag::err_builtin_func_cast_more_than_one_arg)
257 << FullRange);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000258
259 assert(NumExprs == 0 && "Expected 0 expressions");
Douglas Gregor506ae412009-01-16 18:33:17 +0000260 // C++ [expr.type.conv]p2:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000261 // The expression T(), where T is a simple-type-specifier for a non-array
262 // complete object type or the (possibly cv-qualified) void type, creates an
263 // rvalue of the specified type, which is value-initialized.
264 //
Sebastian Redlf53597f2009-03-15 17:47:39 +0000265 exprs.release();
266 return Owned(new (Context) CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000267}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000268
269
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000270/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
271/// @code new (memory) int[size][4] @endcode
272/// or
273/// @code ::new Foo(23, "hello") @endcode
274/// For the interpretation of this heap of arguments, consult the base version.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000275Action::OwningExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000276Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000277 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000278 SourceLocation PlacementRParen, bool ParenTypeId,
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000279 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000280 MultiExprArg ConstructorArgs,
Mike Stump1eb44332009-09-09 15:08:12 +0000281 SourceLocation ConstructorRParen) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000282 Expr *ArraySize = 0;
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000283 // If the specified type is an array, unwrap it and save the expression.
284 if (D.getNumTypeObjects() > 0 &&
285 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
286 DeclaratorChunk &Chunk = D.getTypeObject(0);
287 if (Chunk.Arr.hasStatic)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000288 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
289 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000290 if (!Chunk.Arr.NumElts)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000291 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
292 << D.getSourceRange());
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000293
294 if (ParenTypeId) {
295 // Can't have dynamic array size when the type-id is in parentheses.
296 Expr *NumElts = (Expr *)Chunk.Arr.NumElts;
297 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
298 !NumElts->isIntegerConstantExpr(Context)) {
299 Diag(D.getTypeObject(0).Loc, diag::err_new_paren_array_nonconst)
300 << NumElts->getSourceRange();
301 return ExprError();
302 }
303 }
304
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000305 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000306 D.DropFirstTypeObject();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000307 }
308
Douglas Gregor043cad22009-09-11 00:18:58 +0000309 // Every dimension shall be of constant size.
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000310 if (ArraySize) {
311 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor043cad22009-09-11 00:18:58 +0000312 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
313 break;
314
315 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
316 if (Expr *NumElts = (Expr *)Array.NumElts) {
317 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
318 !NumElts->isIntegerConstantExpr(Context)) {
319 Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst)
320 << NumElts->getSourceRange();
321 return ExprError();
322 }
323 }
324 }
325 }
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000326
John McCalla93c9342009-12-07 02:54:59 +0000327 //FIXME: Store TypeSourceInfo in CXXNew expression.
328 TypeSourceInfo *TInfo = 0;
329 QualType AllocType = GetTypeForDeclarator(D, /*Scope=*/0, &TInfo);
Chris Lattnereaaebc72009-04-25 08:06:05 +0000330 if (D.isInvalidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000331 return ExprError();
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000332
Mike Stump1eb44332009-09-09 15:08:12 +0000333 return BuildCXXNew(StartLoc, UseGlobal,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000334 PlacementLParen,
Mike Stump1eb44332009-09-09 15:08:12 +0000335 move(PlacementArgs),
Douglas Gregor3433cf72009-05-21 00:00:09 +0000336 PlacementRParen,
337 ParenTypeId,
Mike Stump1eb44332009-09-09 15:08:12 +0000338 AllocType,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000339 D.getSourceRange().getBegin(),
340 D.getSourceRange(),
341 Owned(ArraySize),
342 ConstructorLParen,
343 move(ConstructorArgs),
344 ConstructorRParen);
345}
346
Mike Stump1eb44332009-09-09 15:08:12 +0000347Sema::OwningExprResult
Douglas Gregor3433cf72009-05-21 00:00:09 +0000348Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
349 SourceLocation PlacementLParen,
350 MultiExprArg PlacementArgs,
351 SourceLocation PlacementRParen,
Mike Stump1eb44332009-09-09 15:08:12 +0000352 bool ParenTypeId,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000353 QualType AllocType,
354 SourceLocation TypeLoc,
355 SourceRange TypeRange,
356 ExprArg ArraySizeE,
357 SourceLocation ConstructorLParen,
358 MultiExprArg ConstructorArgs,
359 SourceLocation ConstructorRParen) {
360 if (CheckAllocatedType(AllocType, TypeLoc, TypeRange))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000361 return ExprError();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000362
Douglas Gregor3433cf72009-05-21 00:00:09 +0000363 QualType ResultType = Context.getPointerType(AllocType);
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000364
365 // That every array dimension except the first is constant was already
366 // checked by the type check above.
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000367
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000368 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
369 // or enumeration type with a non-negative value."
Douglas Gregor3433cf72009-05-21 00:00:09 +0000370 Expr *ArraySize = (Expr *)ArraySizeE.get();
Sebastian Redl28507842009-02-26 14:39:58 +0000371 if (ArraySize && !ArraySize->isTypeDependent()) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000372 QualType SizeType = ArraySize->getType();
373 if (!SizeType->isIntegralType() && !SizeType->isEnumeralType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000374 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
375 diag::err_array_size_not_integral)
376 << SizeType << ArraySize->getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000377 // Let's see if this is a constant < 0. If so, we reject it out of hand.
378 // We don't care about special rules, so we tell the machinery it's not
379 // evaluated - it gives us a result in more cases.
Sebastian Redl28507842009-02-26 14:39:58 +0000380 if (!ArraySize->isValueDependent()) {
381 llvm::APSInt Value;
382 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
383 if (Value < llvm::APSInt(
Anders Carlssonac18b2e2009-09-23 00:37:25 +0000384 llvm::APInt::getNullValue(Value.getBitWidth()),
385 Value.isUnsigned()))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000386 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
387 diag::err_typecheck_negative_array_size)
388 << ArraySize->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +0000389 }
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000390 }
Anders Carlssonac18b2e2009-09-23 00:37:25 +0000391
Eli Friedman73c39ab2009-10-20 08:27:19 +0000392 ImpCastExprToType(ArraySize, Context.getSizeType(),
393 CastExpr::CK_IntegralCast);
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000394 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000395
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000396 FunctionDecl *OperatorNew = 0;
397 FunctionDecl *OperatorDelete = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000398 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
399 unsigned NumPlaceArgs = PlacementArgs.size();
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000400
Sebastian Redl28507842009-02-26 14:39:58 +0000401 if (!AllocType->isDependentType() &&
402 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
403 FindAllocationFunctions(StartLoc,
Sebastian Redl00e68e22009-02-09 18:24:27 +0000404 SourceRange(PlacementLParen, PlacementRParen),
405 UseGlobal, AllocType, ArraySize, PlaceArgs,
406 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000407 return ExprError();
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000408 llvm::SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000409 if (OperatorNew) {
410 // Add default arguments, if any.
411 const FunctionProtoType *Proto =
412 OperatorNew->getType()->getAs<FunctionProtoType>();
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +0000413 VariadicCallType CallType =
414 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000415 bool Invalid = GatherArgumentsForCall(PlacementLParen, OperatorNew,
416 Proto, 1, PlaceArgs, NumPlaceArgs,
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +0000417 AllPlaceArgs, CallType);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000418 if (Invalid)
419 return ExprError();
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000420
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000421 NumPlaceArgs = AllPlaceArgs.size();
422 if (NumPlaceArgs > 0)
423 PlaceArgs = &AllPlaceArgs[0];
424 }
425
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000426 bool Init = ConstructorLParen.isValid();
427 // --- Choosing a constructor ---
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000428 CXXConstructorDecl *Constructor = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000429 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
430 unsigned NumConsArgs = ConstructorArgs.size();
Eli Friedmana8ce9ec2009-11-08 22:15:39 +0000431 ASTOwningVector<&ActionBase::DeleteExpr> ConvertedConstructorArgs(*this);
432
Douglas Gregor99a2e602009-12-16 01:38:02 +0000433 if (!AllocType->isDependentType() &&
434 !Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) {
435 // C++0x [expr.new]p15:
436 // A new-expression that creates an object of type T initializes that
437 // object as follows:
438 InitializationKind Kind
439 // - If the new-initializer is omitted, the object is default-
440 // initialized (8.5); if no initialization is performed,
441 // the object has indeterminate value
442 = !Init? InitializationKind::CreateDefault(TypeLoc)
443 // - Otherwise, the new-initializer is interpreted according to the
444 // initialization rules of 8.5 for direct-initialization.
445 : InitializationKind::CreateDirect(TypeLoc,
446 ConstructorLParen,
447 ConstructorRParen);
448
449 // FIXME: We shouldn't have to fake this.
450 TypeSourceInfo *TInfo
451 = Context.getTrivialTypeSourceInfo(AllocType, TypeLoc);
452 InitializedEntity Entity
453 = InitializedEntity::InitializeTemporary(TInfo->getTypeLoc());
454 InitializationSequence InitSeq(*this, Entity, Kind, ConsArgs, NumConsArgs);
455
456 if (!InitSeq) {
457 InitSeq.Diagnose(*this, Entity, Kind, ConsArgs, NumConsArgs);
Sebastian Redlf53597f2009-03-15 17:47:39 +0000458 return ExprError();
Douglas Gregor99a2e602009-12-16 01:38:02 +0000459 }
Douglas Gregor39da0b82009-09-09 23:08:42 +0000460
Douglas Gregor99a2e602009-12-16 01:38:02 +0000461 OwningExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
462 move(ConstructorArgs));
463 if (FullInit.isInvalid())
464 return ExprError();
465
466 // FullInit is our initializer; walk through it to determine if it's a
467 // constructor call, which CXXNewExpr handles directly.
468 if (Expr *FullInitExpr = (Expr *)FullInit.get()) {
469 if (CXXBindTemporaryExpr *Binder
470 = dyn_cast<CXXBindTemporaryExpr>(FullInitExpr))
471 FullInitExpr = Binder->getSubExpr();
472 if (CXXConstructExpr *Construct
473 = dyn_cast<CXXConstructExpr>(FullInitExpr)) {
474 Constructor = Construct->getConstructor();
475 for (CXXConstructExpr::arg_iterator A = Construct->arg_begin(),
476 AEnd = Construct->arg_end();
477 A != AEnd; ++A)
478 ConvertedConstructorArgs.push_back(A->Retain());
479 } else {
480 // Take the converted initializer.
481 ConvertedConstructorArgs.push_back(FullInit.release());
482 }
483 } else {
484 // No initialization required.
485 }
486
487 // Take the converted arguments and use them for the new expression.
Douglas Gregor39da0b82009-09-09 23:08:42 +0000488 NumConsArgs = ConvertedConstructorArgs.size();
489 ConsArgs = (Expr **)ConvertedConstructorArgs.take();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000490 }
Douglas Gregor99a2e602009-12-16 01:38:02 +0000491
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000492 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
Douglas Gregor089407b2009-10-17 21:40:42 +0000493
Sebastian Redlf53597f2009-03-15 17:47:39 +0000494 PlacementArgs.release();
495 ConstructorArgs.release();
Douglas Gregor3433cf72009-05-21 00:00:09 +0000496 ArraySizeE.release();
Sebastian Redlf53597f2009-03-15 17:47:39 +0000497 return Owned(new (Context) CXXNewExpr(UseGlobal, OperatorNew, PlaceArgs,
Ted Kremenek8189cde2009-02-07 01:47:29 +0000498 NumPlaceArgs, ParenTypeId, ArraySize, Constructor, Init,
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000499 ConsArgs, NumConsArgs, OperatorDelete, ResultType,
Mike Stump1eb44332009-09-09 15:08:12 +0000500 StartLoc, Init ? ConstructorRParen : SourceLocation()));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000501}
502
503/// CheckAllocatedType - Checks that a type is suitable as the allocated type
504/// in a new-expression.
505/// dimension off and stores the size expression in ArraySize.
Douglas Gregor3433cf72009-05-21 00:00:09 +0000506bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +0000507 SourceRange R) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000508 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
509 // abstract class type or array thereof.
Douglas Gregore7450f52009-03-24 19:52:54 +0000510 if (AllocType->isFunctionType())
Douglas Gregor3433cf72009-05-21 00:00:09 +0000511 return Diag(Loc, diag::err_bad_new_type)
512 << AllocType << 0 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +0000513 else if (AllocType->isReferenceType())
Douglas Gregor3433cf72009-05-21 00:00:09 +0000514 return Diag(Loc, diag::err_bad_new_type)
515 << AllocType << 1 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +0000516 else if (!AllocType->isDependentType() &&
Douglas Gregor3433cf72009-05-21 00:00:09 +0000517 RequireCompleteType(Loc, AllocType,
Anders Carlssonb7906612009-08-26 23:45:07 +0000518 PDiag(diag::err_new_incomplete_type)
519 << R))
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000520 return true;
Douglas Gregor3433cf72009-05-21 00:00:09 +0000521 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregore7450f52009-03-24 19:52:54 +0000522 diag::err_allocation_of_abstract_type))
523 return true;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000524
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000525 return false;
526}
527
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000528/// FindAllocationFunctions - Finds the overloads of operator new and delete
529/// that are appropriate for the allocation.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000530bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
531 bool UseGlobal, QualType AllocType,
532 bool IsArray, Expr **PlaceArgs,
533 unsigned NumPlaceArgs,
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000534 FunctionDecl *&OperatorNew,
Mike Stump1eb44332009-09-09 15:08:12 +0000535 FunctionDecl *&OperatorDelete) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000536 // --- Choosing an allocation function ---
537 // C++ 5.3.4p8 - 14 & 18
538 // 1) If UseGlobal is true, only look in the global scope. Else, also look
539 // in the scope of the allocated class.
540 // 2) If an array size is given, look for operator new[], else look for
541 // operator new.
542 // 3) The first argument is always size_t. Append the arguments from the
543 // placement form.
544 // FIXME: Also find the appropriate delete operator.
545
546 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
547 // We don't care about the actual value of this argument.
548 // FIXME: Should the Sema create the expression and embed it in the syntax
549 // tree? Or should the consumer just recalculate the value?
Anders Carlssond67c4c32009-08-16 20:29:29 +0000550 IntegerLiteral Size(llvm::APInt::getNullValue(
551 Context.Target.getPointerWidth(0)),
552 Context.getSizeType(),
553 SourceLocation());
554 AllocArgs[0] = &Size;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000555 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
556
557 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
558 IsArray ? OO_Array_New : OO_New);
559 if (AllocType->isRecordType() && !UseGlobal) {
Mike Stump1eb44332009-09-09 15:08:12 +0000560 CXXRecordDecl *Record
Ted Kremenek6217b802009-07-29 21:53:49 +0000561 = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl());
Sebastian Redl7f662392008-12-04 22:20:51 +0000562 // FIXME: We fail to find inherited overloads.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000563 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000564 AllocArgs.size(), Record, /*AllowMissing=*/true,
565 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000566 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000567 }
568 if (!OperatorNew) {
569 // Didn't find a member overload. Look for a global one.
570 DeclareGlobalNewDelete();
Sebastian Redl7f662392008-12-04 22:20:51 +0000571 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl00e68e22009-02-09 18:24:27 +0000572 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000573 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
574 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000575 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000576 }
577
Anders Carlssond9583892009-05-31 20:26:12 +0000578 // FindAllocationOverload can change the passed in arguments, so we need to
579 // copy them back.
580 if (NumPlaceArgs > 0)
581 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
Mike Stump1eb44332009-09-09 15:08:12 +0000582
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000583 return false;
584}
585
Sebastian Redl7f662392008-12-04 22:20:51 +0000586/// FindAllocationOverload - Find an fitting overload for the allocation
587/// function in the specified scope.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000588bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
589 DeclarationName Name, Expr** Args,
590 unsigned NumArgs, DeclContext *Ctx,
Mike Stump1eb44332009-09-09 15:08:12 +0000591 bool AllowMissing, FunctionDecl *&Operator) {
John McCalla24dc2e2009-11-17 02:14:36 +0000592 LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
593 LookupQualifiedName(R, Ctx);
John McCallf36e02d2009-10-09 21:13:30 +0000594 if (R.empty()) {
Sebastian Redl7f662392008-12-04 22:20:51 +0000595 if (AllowMissing)
596 return false;
Sebastian Redl7f662392008-12-04 22:20:51 +0000597 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +0000598 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +0000599 }
600
John McCallf36e02d2009-10-09 21:13:30 +0000601 // FIXME: handle ambiguity
602
Sebastian Redl7f662392008-12-04 22:20:51 +0000603 OverloadCandidateSet Candidates;
Douglas Gregor5d64e5b2009-09-30 00:03:47 +0000604 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
605 Alloc != AllocEnd; ++Alloc) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000606 // Even member operator new/delete are implicitly treated as
607 // static, so don't use AddMemberCandidate.
Anders Carlssoneac81392009-12-09 07:39:44 +0000608 if (FunctionDecl *Fn =
609 dyn_cast<FunctionDecl>((*Alloc)->getUnderlyingDecl())) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000610 AddOverloadCandidate(Fn, Args, NumArgs, Candidates,
611 /*SuppressUserConversions=*/false);
Douglas Gregor90916562009-09-29 18:16:17 +0000612 continue;
613 }
614
615 // FIXME: Handle function templates
Sebastian Redl7f662392008-12-04 22:20:51 +0000616 }
617
618 // Do the resolution.
619 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +0000620 switch(BestViableFunction(Candidates, StartLoc, Best)) {
Sebastian Redl7f662392008-12-04 22:20:51 +0000621 case OR_Success: {
622 // Got one!
623 FunctionDecl *FnDecl = Best->Function;
624 // The first argument is size_t, and the first parameter must be size_t,
625 // too. This is checked on declaration and can be assumed. (It can't be
626 // asserted on, though, since invalid decls are left in there.)
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000627 // Whatch out for variadic allocator function.
628 unsigned NumArgsInFnDecl = FnDecl->getNumParams();
629 for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) {
Anders Carlssonfc27d262009-05-31 19:49:47 +0000630 if (PerformCopyInitialization(Args[i],
Sebastian Redl7f662392008-12-04 22:20:51 +0000631 FnDecl->getParamDecl(i)->getType(),
Douglas Gregor68647482009-12-16 03:45:30 +0000632 AA_Passing))
Sebastian Redl7f662392008-12-04 22:20:51 +0000633 return true;
634 }
635 Operator = FnDecl;
636 return false;
637 }
638
639 case OR_No_Viable_Function:
Sebastian Redl7f662392008-12-04 22:20:51 +0000640 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +0000641 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +0000642 PrintOverloadCandidates(Candidates, /*OnlyViable=*/false);
643 return true;
644
645 case OR_Ambiguous:
Sebastian Redl7f662392008-12-04 22:20:51 +0000646 Diag(StartLoc, diag::err_ovl_ambiguous_call)
Sebastian Redl00e68e22009-02-09 18:24:27 +0000647 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +0000648 PrintOverloadCandidates(Candidates, /*OnlyViable=*/true);
649 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000650
651 case OR_Deleted:
652 Diag(StartLoc, diag::err_ovl_deleted_call)
653 << Best->Function->isDeleted()
654 << Name << Range;
655 PrintOverloadCandidates(Candidates, /*OnlyViable=*/true);
656 return true;
Sebastian Redl7f662392008-12-04 22:20:51 +0000657 }
658 assert(false && "Unreachable, bad result from BestViableFunction");
659 return true;
660}
661
662
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000663/// DeclareGlobalNewDelete - Declare the global forms of operator new and
664/// delete. These are:
665/// @code
666/// void* operator new(std::size_t) throw(std::bad_alloc);
667/// void* operator new[](std::size_t) throw(std::bad_alloc);
668/// void operator delete(void *) throw();
669/// void operator delete[](void *) throw();
670/// @endcode
671/// Note that the placement and nothrow forms of new are *not* implicitly
672/// declared. Their use requires including \<new\>.
Mike Stump1eb44332009-09-09 15:08:12 +0000673void Sema::DeclareGlobalNewDelete() {
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000674 if (GlobalNewDeleteDeclared)
675 return;
Douglas Gregor7adb10f2009-09-15 22:30:29 +0000676
677 // C++ [basic.std.dynamic]p2:
678 // [...] The following allocation and deallocation functions (18.4) are
679 // implicitly declared in global scope in each translation unit of a
680 // program
681 //
682 // void* operator new(std::size_t) throw(std::bad_alloc);
683 // void* operator new[](std::size_t) throw(std::bad_alloc);
684 // void operator delete(void*) throw();
685 // void operator delete[](void*) throw();
686 //
687 // These implicit declarations introduce only the function names operator
688 // new, operator new[], operator delete, operator delete[].
689 //
690 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
691 // "std" or "bad_alloc" as necessary to form the exception specification.
692 // However, we do not make these implicit declarations visible to name
693 // lookup.
694 if (!StdNamespace) {
695 // The "std" namespace has not yet been defined, so build one implicitly.
696 StdNamespace = NamespaceDecl::Create(Context,
697 Context.getTranslationUnitDecl(),
698 SourceLocation(),
699 &PP.getIdentifierTable().get("std"));
700 StdNamespace->setImplicit(true);
701 }
702
703 if (!StdBadAlloc) {
704 // The "std::bad_alloc" class has not yet been declared, so build it
705 // implicitly.
706 StdBadAlloc = CXXRecordDecl::Create(Context, TagDecl::TK_class,
707 StdNamespace,
708 SourceLocation(),
709 &PP.getIdentifierTable().get("bad_alloc"),
710 SourceLocation(), 0);
711 StdBadAlloc->setImplicit(true);
712 }
713
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000714 GlobalNewDeleteDeclared = true;
715
716 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
717 QualType SizeT = Context.getSizeType();
718
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000719 DeclareGlobalAllocationFunction(
720 Context.DeclarationNames.getCXXOperatorName(OO_New),
721 VoidPtr, SizeT);
722 DeclareGlobalAllocationFunction(
723 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
724 VoidPtr, SizeT);
725 DeclareGlobalAllocationFunction(
726 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
727 Context.VoidTy, VoidPtr);
728 DeclareGlobalAllocationFunction(
729 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
730 Context.VoidTy, VoidPtr);
731}
732
733/// DeclareGlobalAllocationFunction - Declares a single implicit global
734/// allocation function if it doesn't already exist.
735void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Mike Stump1eb44332009-09-09 15:08:12 +0000736 QualType Return, QualType Argument) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000737 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
738
739 // Check if this function is already declared.
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000740 {
Douglas Gregor5cc37092008-12-23 22:05:29 +0000741 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000742 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000743 Alloc != AllocEnd; ++Alloc) {
744 // FIXME: Do we need to check for default arguments here?
745 FunctionDecl *Func = cast<FunctionDecl>(*Alloc);
746 if (Func->getNumParams() == 1 &&
Ted Kremenek8189cde2009-02-07 01:47:29 +0000747 Context.getCanonicalType(Func->getParamDecl(0)->getType())==Argument)
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000748 return;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000749 }
750 }
751
Douglas Gregor7adb10f2009-09-15 22:30:29 +0000752 QualType BadAllocType;
753 bool HasBadAllocExceptionSpec
754 = (Name.getCXXOverloadedOperator() == OO_New ||
755 Name.getCXXOverloadedOperator() == OO_Array_New);
756 if (HasBadAllocExceptionSpec) {
757 assert(StdBadAlloc && "Must have std::bad_alloc declared");
758 BadAllocType = Context.getTypeDeclType(StdBadAlloc);
759 }
760
761 QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0,
762 true, false,
763 HasBadAllocExceptionSpec? 1 : 0,
764 &BadAllocType);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000765 FunctionDecl *Alloc =
766 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
John McCalla93c9342009-12-07 02:54:59 +0000767 FnType, /*TInfo=*/0, FunctionDecl::None, false, true);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000768 Alloc->setImplicit();
769 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
John McCalla93c9342009-12-07 02:54:59 +0000770 0, Argument, /*TInfo=*/0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000771 VarDecl::None, 0);
Ted Kremenekfc767612009-01-14 00:42:25 +0000772 Alloc->setParams(Context, &Param, 1);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000773
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000774 // FIXME: Also add this declaration to the IdentifierResolver, but
775 // make sure it is at the end of the chain to coincide with the
776 // global scope.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000777 ((DeclContext *)TUScope->getEntity())->addDecl(Alloc);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000778}
779
Anders Carlsson78f74552009-11-15 18:45:20 +0000780bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
781 DeclarationName Name,
Anders Carlsson5ec02ae2009-12-02 17:15:43 +0000782 FunctionDecl* &Operator) {
John McCalla24dc2e2009-11-17 02:14:36 +0000783 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlsson78f74552009-11-15 18:45:20 +0000784 // Try to find operator delete/operator delete[] in class scope.
John McCalla24dc2e2009-11-17 02:14:36 +0000785 LookupQualifiedName(Found, RD);
Anders Carlsson78f74552009-11-15 18:45:20 +0000786
John McCalla24dc2e2009-11-17 02:14:36 +0000787 if (Found.isAmbiguous())
Anders Carlsson78f74552009-11-15 18:45:20 +0000788 return true;
Anders Carlsson78f74552009-11-15 18:45:20 +0000789
790 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
791 F != FEnd; ++F) {
792 if (CXXMethodDecl *Delete = dyn_cast<CXXMethodDecl>(*F))
793 if (Delete->isUsualDeallocationFunction()) {
794 Operator = Delete;
795 return false;
796 }
797 }
798
799 // We did find operator delete/operator delete[] declarations, but
800 // none of them were suitable.
801 if (!Found.empty()) {
802 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
803 << Name << RD;
804
805 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
806 F != FEnd; ++F) {
807 Diag((*F)->getLocation(),
808 diag::note_delete_member_function_declared_here)
809 << Name;
810 }
811
812 return true;
813 }
814
815 // Look for a global declaration.
816 DeclareGlobalNewDelete();
817 DeclContext *TUDecl = Context.getTranslationUnitDecl();
818
819 CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation());
820 Expr* DeallocArgs[1];
821 DeallocArgs[0] = &Null;
822 if (FindAllocationOverload(StartLoc, SourceRange(), Name,
823 DeallocArgs, 1, TUDecl, /*AllowMissing=*/false,
824 Operator))
825 return true;
826
827 assert(Operator && "Did not find a deallocation function!");
828 return false;
829}
830
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000831/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
832/// @code ::delete ptr; @endcode
833/// or
834/// @code delete [] ptr; @endcode
Sebastian Redlf53597f2009-03-15 17:47:39 +0000835Action::OwningExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000836Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
Mike Stump1eb44332009-09-09 15:08:12 +0000837 bool ArrayForm, ExprArg Operand) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000838 // C++ [expr.delete]p1:
839 // The operand shall have a pointer type, or a class type having a single
840 // conversion function to a pointer type. The result has type void.
841 //
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000842 // DR599 amends "pointer type" to "pointer to object type" in both cases.
843
Anders Carlssond67c4c32009-08-16 20:29:29 +0000844 FunctionDecl *OperatorDelete = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000845
Sebastian Redlf53597f2009-03-15 17:47:39 +0000846 Expr *Ex = (Expr *)Operand.get();
Sebastian Redl28507842009-02-26 14:39:58 +0000847 if (!Ex->isTypeDependent()) {
848 QualType Type = Ex->getType();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000849
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000850 if (const RecordType *Record = Type->getAs<RecordType>()) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000851 llvm::SmallVector<CXXConversionDecl *, 4> ObjectPtrConversions;
Fariborz Jahanian53462782009-09-11 21:44:33 +0000852 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
John McCallba135432009-11-21 08:51:07 +0000853 const UnresolvedSet *Conversions = RD->getVisibleConversionFunctions();
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000854
John McCallba135432009-11-21 08:51:07 +0000855 for (UnresolvedSet::iterator I = Conversions->begin(),
856 E = Conversions->end(); I != E; ++I) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000857 // Skip over templated conversion functions; they aren't considered.
John McCallba135432009-11-21 08:51:07 +0000858 if (isa<FunctionTemplateDecl>(*I))
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000859 continue;
860
John McCallba135432009-11-21 08:51:07 +0000861 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*I);
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000862
863 QualType ConvType = Conv->getConversionType().getNonReferenceType();
864 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
865 if (ConvPtrType->getPointeeType()->isObjectType())
Fariborz Jahanian8b915e72009-09-15 22:15:23 +0000866 ObjectPtrConversions.push_back(Conv);
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000867 }
Fariborz Jahanian8b915e72009-09-15 22:15:23 +0000868 if (ObjectPtrConversions.size() == 1) {
869 // We have a single conversion to a pointer-to-object type. Perform
870 // that conversion.
871 Operand.release();
872 if (!PerformImplicitConversion(Ex,
873 ObjectPtrConversions.front()->getConversionType(),
Douglas Gregor68647482009-12-16 03:45:30 +0000874 AA_Converting)) {
Fariborz Jahanian8b915e72009-09-15 22:15:23 +0000875 Operand = Owned(Ex);
876 Type = Ex->getType();
877 }
878 }
879 else if (ObjectPtrConversions.size() > 1) {
880 Diag(StartLoc, diag::err_ambiguous_delete_operand)
881 << Type << Ex->getSourceRange();
882 for (unsigned i= 0; i < ObjectPtrConversions.size(); i++) {
883 CXXConversionDecl *Conv = ObjectPtrConversions[i];
884 Diag(Conv->getLocation(), diag::err_ovl_candidate);
885 }
886 return ExprError();
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000887 }
Sebastian Redl28507842009-02-26 14:39:58 +0000888 }
889
Sebastian Redlf53597f2009-03-15 17:47:39 +0000890 if (!Type->isPointerType())
891 return ExprError(Diag(StartLoc, diag::err_delete_operand)
892 << Type << Ex->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +0000893
Ted Kremenek6217b802009-07-29 21:53:49 +0000894 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Douglas Gregor8dcb29d2009-03-24 20:13:58 +0000895 if (Pointee->isFunctionType() || Pointee->isVoidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000896 return ExprError(Diag(StartLoc, diag::err_delete_operand)
897 << Type << Ex->getSourceRange());
Douglas Gregor8dcb29d2009-03-24 20:13:58 +0000898 else if (!Pointee->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +0000899 RequireCompleteType(StartLoc, Pointee,
Anders Carlssonb7906612009-08-26 23:45:07 +0000900 PDiag(diag::warn_delete_incomplete)
901 << Ex->getSourceRange()))
Douglas Gregor8dcb29d2009-03-24 20:13:58 +0000902 return ExprError();
Sebastian Redl28507842009-02-26 14:39:58 +0000903
Douglas Gregor1070c9f2009-09-29 21:38:53 +0000904 // C++ [expr.delete]p2:
905 // [Note: a pointer to a const type can be the operand of a
906 // delete-expression; it is not necessary to cast away the constness
907 // (5.2.11) of the pointer expression before it is used as the operand
908 // of the delete-expression. ]
909 ImpCastExprToType(Ex, Context.getPointerType(Context.VoidTy),
910 CastExpr::CK_NoOp);
911
912 // Update the operand.
913 Operand.take();
914 Operand = ExprArg(*this, Ex);
915
Anders Carlssond67c4c32009-08-16 20:29:29 +0000916 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
917 ArrayForm ? OO_Array_Delete : OO_Delete);
918
Anders Carlsson78f74552009-11-15 18:45:20 +0000919 if (const RecordType *RT = Pointee->getAs<RecordType>()) {
920 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
921
922 if (!UseGlobal &&
923 FindDeallocationFunction(StartLoc, RD, DeleteName, OperatorDelete))
Anders Carlsson0ba63ea2009-11-14 03:17:38 +0000924 return ExprError();
Anders Carlsson0ba63ea2009-11-14 03:17:38 +0000925
Anders Carlsson78f74552009-11-15 18:45:20 +0000926 if (!RD->hasTrivialDestructor())
927 if (const CXXDestructorDecl *Dtor = RD->getDestructor(Context))
Mike Stump1eb44332009-09-09 15:08:12 +0000928 MarkDeclarationReferenced(StartLoc,
Fariborz Jahanian34374e62009-09-03 23:18:17 +0000929 const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssond67c4c32009-08-16 20:29:29 +0000930 }
Anders Carlsson78f74552009-11-15 18:45:20 +0000931
Anders Carlssond67c4c32009-08-16 20:29:29 +0000932 if (!OperatorDelete) {
Anders Carlsson78f74552009-11-15 18:45:20 +0000933 // Look for a global declaration.
Anders Carlssond67c4c32009-08-16 20:29:29 +0000934 DeclareGlobalNewDelete();
935 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000936 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
Douglas Gregor90916562009-09-29 18:16:17 +0000937 &Ex, 1, TUDecl, /*AllowMissing=*/false,
Anders Carlssond67c4c32009-08-16 20:29:29 +0000938 OperatorDelete))
939 return ExprError();
940 }
Mike Stump1eb44332009-09-09 15:08:12 +0000941
Sebastian Redl28507842009-02-26 14:39:58 +0000942 // FIXME: Check access and ambiguity of operator delete and destructor.
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000943 }
944
Sebastian Redlf53597f2009-03-15 17:47:39 +0000945 Operand.release();
946 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
Anders Carlssond67c4c32009-08-16 20:29:29 +0000947 OperatorDelete, Ex, StartLoc));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000948}
949
Douglas Gregor8cfe5a72009-11-23 23:44:04 +0000950/// \brief Check the use of the given variable as a C++ condition in an if,
951/// while, do-while, or switch statement.
952Action::OwningExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar) {
953 QualType T = ConditionVar->getType();
954
955 // C++ [stmt.select]p2:
956 // The declarator shall not specify a function or an array.
957 if (T->isFunctionType())
958 return ExprError(Diag(ConditionVar->getLocation(),
959 diag::err_invalid_use_of_function_type)
960 << ConditionVar->getSourceRange());
961 else if (T->isArrayType())
962 return ExprError(Diag(ConditionVar->getLocation(),
963 diag::err_invalid_use_of_array_type)
964 << ConditionVar->getSourceRange());
Douglas Gregora7605db2009-11-24 16:07:02 +0000965
Douglas Gregor8cfe5a72009-11-23 23:44:04 +0000966 return Owned(DeclRefExpr::Create(Context, 0, SourceRange(), ConditionVar,
967 ConditionVar->getLocation(),
968 ConditionVar->getType().getNonReferenceType()));
969}
970
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000971/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
972bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
973 // C++ 6.4p4:
974 // The value of a condition that is an initialized declaration in a statement
975 // other than a switch statement is the value of the declared variable
976 // implicitly converted to type bool. If that conversion is ill-formed, the
977 // program is ill-formed.
978 // The value of a condition that is an expression is the value of the
979 // expression, implicitly converted to bool.
980 //
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000981 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000982}
Douglas Gregor77a52232008-09-12 00:47:35 +0000983
984/// Helper function to determine whether this is the (deprecated) C++
985/// conversion from a string literal to a pointer to non-const char or
986/// non-const wchar_t (for narrow and wide string literals,
987/// respectively).
Mike Stump1eb44332009-09-09 15:08:12 +0000988bool
Douglas Gregor77a52232008-09-12 00:47:35 +0000989Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
990 // Look inside the implicit cast, if it exists.
991 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
992 From = Cast->getSubExpr();
993
994 // A string literal (2.13.4) that is not a wide string literal can
995 // be converted to an rvalue of type "pointer to char"; a wide
996 // string literal can be converted to an rvalue of type "pointer
997 // to wchar_t" (C++ 4.2p2).
998 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From))
Ted Kremenek6217b802009-07-29 21:53:49 +0000999 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump1eb44332009-09-09 15:08:12 +00001000 if (const BuiltinType *ToPointeeType
John McCall183700f2009-09-21 23:43:11 +00001001 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregor77a52232008-09-12 00:47:35 +00001002 // This conversion is considered only when there is an
1003 // explicit appropriate pointer target type (C++ 4.2p2).
John McCall0953e762009-09-24 19:53:00 +00001004 if (!ToPtrType->getPointeeType().hasQualifiers() &&
Douglas Gregor77a52232008-09-12 00:47:35 +00001005 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
1006 (!StrLit->isWide() &&
1007 (ToPointeeType->getKind() == BuiltinType::Char_U ||
1008 ToPointeeType->getKind() == BuiltinType::Char_S))))
1009 return true;
1010 }
1011
1012 return false;
1013}
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001014
1015/// PerformImplicitConversion - Perform an implicit conversion of the
1016/// expression From to the type ToType. Returns true if there was an
1017/// error, false otherwise. The expression From is replaced with the
Douglas Gregor45920e82008-12-19 17:40:08 +00001018/// converted expression. Flavor is the kind of conversion we're
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001019/// performing, used in the error message. If @p AllowExplicit,
Sebastian Redle2b68332009-04-12 17:16:29 +00001020/// explicit user-defined conversions are permitted. @p Elidable should be true
1021/// when called for copies which may be elided (C++ 12.8p15). C++0x overload
1022/// resolution works differently in that case.
1023bool
Douglas Gregor45920e82008-12-19 17:40:08 +00001024Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor68647482009-12-16 03:45:30 +00001025 AssignmentAction Action, bool AllowExplicit,
Mike Stump1eb44332009-09-09 15:08:12 +00001026 bool Elidable) {
Sebastian Redle2b68332009-04-12 17:16:29 +00001027 ImplicitConversionSequence ICS;
Douglas Gregor68647482009-12-16 03:45:30 +00001028 return PerformImplicitConversion(From, ToType, Action, AllowExplicit,
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00001029 Elidable, ICS);
1030}
1031
1032bool
1033Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor68647482009-12-16 03:45:30 +00001034 AssignmentAction Action, bool AllowExplicit,
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00001035 bool Elidable,
1036 ImplicitConversionSequence& ICS) {
Sebastian Redle2b68332009-04-12 17:16:29 +00001037 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1038 if (Elidable && getLangOptions().CPlusPlus0x) {
Mike Stump1eb44332009-09-09 15:08:12 +00001039 ICS = TryImplicitConversion(From, ToType,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001040 /*SuppressUserConversions=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +00001041 AllowExplicit,
Anders Carlsson08972922009-08-28 15:33:32 +00001042 /*ForceRValue=*/true,
1043 /*InOverloadResolution=*/false);
Sebastian Redle2b68332009-04-12 17:16:29 +00001044 }
1045 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion) {
Mike Stump1eb44332009-09-09 15:08:12 +00001046 ICS = TryImplicitConversion(From, ToType,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001047 /*SuppressUserConversions=*/false,
1048 AllowExplicit,
Anders Carlsson08972922009-08-28 15:33:32 +00001049 /*ForceRValue=*/false,
1050 /*InOverloadResolution=*/false);
Sebastian Redle2b68332009-04-12 17:16:29 +00001051 }
Douglas Gregor68647482009-12-16 03:45:30 +00001052 return PerformImplicitConversion(From, ToType, ICS, Action);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001053}
1054
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001055/// BuildCXXDerivedToBaseExpr - This routine generates the suitable AST
1056/// for the derived to base conversion of the expression 'From'. All
1057/// necessary information is passed in ICS.
1058bool
1059Sema::BuildCXXDerivedToBaseExpr(Expr *&From, CastExpr::CastKind CastKind,
Douglas Gregor68647482009-12-16 03:45:30 +00001060 const ImplicitConversionSequence& ICS) {
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001061 QualType BaseType =
1062 QualType::getFromOpaquePtr(ICS.UserDefined.After.ToTypePtr);
1063 // Must do additional defined to base conversion.
1064 QualType DerivedType =
1065 QualType::getFromOpaquePtr(ICS.UserDefined.After.FromTypePtr);
1066
1067 From = new (Context) ImplicitCastExpr(
1068 DerivedType.getNonReferenceType(),
1069 CastKind,
1070 From,
1071 DerivedType->isLValueReferenceType());
1072 From = new (Context) ImplicitCastExpr(BaseType.getNonReferenceType(),
1073 CastExpr::CK_DerivedToBase, From,
1074 BaseType->isLValueReferenceType());
1075 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1076 OwningExprResult FromResult =
1077 BuildCXXConstructExpr(
1078 ICS.UserDefined.After.CopyConstructor->getLocation(),
1079 BaseType,
1080 ICS.UserDefined.After.CopyConstructor,
1081 MultiExprArg(*this, (void **)&From, 1));
1082 if (FromResult.isInvalid())
1083 return true;
1084 From = FromResult.takeAs<Expr>();
1085 return false;
1086}
1087
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001088/// PerformImplicitConversion - Perform an implicit conversion of the
1089/// expression From to the type ToType using the pre-computed implicit
1090/// conversion sequence ICS. Returns true if there was an error, false
1091/// otherwise. The expression From is replaced with the converted
Douglas Gregor68647482009-12-16 03:45:30 +00001092/// expression. Action is the kind of conversion we're performing,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001093/// used in the error message.
1094bool
1095Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
1096 const ImplicitConversionSequence &ICS,
Douglas Gregor68647482009-12-16 03:45:30 +00001097 AssignmentAction Action, bool IgnoreBaseAccess) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001098 switch (ICS.ConversionKind) {
1099 case ImplicitConversionSequence::StandardConversion:
Douglas Gregor68647482009-12-16 03:45:30 +00001100 if (PerformImplicitConversion(From, ToType, ICS.Standard, Action,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001101 IgnoreBaseAccess))
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001102 return true;
1103 break;
1104
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001105 case ImplicitConversionSequence::UserDefinedConversion: {
1106
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00001107 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
1108 CastExpr::CastKind CastKind = CastExpr::CK_Unknown;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001109 QualType BeforeToType;
1110 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00001111 CastKind = CastExpr::CK_UserDefinedConversion;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001112
1113 // If the user-defined conversion is specified by a conversion function,
1114 // the initial standard conversion sequence converts the source type to
1115 // the implicit object parameter of the conversion function.
1116 BeforeToType = Context.getTagDeclType(Conv->getParent());
1117 } else if (const CXXConstructorDecl *Ctor =
1118 dyn_cast<CXXConstructorDecl>(FD)) {
Anders Carlsson0aebc812009-09-09 21:33:21 +00001119 CastKind = CastExpr::CK_ConstructorConversion;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001120 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregore44201a2009-11-20 02:31:03 +00001121 if (!ICS.UserDefined.EllipsisConversion) {
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001122 // If the user-defined conversion is specified by a constructor, the
1123 // initial standard conversion sequence converts the source type to the
1124 // type required by the argument of the constructor
Douglas Gregore44201a2009-11-20 02:31:03 +00001125 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
1126 }
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001127 }
Anders Carlsson0aebc812009-09-09 21:33:21 +00001128 else
1129 assert(0 && "Unknown conversion function kind!");
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001130 // Whatch out for elipsis conversion.
Fariborz Jahanian4c0cea22009-11-06 00:55:14 +00001131 if (!ICS.UserDefined.EllipsisConversion) {
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001132 if (PerformImplicitConversion(From, BeforeToType,
Douglas Gregor68647482009-12-16 03:45:30 +00001133 ICS.UserDefined.Before, AA_Converting,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001134 IgnoreBaseAccess))
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001135 return true;
1136 }
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001137
Anders Carlsson0aebc812009-09-09 21:33:21 +00001138 OwningExprResult CastArg
1139 = BuildCXXCastArgument(From->getLocStart(),
1140 ToType.getNonReferenceType(),
1141 CastKind, cast<CXXMethodDecl>(FD),
1142 Owned(From));
1143
1144 if (CastArg.isInvalid())
1145 return true;
Eli Friedmand8889622009-11-27 04:41:50 +00001146
1147 From = CastArg.takeAs<Expr>();
1148
1149 // FIXME: This and the following if statement shouldn't be necessary, but
1150 // there's some nasty stuff involving MaybeBindToTemporary going on here.
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001151 if (ICS.UserDefined.After.Second == ICK_Derived_To_Base &&
1152 ICS.UserDefined.After.CopyConstructor) {
Douglas Gregor68647482009-12-16 03:45:30 +00001153 return BuildCXXDerivedToBaseExpr(From, CastKind, ICS);
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001154 }
Eli Friedmand8889622009-11-27 04:41:50 +00001155
1156 if (ICS.UserDefined.After.CopyConstructor) {
1157 From = new (Context) ImplicitCastExpr(ToType.getNonReferenceType(),
1158 CastKind, From,
1159 ToType->isLValueReferenceType());
1160 return false;
1161 }
1162
1163 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
Douglas Gregor68647482009-12-16 03:45:30 +00001164 AA_Converting, IgnoreBaseAccess);
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001165 }
1166
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001167 case ImplicitConversionSequence::EllipsisConversion:
1168 assert(false && "Cannot perform an ellipsis conversion");
Douglas Gregor60d62c22008-10-31 16:23:19 +00001169 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001170
1171 case ImplicitConversionSequence::BadConversion:
1172 return true;
1173 }
1174
1175 // Everything went well.
1176 return false;
1177}
1178
1179/// PerformImplicitConversion - Perform an implicit conversion of the
1180/// expression From to the type ToType by following the standard
1181/// conversion sequence SCS. Returns true if there was an error, false
1182/// otherwise. The expression From is replaced with the converted
Douglas Gregor45920e82008-12-19 17:40:08 +00001183/// expression. Flavor is the context in which we're performing this
1184/// conversion, for use in error messages.
Mike Stump1eb44332009-09-09 15:08:12 +00001185bool
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001186Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor45920e82008-12-19 17:40:08 +00001187 const StandardConversionSequence& SCS,
Douglas Gregor68647482009-12-16 03:45:30 +00001188 AssignmentAction Action, bool IgnoreBaseAccess) {
Mike Stump390b4cc2009-05-16 07:39:55 +00001189 // Overall FIXME: we are recomputing too many types here and doing far too
1190 // much extra work. What this means is that we need to keep track of more
1191 // information that is computed when we try the implicit conversion initially,
1192 // so that we don't need to recompute anything here.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001193 QualType FromType = From->getType();
1194
Douglas Gregor225c41e2008-11-03 19:09:14 +00001195 if (SCS.CopyConstructor) {
Anders Carlsson7c3e8a12009-05-19 04:45:15 +00001196 // FIXME: When can ToType be a reference type?
1197 assert(!ToType->isReferenceType());
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00001198 if (SCS.Second == ICK_Derived_To_Base) {
1199 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1200 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
1201 MultiExprArg(*this, (void **)&From, 1),
1202 /*FIXME:ConstructLoc*/SourceLocation(),
1203 ConstructorArgs))
1204 return true;
1205 OwningExprResult FromResult =
1206 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1207 ToType, SCS.CopyConstructor,
1208 move_arg(ConstructorArgs));
1209 if (FromResult.isInvalid())
1210 return true;
1211 From = FromResult.takeAs<Expr>();
1212 return false;
1213 }
Mike Stump1eb44332009-09-09 15:08:12 +00001214 OwningExprResult FromResult =
1215 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1216 ToType, SCS.CopyConstructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00001217 MultiExprArg(*this, (void**)&From, 1));
Mike Stump1eb44332009-09-09 15:08:12 +00001218
Anders Carlssonda3f4e22009-08-25 05:12:04 +00001219 if (FromResult.isInvalid())
1220 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001221
Anders Carlssonda3f4e22009-08-25 05:12:04 +00001222 From = FromResult.takeAs<Expr>();
Douglas Gregor225c41e2008-11-03 19:09:14 +00001223 return false;
1224 }
1225
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001226 // Perform the first implicit conversion.
1227 switch (SCS.First) {
1228 case ICK_Identity:
1229 case ICK_Lvalue_To_Rvalue:
1230 // Nothing to do.
1231 break;
1232
1233 case ICK_Array_To_Pointer:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001234 FromType = Context.getArrayDecayedType(FromType);
Anders Carlsson82495762009-08-08 21:04:35 +00001235 ImpCastExprToType(From, FromType, CastExpr::CK_ArrayToPointerDecay);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001236 break;
1237
1238 case ICK_Function_To_Pointer:
Douglas Gregor063daf62009-03-13 18:40:31 +00001239 if (Context.getCanonicalType(FromType) == Context.OverloadTy) {
Douglas Gregor904eed32008-11-10 20:40:00 +00001240 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, true);
1241 if (!Fn)
1242 return true;
1243
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001244 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
1245 return true;
1246
Anders Carlsson96ad5332009-10-21 17:16:23 +00001247 From = FixOverloadedFunctionReference(From, Fn);
Douglas Gregor904eed32008-11-10 20:40:00 +00001248 FromType = From->getType();
Anders Carlsson96ad5332009-10-21 17:16:23 +00001249
Sebastian Redl759986e2009-10-17 20:50:27 +00001250 // If there's already an address-of operator in the expression, we have
1251 // the right type already, and the code below would just introduce an
1252 // invalid additional pointer level.
Anders Carlsson96ad5332009-10-21 17:16:23 +00001253 if (FromType->isPointerType() || FromType->isMemberFunctionPointerType())
Sebastian Redl759986e2009-10-17 20:50:27 +00001254 break;
Douglas Gregor904eed32008-11-10 20:40:00 +00001255 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001256 FromType = Context.getPointerType(FromType);
Anders Carlssonb633c4e2009-09-01 20:37:18 +00001257 ImpCastExprToType(From, FromType, CastExpr::CK_FunctionToPointerDecay);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001258 break;
1259
1260 default:
1261 assert(false && "Improper first standard conversion");
1262 break;
1263 }
1264
1265 // Perform the second implicit conversion
1266 switch (SCS.Second) {
1267 case ICK_Identity:
Sebastian Redl2c7588f2009-10-10 12:04:10 +00001268 // If both sides are functions (or pointers/references to them), there could
1269 // be incompatible exception declarations.
1270 if (CheckExceptionSpecCompatibility(From, ToType))
1271 return true;
1272 // Nothing else to do.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001273 break;
1274
Douglas Gregor43c79c22009-12-09 00:47:37 +00001275 case ICK_NoReturn_Adjustment:
1276 // If both sides are functions (or pointers/references to them), there could
1277 // be incompatible exception declarations.
1278 if (CheckExceptionSpecCompatibility(From, ToType))
1279 return true;
1280
1281 ImpCastExprToType(From, Context.getNoReturnType(From->getType(), false),
1282 CastExpr::CK_NoOp);
1283 break;
1284
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001285 case ICK_Integral_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001286 case ICK_Integral_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001287 ImpCastExprToType(From, ToType, CastExpr::CK_IntegralCast);
1288 break;
1289
1290 case ICK_Floating_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001291 case ICK_Floating_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001292 ImpCastExprToType(From, ToType, CastExpr::CK_FloatingCast);
1293 break;
1294
1295 case ICK_Complex_Promotion:
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001296 case ICK_Complex_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001297 ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1298 break;
1299
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001300 case ICK_Floating_Integral:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001301 if (ToType->isFloatingType())
1302 ImpCastExprToType(From, ToType, CastExpr::CK_IntegralToFloating);
1303 else
1304 ImpCastExprToType(From, ToType, CastExpr::CK_FloatingToIntegral);
1305 break;
1306
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001307 case ICK_Complex_Real:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001308 ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1309 break;
1310
Douglas Gregorf9201e02009-02-11 23:02:49 +00001311 case ICK_Compatible_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001312 ImpCastExprToType(From, ToType, CastExpr::CK_NoOp);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001313 break;
1314
Anders Carlsson61faec12009-09-12 04:46:44 +00001315 case ICK_Pointer_Conversion: {
Douglas Gregor45920e82008-12-19 17:40:08 +00001316 if (SCS.IncompatibleObjC) {
1317 // Diagnose incompatible Objective-C conversions
Mike Stump1eb44332009-09-09 15:08:12 +00001318 Diag(From->getSourceRange().getBegin(),
Douglas Gregor45920e82008-12-19 17:40:08 +00001319 diag::ext_typecheck_convert_incompatible_pointer)
Douglas Gregor68647482009-12-16 03:45:30 +00001320 << From->getType() << ToType << Action
Douglas Gregor45920e82008-12-19 17:40:08 +00001321 << From->getSourceRange();
1322 }
1323
Anders Carlsson61faec12009-09-12 04:46:44 +00001324
1325 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001326 if (CheckPointerConversion(From, ToType, Kind, IgnoreBaseAccess))
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001327 return true;
Anders Carlsson61faec12009-09-12 04:46:44 +00001328 ImpCastExprToType(From, ToType, Kind);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001329 break;
Anders Carlsson61faec12009-09-12 04:46:44 +00001330 }
1331
1332 case ICK_Pointer_Member: {
1333 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001334 if (CheckMemberPointerConversion(From, ToType, Kind, IgnoreBaseAccess))
Anders Carlsson61faec12009-09-12 04:46:44 +00001335 return true;
Sebastian Redl2c7588f2009-10-10 12:04:10 +00001336 if (CheckExceptionSpecCompatibility(From, ToType))
1337 return true;
Anders Carlsson61faec12009-09-12 04:46:44 +00001338 ImpCastExprToType(From, ToType, Kind);
1339 break;
1340 }
Anders Carlssonbc0e0782009-11-23 20:04:44 +00001341 case ICK_Boolean_Conversion: {
1342 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
1343 if (FromType->isMemberPointerType())
1344 Kind = CastExpr::CK_MemberPointerToBoolean;
1345
1346 ImpCastExprToType(From, Context.BoolTy, Kind);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001347 break;
Anders Carlssonbc0e0782009-11-23 20:04:44 +00001348 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001349
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001350 case ICK_Derived_To_Base:
1351 if (CheckDerivedToBaseConversion(From->getType(),
1352 ToType.getNonReferenceType(),
1353 From->getLocStart(),
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001354 From->getSourceRange(),
1355 IgnoreBaseAccess))
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001356 return true;
1357 ImpCastExprToType(From, ToType.getNonReferenceType(),
1358 CastExpr::CK_DerivedToBase);
1359 break;
1360
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001361 default:
1362 assert(false && "Improper second standard conversion");
1363 break;
1364 }
1365
1366 switch (SCS.Third) {
1367 case ICK_Identity:
1368 // Nothing to do.
1369 break;
1370
1371 case ICK_Qualification:
Mike Stump390b4cc2009-05-16 07:39:55 +00001372 // FIXME: Not sure about lvalue vs rvalue here in the presence of rvalue
1373 // references.
Mike Stump1eb44332009-09-09 15:08:12 +00001374 ImpCastExprToType(From, ToType.getNonReferenceType(),
Eli Friedman73c39ab2009-10-20 08:27:19 +00001375 CastExpr::CK_NoOp,
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001376 ToType->isLValueReferenceType());
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001377 break;
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001378
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001379 default:
1380 assert(false && "Improper second standard conversion");
1381 break;
1382 }
1383
1384 return false;
1385}
1386
Sebastian Redl64b45f72009-01-05 20:52:13 +00001387Sema::OwningExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
1388 SourceLocation KWLoc,
1389 SourceLocation LParen,
1390 TypeTy *Ty,
1391 SourceLocation RParen) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00001392 QualType T = GetTypeFromParser(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00001393
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001394 // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
1395 // all traits except __is_class, __is_enum and __is_union require a the type
1396 // to be complete.
1397 if (OTT != UTT_IsClass && OTT != UTT_IsEnum && OTT != UTT_IsUnion) {
Mike Stump1eb44332009-09-09 15:08:12 +00001398 if (RequireCompleteType(KWLoc, T,
Anders Carlssond497ba72009-08-26 22:59:12 +00001399 diag::err_incomplete_type_used_in_type_trait_expr))
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001400 return ExprError();
1401 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00001402
1403 // There is no point in eagerly computing the value. The traits are designed
1404 // to be used from type trait templates, so Ty will be a template parameter
1405 // 99% of the time.
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001406 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT, T,
1407 RParen, Context.BoolTy));
Sebastian Redl64b45f72009-01-05 20:52:13 +00001408}
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001409
1410QualType Sema::CheckPointerToMemberOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00001411 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001412 const char *OpSpelling = isIndirect ? "->*" : ".*";
1413 // C++ 5.5p2
1414 // The binary operator .* [p3: ->*] binds its second operand, which shall
1415 // be of type "pointer to member of T" (where T is a completely-defined
1416 // class type) [...]
1417 QualType RType = rex->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001418 const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
Douglas Gregore7450f52009-03-24 19:52:54 +00001419 if (!MemPtr) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001420 Diag(Loc, diag::err_bad_memptr_rhs)
1421 << OpSpelling << RType << rex->getSourceRange();
1422 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00001423 }
Douglas Gregore7450f52009-03-24 19:52:54 +00001424
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001425 QualType Class(MemPtr->getClass(), 0);
1426
1427 // C++ 5.5p2
1428 // [...] to its first operand, which shall be of class T or of a class of
1429 // which T is an unambiguous and accessible base class. [p3: a pointer to
1430 // such a class]
1431 QualType LType = lex->getType();
1432 if (isIndirect) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001433 if (const PointerType *Ptr = LType->getAs<PointerType>())
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001434 LType = Ptr->getPointeeType().getNonReferenceType();
1435 else {
1436 Diag(Loc, diag::err_bad_memptr_lhs)
Fariborz Jahanianef78ac62009-10-26 20:45:27 +00001437 << OpSpelling << 1 << LType
1438 << CodeModificationHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001439 return QualType();
1440 }
1441 }
1442
Douglas Gregora4923eb2009-11-16 21:35:15 +00001443 if (!Context.hasSameUnqualifiedType(Class, LType)) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001444 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1445 /*DetectVirtual=*/false);
Mike Stump390b4cc2009-05-16 07:39:55 +00001446 // FIXME: Would it be useful to print full ambiguity paths, or is that
1447 // overkill?
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001448 if (!IsDerivedFrom(LType, Class, Paths) ||
1449 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
Fariborz Jahanianef78ac62009-10-26 20:45:27 +00001450 const char *ReplaceStr = isIndirect ? ".*" : "->*";
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001451 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Fariborz Jahanianef78ac62009-10-26 20:45:27 +00001452 << (int)isIndirect << lex->getType() <<
1453 CodeModificationHint::CreateReplacement(SourceRange(Loc), ReplaceStr);
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001454 return QualType();
1455 }
1456 }
1457
Fariborz Jahanian19d70732009-11-18 22:16:17 +00001458 if (isa<CXXZeroInitValueExpr>(rex->IgnoreParens())) {
Fariborz Jahanian05ebda92009-11-18 21:54:48 +00001459 // Diagnose use of pointer-to-member type which when used as
1460 // the functional cast in a pointer-to-member expression.
1461 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
1462 return QualType();
1463 }
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001464 // C++ 5.5p2
1465 // The result is an object or a function of the type specified by the
1466 // second operand.
1467 // The cv qualifiers are the union of those in the pointer and the left side,
1468 // in accordance with 5.5p5 and 5.2.5.
1469 // FIXME: This returns a dereferenced member function pointer as a normal
1470 // function type. However, the only operation valid on such functions is
Mike Stump390b4cc2009-05-16 07:39:55 +00001471 // calling them. There's also a GCC extension to get a function pointer to the
1472 // thing, which is another complication, because this type - unlike the type
1473 // that is the result of this expression - takes the class as the first
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001474 // argument.
1475 // We probably need a "MemberFunctionClosureType" or something like that.
1476 QualType Result = MemPtr->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00001477 Result = Context.getCVRQualifiedType(Result, LType.getCVRQualifiers());
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001478 return Result;
1479}
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001480
1481/// \brief Get the target type of a standard or user-defined conversion.
1482static QualType TargetType(const ImplicitConversionSequence &ICS) {
1483 assert((ICS.ConversionKind ==
1484 ImplicitConversionSequence::StandardConversion ||
1485 ICS.ConversionKind ==
1486 ImplicitConversionSequence::UserDefinedConversion) &&
1487 "function only valid for standard or user-defined conversions");
1488 if (ICS.ConversionKind == ImplicitConversionSequence::StandardConversion)
1489 return QualType::getFromOpaquePtr(ICS.Standard.ToTypePtr);
1490 return QualType::getFromOpaquePtr(ICS.UserDefined.After.ToTypePtr);
1491}
1492
1493/// \brief Try to convert a type to another according to C++0x 5.16p3.
1494///
1495/// This is part of the parameter validation for the ? operator. If either
1496/// value operand is a class type, the two operands are attempted to be
1497/// converted to each other. This function does the conversion in one direction.
1498/// It emits a diagnostic and returns true only if it finds an ambiguous
1499/// conversion.
1500static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
1501 SourceLocation QuestionLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00001502 ImplicitConversionSequence &ICS) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001503 // C++0x 5.16p3
1504 // The process for determining whether an operand expression E1 of type T1
1505 // can be converted to match an operand expression E2 of type T2 is defined
1506 // as follows:
1507 // -- If E2 is an lvalue:
1508 if (To->isLvalue(Self.Context) == Expr::LV_Valid) {
1509 // E1 can be converted to match E2 if E1 can be implicitly converted to
1510 // type "lvalue reference to T2", subject to the constraint that in the
1511 // conversion the reference must bind directly to E1.
1512 if (!Self.CheckReferenceInit(From,
1513 Self.Context.getLValueReferenceType(To->getType()),
Douglas Gregor739d8282009-09-23 23:04:10 +00001514 To->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001515 /*SuppressUserConversions=*/false,
1516 /*AllowExplicit=*/false,
1517 /*ForceRValue=*/false,
1518 &ICS))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001519 {
1520 assert((ICS.ConversionKind ==
1521 ImplicitConversionSequence::StandardConversion ||
1522 ICS.ConversionKind ==
1523 ImplicitConversionSequence::UserDefinedConversion) &&
1524 "expected a definite conversion");
1525 bool DirectBinding =
1526 ICS.ConversionKind == ImplicitConversionSequence::StandardConversion ?
1527 ICS.Standard.DirectBinding : ICS.UserDefined.After.DirectBinding;
1528 if (DirectBinding)
1529 return false;
1530 }
1531 }
1532 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1533 // -- If E2 is an rvalue, or if the conversion above cannot be done:
1534 // -- if E1 and E2 have class type, and the underlying class types are
1535 // the same or one is a base class of the other:
1536 QualType FTy = From->getType();
1537 QualType TTy = To->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001538 const RecordType *FRec = FTy->getAs<RecordType>();
1539 const RecordType *TRec = TTy->getAs<RecordType>();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001540 bool FDerivedFromT = FRec && TRec && Self.IsDerivedFrom(FTy, TTy);
1541 if (FRec && TRec && (FRec == TRec ||
1542 FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
1543 // E1 can be converted to match E2 if the class of T2 is the
1544 // same type as, or a base class of, the class of T1, and
1545 // [cv2 > cv1].
1546 if ((FRec == TRec || FDerivedFromT) && TTy.isAtLeastAsQualifiedAs(FTy)) {
1547 // Could still fail if there's no copy constructor.
1548 // FIXME: Is this a hard error then, or just a conversion failure? The
1549 // standard doesn't say.
Mike Stump1eb44332009-09-09 15:08:12 +00001550 ICS = Self.TryCopyInitialization(From, TTy,
Anders Carlssond28b4282009-08-27 17:18:13 +00001551 /*SuppressUserConversions=*/false,
Anders Carlsson7b361b52009-08-27 17:37:39 +00001552 /*ForceRValue=*/false,
1553 /*InOverloadResolution=*/false);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001554 }
1555 } else {
1556 // -- Otherwise: E1 can be converted to match E2 if E1 can be
1557 // implicitly converted to the type that expression E2 would have
1558 // if E2 were converted to an rvalue.
1559 // First find the decayed type.
1560 if (TTy->isFunctionType())
1561 TTy = Self.Context.getPointerType(TTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001562 else if (TTy->isArrayType())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001563 TTy = Self.Context.getArrayDecayedType(TTy);
1564
1565 // Now try the implicit conversion.
1566 // FIXME: This doesn't detect ambiguities.
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001567 ICS = Self.TryImplicitConversion(From, TTy,
1568 /*SuppressUserConversions=*/false,
1569 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00001570 /*ForceRValue=*/false,
1571 /*InOverloadResolution=*/false);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001572 }
1573 return false;
1574}
1575
1576/// \brief Try to find a common type for two according to C++0x 5.16p5.
1577///
1578/// This is part of the parameter validation for the ? operator. If either
1579/// value operand is a class type, overload resolution is used to find a
1580/// conversion to a common type.
1581static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
1582 SourceLocation Loc) {
1583 Expr *Args[2] = { LHS, RHS };
1584 OverloadCandidateSet CandidateSet;
Douglas Gregor573d9c32009-10-21 23:19:44 +00001585 Self.AddBuiltinOperatorCandidates(OO_Conditional, Loc, Args, 2, CandidateSet);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001586
1587 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00001588 switch (Self.BestViableFunction(CandidateSet, Loc, Best)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00001589 case OR_Success:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001590 // We found a match. Perform the conversions on the arguments and move on.
1591 if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00001592 Best->Conversions[0], Sema::AA_Converting) ||
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001593 Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor68647482009-12-16 03:45:30 +00001594 Best->Conversions[1], Sema::AA_Converting))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001595 break;
1596 return false;
1597
Douglas Gregor20093b42009-12-09 23:02:17 +00001598 case OR_No_Viable_Function:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001599 Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
1600 << LHS->getType() << RHS->getType()
1601 << LHS->getSourceRange() << RHS->getSourceRange();
1602 return true;
1603
Douglas Gregor20093b42009-12-09 23:02:17 +00001604 case OR_Ambiguous:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001605 Self.Diag(Loc, diag::err_conditional_ambiguous_ovl)
1606 << LHS->getType() << RHS->getType()
1607 << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stump390b4cc2009-05-16 07:39:55 +00001608 // FIXME: Print the possible common types by printing the return types of
1609 // the viable candidates.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001610 break;
1611
Douglas Gregor20093b42009-12-09 23:02:17 +00001612 case OR_Deleted:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001613 assert(false && "Conditional operator has only built-in overloads");
1614 break;
1615 }
1616 return true;
1617}
1618
Sebastian Redl76458502009-04-17 16:30:52 +00001619/// \brief Perform an "extended" implicit conversion as returned by
1620/// TryClassUnification.
1621///
1622/// TryClassUnification generates ICSs that include reference bindings.
1623/// PerformImplicitConversion is not suitable for this; it chokes if the
1624/// second part of a standard conversion is ICK_DerivedToBase. This function
1625/// handles the reference binding specially.
1626static bool ConvertForConditional(Sema &Self, Expr *&E,
Mike Stump1eb44332009-09-09 15:08:12 +00001627 const ImplicitConversionSequence &ICS) {
Sebastian Redl76458502009-04-17 16:30:52 +00001628 if (ICS.ConversionKind == ImplicitConversionSequence::StandardConversion &&
1629 ICS.Standard.ReferenceBinding) {
1630 assert(ICS.Standard.DirectBinding &&
1631 "TryClassUnification should never generate indirect ref bindings");
Sebastian Redla5cd2cd2009-04-26 11:21:02 +00001632 // FIXME: CheckReferenceInit should be able to reuse the ICS instead of
1633 // redoing all the work.
1634 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001635 TargetType(ICS)),
Douglas Gregor739d8282009-09-23 23:04:10 +00001636 /*FIXME:*/E->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001637 /*SuppressUserConversions=*/false,
1638 /*AllowExplicit=*/false,
1639 /*ForceRValue=*/false);
Sebastian Redl76458502009-04-17 16:30:52 +00001640 }
1641 if (ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion &&
1642 ICS.UserDefined.After.ReferenceBinding) {
1643 assert(ICS.UserDefined.After.DirectBinding &&
1644 "TryClassUnification should never generate indirect ref bindings");
Sebastian Redla5cd2cd2009-04-26 11:21:02 +00001645 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001646 TargetType(ICS)),
Douglas Gregor739d8282009-09-23 23:04:10 +00001647 /*FIXME:*/E->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001648 /*SuppressUserConversions=*/false,
1649 /*AllowExplicit=*/false,
1650 /*ForceRValue=*/false);
Sebastian Redl76458502009-04-17 16:30:52 +00001651 }
Douglas Gregor68647482009-12-16 03:45:30 +00001652 if (Self.PerformImplicitConversion(E, TargetType(ICS), ICS, Sema::AA_Converting))
Sebastian Redl76458502009-04-17 16:30:52 +00001653 return true;
1654 return false;
1655}
1656
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001657/// \brief Check the operands of ?: under C++ semantics.
1658///
1659/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
1660/// extension. In this case, LHS == Cond. (But they're not aliases.)
1661QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
1662 SourceLocation QuestionLoc) {
Mike Stump390b4cc2009-05-16 07:39:55 +00001663 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
1664 // interface pointers.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001665
1666 // C++0x 5.16p1
1667 // The first expression is contextually converted to bool.
1668 if (!Cond->isTypeDependent()) {
1669 if (CheckCXXBooleanCondition(Cond))
1670 return QualType();
1671 }
1672
1673 // Either of the arguments dependent?
1674 if (LHS->isTypeDependent() || RHS->isTypeDependent())
1675 return Context.DependentTy;
1676
John McCallb13c87f2009-11-05 09:23:39 +00001677 CheckSignCompare(LHS, RHS, QuestionLoc, diag::warn_mixed_sign_conditional);
1678
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001679 // C++0x 5.16p2
1680 // If either the second or the third operand has type (cv) void, ...
1681 QualType LTy = LHS->getType();
1682 QualType RTy = RHS->getType();
1683 bool LVoid = LTy->isVoidType();
1684 bool RVoid = RTy->isVoidType();
1685 if (LVoid || RVoid) {
1686 // ... then the [l2r] conversions are performed on the second and third
1687 // operands ...
1688 DefaultFunctionArrayConversion(LHS);
1689 DefaultFunctionArrayConversion(RHS);
1690 LTy = LHS->getType();
1691 RTy = RHS->getType();
1692
1693 // ... and one of the following shall hold:
1694 // -- The second or the third operand (but not both) is a throw-
1695 // expression; the result is of the type of the other and is an rvalue.
1696 bool LThrow = isa<CXXThrowExpr>(LHS);
1697 bool RThrow = isa<CXXThrowExpr>(RHS);
1698 if (LThrow && !RThrow)
1699 return RTy;
1700 if (RThrow && !LThrow)
1701 return LTy;
1702
1703 // -- Both the second and third operands have type void; the result is of
1704 // type void and is an rvalue.
1705 if (LVoid && RVoid)
1706 return Context.VoidTy;
1707
1708 // Neither holds, error.
1709 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
1710 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
1711 << LHS->getSourceRange() << RHS->getSourceRange();
1712 return QualType();
1713 }
1714
1715 // Neither is void.
1716
1717 // C++0x 5.16p3
1718 // Otherwise, if the second and third operand have different types, and
1719 // either has (cv) class type, and attempt is made to convert each of those
1720 // operands to the other.
1721 if (Context.getCanonicalType(LTy) != Context.getCanonicalType(RTy) &&
1722 (LTy->isRecordType() || RTy->isRecordType())) {
1723 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
1724 // These return true if a single direction is already ambiguous.
1725 if (TryClassUnification(*this, LHS, RHS, QuestionLoc, ICSLeftToRight))
1726 return QualType();
1727 if (TryClassUnification(*this, RHS, LHS, QuestionLoc, ICSRightToLeft))
1728 return QualType();
1729
1730 bool HaveL2R = ICSLeftToRight.ConversionKind !=
1731 ImplicitConversionSequence::BadConversion;
1732 bool HaveR2L = ICSRightToLeft.ConversionKind !=
1733 ImplicitConversionSequence::BadConversion;
1734 // If both can be converted, [...] the program is ill-formed.
1735 if (HaveL2R && HaveR2L) {
1736 Diag(QuestionLoc, diag::err_conditional_ambiguous)
1737 << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
1738 return QualType();
1739 }
1740
1741 // If exactly one conversion is possible, that conversion is applied to
1742 // the chosen operand and the converted operands are used in place of the
1743 // original operands for the remainder of this section.
1744 if (HaveL2R) {
Sebastian Redl76458502009-04-17 16:30:52 +00001745 if (ConvertForConditional(*this, LHS, ICSLeftToRight))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001746 return QualType();
1747 LTy = LHS->getType();
1748 } else if (HaveR2L) {
Sebastian Redl76458502009-04-17 16:30:52 +00001749 if (ConvertForConditional(*this, RHS, ICSRightToLeft))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001750 return QualType();
1751 RTy = RHS->getType();
1752 }
1753 }
1754
1755 // C++0x 5.16p4
1756 // If the second and third operands are lvalues and have the same type,
1757 // the result is of that type [...]
1758 bool Same = Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy);
1759 if (Same && LHS->isLvalue(Context) == Expr::LV_Valid &&
1760 RHS->isLvalue(Context) == Expr::LV_Valid)
1761 return LTy;
1762
1763 // C++0x 5.16p5
1764 // Otherwise, the result is an rvalue. If the second and third operands
1765 // do not have the same type, and either has (cv) class type, ...
1766 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
1767 // ... overload resolution is used to determine the conversions (if any)
1768 // to be applied to the operands. If the overload resolution fails, the
1769 // program is ill-formed.
1770 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
1771 return QualType();
1772 }
1773
1774 // C++0x 5.16p6
1775 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
1776 // conversions are performed on the second and third operands.
1777 DefaultFunctionArrayConversion(LHS);
1778 DefaultFunctionArrayConversion(RHS);
1779 LTy = LHS->getType();
1780 RTy = RHS->getType();
1781
1782 // After those conversions, one of the following shall hold:
1783 // -- The second and third operands have the same type; the result
1784 // is of that type.
1785 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy))
1786 return LTy;
1787
1788 // -- The second and third operands have arithmetic or enumeration type;
1789 // the usual arithmetic conversions are performed to bring them to a
1790 // common type, and the result is of that type.
1791 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
1792 UsualArithmeticConversions(LHS, RHS);
1793 return LHS->getType();
1794 }
1795
1796 // -- The second and third operands have pointer type, or one has pointer
1797 // type and the other is a null pointer constant; pointer conversions
1798 // and qualification conversions are performed to bring them to their
1799 // composite pointer type. The result is of the composite pointer type.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001800 QualType Composite = FindCompositePointerType(LHS, RHS);
1801 if (!Composite.isNull())
1802 return Composite;
Fariborz Jahanian55016362009-12-10 20:46:08 +00001803
1804 // Similarly, attempt to find composite type of twp objective-c pointers.
1805 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
1806 if (!Composite.isNull())
1807 return Composite;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001808
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001809 // Fourth bullet is same for pointers-to-member. However, the possible
1810 // conversions are far more limited: we have null-to-pointer, upcast of
1811 // containing class, and second-level cv-ness.
1812 // cv-ness is not a union, but must match one of the two operands. (Which,
1813 // frankly, is stupid.)
Ted Kremenek6217b802009-07-29 21:53:49 +00001814 const MemberPointerType *LMemPtr = LTy->getAs<MemberPointerType>();
1815 const MemberPointerType *RMemPtr = RTy->getAs<MemberPointerType>();
Douglas Gregorce940492009-09-25 04:25:58 +00001816 if (LMemPtr &&
1817 RHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00001818 ImpCastExprToType(RHS, LTy, CastExpr::CK_NullToMemberPointer);
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001819 return LTy;
1820 }
Douglas Gregorce940492009-09-25 04:25:58 +00001821 if (RMemPtr &&
1822 LHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00001823 ImpCastExprToType(LHS, RTy, CastExpr::CK_NullToMemberPointer);
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001824 return RTy;
1825 }
1826 if (LMemPtr && RMemPtr) {
1827 QualType LPointee = LMemPtr->getPointeeType();
1828 QualType RPointee = RMemPtr->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00001829
1830 QualifierCollector LPQuals, RPQuals;
1831 const Type *LPCan = LPQuals.strip(Context.getCanonicalType(LPointee));
1832 const Type *RPCan = RPQuals.strip(Context.getCanonicalType(RPointee));
1833
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001834 // First, we check that the unqualified pointee type is the same. If it's
1835 // not, there's no conversion that will unify the two pointers.
John McCall0953e762009-09-24 19:53:00 +00001836 if (LPCan == RPCan) {
1837
1838 // Second, we take the greater of the two qualifications. If neither
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001839 // is greater than the other, the conversion is not possible.
John McCall0953e762009-09-24 19:53:00 +00001840
1841 Qualifiers MergedQuals = LPQuals + RPQuals;
1842
1843 bool CompatibleQuals = true;
1844 if (MergedQuals.getCVRQualifiers() != LPQuals.getCVRQualifiers() &&
1845 MergedQuals.getCVRQualifiers() != RPQuals.getCVRQualifiers())
1846 CompatibleQuals = false;
1847 else if (LPQuals.getAddressSpace() != RPQuals.getAddressSpace())
1848 // FIXME:
1849 // C99 6.5.15 as modified by TR 18037:
1850 // If the second and third operands are pointers into different
1851 // address spaces, the address spaces must overlap.
1852 CompatibleQuals = false;
1853 // FIXME: GC qualifiers?
1854
1855 if (CompatibleQuals) {
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001856 // Third, we check if either of the container classes is derived from
1857 // the other.
1858 QualType LContainer(LMemPtr->getClass(), 0);
1859 QualType RContainer(RMemPtr->getClass(), 0);
1860 QualType MoreDerived;
1861 if (Context.getCanonicalType(LContainer) ==
1862 Context.getCanonicalType(RContainer))
1863 MoreDerived = LContainer;
1864 else if (IsDerivedFrom(LContainer, RContainer))
1865 MoreDerived = LContainer;
1866 else if (IsDerivedFrom(RContainer, LContainer))
1867 MoreDerived = RContainer;
1868
1869 if (!MoreDerived.isNull()) {
1870 // The type 'Q Pointee (MoreDerived::*)' is the common type.
1871 // We don't use ImpCastExprToType here because this could still fail
1872 // for ambiguous or inaccessible conversions.
John McCall0953e762009-09-24 19:53:00 +00001873 LPointee = Context.getQualifiedType(LPointee, MergedQuals);
1874 QualType Common
1875 = Context.getMemberPointerType(LPointee, MoreDerived.getTypePtr());
Douglas Gregor68647482009-12-16 03:45:30 +00001876 if (PerformImplicitConversion(LHS, Common, Sema::AA_Converting))
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001877 return QualType();
Douglas Gregor68647482009-12-16 03:45:30 +00001878 if (PerformImplicitConversion(RHS, Common, Sema::AA_Converting))
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001879 return QualType();
1880 return Common;
1881 }
1882 }
1883 }
1884 }
1885
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001886 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
1887 << LHS->getType() << RHS->getType()
1888 << LHS->getSourceRange() << RHS->getSourceRange();
1889 return QualType();
1890}
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001891
1892/// \brief Find a merged pointer type and convert the two expressions to it.
1893///
Douglas Gregor20b3e992009-08-24 17:42:35 +00001894/// This finds the composite pointer type (or member pointer type) for @p E1
1895/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
1896/// type and returns it.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001897/// It does not emit diagnostics.
1898QualType Sema::FindCompositePointerType(Expr *&E1, Expr *&E2) {
1899 assert(getLangOptions().CPlusPlus && "This function assumes C++");
1900 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001901
Fariborz Jahanian0cedfbd2009-12-08 20:04:24 +00001902 if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
1903 !T2->isAnyPointerType() && !T2->isMemberPointerType())
Douglas Gregor20b3e992009-08-24 17:42:35 +00001904 return QualType();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001905
1906 // C++0x 5.9p2
1907 // Pointer conversions and qualification conversions are performed on
1908 // pointer operands to bring them to their composite pointer type. If
1909 // one operand is a null pointer constant, the composite pointer type is
1910 // the type of the other operand.
Douglas Gregorce940492009-09-25 04:25:58 +00001911 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00001912 if (T2->isMemberPointerType())
1913 ImpCastExprToType(E1, T2, CastExpr::CK_NullToMemberPointer);
1914 else
1915 ImpCastExprToType(E1, T2, CastExpr::CK_IntegralToPointer);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001916 return T2;
1917 }
Douglas Gregorce940492009-09-25 04:25:58 +00001918 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00001919 if (T1->isMemberPointerType())
1920 ImpCastExprToType(E2, T1, CastExpr::CK_NullToMemberPointer);
1921 else
1922 ImpCastExprToType(E2, T1, CastExpr::CK_IntegralToPointer);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001923 return T1;
1924 }
Mike Stump1eb44332009-09-09 15:08:12 +00001925
Douglas Gregor20b3e992009-08-24 17:42:35 +00001926 // Now both have to be pointers or member pointers.
Sebastian Redla439e6f2009-11-16 21:03:45 +00001927 if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
1928 (!T2->isPointerType() && !T2->isMemberPointerType()))
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001929 return QualType();
1930
1931 // Otherwise, of one of the operands has type "pointer to cv1 void," then
1932 // the other has type "pointer to cv2 T" and the composite pointer type is
1933 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
1934 // Otherwise, the composite pointer type is a pointer type similar to the
1935 // type of one of the operands, with a cv-qualification signature that is
1936 // the union of the cv-qualification signatures of the operand types.
1937 // In practice, the first part here is redundant; it's subsumed by the second.
1938 // What we do here is, we build the two possible composite types, and try the
1939 // conversions in both directions. If only one works, or if the two composite
1940 // types are the same, we have succeeded.
John McCall0953e762009-09-24 19:53:00 +00001941 // FIXME: extended qualifiers?
Sebastian Redla439e6f2009-11-16 21:03:45 +00001942 typedef llvm::SmallVector<unsigned, 4> QualifierVector;
1943 QualifierVector QualifierUnion;
1944 typedef llvm::SmallVector<std::pair<const Type *, const Type *>, 4>
1945 ContainingClassVector;
1946 ContainingClassVector MemberOfClass;
1947 QualType Composite1 = Context.getCanonicalType(T1),
1948 Composite2 = Context.getCanonicalType(T2);
Douglas Gregor20b3e992009-08-24 17:42:35 +00001949 do {
1950 const PointerType *Ptr1, *Ptr2;
1951 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
1952 (Ptr2 = Composite2->getAs<PointerType>())) {
1953 Composite1 = Ptr1->getPointeeType();
1954 Composite2 = Ptr2->getPointeeType();
1955 QualifierUnion.push_back(
1956 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
1957 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
1958 continue;
1959 }
Mike Stump1eb44332009-09-09 15:08:12 +00001960
Douglas Gregor20b3e992009-08-24 17:42:35 +00001961 const MemberPointerType *MemPtr1, *MemPtr2;
1962 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
1963 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
1964 Composite1 = MemPtr1->getPointeeType();
1965 Composite2 = MemPtr2->getPointeeType();
1966 QualifierUnion.push_back(
1967 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
1968 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
1969 MemPtr2->getClass()));
1970 continue;
1971 }
Mike Stump1eb44332009-09-09 15:08:12 +00001972
Douglas Gregor20b3e992009-08-24 17:42:35 +00001973 // FIXME: block pointer types?
Mike Stump1eb44332009-09-09 15:08:12 +00001974
Douglas Gregor20b3e992009-08-24 17:42:35 +00001975 // Cannot unwrap any more types.
1976 break;
1977 } while (true);
Mike Stump1eb44332009-09-09 15:08:12 +00001978
Douglas Gregor20b3e992009-08-24 17:42:35 +00001979 // Rewrap the composites as pointers or member pointers with the union CVRs.
Sebastian Redla439e6f2009-11-16 21:03:45 +00001980 ContainingClassVector::reverse_iterator MOC
1981 = MemberOfClass.rbegin();
1982 for (QualifierVector::reverse_iterator
1983 I = QualifierUnion.rbegin(),
1984 E = QualifierUnion.rend();
Douglas Gregor20b3e992009-08-24 17:42:35 +00001985 I != E; (void)++I, ++MOC) {
John McCall0953e762009-09-24 19:53:00 +00001986 Qualifiers Quals = Qualifiers::fromCVRMask(*I);
Douglas Gregor20b3e992009-08-24 17:42:35 +00001987 if (MOC->first && MOC->second) {
1988 // Rebuild member pointer type
John McCall0953e762009-09-24 19:53:00 +00001989 Composite1 = Context.getMemberPointerType(
1990 Context.getQualifiedType(Composite1, Quals),
1991 MOC->first);
1992 Composite2 = Context.getMemberPointerType(
1993 Context.getQualifiedType(Composite2, Quals),
1994 MOC->second);
Douglas Gregor20b3e992009-08-24 17:42:35 +00001995 } else {
1996 // Rebuild pointer type
John McCall0953e762009-09-24 19:53:00 +00001997 Composite1
1998 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
1999 Composite2
2000 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregor20b3e992009-08-24 17:42:35 +00002001 }
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002002 }
2003
Mike Stump1eb44332009-09-09 15:08:12 +00002004 ImplicitConversionSequence E1ToC1 =
Anders Carlssonda7a18b2009-08-27 17:24:15 +00002005 TryImplicitConversion(E1, Composite1,
2006 /*SuppressUserConversions=*/false,
2007 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00002008 /*ForceRValue=*/false,
2009 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00002010 ImplicitConversionSequence E2ToC1 =
Anders Carlssonda7a18b2009-08-27 17:24:15 +00002011 TryImplicitConversion(E2, Composite1,
2012 /*SuppressUserConversions=*/false,
2013 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00002014 /*ForceRValue=*/false,
2015 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00002016
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002017 ImplicitConversionSequence E1ToC2, E2ToC2;
2018 E1ToC2.ConversionKind = ImplicitConversionSequence::BadConversion;
2019 E2ToC2.ConversionKind = ImplicitConversionSequence::BadConversion;
2020 if (Context.getCanonicalType(Composite1) !=
2021 Context.getCanonicalType(Composite2)) {
Anders Carlssonda7a18b2009-08-27 17:24:15 +00002022 E1ToC2 = TryImplicitConversion(E1, Composite2,
2023 /*SuppressUserConversions=*/false,
2024 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00002025 /*ForceRValue=*/false,
2026 /*InOverloadResolution=*/false);
Anders Carlssonda7a18b2009-08-27 17:24:15 +00002027 E2ToC2 = TryImplicitConversion(E2, Composite2,
2028 /*SuppressUserConversions=*/false,
2029 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00002030 /*ForceRValue=*/false,
2031 /*InOverloadResolution=*/false);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002032 }
2033
2034 bool ToC1Viable = E1ToC1.ConversionKind !=
2035 ImplicitConversionSequence::BadConversion
2036 && E2ToC1.ConversionKind !=
2037 ImplicitConversionSequence::BadConversion;
2038 bool ToC2Viable = E1ToC2.ConversionKind !=
2039 ImplicitConversionSequence::BadConversion
2040 && E2ToC2.ConversionKind !=
2041 ImplicitConversionSequence::BadConversion;
2042 if (ToC1Viable && !ToC2Viable) {
Douglas Gregor68647482009-12-16 03:45:30 +00002043 if (!PerformImplicitConversion(E1, Composite1, E1ToC1, Sema::AA_Converting) &&
2044 !PerformImplicitConversion(E2, Composite1, E2ToC1, Sema::AA_Converting))
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002045 return Composite1;
2046 }
2047 if (ToC2Viable && !ToC1Viable) {
Douglas Gregor68647482009-12-16 03:45:30 +00002048 if (!PerformImplicitConversion(E1, Composite2, E1ToC2, Sema::AA_Converting) &&
2049 !PerformImplicitConversion(E2, Composite2, E2ToC2, Sema::AA_Converting))
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002050 return Composite2;
2051 }
2052 return QualType();
2053}
Anders Carlsson165a0a02009-05-17 18:41:29 +00002054
Anders Carlssondef11992009-05-30 20:36:53 +00002055Sema::OwningExprResult Sema::MaybeBindToTemporary(Expr *E) {
Anders Carlsson089c2602009-08-15 23:41:35 +00002056 if (!Context.getLangOptions().CPlusPlus)
2057 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002058
Ted Kremenek6217b802009-07-29 21:53:49 +00002059 const RecordType *RT = E->getType()->getAs<RecordType>();
Anders Carlssondef11992009-05-30 20:36:53 +00002060 if (!RT)
2061 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002062
Anders Carlssondef11992009-05-30 20:36:53 +00002063 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2064 if (RD->hasTrivialDestructor())
2065 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002066
Anders Carlsson283e4d52009-09-14 01:30:44 +00002067 if (CallExpr *CE = dyn_cast<CallExpr>(E)) {
2068 QualType Ty = CE->getCallee()->getType();
2069 if (const PointerType *PT = Ty->getAs<PointerType>())
2070 Ty = PT->getPointeeType();
2071
John McCall183700f2009-09-21 23:43:11 +00002072 const FunctionType *FTy = Ty->getAs<FunctionType>();
Anders Carlsson283e4d52009-09-14 01:30:44 +00002073 if (FTy->getResultType()->isReferenceType())
2074 return Owned(E);
2075 }
Mike Stump1eb44332009-09-09 15:08:12 +00002076 CXXTemporary *Temp = CXXTemporary::Create(Context,
Anders Carlssondef11992009-05-30 20:36:53 +00002077 RD->getDestructor(Context));
Anders Carlsson860306e2009-05-30 21:21:49 +00002078 ExprTemporaries.push_back(Temp);
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00002079 if (CXXDestructorDecl *Destructor =
2080 const_cast<CXXDestructorDecl*>(RD->getDestructor(Context)))
2081 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
Anders Carlssondef11992009-05-30 20:36:53 +00002082 // FIXME: Add the temporary to the temporaries vector.
2083 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
2084}
2085
Anders Carlsson0ece4912009-12-15 20:51:39 +00002086Expr *Sema::MaybeCreateCXXExprWithTemporaries(Expr *SubExpr) {
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002087 assert(SubExpr && "sub expression can't be null!");
Mike Stump1eb44332009-09-09 15:08:12 +00002088
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00002089 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
2090 assert(ExprTemporaries.size() >= FirstTemporary);
2091 if (ExprTemporaries.size() == FirstTemporary)
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002092 return SubExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00002093
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002094 Expr *E = CXXExprWithTemporaries::Create(Context, SubExpr,
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00002095 &ExprTemporaries[FirstTemporary],
Anders Carlsson0ece4912009-12-15 20:51:39 +00002096 ExprTemporaries.size() - FirstTemporary);
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00002097 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
2098 ExprTemporaries.end());
Mike Stump1eb44332009-09-09 15:08:12 +00002099
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002100 return E;
2101}
2102
Anders Carlsson5ee56e92009-12-16 02:09:40 +00002103FullExpr Sema::CreateFullExpr(Expr *SubExpr) {
2104 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
2105 assert(ExprTemporaries.size() >= FirstTemporary);
2106
2107 unsigned NumTemporaries = ExprTemporaries.size() - FirstTemporary;
2108 CXXTemporary **Temporaries =
2109 NumTemporaries == 0 ? 0 : &ExprTemporaries[FirstTemporary];
2110
2111 FullExpr E = FullExpr::Create(Context, SubExpr, Temporaries, NumTemporaries);
2112
2113 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
2114 ExprTemporaries.end());
2115
2116 return E;
2117}
2118
Mike Stump1eb44332009-09-09 15:08:12 +00002119Sema::OwningExprResult
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002120Sema::ActOnStartCXXMemberReference(Scope *S, ExprArg Base, SourceLocation OpLoc,
2121 tok::TokenKind OpKind, TypeTy *&ObjectType) {
2122 // Since this might be a postfix expression, get rid of ParenListExprs.
2123 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
Mike Stump1eb44332009-09-09 15:08:12 +00002124
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002125 Expr *BaseExpr = (Expr*)Base.get();
2126 assert(BaseExpr && "no record expansion");
Mike Stump1eb44332009-09-09 15:08:12 +00002127
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002128 QualType BaseType = BaseExpr->getType();
2129 if (BaseType->isDependentType()) {
Douglas Gregor43d88632009-11-04 22:49:18 +00002130 // If we have a pointer to a dependent type and are using the -> operator,
2131 // the object type is the type that the pointer points to. We might still
2132 // have enough information about that type to do something useful.
2133 if (OpKind == tok::arrow)
2134 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
2135 BaseType = Ptr->getPointeeType();
2136
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002137 ObjectType = BaseType.getAsOpaquePtr();
2138 return move(Base);
2139 }
Mike Stump1eb44332009-09-09 15:08:12 +00002140
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002141 // C++ [over.match.oper]p8:
Mike Stump1eb44332009-09-09 15:08:12 +00002142 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002143 // returned, with the original second operand.
2144 if (OpKind == tok::arrow) {
John McCallc4e83212009-09-30 01:01:30 +00002145 // The set of types we've considered so far.
John McCall432887f2009-09-30 01:30:54 +00002146 llvm::SmallPtrSet<CanQualType,8> CTypes;
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002147 llvm::SmallVector<SourceLocation, 8> Locations;
John McCall432887f2009-09-30 01:30:54 +00002148 CTypes.insert(Context.getCanonicalType(BaseType));
John McCallc4e83212009-09-30 01:01:30 +00002149
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002150 while (BaseType->isRecordType()) {
Anders Carlsson15ea3782009-10-13 22:43:21 +00002151 Base = BuildOverloadedArrowExpr(S, move(Base), OpLoc);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002152 BaseExpr = (Expr*)Base.get();
2153 if (BaseExpr == NULL)
2154 return ExprError();
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002155 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(BaseExpr))
Anders Carlssonde699e52009-10-13 22:55:59 +00002156 Locations.push_back(OpCall->getDirectCallee()->getLocation());
John McCallc4e83212009-09-30 01:01:30 +00002157 BaseType = BaseExpr->getType();
2158 CanQualType CBaseType = Context.getCanonicalType(BaseType);
John McCall432887f2009-09-30 01:30:54 +00002159 if (!CTypes.insert(CBaseType)) {
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00002160 Diag(OpLoc, diag::err_operator_arrow_circular);
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002161 for (unsigned i = 0; i < Locations.size(); i++)
2162 Diag(Locations[i], diag::note_declared_at);
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00002163 return ExprError();
2164 }
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002165 }
Mike Stump1eb44332009-09-09 15:08:12 +00002166
Douglas Gregor31658df2009-11-20 19:58:21 +00002167 if (BaseType->isPointerType())
2168 BaseType = BaseType->getPointeeType();
2169 }
Mike Stump1eb44332009-09-09 15:08:12 +00002170
2171 // We could end up with various non-record types here, such as extended
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002172 // vector types or Objective-C interfaces. Just return early and let
2173 // ActOnMemberReferenceExpr do the work.
Douglas Gregorc68afe22009-09-03 21:38:09 +00002174 if (!BaseType->isRecordType()) {
2175 // C++ [basic.lookup.classref]p2:
2176 // [...] If the type of the object expression is of pointer to scalar
2177 // type, the unqualified-id is looked up in the context of the complete
2178 // postfix-expression.
2179 ObjectType = 0;
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002180 return move(Base);
Douglas Gregorc68afe22009-09-03 21:38:09 +00002181 }
Mike Stump1eb44332009-09-09 15:08:12 +00002182
Douglas Gregor03c57052009-11-17 05:17:33 +00002183 // The object type must be complete (or dependent).
2184 if (!BaseType->isDependentType() &&
2185 RequireCompleteType(OpLoc, BaseType,
2186 PDiag(diag::err_incomplete_member_access)))
2187 return ExprError();
2188
Douglas Gregorc68afe22009-09-03 21:38:09 +00002189 // C++ [basic.lookup.classref]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00002190 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor03c57052009-11-17 05:17:33 +00002191 // unqualified-id, and the type of the object expression is of a class
Douglas Gregorc68afe22009-09-03 21:38:09 +00002192 // type C (or of pointer to a class type C), the unqualified-id is looked
2193 // up in the scope of class C. [...]
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002194 ObjectType = BaseType.getAsOpaquePtr();
Douglas Gregor03c57052009-11-17 05:17:33 +00002195
Mike Stump1eb44332009-09-09 15:08:12 +00002196 return move(Base);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002197}
2198
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002199CXXMemberCallExpr *Sema::BuildCXXMemberCallExpr(Expr *Exp,
2200 CXXMethodDecl *Method) {
Eli Friedman772fffa2009-12-09 04:53:56 +00002201 if (PerformObjectArgumentInitialization(Exp, Method))
2202 assert(0 && "Calling BuildCXXMemberCallExpr with invalid call?");
2203
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002204 MemberExpr *ME =
2205 new (Context) MemberExpr(Exp, /*IsArrow=*/false, Method,
2206 SourceLocation(), Method->getType());
Eli Friedman772fffa2009-12-09 04:53:56 +00002207 QualType ResultType = Method->getResultType().getNonReferenceType();
Douglas Gregor7edfb692009-11-23 12:27:39 +00002208 MarkDeclarationReferenced(Exp->getLocStart(), Method);
2209 CXXMemberCallExpr *CE =
2210 new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType,
2211 Exp->getLocEnd());
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002212 return CE;
2213}
2214
Anders Carlsson0aebc812009-09-09 21:33:21 +00002215Sema::OwningExprResult Sema::BuildCXXCastArgument(SourceLocation CastLoc,
2216 QualType Ty,
2217 CastExpr::CastKind Kind,
2218 CXXMethodDecl *Method,
2219 ExprArg Arg) {
2220 Expr *From = Arg.takeAs<Expr>();
2221
2222 switch (Kind) {
2223 default: assert(0 && "Unhandled cast kind!");
2224 case CastExpr::CK_ConstructorConversion: {
Douglas Gregor39da0b82009-09-09 23:08:42 +00002225 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
2226
2227 if (CompleteConstructorCall(cast<CXXConstructorDecl>(Method),
2228 MultiExprArg(*this, (void **)&From, 1),
2229 CastLoc, ConstructorArgs))
2230 return ExprError();
Anders Carlsson4fa26842009-10-18 21:20:14 +00002231
2232 OwningExprResult Result =
2233 BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
2234 move_arg(ConstructorArgs));
2235 if (Result.isInvalid())
2236 return ExprError();
2237
2238 return MaybeBindToTemporary(Result.takeAs<Expr>());
Anders Carlsson0aebc812009-09-09 21:33:21 +00002239 }
2240
2241 case CastExpr::CK_UserDefinedConversion: {
Anders Carlssonaac6e3a2009-09-15 07:42:44 +00002242 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
Eli Friedman772fffa2009-12-09 04:53:56 +00002243
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002244 // Create an implicit call expr that calls it.
2245 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(From, Method);
Anders Carlsson4fa26842009-10-18 21:20:14 +00002246 return MaybeBindToTemporary(CE);
Anders Carlsson0aebc812009-09-09 21:33:21 +00002247 }
Anders Carlsson0aebc812009-09-09 21:33:21 +00002248 }
2249}
2250
Anders Carlsson165a0a02009-05-17 18:41:29 +00002251Sema::OwningExprResult Sema::ActOnFinishFullExpr(ExprArg Arg) {
2252 Expr *FullExpr = Arg.takeAs<Expr>();
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002253 if (FullExpr)
Anders Carlsson0ece4912009-12-15 20:51:39 +00002254 FullExpr = MaybeCreateCXXExprWithTemporaries(FullExpr);
Anders Carlssonec773872009-08-25 23:46:41 +00002255
Anders Carlsson165a0a02009-05-17 18:41:29 +00002256 return Owned(FullExpr);
2257}
Douglas Gregore961afb2009-10-22 07:08:30 +00002258
2259/// \brief Determine whether a reference to the given declaration in the
2260/// current context is an implicit member access
2261/// (C++ [class.mfct.non-static]p2).
2262///
2263/// FIXME: Should Objective-C also use this approach?
2264///
Douglas Gregore961afb2009-10-22 07:08:30 +00002265/// \param D the declaration being referenced from the current scope.
2266///
2267/// \param NameLoc the location of the name in the source.
2268///
2269/// \param ThisType if the reference to this declaration is an implicit member
2270/// access, will be set to the type of the "this" pointer to be used when
2271/// building that implicit member access.
2272///
Douglas Gregore961afb2009-10-22 07:08:30 +00002273/// \returns true if this is an implicit member reference (in which case
2274/// \p ThisType and \p MemberType will be set), or false if it is not an
2275/// implicit member reference.
John McCall129e2df2009-11-30 22:42:35 +00002276bool Sema::isImplicitMemberReference(const LookupResult &R,
2277 QualType &ThisType) {
Douglas Gregore961afb2009-10-22 07:08:30 +00002278 // If this isn't a C++ method, then it isn't an implicit member reference.
2279 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext);
2280 if (!MD || MD->isStatic())
2281 return false;
2282
2283 // C++ [class.mfct.nonstatic]p2:
2284 // [...] if name lookup (3.4.1) resolves the name in the
2285 // id-expression to a nonstatic nontype member of class X or of
2286 // a base class of X, the id-expression is transformed into a
2287 // class member access expression (5.2.5) using (*this) (9.3.2)
2288 // as the postfix-expression to the left of the '.' operator.
2289 DeclContext *Ctx = 0;
John McCall129e2df2009-11-30 22:42:35 +00002290 if (R.isUnresolvableResult()) {
2291 // FIXME: this is just picking one at random
2292 Ctx = R.getRepresentativeDecl()->getDeclContext();
2293 } else if (FieldDecl *FD = R.getAsSingle<FieldDecl>()) {
Douglas Gregore961afb2009-10-22 07:08:30 +00002294 Ctx = FD->getDeclContext();
Douglas Gregore961afb2009-10-22 07:08:30 +00002295 } else {
John McCall129e2df2009-11-30 22:42:35 +00002296 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2297 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*I);
Douglas Gregore961afb2009-10-22 07:08:30 +00002298 FunctionTemplateDecl *FunTmpl = 0;
John McCall129e2df2009-11-30 22:42:35 +00002299 if (!Method && (FunTmpl = dyn_cast<FunctionTemplateDecl>(*I)))
Douglas Gregore961afb2009-10-22 07:08:30 +00002300 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
2301
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00002302 // FIXME: Do we have to know if there are explicit template arguments?
Douglas Gregore961afb2009-10-22 07:08:30 +00002303 if (Method && !Method->isStatic()) {
2304 Ctx = Method->getParent();
Douglas Gregore961afb2009-10-22 07:08:30 +00002305 break;
2306 }
2307 }
2308 }
2309
2310 if (!Ctx || !Ctx->isRecord())
2311 return false;
2312
2313 // Determine whether the declaration(s) we found are actually in a base
2314 // class. If not, this isn't an implicit member reference.
2315 ThisType = MD->getThisType(Context);
John McCall129e2df2009-11-30 22:42:35 +00002316
2317 // FIXME: this doesn't really work for overloaded lookups.
Douglas Gregor7a343142009-11-01 17:08:18 +00002318
Douglas Gregore961afb2009-10-22 07:08:30 +00002319 QualType CtxType = Context.getTypeDeclType(cast<CXXRecordDecl>(Ctx));
2320 QualType ClassType
2321 = Context.getTypeDeclType(cast<CXXRecordDecl>(MD->getParent()));
2322 return Context.hasSameType(CtxType, ClassType) ||
2323 IsDerivedFrom(ClassType, CtxType);
2324}
2325