blob: 753d1e47ba38a2dcec3f943325239178101acc66 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ expressions.
11//
12//===----------------------------------------------------------------------===//
13
Sebastian Redl7c8bd602009-02-07 20:10:22 +000014#include "SemaInherit.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000015#include "Sema.h"
16#include "clang/AST/ExprCXX.h"
Steve Naroff210679c2007-08-25 14:02:58 +000017#include "clang/AST/ASTContext.h"
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +000018#include "clang/Parse/DeclSpec.h"
Argyrios Kyrtzidis4021a842008-10-06 23:16:35 +000019#include "clang/Lex/Preprocessor.h"
Sebastian Redlb5a57a62008-12-03 20:26:15 +000020#include "clang/Basic/TargetInfo.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000021#include "llvm/ADT/STLExtras.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000022using namespace clang;
23
Douglas Gregor487a75a2008-11-19 19:09:45 +000024/// ActOnCXXConversionFunctionExpr - Parse a C++ conversion function
Douglas Gregor2def4832008-11-17 20:34:05 +000025/// name (e.g., operator void const *) as an expression. This is
26/// very similar to ActOnIdentifierExpr, except that instead of
27/// providing an identifier the parser provides the type of the
28/// conversion function.
Sebastian Redlcd965b92009-01-18 18:53:16 +000029Sema::OwningExprResult
Douglas Gregor487a75a2008-11-19 19:09:45 +000030Sema::ActOnCXXConversionFunctionExpr(Scope *S, SourceLocation OperatorLoc,
31 TypeTy *Ty, bool HasTrailingLParen,
Sebastian Redlebc07d52009-02-03 20:19:35 +000032 const CXXScopeSpec &SS,
33 bool isAddressOfOperand) {
Douglas Gregor2def4832008-11-17 20:34:05 +000034 QualType ConvType = QualType::getFromOpaquePtr(Ty);
35 QualType ConvTypeCanon = Context.getCanonicalType(ConvType);
36 DeclarationName ConvName
37 = Context.DeclarationNames.getCXXConversionFunctionName(ConvTypeCanon);
Sebastian Redlcd965b92009-01-18 18:53:16 +000038 return ActOnDeclarationNameExpr(S, OperatorLoc, ConvName, HasTrailingLParen,
Douglas Gregor17330012009-02-04 15:01:18 +000039 &SS, isAddressOfOperand);
Douglas Gregor2def4832008-11-17 20:34:05 +000040}
Sebastian Redlc42e1182008-11-11 11:37:55 +000041
Douglas Gregor487a75a2008-11-19 19:09:45 +000042/// ActOnCXXOperatorFunctionIdExpr - Parse a C++ overloaded operator
Douglas Gregore94ca9e42008-11-18 14:39:36 +000043/// name (e.g., @c operator+ ) as an expression. This is very
44/// similar to ActOnIdentifierExpr, except that instead of providing
45/// an identifier the parser provides the kind of overloaded
46/// operator that was parsed.
Sebastian Redlcd965b92009-01-18 18:53:16 +000047Sema::OwningExprResult
Douglas Gregor487a75a2008-11-19 19:09:45 +000048Sema::ActOnCXXOperatorFunctionIdExpr(Scope *S, SourceLocation OperatorLoc,
49 OverloadedOperatorKind Op,
50 bool HasTrailingLParen,
Sebastian Redlebc07d52009-02-03 20:19:35 +000051 const CXXScopeSpec &SS,
52 bool isAddressOfOperand) {
Douglas Gregore94ca9e42008-11-18 14:39:36 +000053 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(Op);
Sebastian Redlebc07d52009-02-03 20:19:35 +000054 return ActOnDeclarationNameExpr(S, OperatorLoc, Name, HasTrailingLParen, &SS,
Douglas Gregor17330012009-02-04 15:01:18 +000055 isAddressOfOperand);
Douglas Gregore94ca9e42008-11-18 14:39:36 +000056}
57
Sebastian Redlc42e1182008-11-11 11:37:55 +000058/// ActOnCXXTypeidOfType - Parse typeid( type-id ).
Sebastian Redlf53597f2009-03-15 17:47:39 +000059Action::OwningExprResult
Sebastian Redlc42e1182008-11-11 11:37:55 +000060Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
61 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Douglas Gregor4c921ae2009-01-30 01:04:22 +000062 NamespaceDecl *StdNs = GetStdNamespace();
Chris Lattner572af492008-11-20 05:51:55 +000063 if (!StdNs)
Sebastian Redlf53597f2009-03-15 17:47:39 +000064 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Chris Lattner572af492008-11-20 05:51:55 +000065
66 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
Douglas Gregor4c921ae2009-01-30 01:04:22 +000067 Decl *TypeInfoDecl = LookupQualifiedName(StdNs, TypeInfoII, LookupTagName);
Sebastian Redlc42e1182008-11-11 11:37:55 +000068 RecordDecl *TypeInfoRecordDecl = dyn_cast_or_null<RecordDecl>(TypeInfoDecl);
Chris Lattner572af492008-11-20 05:51:55 +000069 if (!TypeInfoRecordDecl)
Sebastian Redlf53597f2009-03-15 17:47:39 +000070 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Sebastian Redlc42e1182008-11-11 11:37:55 +000071
72 QualType TypeInfoType = Context.getTypeDeclType(TypeInfoRecordDecl);
73
Sebastian Redlf53597f2009-03-15 17:47:39 +000074 return Owned(new (Context) CXXTypeidExpr(isType, TyOrExpr,
75 TypeInfoType.withConst(),
76 SourceRange(OpLoc, RParenLoc)));
Sebastian Redlc42e1182008-11-11 11:37:55 +000077}
78
Steve Naroff1b273c42007-09-16 14:56:35 +000079/// ActOnCXXBoolLiteral - Parse {true,false} literals.
Sebastian Redlf53597f2009-03-15 17:47:39 +000080Action::OwningExprResult
Steve Naroff1b273c42007-09-16 14:56:35 +000081Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor2f639b92008-10-24 15:36:09 +000082 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Reid Spencer5f016e22007-07-11 17:01:13 +000083 "Unknown C++ Boolean value!");
Sebastian Redlf53597f2009-03-15 17:47:39 +000084 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
85 Context.BoolTy, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +000086}
Chris Lattner50dd2892008-02-26 00:51:44 +000087
88/// ActOnCXXThrow - Parse throw expressions.
Sebastian Redlf53597f2009-03-15 17:47:39 +000089Action::OwningExprResult
90Sema::ActOnCXXThrow(SourceLocation OpLoc, ExprArg E) {
91 return Owned(new (Context) CXXThrowExpr((Expr*)E.release(), Context.VoidTy,
92 OpLoc));
Chris Lattner50dd2892008-02-26 00:51:44 +000093}
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000094
Sebastian Redlf53597f2009-03-15 17:47:39 +000095Action::OwningExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000096 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
97 /// is a non-lvalue expression whose value is the address of the object for
98 /// which the function is called.
99
Sebastian Redlf53597f2009-03-15 17:47:39 +0000100 if (!isa<FunctionDecl>(CurContext))
101 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000102
103 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext))
104 if (MD->isInstance())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000105 return Owned(new (Context) CXXThisExpr(ThisLoc,
106 MD->getThisType(Context)));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000107
Sebastian Redlf53597f2009-03-15 17:47:39 +0000108 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000109}
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000110
111/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
112/// Can be interpreted either as function-style casting ("int(x)")
113/// or class type construction ("ClassType(x,y,z)")
114/// or creation of a value-initialized type ("int()").
Sebastian Redlf53597f2009-03-15 17:47:39 +0000115Action::OwningExprResult
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000116Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep,
117 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000118 MultiExprArg exprs,
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000119 SourceLocation *CommaLocs,
120 SourceLocation RParenLoc) {
121 assert(TypeRep && "Missing type!");
122 QualType Ty = QualType::getFromOpaquePtr(TypeRep);
Sebastian Redlf53597f2009-03-15 17:47:39 +0000123 unsigned NumExprs = exprs.size();
124 Expr **Exprs = (Expr**)exprs.get();
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000125 SourceLocation TyBeginLoc = TypeRange.getBegin();
126 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
127
Sebastian Redlf53597f2009-03-15 17:47:39 +0000128 if (Ty->isDependentType() ||
Douglas Gregorba498172009-03-13 21:01:28 +0000129 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
Sebastian Redlf53597f2009-03-15 17:47:39 +0000130 exprs.release();
Anders Carlsson26de5492009-04-24 05:23:13 +0000131
132 // FIXME: Is this correct?
133 CXXTempVarDecl *Temp = CXXTempVarDecl::Create(Context, CurContext, Ty);
134 return Owned(new (Context) CXXTemporaryObjectExpr(Temp, 0, Ty, TyBeginLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000135 Exprs, NumExprs,
136 RParenLoc));
Douglas Gregorba498172009-03-13 21:01:28 +0000137 }
138
139
Douglas Gregor506ae412009-01-16 18:33:17 +0000140 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000141 // If the expression list is a single expression, the type conversion
142 // expression is equivalent (in definedness, and if defined in meaning) to the
143 // corresponding cast expression.
144 //
145 if (NumExprs == 1) {
146 if (CheckCastTypes(TypeRange, Ty, Exprs[0]))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000147 return ExprError();
148 exprs.release();
149 return Owned(new (Context) CXXFunctionalCastExpr(Ty.getNonReferenceType(),
150 Ty, TyBeginLoc, Exprs[0],
151 RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000152 }
153
Douglas Gregor506ae412009-01-16 18:33:17 +0000154 if (const RecordType *RT = Ty->getAsRecordType()) {
155 CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
Sebastian Redlf53597f2009-03-15 17:47:39 +0000156
Douglas Gregor506ae412009-01-16 18:33:17 +0000157 if (NumExprs > 1 || Record->hasUserDeclaredConstructor()) {
158 CXXConstructorDecl *Constructor
159 = PerformInitializationByConstructor(Ty, Exprs, NumExprs,
160 TypeRange.getBegin(),
161 SourceRange(TypeRange.getBegin(),
162 RParenLoc),
163 DeclarationName(),
164 IK_Direct);
Douglas Gregor506ae412009-01-16 18:33:17 +0000165
Sebastian Redlf53597f2009-03-15 17:47:39 +0000166 if (!Constructor)
167 return ExprError();
168
Anders Carlsson26de5492009-04-24 05:23:13 +0000169 CXXTempVarDecl *Temp = CXXTempVarDecl::Create(Context, CurContext, Ty);
170
Sebastian Redlf53597f2009-03-15 17:47:39 +0000171 exprs.release();
Anders Carlsson26de5492009-04-24 05:23:13 +0000172 return Owned(new (Context) CXXTemporaryObjectExpr(Temp, Constructor, Ty,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000173 TyBeginLoc, Exprs,
174 NumExprs, RParenLoc));
Douglas Gregor506ae412009-01-16 18:33:17 +0000175 }
176
177 // Fall through to value-initialize an object of class type that
178 // doesn't have a user-declared default constructor.
179 }
180
181 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000182 // If the expression list specifies more than a single value, the type shall
183 // be a class with a suitably declared constructor.
184 //
185 if (NumExprs > 1)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000186 return ExprError(Diag(CommaLocs[0],
187 diag::err_builtin_func_cast_more_than_one_arg)
188 << FullRange);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000189
190 assert(NumExprs == 0 && "Expected 0 expressions");
191
Douglas Gregor506ae412009-01-16 18:33:17 +0000192 // C++ [expr.type.conv]p2:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000193 // The expression T(), where T is a simple-type-specifier for a non-array
194 // complete object type or the (possibly cv-qualified) void type, creates an
195 // rvalue of the specified type, which is value-initialized.
196 //
197 if (Ty->isArrayType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000198 return ExprError(Diag(TyBeginLoc,
199 diag::err_value_init_for_array_type) << FullRange);
Douglas Gregor4ec339f2009-01-19 19:26:10 +0000200 if (!Ty->isDependentType() && !Ty->isVoidType() &&
Sebastian Redlf53597f2009-03-15 17:47:39 +0000201 RequireCompleteType(TyBeginLoc, Ty,
202 diag::err_invalid_incomplete_type_use, FullRange))
203 return ExprError();
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000204
Anders Carlsson8211eff2009-03-24 01:19:16 +0000205 if (RequireNonAbstractType(TyBeginLoc, Ty,
206 diag::err_allocation_of_abstract_type))
Anders Carlsson11f21a02009-03-23 19:10:31 +0000207 return ExprError();
208
Sebastian Redlf53597f2009-03-15 17:47:39 +0000209 exprs.release();
210 return Owned(new (Context) CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000211}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000212
213
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000214/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
215/// @code new (memory) int[size][4] @endcode
216/// or
217/// @code ::new Foo(23, "hello") @endcode
218/// For the interpretation of this heap of arguments, consult the base version.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000219Action::OwningExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000220Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000221 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000222 SourceLocation PlacementRParen, bool ParenTypeId,
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000223 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000224 MultiExprArg ConstructorArgs,
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000225 SourceLocation ConstructorRParen)
226{
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000227 Expr *ArraySize = 0;
228 unsigned Skip = 0;
229 // If the specified type is an array, unwrap it and save the expression.
230 if (D.getNumTypeObjects() > 0 &&
231 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
232 DeclaratorChunk &Chunk = D.getTypeObject(0);
233 if (Chunk.Arr.hasStatic)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000234 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
235 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000236 if (!Chunk.Arr.NumElts)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000237 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
238 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000239 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
240 Skip = 1;
241 }
242
243 QualType AllocType = GetTypeForDeclarator(D, /*Scope=*/0, Skip);
244 if (D.getInvalidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000245 return ExprError();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000246
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000247 if (CheckAllocatedType(AllocType, D))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000248 return ExprError();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000249
Sebastian Redl28507842009-02-26 14:39:58 +0000250 QualType ResultType = AllocType->isDependentType()
251 ? Context.DependentTy
252 : Context.getPointerType(AllocType);
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000253
254 // That every array dimension except the first is constant was already
255 // checked by the type check above.
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000256
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000257 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
258 // or enumeration type with a non-negative value."
Sebastian Redl28507842009-02-26 14:39:58 +0000259 if (ArraySize && !ArraySize->isTypeDependent()) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000260 QualType SizeType = ArraySize->getType();
261 if (!SizeType->isIntegralType() && !SizeType->isEnumeralType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000262 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
263 diag::err_array_size_not_integral)
264 << SizeType << ArraySize->getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000265 // Let's see if this is a constant < 0. If so, we reject it out of hand.
266 // We don't care about special rules, so we tell the machinery it's not
267 // evaluated - it gives us a result in more cases.
Sebastian Redl28507842009-02-26 14:39:58 +0000268 if (!ArraySize->isValueDependent()) {
269 llvm::APSInt Value;
270 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
271 if (Value < llvm::APSInt(
272 llvm::APInt::getNullValue(Value.getBitWidth()), false))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000273 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
274 diag::err_typecheck_negative_array_size)
275 << ArraySize->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +0000276 }
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000277 }
278 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000279
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000280 FunctionDecl *OperatorNew = 0;
281 FunctionDecl *OperatorDelete = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000282 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
283 unsigned NumPlaceArgs = PlacementArgs.size();
Sebastian Redl28507842009-02-26 14:39:58 +0000284 if (!AllocType->isDependentType() &&
285 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
286 FindAllocationFunctions(StartLoc,
Sebastian Redl00e68e22009-02-09 18:24:27 +0000287 SourceRange(PlacementLParen, PlacementRParen),
288 UseGlobal, AllocType, ArraySize, PlaceArgs,
289 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000290 return ExprError();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000291
292 bool Init = ConstructorLParen.isValid();
293 // --- Choosing a constructor ---
294 // C++ 5.3.4p15
295 // 1) If T is a POD and there's no initializer (ConstructorLParen is invalid)
296 // the object is not initialized. If the object, or any part of it, is
297 // const-qualified, it's an error.
298 // 2) If T is a POD and there's an empty initializer, the object is value-
299 // initialized.
300 // 3) If T is a POD and there's one initializer argument, the object is copy-
301 // constructed.
302 // 4) If T is a POD and there's more initializer arguments, it's an error.
303 // 5) If T is not a POD, the initializer arguments are used as constructor
304 // arguments.
305 //
306 // Or by the C++0x formulation:
307 // 1) If there's no initializer, the object is default-initialized according
308 // to C++0x rules.
309 // 2) Otherwise, the object is direct-initialized.
310 CXXConstructorDecl *Constructor = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000311 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
312 unsigned NumConsArgs = ConstructorArgs.size();
Sebastian Redl28507842009-02-26 14:39:58 +0000313 if (AllocType->isDependentType()) {
314 // Skip all the checks.
315 }
Sebastian Redl00e68e22009-02-09 18:24:27 +0000316 // FIXME: Should check for primitive/aggregate here, not record.
Sebastian Redl28507842009-02-26 14:39:58 +0000317 else if (const RecordType *RT = AllocType->getAsRecordType()) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000318 // FIXME: This is incorrect for when there is an empty initializer and
319 // no user-defined constructor. Must zero-initialize, not default-construct.
320 Constructor = PerformInitializationByConstructor(
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000321 AllocType, ConsArgs, NumConsArgs,
Sebastian Redl00e68e22009-02-09 18:24:27 +0000322 D.getSourceRange().getBegin(),
323 SourceRange(D.getSourceRange().getBegin(),
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000324 ConstructorRParen),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000325 RT->getDecl()->getDeclName(),
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000326 NumConsArgs != 0 ? IK_Direct : IK_Default);
327 if (!Constructor)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000328 return ExprError();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000329 } else {
330 if (!Init) {
331 // FIXME: Check that no subpart is const.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000332 if (AllocType.isConstQualified())
333 return ExprError(Diag(StartLoc, diag::err_new_uninitialized_const)
334 << D.getSourceRange());
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000335 } else if (NumConsArgs == 0) {
336 // Object is value-initialized. Do nothing.
337 } else if (NumConsArgs == 1) {
338 // Object is direct-initialized.
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000339 // FIXME: WHAT DeclarationName do we pass in here?
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000340 if (CheckInitializerTypes(ConsArgs[0], AllocType, StartLoc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000341 DeclarationName() /*AllocType.getAsString()*/,
342 /*DirectInit=*/true))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000343 return ExprError();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000344 } else {
Sebastian Redlf53597f2009-03-15 17:47:39 +0000345 return ExprError(Diag(StartLoc,
346 diag::err_builtin_direct_init_more_than_one_arg)
347 << SourceRange(ConstructorLParen, ConstructorRParen));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000348 }
349 }
350
351 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
352
Sebastian Redlf53597f2009-03-15 17:47:39 +0000353 PlacementArgs.release();
354 ConstructorArgs.release();
355 return Owned(new (Context) CXXNewExpr(UseGlobal, OperatorNew, PlaceArgs,
Ted Kremenek8189cde2009-02-07 01:47:29 +0000356 NumPlaceArgs, ParenTypeId, ArraySize, Constructor, Init,
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000357 ConsArgs, NumConsArgs, OperatorDelete, ResultType,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000358 StartLoc, Init ? ConstructorRParen : SourceLocation()));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000359}
360
361/// CheckAllocatedType - Checks that a type is suitable as the allocated type
362/// in a new-expression.
363/// dimension off and stores the size expression in ArraySize.
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000364bool Sema::CheckAllocatedType(QualType AllocType, const Declarator &D)
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000365{
366 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
367 // abstract class type or array thereof.
Douglas Gregore7450f52009-03-24 19:52:54 +0000368 if (AllocType->isFunctionType())
369 return Diag(D.getSourceRange().getBegin(), diag::err_bad_new_type)
370 << AllocType << 0 << D.getSourceRange();
371 else if (AllocType->isReferenceType())
372 return Diag(D.getSourceRange().getBegin(), diag::err_bad_new_type)
373 << AllocType << 1 << D.getSourceRange();
374 else if (!AllocType->isDependentType() &&
375 RequireCompleteType(D.getSourceRange().getBegin(), AllocType,
376 diag::err_new_incomplete_type,
377 D.getSourceRange()))
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000378 return true;
Douglas Gregore7450f52009-03-24 19:52:54 +0000379 else if (RequireNonAbstractType(D.getSourceRange().getBegin(), AllocType,
380 diag::err_allocation_of_abstract_type))
381 return true;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000382
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000383 // Every dimension shall be of constant size.
384 unsigned i = 1;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000385 while (const ArrayType *Array = Context.getAsArrayType(AllocType)) {
386 if (!Array->isConstantArrayType()) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000387 Diag(D.getTypeObject(i).Loc, diag::err_new_array_nonconst)
388 << static_cast<Expr*>(D.getTypeObject(i).Arr.NumElts)->getSourceRange();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000389 return true;
390 }
391 AllocType = Array->getElementType();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000392 ++i;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000393 }
394
395 return false;
396}
397
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000398/// FindAllocationFunctions - Finds the overloads of operator new and delete
399/// that are appropriate for the allocation.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000400bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
401 bool UseGlobal, QualType AllocType,
402 bool IsArray, Expr **PlaceArgs,
403 unsigned NumPlaceArgs,
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000404 FunctionDecl *&OperatorNew,
405 FunctionDecl *&OperatorDelete)
406{
407 // --- Choosing an allocation function ---
408 // C++ 5.3.4p8 - 14 & 18
409 // 1) If UseGlobal is true, only look in the global scope. Else, also look
410 // in the scope of the allocated class.
411 // 2) If an array size is given, look for operator new[], else look for
412 // operator new.
413 // 3) The first argument is always size_t. Append the arguments from the
414 // placement form.
415 // FIXME: Also find the appropriate delete operator.
416
417 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
418 // We don't care about the actual value of this argument.
419 // FIXME: Should the Sema create the expression and embed it in the syntax
420 // tree? Or should the consumer just recalculate the value?
Ted Kremenek8189cde2009-02-07 01:47:29 +0000421 AllocArgs[0] = new (Context) IntegerLiteral(llvm::APInt::getNullValue(
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000422 Context.Target.getPointerWidth(0)),
423 Context.getSizeType(),
424 SourceLocation());
425 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
426
427 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
428 IsArray ? OO_Array_New : OO_New);
429 if (AllocType->isRecordType() && !UseGlobal) {
Douglas Gregorc1efaec2009-02-28 01:32:25 +0000430 CXXRecordDecl *Record
431 = cast<CXXRecordDecl>(AllocType->getAsRecordType()->getDecl());
Sebastian Redl7f662392008-12-04 22:20:51 +0000432 // FIXME: We fail to find inherited overloads.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000433 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000434 AllocArgs.size(), Record, /*AllowMissing=*/true,
435 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000436 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000437 }
438 if (!OperatorNew) {
439 // Didn't find a member overload. Look for a global one.
440 DeclareGlobalNewDelete();
Sebastian Redl7f662392008-12-04 22:20:51 +0000441 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl00e68e22009-02-09 18:24:27 +0000442 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000443 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
444 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000445 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000446 }
447
Sebastian Redl7f662392008-12-04 22:20:51 +0000448 // FIXME: This is leaked on error. But so much is currently in Sema that it's
449 // easier to clean it in one go.
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000450 AllocArgs[0]->Destroy(Context);
451 return false;
452}
453
Sebastian Redl7f662392008-12-04 22:20:51 +0000454/// FindAllocationOverload - Find an fitting overload for the allocation
455/// function in the specified scope.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000456bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
457 DeclarationName Name, Expr** Args,
458 unsigned NumArgs, DeclContext *Ctx,
459 bool AllowMissing, FunctionDecl *&Operator)
Sebastian Redl7f662392008-12-04 22:20:51 +0000460{
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000461 DeclContext::lookup_iterator Alloc, AllocEnd;
Douglas Gregor6ab35242009-04-09 21:40:53 +0000462 llvm::tie(Alloc, AllocEnd) = Ctx->lookup(Context, Name);
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000463 if (Alloc == AllocEnd) {
Sebastian Redl7f662392008-12-04 22:20:51 +0000464 if (AllowMissing)
465 return false;
Sebastian Redl7f662392008-12-04 22:20:51 +0000466 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +0000467 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +0000468 }
469
470 OverloadCandidateSet Candidates;
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000471 for (; Alloc != AllocEnd; ++Alloc) {
472 // Even member operator new/delete are implicitly treated as
473 // static, so don't use AddMemberCandidate.
474 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>(*Alloc))
475 AddOverloadCandidate(Fn, Args, NumArgs, Candidates,
476 /*SuppressUserConversions=*/false);
Sebastian Redl7f662392008-12-04 22:20:51 +0000477 }
478
479 // Do the resolution.
480 OverloadCandidateSet::iterator Best;
481 switch(BestViableFunction(Candidates, Best)) {
482 case OR_Success: {
483 // Got one!
484 FunctionDecl *FnDecl = Best->Function;
485 // The first argument is size_t, and the first parameter must be size_t,
486 // too. This is checked on declaration and can be assumed. (It can't be
487 // asserted on, though, since invalid decls are left in there.)
488 for (unsigned i = 1; i < NumArgs; ++i) {
489 // FIXME: Passing word to diagnostic.
490 if (PerformCopyInitialization(Args[i-1],
491 FnDecl->getParamDecl(i)->getType(),
492 "passing"))
493 return true;
494 }
495 Operator = FnDecl;
496 return false;
497 }
498
499 case OR_No_Viable_Function:
500 if (AllowMissing)
501 return false;
Sebastian Redl7f662392008-12-04 22:20:51 +0000502 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +0000503 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +0000504 PrintOverloadCandidates(Candidates, /*OnlyViable=*/false);
505 return true;
506
507 case OR_Ambiguous:
Sebastian Redl7f662392008-12-04 22:20:51 +0000508 Diag(StartLoc, diag::err_ovl_ambiguous_call)
Sebastian Redl00e68e22009-02-09 18:24:27 +0000509 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +0000510 PrintOverloadCandidates(Candidates, /*OnlyViable=*/true);
511 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000512
513 case OR_Deleted:
514 Diag(StartLoc, diag::err_ovl_deleted_call)
515 << Best->Function->isDeleted()
516 << Name << Range;
517 PrintOverloadCandidates(Candidates, /*OnlyViable=*/true);
518 return true;
Sebastian Redl7f662392008-12-04 22:20:51 +0000519 }
520 assert(false && "Unreachable, bad result from BestViableFunction");
521 return true;
522}
523
524
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000525/// DeclareGlobalNewDelete - Declare the global forms of operator new and
526/// delete. These are:
527/// @code
528/// void* operator new(std::size_t) throw(std::bad_alloc);
529/// void* operator new[](std::size_t) throw(std::bad_alloc);
530/// void operator delete(void *) throw();
531/// void operator delete[](void *) throw();
532/// @endcode
533/// Note that the placement and nothrow forms of new are *not* implicitly
534/// declared. Their use requires including \<new\>.
535void Sema::DeclareGlobalNewDelete()
536{
537 if (GlobalNewDeleteDeclared)
538 return;
539 GlobalNewDeleteDeclared = true;
540
541 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
542 QualType SizeT = Context.getSizeType();
543
544 // FIXME: Exception specifications are not added.
545 DeclareGlobalAllocationFunction(
546 Context.DeclarationNames.getCXXOperatorName(OO_New),
547 VoidPtr, SizeT);
548 DeclareGlobalAllocationFunction(
549 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
550 VoidPtr, SizeT);
551 DeclareGlobalAllocationFunction(
552 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
553 Context.VoidTy, VoidPtr);
554 DeclareGlobalAllocationFunction(
555 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
556 Context.VoidTy, VoidPtr);
557}
558
559/// DeclareGlobalAllocationFunction - Declares a single implicit global
560/// allocation function if it doesn't already exist.
561void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
562 QualType Return, QualType Argument)
563{
564 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
565
566 // Check if this function is already declared.
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000567 {
Douglas Gregor5cc37092008-12-23 22:05:29 +0000568 DeclContext::lookup_iterator Alloc, AllocEnd;
Douglas Gregor6ab35242009-04-09 21:40:53 +0000569 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Context, Name);
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000570 Alloc != AllocEnd; ++Alloc) {
571 // FIXME: Do we need to check for default arguments here?
572 FunctionDecl *Func = cast<FunctionDecl>(*Alloc);
573 if (Func->getNumParams() == 1 &&
Ted Kremenek8189cde2009-02-07 01:47:29 +0000574 Context.getCanonicalType(Func->getParamDecl(0)->getType())==Argument)
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000575 return;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000576 }
577 }
578
579 QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0);
580 FunctionDecl *Alloc =
581 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
Douglas Gregor2224f842009-02-25 16:33:18 +0000582 FnType, FunctionDecl::None, false, true,
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000583 SourceLocation());
584 Alloc->setImplicit();
585 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000586 0, Argument, VarDecl::None, 0);
Ted Kremenekfc767612009-01-14 00:42:25 +0000587 Alloc->setParams(Context, &Param, 1);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000588
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000589 // FIXME: Also add this declaration to the IdentifierResolver, but
590 // make sure it is at the end of the chain to coincide with the
591 // global scope.
Douglas Gregor6ab35242009-04-09 21:40:53 +0000592 ((DeclContext *)TUScope->getEntity())->addDecl(Context, Alloc);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000593}
594
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000595/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
596/// @code ::delete ptr; @endcode
597/// or
598/// @code delete [] ptr; @endcode
Sebastian Redlf53597f2009-03-15 17:47:39 +0000599Action::OwningExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000600Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000601 bool ArrayForm, ExprArg Operand)
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000602{
603 // C++ 5.3.5p1: "The operand shall have a pointer type, or a class type
604 // having a single conversion function to a pointer type. The result has
605 // type void."
606 // DR599 amends "pointer type" to "pointer to object type" in both cases.
607
Sebastian Redlf53597f2009-03-15 17:47:39 +0000608 Expr *Ex = (Expr *)Operand.get();
Sebastian Redl28507842009-02-26 14:39:58 +0000609 if (!Ex->isTypeDependent()) {
610 QualType Type = Ex->getType();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000611
Sebastian Redl28507842009-02-26 14:39:58 +0000612 if (Type->isRecordType()) {
613 // FIXME: Find that one conversion function and amend the type.
614 }
615
Sebastian Redlf53597f2009-03-15 17:47:39 +0000616 if (!Type->isPointerType())
617 return ExprError(Diag(StartLoc, diag::err_delete_operand)
618 << Type << Ex->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +0000619
620 QualType Pointee = Type->getAsPointerType()->getPointeeType();
Douglas Gregor8dcb29d2009-03-24 20:13:58 +0000621 if (Pointee->isFunctionType() || Pointee->isVoidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000622 return ExprError(Diag(StartLoc, diag::err_delete_operand)
623 << Type << Ex->getSourceRange());
Douglas Gregor8dcb29d2009-03-24 20:13:58 +0000624 else if (!Pointee->isDependentType() &&
625 RequireCompleteType(StartLoc, Pointee,
626 diag::warn_delete_incomplete,
627 Ex->getSourceRange()))
628 return ExprError();
Sebastian Redl28507842009-02-26 14:39:58 +0000629
630 // FIXME: Look up the correct operator delete overload and pass a pointer
631 // along.
632 // FIXME: Check access and ambiguity of operator delete and destructor.
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000633 }
634
Sebastian Redlf53597f2009-03-15 17:47:39 +0000635 Operand.release();
636 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
637 0, Ex, StartLoc));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000638}
639
640
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000641/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
642/// C++ if/switch/while/for statement.
643/// e.g: "if (int x = f()) {...}"
Sebastian Redlf53597f2009-03-15 17:47:39 +0000644Action::OwningExprResult
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000645Sema::ActOnCXXConditionDeclarationExpr(Scope *S, SourceLocation StartLoc,
646 Declarator &D,
647 SourceLocation EqualLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000648 ExprArg AssignExprVal) {
649 assert(AssignExprVal.get() && "Null assignment expression");
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000650
651 // C++ 6.4p2:
652 // The declarator shall not specify a function or an array.
653 // The type-specifier-seq shall not contain typedef and shall not declare a
654 // new class or enumeration.
655
656 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
657 "Parser allowed 'typedef' as storage class of condition decl.");
658
659 QualType Ty = GetTypeForDeclarator(D, S);
660
661 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
662 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
663 // would be created and CXXConditionDeclExpr wants a VarDecl.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000664 return ExprError(Diag(StartLoc, diag::err_invalid_use_of_function_type)
665 << SourceRange(StartLoc, EqualLoc));
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000666 } else if (Ty->isArrayType()) { // ...or an array.
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000667 Diag(StartLoc, diag::err_invalid_use_of_array_type)
668 << SourceRange(StartLoc, EqualLoc);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000669 } else if (const RecordType *RT = Ty->getAsRecordType()) {
670 RecordDecl *RD = RT->getDecl();
671 // The type-specifier-seq shall not declare a new class...
Chris Lattnerb28317a2009-03-28 19:18:32 +0000672 if (RD->isDefinition() &&
673 (RD->getIdentifier() == 0 || S->isDeclScope(DeclPtrTy::make(RD))))
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000674 Diag(RD->getLocation(), diag::err_type_defined_in_condition);
675 } else if (const EnumType *ET = Ty->getAsEnumType()) {
676 EnumDecl *ED = ET->getDecl();
677 // ...or enumeration.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000678 if (ED->isDefinition() &&
679 (ED->getIdentifier() == 0 || S->isDeclScope(DeclPtrTy::make(ED))))
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000680 Diag(ED->getLocation(), diag::err_type_defined_in_condition);
681 }
682
Chris Lattnerb28317a2009-03-28 19:18:32 +0000683 DeclPtrTy Dcl = ActOnDeclarator(S, D, DeclPtrTy());
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000684 if (!Dcl)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000685 return ExprError();
686 AddInitializerToDecl(Dcl, move(AssignExprVal));
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000687
Douglas Gregorcaaf29a2008-12-10 23:01:14 +0000688 // Mark this variable as one that is declared within a conditional.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000689 // We know that the decl had to be a VarDecl because that is the only type of
690 // decl that can be assigned and the grammar requires an '='.
691 VarDecl *VD = cast<VarDecl>(Dcl.getAs<Decl>());
692 VD->setDeclaredInCondition(true);
693 return Owned(new (Context) CXXConditionDeclExpr(StartLoc, EqualLoc, VD));
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000694}
695
696/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
697bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
698 // C++ 6.4p4:
699 // The value of a condition that is an initialized declaration in a statement
700 // other than a switch statement is the value of the declared variable
701 // implicitly converted to type bool. If that conversion is ill-formed, the
702 // program is ill-formed.
703 // The value of a condition that is an expression is the value of the
704 // expression, implicitly converted to bool.
705 //
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000706 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000707}
Douglas Gregor77a52232008-09-12 00:47:35 +0000708
709/// Helper function to determine whether this is the (deprecated) C++
710/// conversion from a string literal to a pointer to non-const char or
711/// non-const wchar_t (for narrow and wide string literals,
712/// respectively).
713bool
714Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
715 // Look inside the implicit cast, if it exists.
716 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
717 From = Cast->getSubExpr();
718
719 // A string literal (2.13.4) that is not a wide string literal can
720 // be converted to an rvalue of type "pointer to char"; a wide
721 // string literal can be converted to an rvalue of type "pointer
722 // to wchar_t" (C++ 4.2p2).
723 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From))
724 if (const PointerType *ToPtrType = ToType->getAsPointerType())
725 if (const BuiltinType *ToPointeeType
726 = ToPtrType->getPointeeType()->getAsBuiltinType()) {
727 // This conversion is considered only when there is an
728 // explicit appropriate pointer target type (C++ 4.2p2).
729 if (ToPtrType->getPointeeType().getCVRQualifiers() == 0 &&
730 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
731 (!StrLit->isWide() &&
732 (ToPointeeType->getKind() == BuiltinType::Char_U ||
733 ToPointeeType->getKind() == BuiltinType::Char_S))))
734 return true;
735 }
736
737 return false;
738}
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000739
740/// PerformImplicitConversion - Perform an implicit conversion of the
741/// expression From to the type ToType. Returns true if there was an
742/// error, false otherwise. The expression From is replaced with the
Douglas Gregor45920e82008-12-19 17:40:08 +0000743/// converted expression. Flavor is the kind of conversion we're
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000744/// performing, used in the error message. If @p AllowExplicit,
Sebastian Redle2b68332009-04-12 17:16:29 +0000745/// explicit user-defined conversions are permitted. @p Elidable should be true
746/// when called for copies which may be elided (C++ 12.8p15). C++0x overload
747/// resolution works differently in that case.
748bool
Douglas Gregor45920e82008-12-19 17:40:08 +0000749Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Sebastian Redle2b68332009-04-12 17:16:29 +0000750 const char *Flavor, bool AllowExplicit,
751 bool Elidable)
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000752{
Sebastian Redle2b68332009-04-12 17:16:29 +0000753 ImplicitConversionSequence ICS;
754 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
755 if (Elidable && getLangOptions().CPlusPlus0x) {
756 ICS = TryImplicitConversion(From, ToType, /*SuppressUserConversions*/false,
757 AllowExplicit, /*ForceRValue*/true);
758 }
759 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion) {
760 ICS = TryImplicitConversion(From, ToType, false, AllowExplicit);
761 }
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000762 return PerformImplicitConversion(From, ToType, ICS, Flavor);
763}
764
765/// PerformImplicitConversion - Perform an implicit conversion of the
766/// expression From to the type ToType using the pre-computed implicit
767/// conversion sequence ICS. Returns true if there was an error, false
768/// otherwise. The expression From is replaced with the converted
769/// expression. Flavor is the kind of conversion we're performing,
770/// used in the error message.
771bool
772Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
773 const ImplicitConversionSequence &ICS,
774 const char* Flavor) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000775 switch (ICS.ConversionKind) {
776 case ImplicitConversionSequence::StandardConversion:
Douglas Gregor45920e82008-12-19 17:40:08 +0000777 if (PerformImplicitConversion(From, ToType, ICS.Standard, Flavor))
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000778 return true;
779 break;
780
781 case ImplicitConversionSequence::UserDefinedConversion:
782 // FIXME: This is, of course, wrong. We'll need to actually call
783 // the constructor or conversion operator, and then cope with the
784 // standard conversions.
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000785 ImpCastExprToType(From, ToType.getNonReferenceType(),
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000786 ToType->isLValueReferenceType());
Douglas Gregor60d62c22008-10-31 16:23:19 +0000787 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000788
789 case ImplicitConversionSequence::EllipsisConversion:
790 assert(false && "Cannot perform an ellipsis conversion");
Douglas Gregor60d62c22008-10-31 16:23:19 +0000791 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000792
793 case ImplicitConversionSequence::BadConversion:
794 return true;
795 }
796
797 // Everything went well.
798 return false;
799}
800
801/// PerformImplicitConversion - Perform an implicit conversion of the
802/// expression From to the type ToType by following the standard
803/// conversion sequence SCS. Returns true if there was an error, false
804/// otherwise. The expression From is replaced with the converted
Douglas Gregor45920e82008-12-19 17:40:08 +0000805/// expression. Flavor is the context in which we're performing this
806/// conversion, for use in error messages.
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000807bool
808Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor45920e82008-12-19 17:40:08 +0000809 const StandardConversionSequence& SCS,
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000810 const char *Flavor) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000811 // Overall FIXME: we are recomputing too many types here and doing
812 // far too much extra work. What this means is that we need to keep
813 // track of more information that is computed when we try the
814 // implicit conversion initially, so that we don't need to recompute
815 // anything here.
816 QualType FromType = From->getType();
817
Douglas Gregor225c41e2008-11-03 19:09:14 +0000818 if (SCS.CopyConstructor) {
819 // FIXME: Create a temporary object by calling the copy
820 // constructor.
Douglas Gregor66b947f2009-01-16 19:38:23 +0000821 ImpCastExprToType(From, ToType.getNonReferenceType(),
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000822 ToType->isLValueReferenceType());
Douglas Gregor225c41e2008-11-03 19:09:14 +0000823 return false;
824 }
825
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000826 // Perform the first implicit conversion.
827 switch (SCS.First) {
828 case ICK_Identity:
829 case ICK_Lvalue_To_Rvalue:
830 // Nothing to do.
831 break;
832
833 case ICK_Array_To_Pointer:
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000834 FromType = Context.getArrayDecayedType(FromType);
835 ImpCastExprToType(From, FromType);
836 break;
837
838 case ICK_Function_To_Pointer:
Douglas Gregor063daf62009-03-13 18:40:31 +0000839 if (Context.getCanonicalType(FromType) == Context.OverloadTy) {
Douglas Gregor904eed32008-11-10 20:40:00 +0000840 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, true);
841 if (!Fn)
842 return true;
843
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000844 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
845 return true;
846
Douglas Gregor904eed32008-11-10 20:40:00 +0000847 FixOverloadedFunctionReference(From, Fn);
848 FromType = From->getType();
Douglas Gregor904eed32008-11-10 20:40:00 +0000849 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000850 FromType = Context.getPointerType(FromType);
851 ImpCastExprToType(From, FromType);
852 break;
853
854 default:
855 assert(false && "Improper first standard conversion");
856 break;
857 }
858
859 // Perform the second implicit conversion
860 switch (SCS.Second) {
861 case ICK_Identity:
862 // Nothing to do.
863 break;
864
865 case ICK_Integral_Promotion:
866 case ICK_Floating_Promotion:
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000867 case ICK_Complex_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000868 case ICK_Integral_Conversion:
869 case ICK_Floating_Conversion:
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000870 case ICK_Complex_Conversion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000871 case ICK_Floating_Integral:
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000872 case ICK_Complex_Real:
Douglas Gregorf9201e02009-02-11 23:02:49 +0000873 case ICK_Compatible_Conversion:
874 // FIXME: Go deeper to get the unqualified type!
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000875 FromType = ToType.getUnqualifiedType();
876 ImpCastExprToType(From, FromType);
877 break;
878
879 case ICK_Pointer_Conversion:
Douglas Gregor45920e82008-12-19 17:40:08 +0000880 if (SCS.IncompatibleObjC) {
881 // Diagnose incompatible Objective-C conversions
882 Diag(From->getSourceRange().getBegin(),
883 diag::ext_typecheck_convert_incompatible_pointer)
884 << From->getType() << ToType << Flavor
885 << From->getSourceRange();
886 }
887
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000888 if (CheckPointerConversion(From, ToType))
889 return true;
890 ImpCastExprToType(From, ToType);
891 break;
892
893 case ICK_Pointer_Member:
Sebastian Redl4433aaf2009-01-25 19:43:20 +0000894 if (CheckMemberPointerConversion(From, ToType))
895 return true;
896 ImpCastExprToType(From, ToType);
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000897 break;
898
899 case ICK_Boolean_Conversion:
900 FromType = Context.BoolTy;
901 ImpCastExprToType(From, FromType);
902 break;
903
904 default:
905 assert(false && "Improper second standard conversion");
906 break;
907 }
908
909 switch (SCS.Third) {
910 case ICK_Identity:
911 // Nothing to do.
912 break;
913
914 case ICK_Qualification:
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000915 // FIXME: Not sure about lvalue vs rvalue here in the presence of
916 // rvalue references.
Douglas Gregor66b947f2009-01-16 19:38:23 +0000917 ImpCastExprToType(From, ToType.getNonReferenceType(),
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000918 ToType->isLValueReferenceType());
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000919 break;
920
921 default:
922 assert(false && "Improper second standard conversion");
923 break;
924 }
925
926 return false;
927}
928
Sebastian Redl64b45f72009-01-05 20:52:13 +0000929Sema::OwningExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
930 SourceLocation KWLoc,
931 SourceLocation LParen,
932 TypeTy *Ty,
933 SourceLocation RParen) {
934 // FIXME: Some of the type traits have requirements. Interestingly, only the
935 // __is_base_of requirement is explicitly stated to be diagnosed. Indeed,
936 // G++ accepts __is_pod(Incomplete) without complaints, and claims that the
937 // type is indeed a POD.
938
939 // There is no point in eagerly computing the value. The traits are designed
940 // to be used from type trait templates, so Ty will be a template parameter
941 // 99% of the time.
Ted Kremenek8189cde2009-02-07 01:47:29 +0000942 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT,
Sebastian Redl64b45f72009-01-05 20:52:13 +0000943 QualType::getFromOpaquePtr(Ty),
944 RParen, Context.BoolTy));
945}
Sebastian Redl7c8bd602009-02-07 20:10:22 +0000946
947QualType Sema::CheckPointerToMemberOperands(
948 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect)
949{
950 const char *OpSpelling = isIndirect ? "->*" : ".*";
951 // C++ 5.5p2
952 // The binary operator .* [p3: ->*] binds its second operand, which shall
953 // be of type "pointer to member of T" (where T is a completely-defined
954 // class type) [...]
955 QualType RType = rex->getType();
956 const MemberPointerType *MemPtr = RType->getAsMemberPointerType();
Douglas Gregore7450f52009-03-24 19:52:54 +0000957 if (!MemPtr) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +0000958 Diag(Loc, diag::err_bad_memptr_rhs)
959 << OpSpelling << RType << rex->getSourceRange();
960 return QualType();
Douglas Gregore7450f52009-03-24 19:52:54 +0000961 } else if (RequireCompleteType(Loc, QualType(MemPtr->getClass(), 0),
962 diag::err_memptr_rhs_incomplete,
963 rex->getSourceRange()))
964 return QualType();
965
Sebastian Redl7c8bd602009-02-07 20:10:22 +0000966 QualType Class(MemPtr->getClass(), 0);
967
968 // C++ 5.5p2
969 // [...] to its first operand, which shall be of class T or of a class of
970 // which T is an unambiguous and accessible base class. [p3: a pointer to
971 // such a class]
972 QualType LType = lex->getType();
973 if (isIndirect) {
974 if (const PointerType *Ptr = LType->getAsPointerType())
975 LType = Ptr->getPointeeType().getNonReferenceType();
976 else {
977 Diag(Loc, diag::err_bad_memptr_lhs)
978 << OpSpelling << 1 << LType << lex->getSourceRange();
979 return QualType();
980 }
981 }
982
983 if (Context.getCanonicalType(Class).getUnqualifiedType() !=
984 Context.getCanonicalType(LType).getUnqualifiedType()) {
985 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
986 /*DetectVirtual=*/false);
987 // FIXME: Would it be useful to print full ambiguity paths,
988 // or is that overkill?
989 if (!IsDerivedFrom(LType, Class, Paths) ||
990 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
991 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
992 << (int)isIndirect << lex->getType() << lex->getSourceRange();
993 return QualType();
994 }
995 }
996
997 // C++ 5.5p2
998 // The result is an object or a function of the type specified by the
999 // second operand.
1000 // The cv qualifiers are the union of those in the pointer and the left side,
1001 // in accordance with 5.5p5 and 5.2.5.
1002 // FIXME: This returns a dereferenced member function pointer as a normal
1003 // function type. However, the only operation valid on such functions is
1004 // calling them. There's also a GCC extension to get a function pointer to
1005 // the thing, which is another complication, because this type - unlike the
1006 // type that is the result of this expression - takes the class as the first
1007 // argument.
1008 // We probably need a "MemberFunctionClosureType" or something like that.
1009 QualType Result = MemPtr->getPointeeType();
1010 if (LType.isConstQualified())
1011 Result.addConst();
1012 if (LType.isVolatileQualified())
1013 Result.addVolatile();
1014 return Result;
1015}
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001016
1017/// \brief Get the target type of a standard or user-defined conversion.
1018static QualType TargetType(const ImplicitConversionSequence &ICS) {
1019 assert((ICS.ConversionKind ==
1020 ImplicitConversionSequence::StandardConversion ||
1021 ICS.ConversionKind ==
1022 ImplicitConversionSequence::UserDefinedConversion) &&
1023 "function only valid for standard or user-defined conversions");
1024 if (ICS.ConversionKind == ImplicitConversionSequence::StandardConversion)
1025 return QualType::getFromOpaquePtr(ICS.Standard.ToTypePtr);
1026 return QualType::getFromOpaquePtr(ICS.UserDefined.After.ToTypePtr);
1027}
1028
1029/// \brief Try to convert a type to another according to C++0x 5.16p3.
1030///
1031/// This is part of the parameter validation for the ? operator. If either
1032/// value operand is a class type, the two operands are attempted to be
1033/// converted to each other. This function does the conversion in one direction.
1034/// It emits a diagnostic and returns true only if it finds an ambiguous
1035/// conversion.
1036static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
1037 SourceLocation QuestionLoc,
1038 ImplicitConversionSequence &ICS)
1039{
1040 // C++0x 5.16p3
1041 // The process for determining whether an operand expression E1 of type T1
1042 // can be converted to match an operand expression E2 of type T2 is defined
1043 // as follows:
1044 // -- If E2 is an lvalue:
1045 if (To->isLvalue(Self.Context) == Expr::LV_Valid) {
1046 // E1 can be converted to match E2 if E1 can be implicitly converted to
1047 // type "lvalue reference to T2", subject to the constraint that in the
1048 // conversion the reference must bind directly to E1.
1049 if (!Self.CheckReferenceInit(From,
1050 Self.Context.getLValueReferenceType(To->getType()),
1051 &ICS))
1052 {
1053 assert((ICS.ConversionKind ==
1054 ImplicitConversionSequence::StandardConversion ||
1055 ICS.ConversionKind ==
1056 ImplicitConversionSequence::UserDefinedConversion) &&
1057 "expected a definite conversion");
1058 bool DirectBinding =
1059 ICS.ConversionKind == ImplicitConversionSequence::StandardConversion ?
1060 ICS.Standard.DirectBinding : ICS.UserDefined.After.DirectBinding;
1061 if (DirectBinding)
1062 return false;
1063 }
1064 }
1065 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1066 // -- If E2 is an rvalue, or if the conversion above cannot be done:
1067 // -- if E1 and E2 have class type, and the underlying class types are
1068 // the same or one is a base class of the other:
1069 QualType FTy = From->getType();
1070 QualType TTy = To->getType();
1071 const RecordType *FRec = FTy->getAsRecordType();
1072 const RecordType *TRec = TTy->getAsRecordType();
1073 bool FDerivedFromT = FRec && TRec && Self.IsDerivedFrom(FTy, TTy);
1074 if (FRec && TRec && (FRec == TRec ||
1075 FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
1076 // E1 can be converted to match E2 if the class of T2 is the
1077 // same type as, or a base class of, the class of T1, and
1078 // [cv2 > cv1].
1079 if ((FRec == TRec || FDerivedFromT) && TTy.isAtLeastAsQualifiedAs(FTy)) {
1080 // Could still fail if there's no copy constructor.
1081 // FIXME: Is this a hard error then, or just a conversion failure? The
1082 // standard doesn't say.
1083 ICS = Self.TryCopyInitialization(From, TTy);
1084 }
1085 } else {
1086 // -- Otherwise: E1 can be converted to match E2 if E1 can be
1087 // implicitly converted to the type that expression E2 would have
1088 // if E2 were converted to an rvalue.
1089 // First find the decayed type.
1090 if (TTy->isFunctionType())
1091 TTy = Self.Context.getPointerType(TTy);
1092 else if(TTy->isArrayType())
1093 TTy = Self.Context.getArrayDecayedType(TTy);
1094
1095 // Now try the implicit conversion.
1096 // FIXME: This doesn't detect ambiguities.
1097 ICS = Self.TryImplicitConversion(From, TTy);
1098 }
1099 return false;
1100}
1101
1102/// \brief Try to find a common type for two according to C++0x 5.16p5.
1103///
1104/// This is part of the parameter validation for the ? operator. If either
1105/// value operand is a class type, overload resolution is used to find a
1106/// conversion to a common type.
1107static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
1108 SourceLocation Loc) {
1109 Expr *Args[2] = { LHS, RHS };
1110 OverloadCandidateSet CandidateSet;
1111 Self.AddBuiltinOperatorCandidates(OO_Conditional, Args, 2, CandidateSet);
1112
1113 OverloadCandidateSet::iterator Best;
1114 switch (Self.BestViableFunction(CandidateSet, Best)) {
1115 case Sema::OR_Success:
1116 // We found a match. Perform the conversions on the arguments and move on.
1117 if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
1118 Best->Conversions[0], "converting") ||
1119 Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
1120 Best->Conversions[1], "converting"))
1121 break;
1122 return false;
1123
1124 case Sema::OR_No_Viable_Function:
1125 Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
1126 << LHS->getType() << RHS->getType()
1127 << LHS->getSourceRange() << RHS->getSourceRange();
1128 return true;
1129
1130 case Sema::OR_Ambiguous:
1131 Self.Diag(Loc, diag::err_conditional_ambiguous_ovl)
1132 << LHS->getType() << RHS->getType()
1133 << LHS->getSourceRange() << RHS->getSourceRange();
1134 // FIXME: Print the possible common types by printing the return types
1135 // of the viable candidates.
1136 break;
1137
1138 case Sema::OR_Deleted:
1139 assert(false && "Conditional operator has only built-in overloads");
1140 break;
1141 }
1142 return true;
1143}
1144
Sebastian Redl76458502009-04-17 16:30:52 +00001145/// \brief Perform an "extended" implicit conversion as returned by
1146/// TryClassUnification.
1147///
1148/// TryClassUnification generates ICSs that include reference bindings.
1149/// PerformImplicitConversion is not suitable for this; it chokes if the
1150/// second part of a standard conversion is ICK_DerivedToBase. This function
1151/// handles the reference binding specially.
1152static bool ConvertForConditional(Sema &Self, Expr *&E,
1153 const ImplicitConversionSequence &ICS)
1154{
1155 if (ICS.ConversionKind == ImplicitConversionSequence::StandardConversion &&
1156 ICS.Standard.ReferenceBinding) {
1157 assert(ICS.Standard.DirectBinding &&
1158 "TryClassUnification should never generate indirect ref bindings");
Sebastian Redl78eb8742009-04-19 21:53:20 +00001159 // FIXME: Should use CheckReferenceInit here, but we no longer have a
1160 // reference type.
Sebastian Redl76458502009-04-17 16:30:52 +00001161 Self.ImpCastExprToType(E, TargetType(ICS), true);
1162 return false;
1163 }
1164 if (ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion &&
1165 ICS.UserDefined.After.ReferenceBinding) {
1166 assert(ICS.UserDefined.After.DirectBinding &&
1167 "TryClassUnification should never generate indirect ref bindings");
1168 Self.ImpCastExprToType(E, TargetType(ICS), true);
1169 return false;
1170 }
1171 if (Self.PerformImplicitConversion(E, TargetType(ICS), ICS, "converting"))
1172 return true;
1173 return false;
1174}
1175
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001176/// \brief Check the operands of ?: under C++ semantics.
1177///
1178/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
1179/// extension. In this case, LHS == Cond. (But they're not aliases.)
1180QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
1181 SourceLocation QuestionLoc) {
1182 // FIXME: Handle C99's complex types, vector types, block pointers and
1183 // Obj-C++ interface pointers.
1184
1185 // C++0x 5.16p1
1186 // The first expression is contextually converted to bool.
1187 if (!Cond->isTypeDependent()) {
1188 if (CheckCXXBooleanCondition(Cond))
1189 return QualType();
1190 }
1191
1192 // Either of the arguments dependent?
1193 if (LHS->isTypeDependent() || RHS->isTypeDependent())
1194 return Context.DependentTy;
1195
1196 // C++0x 5.16p2
1197 // If either the second or the third operand has type (cv) void, ...
1198 QualType LTy = LHS->getType();
1199 QualType RTy = RHS->getType();
1200 bool LVoid = LTy->isVoidType();
1201 bool RVoid = RTy->isVoidType();
1202 if (LVoid || RVoid) {
1203 // ... then the [l2r] conversions are performed on the second and third
1204 // operands ...
1205 DefaultFunctionArrayConversion(LHS);
1206 DefaultFunctionArrayConversion(RHS);
1207 LTy = LHS->getType();
1208 RTy = RHS->getType();
1209
1210 // ... and one of the following shall hold:
1211 // -- The second or the third operand (but not both) is a throw-
1212 // expression; the result is of the type of the other and is an rvalue.
1213 bool LThrow = isa<CXXThrowExpr>(LHS);
1214 bool RThrow = isa<CXXThrowExpr>(RHS);
1215 if (LThrow && !RThrow)
1216 return RTy;
1217 if (RThrow && !LThrow)
1218 return LTy;
1219
1220 // -- Both the second and third operands have type void; the result is of
1221 // type void and is an rvalue.
1222 if (LVoid && RVoid)
1223 return Context.VoidTy;
1224
1225 // Neither holds, error.
1226 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
1227 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
1228 << LHS->getSourceRange() << RHS->getSourceRange();
1229 return QualType();
1230 }
1231
1232 // Neither is void.
1233
1234 // C++0x 5.16p3
1235 // Otherwise, if the second and third operand have different types, and
1236 // either has (cv) class type, and attempt is made to convert each of those
1237 // operands to the other.
1238 if (Context.getCanonicalType(LTy) != Context.getCanonicalType(RTy) &&
1239 (LTy->isRecordType() || RTy->isRecordType())) {
1240 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
1241 // These return true if a single direction is already ambiguous.
1242 if (TryClassUnification(*this, LHS, RHS, QuestionLoc, ICSLeftToRight))
1243 return QualType();
1244 if (TryClassUnification(*this, RHS, LHS, QuestionLoc, ICSRightToLeft))
1245 return QualType();
1246
1247 bool HaveL2R = ICSLeftToRight.ConversionKind !=
1248 ImplicitConversionSequence::BadConversion;
1249 bool HaveR2L = ICSRightToLeft.ConversionKind !=
1250 ImplicitConversionSequence::BadConversion;
1251 // If both can be converted, [...] the program is ill-formed.
1252 if (HaveL2R && HaveR2L) {
1253 Diag(QuestionLoc, diag::err_conditional_ambiguous)
1254 << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
1255 return QualType();
1256 }
1257
1258 // If exactly one conversion is possible, that conversion is applied to
1259 // the chosen operand and the converted operands are used in place of the
1260 // original operands for the remainder of this section.
1261 if (HaveL2R) {
Sebastian Redl76458502009-04-17 16:30:52 +00001262 if (ConvertForConditional(*this, LHS, ICSLeftToRight))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001263 return QualType();
1264 LTy = LHS->getType();
1265 } else if (HaveR2L) {
Sebastian Redl76458502009-04-17 16:30:52 +00001266 if (ConvertForConditional(*this, RHS, ICSRightToLeft))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001267 return QualType();
1268 RTy = RHS->getType();
1269 }
1270 }
1271
1272 // C++0x 5.16p4
1273 // If the second and third operands are lvalues and have the same type,
1274 // the result is of that type [...]
1275 bool Same = Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy);
1276 if (Same && LHS->isLvalue(Context) == Expr::LV_Valid &&
1277 RHS->isLvalue(Context) == Expr::LV_Valid)
1278 return LTy;
1279
1280 // C++0x 5.16p5
1281 // Otherwise, the result is an rvalue. If the second and third operands
1282 // do not have the same type, and either has (cv) class type, ...
1283 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
1284 // ... overload resolution is used to determine the conversions (if any)
1285 // to be applied to the operands. If the overload resolution fails, the
1286 // program is ill-formed.
1287 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
1288 return QualType();
1289 }
1290
1291 // C++0x 5.16p6
1292 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
1293 // conversions are performed on the second and third operands.
1294 DefaultFunctionArrayConversion(LHS);
1295 DefaultFunctionArrayConversion(RHS);
1296 LTy = LHS->getType();
1297 RTy = RHS->getType();
1298
1299 // After those conversions, one of the following shall hold:
1300 // -- The second and third operands have the same type; the result
1301 // is of that type.
1302 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy))
1303 return LTy;
1304
1305 // -- The second and third operands have arithmetic or enumeration type;
1306 // the usual arithmetic conversions are performed to bring them to a
1307 // common type, and the result is of that type.
1308 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
1309 UsualArithmeticConversions(LHS, RHS);
1310 return LHS->getType();
1311 }
1312
1313 // -- The second and third operands have pointer type, or one has pointer
1314 // type and the other is a null pointer constant; pointer conversions
1315 // and qualification conversions are performed to bring them to their
1316 // composite pointer type. The result is of the composite pointer type.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001317 QualType Composite = FindCompositePointerType(LHS, RHS);
1318 if (!Composite.isNull())
1319 return Composite;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001320
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001321 // Fourth bullet is same for pointers-to-member. However, the possible
1322 // conversions are far more limited: we have null-to-pointer, upcast of
1323 // containing class, and second-level cv-ness.
1324 // cv-ness is not a union, but must match one of the two operands. (Which,
1325 // frankly, is stupid.)
1326 const MemberPointerType *LMemPtr = LTy->getAsMemberPointerType();
1327 const MemberPointerType *RMemPtr = RTy->getAsMemberPointerType();
1328 if (LMemPtr && RHS->isNullPointerConstant(Context)) {
1329 ImpCastExprToType(RHS, LTy);
1330 return LTy;
1331 }
1332 if (RMemPtr && LHS->isNullPointerConstant(Context)) {
1333 ImpCastExprToType(LHS, RTy);
1334 return RTy;
1335 }
1336 if (LMemPtr && RMemPtr) {
1337 QualType LPointee = LMemPtr->getPointeeType();
1338 QualType RPointee = RMemPtr->getPointeeType();
1339 // First, we check that the unqualified pointee type is the same. If it's
1340 // not, there's no conversion that will unify the two pointers.
1341 if (Context.getCanonicalType(LPointee).getUnqualifiedType() ==
1342 Context.getCanonicalType(RPointee).getUnqualifiedType()) {
1343 // Second, we take the greater of the two cv qualifications. If neither
1344 // is greater than the other, the conversion is not possible.
1345 unsigned Q = LPointee.getCVRQualifiers() | RPointee.getCVRQualifiers();
1346 if (Q == LPointee.getCVRQualifiers() || Q == RPointee.getCVRQualifiers()){
1347 // Third, we check if either of the container classes is derived from
1348 // the other.
1349 QualType LContainer(LMemPtr->getClass(), 0);
1350 QualType RContainer(RMemPtr->getClass(), 0);
1351 QualType MoreDerived;
1352 if (Context.getCanonicalType(LContainer) ==
1353 Context.getCanonicalType(RContainer))
1354 MoreDerived = LContainer;
1355 else if (IsDerivedFrom(LContainer, RContainer))
1356 MoreDerived = LContainer;
1357 else if (IsDerivedFrom(RContainer, LContainer))
1358 MoreDerived = RContainer;
1359
1360 if (!MoreDerived.isNull()) {
1361 // The type 'Q Pointee (MoreDerived::*)' is the common type.
1362 // We don't use ImpCastExprToType here because this could still fail
1363 // for ambiguous or inaccessible conversions.
1364 QualType Common = Context.getMemberPointerType(
1365 LPointee.getQualifiedType(Q), MoreDerived.getTypePtr());
1366 if (PerformImplicitConversion(LHS, Common, "converting"))
1367 return QualType();
1368 if (PerformImplicitConversion(RHS, Common, "converting"))
1369 return QualType();
1370 return Common;
1371 }
1372 }
1373 }
1374 }
1375
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001376 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
1377 << LHS->getType() << RHS->getType()
1378 << LHS->getSourceRange() << RHS->getSourceRange();
1379 return QualType();
1380}
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001381
1382/// \brief Find a merged pointer type and convert the two expressions to it.
1383///
1384/// This finds the composite pointer type for @p E1 and @p E2 according to
1385/// C++0x 5.9p2. It converts both expressions to this type and returns it.
1386/// It does not emit diagnostics.
1387QualType Sema::FindCompositePointerType(Expr *&E1, Expr *&E2) {
1388 assert(getLangOptions().CPlusPlus && "This function assumes C++");
1389 QualType T1 = E1->getType(), T2 = E2->getType();
1390 if(!T1->isPointerType() && !T2->isPointerType())
1391 return QualType();
1392
1393 // C++0x 5.9p2
1394 // Pointer conversions and qualification conversions are performed on
1395 // pointer operands to bring them to their composite pointer type. If
1396 // one operand is a null pointer constant, the composite pointer type is
1397 // the type of the other operand.
1398 if (E1->isNullPointerConstant(Context)) {
1399 ImpCastExprToType(E1, T2);
1400 return T2;
1401 }
1402 if (E2->isNullPointerConstant(Context)) {
1403 ImpCastExprToType(E2, T1);
1404 return T1;
1405 }
1406 // Now both have to be pointers.
1407 if(!T1->isPointerType() || !T2->isPointerType())
1408 return QualType();
1409
1410 // Otherwise, of one of the operands has type "pointer to cv1 void," then
1411 // the other has type "pointer to cv2 T" and the composite pointer type is
1412 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
1413 // Otherwise, the composite pointer type is a pointer type similar to the
1414 // type of one of the operands, with a cv-qualification signature that is
1415 // the union of the cv-qualification signatures of the operand types.
1416 // In practice, the first part here is redundant; it's subsumed by the second.
1417 // What we do here is, we build the two possible composite types, and try the
1418 // conversions in both directions. If only one works, or if the two composite
1419 // types are the same, we have succeeded.
1420 llvm::SmallVector<unsigned, 4> QualifierUnion;
1421 QualType Composite1 = T1, Composite2 = T2;
1422 const PointerType *Ptr1, *Ptr2;
1423 while ((Ptr1 = Composite1->getAsPointerType()) &&
1424 (Ptr2 = Composite2->getAsPointerType())) {
1425 Composite1 = Ptr1->getPointeeType();
1426 Composite2 = Ptr2->getPointeeType();
1427 QualifierUnion.push_back(
1428 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
1429 }
1430 // Rewrap the composites as pointers with the union CVRs.
1431 for (llvm::SmallVector<unsigned, 4>::iterator I = QualifierUnion.begin(),
1432 E = QualifierUnion.end(); I != E; ++I) {
1433 Composite1 = Context.getPointerType(Composite1.getQualifiedType(*I));
1434 Composite2 = Context.getPointerType(Composite2.getQualifiedType(*I));
1435 }
1436
1437 ImplicitConversionSequence E1ToC1 = TryImplicitConversion(E1, Composite1);
1438 ImplicitConversionSequence E2ToC1 = TryImplicitConversion(E2, Composite1);
1439 ImplicitConversionSequence E1ToC2, E2ToC2;
1440 E1ToC2.ConversionKind = ImplicitConversionSequence::BadConversion;
1441 E2ToC2.ConversionKind = ImplicitConversionSequence::BadConversion;
1442 if (Context.getCanonicalType(Composite1) !=
1443 Context.getCanonicalType(Composite2)) {
1444 E1ToC2 = TryImplicitConversion(E1, Composite2);
1445 E2ToC2 = TryImplicitConversion(E2, Composite2);
1446 }
1447
1448 bool ToC1Viable = E1ToC1.ConversionKind !=
1449 ImplicitConversionSequence::BadConversion
1450 && E2ToC1.ConversionKind !=
1451 ImplicitConversionSequence::BadConversion;
1452 bool ToC2Viable = E1ToC2.ConversionKind !=
1453 ImplicitConversionSequence::BadConversion
1454 && E2ToC2.ConversionKind !=
1455 ImplicitConversionSequence::BadConversion;
1456 if (ToC1Viable && !ToC2Viable) {
1457 if (!PerformImplicitConversion(E1, Composite1, E1ToC1, "converting") &&
1458 !PerformImplicitConversion(E2, Composite1, E2ToC1, "converting"))
1459 return Composite1;
1460 }
1461 if (ToC2Viable && !ToC1Viable) {
1462 if (!PerformImplicitConversion(E1, Composite2, E1ToC2, "converting") &&
1463 !PerformImplicitConversion(E2, Composite2, E2ToC2, "converting"))
1464 return Composite2;
1465 }
1466 return QualType();
1467}