blob: a63ce1e598d0c3d28cca62e8ab79068fa1cc775c [file] [log] [blame]
Chris Lattner5b183d82006-11-10 05:03:26 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner5b183d82006-11-10 05:03:26 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
John McCall5cebab12009-11-18 07:57:50 +000015#include "Lookup.h"
Chris Lattnercb6a3822006-11-10 06:20:45 +000016#include "clang/AST/ASTContext.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000017#include "clang/AST/DeclObjC.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000018#include "clang/AST/DeclTemplate.h"
Chris Lattneraa9c7ae2008-04-08 04:40:51 +000019#include "clang/AST/ExprCXX.h"
Steve Naroff021ca182008-05-29 21:12:08 +000020#include "clang/AST/ExprObjC.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000021#include "clang/Basic/PartialDiagnostic.h"
Steve Narofff2fb89e2007-03-13 20:29:44 +000022#include "clang/Basic/SourceManager.h"
Chris Lattner5b183d82006-11-10 05:03:26 +000023#include "clang/Basic/TargetInfo.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000024#include "clang/Lex/LiteralSupport.h"
25#include "clang/Lex/Preprocessor.h"
Steve Naroffc540d662008-09-03 18:15:37 +000026#include "clang/Parse/DeclSpec.h"
Chris Lattner07d754a2008-10-26 23:43:26 +000027#include "clang/Parse/Designator.h"
Steve Naroffc540d662008-09-03 18:15:37 +000028#include "clang/Parse/Scope.h"
Douglas Gregorb53edfb2009-11-10 19:49:08 +000029#include "clang/Parse/Template.h"
Chris Lattner5b183d82006-11-10 05:03:26 +000030using namespace clang;
31
David Chisnall9f57c292009-08-17 16:35:33 +000032
Douglas Gregor171c45a2009-02-18 21:56:37 +000033/// \brief Determine whether the use of this declaration is valid, and
34/// emit any corresponding diagnostics.
35///
36/// This routine diagnoses various problems with referencing
37/// declarations that can occur when using a declaration. For example,
38/// it might warn if a deprecated or unavailable declaration is being
39/// used, or produce an error (and return true) if a C++0x deleted
40/// function is being used.
41///
Chris Lattnerb7df3c62009-10-25 22:31:57 +000042/// If IgnoreDeprecated is set to true, this should not want about deprecated
43/// decls.
44///
Douglas Gregor171c45a2009-02-18 21:56:37 +000045/// \returns true if there was an error (this declaration cannot be
46/// referenced), false otherwise.
Chris Lattnerb7df3c62009-10-25 22:31:57 +000047///
John McCall28a6aea2009-11-04 02:18:39 +000048bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc) {
Chris Lattner4bf74fd2009-02-15 22:43:40 +000049 // See if the decl is deprecated.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +000050 if (D->getAttr<DeprecatedAttr>()) {
John McCall28a6aea2009-11-04 02:18:39 +000051 EmitDeprecationWarning(D, Loc);
Chris Lattner4bf74fd2009-02-15 22:43:40 +000052 }
53
Chris Lattnera27dd592009-10-25 17:21:40 +000054 // See if the decl is unavailable
55 if (D->getAttr<UnavailableAttr>()) {
56 Diag(Loc, diag::warn_unavailable) << D->getDeclName();
57 Diag(D->getLocation(), diag::note_unavailable_here) << 0;
58 }
59
Douglas Gregor171c45a2009-02-18 21:56:37 +000060 // See if this is a deleted function.
Douglas Gregorde681d42009-02-24 04:26:15 +000061 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +000062 if (FD->isDeleted()) {
63 Diag(Loc, diag::err_deleted_function_use);
64 Diag(D->getLocation(), diag::note_unavailable_here) << true;
65 return true;
66 }
Douglas Gregorde681d42009-02-24 04:26:15 +000067 }
Douglas Gregor171c45a2009-02-18 21:56:37 +000068
Douglas Gregor171c45a2009-02-18 21:56:37 +000069 return false;
Chris Lattner4bf74fd2009-02-15 22:43:40 +000070}
71
Fariborz Jahanian027b8862009-05-13 18:09:35 +000072/// DiagnoseSentinelCalls - This routine checks on method dispatch calls
Mike Stump11289f42009-09-09 15:08:12 +000073/// (and other functions in future), which have been declared with sentinel
Fariborz Jahanian027b8862009-05-13 18:09:35 +000074/// attribute. It warns if call does not have the sentinel argument.
75///
76void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +000077 Expr **Args, unsigned NumArgs) {
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +000078 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Mike Stump11289f42009-09-09 15:08:12 +000079 if (!attr)
Fariborz Jahanian9e877212009-05-13 23:20:50 +000080 return;
Fariborz Jahanian9e877212009-05-13 23:20:50 +000081 int sentinelPos = attr->getSentinel();
82 int nullPos = attr->getNullPos();
Mike Stump11289f42009-09-09 15:08:12 +000083
Mike Stump87c57ac2009-05-16 07:39:55 +000084 // FIXME. ObjCMethodDecl and FunctionDecl need be derived from the same common
85 // base class. Then we won't be needing two versions of the same code.
Fariborz Jahanian9e877212009-05-13 23:20:50 +000086 unsigned int i = 0;
Fariborz Jahanian4a528032009-05-14 18:00:00 +000087 bool warnNotEnoughArgs = false;
88 int isMethod = 0;
89 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
90 // skip over named parameters.
91 ObjCMethodDecl::param_iterator P, E = MD->param_end();
92 for (P = MD->param_begin(); (P != E && i < NumArgs); ++P) {
93 if (nullPos)
94 --nullPos;
95 else
96 ++i;
97 }
98 warnNotEnoughArgs = (P != E || i >= NumArgs);
99 isMethod = 1;
Mike Stump12b8ce12009-08-04 21:02:39 +0000100 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000101 // skip over named parameters.
102 ObjCMethodDecl::param_iterator P, E = FD->param_end();
103 for (P = FD->param_begin(); (P != E && i < NumArgs); ++P) {
104 if (nullPos)
105 --nullPos;
106 else
107 ++i;
108 }
109 warnNotEnoughArgs = (P != E || i >= NumArgs);
Mike Stump12b8ce12009-08-04 21:02:39 +0000110 } else if (VarDecl *V = dyn_cast<VarDecl>(D)) {
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000111 // block or function pointer call.
112 QualType Ty = V->getType();
113 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +0000114 const FunctionType *FT = Ty->isFunctionPointerType()
John McCall9dd450b2009-09-21 23:43:11 +0000115 ? Ty->getAs<PointerType>()->getPointeeType()->getAs<FunctionType>()
116 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000117 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT)) {
118 unsigned NumArgsInProto = Proto->getNumArgs();
119 unsigned k;
120 for (k = 0; (k != NumArgsInProto && i < NumArgs); k++) {
121 if (nullPos)
122 --nullPos;
123 else
124 ++i;
125 }
126 warnNotEnoughArgs = (k != NumArgsInProto || i >= NumArgs);
127 }
128 if (Ty->isBlockPointerType())
129 isMethod = 2;
Mike Stump12b8ce12009-08-04 21:02:39 +0000130 } else
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000131 return;
Mike Stump12b8ce12009-08-04 21:02:39 +0000132 } else
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000133 return;
134
135 if (warnNotEnoughArgs) {
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000136 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000137 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000138 return;
139 }
140 int sentinel = i;
141 while (sentinelPos > 0 && i < NumArgs-1) {
142 --sentinelPos;
143 ++i;
144 }
145 if (sentinelPos > 0) {
146 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000147 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000148 return;
149 }
150 while (i < NumArgs-1) {
151 ++i;
152 ++sentinel;
153 }
154 Expr *sentinelExpr = Args[sentinel];
Anders Carlsson0b11a3e2009-11-24 17:24:21 +0000155 if (sentinelExpr && (!isa<GNUNullExpr>(sentinelExpr) &&
156 (!sentinelExpr->getType()->isPointerType() ||
157 !sentinelExpr->isNullPointerConstant(Context,
158 Expr::NPC_ValueDependentIsNull)))) {
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000159 Diag(Loc, diag::warn_missing_sentinel) << isMethod;
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000160 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000161 }
162 return;
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000163}
164
Douglas Gregor87f95b02009-02-26 21:00:50 +0000165SourceRange Sema::getExprRange(ExprTy *E) const {
166 Expr *Ex = (Expr *)E;
167 return Ex? Ex->getSourceRange() : SourceRange();
168}
169
Chris Lattner513165e2008-07-25 21:10:04 +0000170//===----------------------------------------------------------------------===//
171// Standard Promotions and Conversions
172//===----------------------------------------------------------------------===//
173
Chris Lattner513165e2008-07-25 21:10:04 +0000174/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
175void Sema::DefaultFunctionArrayConversion(Expr *&E) {
176 QualType Ty = E->getType();
177 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
178
Chris Lattner513165e2008-07-25 21:10:04 +0000179 if (Ty->isFunctionType())
Mike Stump11289f42009-09-09 15:08:12 +0000180 ImpCastExprToType(E, Context.getPointerType(Ty),
Anders Carlsson6904f642009-09-01 20:37:18 +0000181 CastExpr::CK_FunctionToPointerDecay);
Chris Lattner61f60a02008-07-25 21:33:13 +0000182 else if (Ty->isArrayType()) {
183 // In C90 mode, arrays only promote to pointers if the array expression is
184 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
185 // type 'array of type' is converted to an expression that has type 'pointer
186 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
187 // that has type 'array of type' ...". The relevant change is "an lvalue"
188 // (C90) to "an expression" (C99).
Argyrios Kyrtzidis9321c742008-09-11 04:25:59 +0000189 //
190 // C++ 4.2p1:
191 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
192 // T" can be converted to an rvalue of type "pointer to T".
193 //
194 if (getLangOptions().C99 || getLangOptions().CPlusPlus ||
195 E->isLvalue(Context) == Expr::LV_Valid)
Anders Carlsson8fc489d2009-08-07 23:48:20 +0000196 ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
197 CastExpr::CK_ArrayToPointerDecay);
Chris Lattner61f60a02008-07-25 21:33:13 +0000198 }
Chris Lattner513165e2008-07-25 21:10:04 +0000199}
200
201/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump11289f42009-09-09 15:08:12 +0000202/// operators (C99 6.3). The conversions of array and function types are
Chris Lattner513165e2008-07-25 21:10:04 +0000203/// sometimes surpressed. For example, the array->pointer conversion doesn't
204/// apply if the array is an argument to the sizeof or address (&) operators.
205/// In these instances, this routine should *not* be called.
206Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
207 QualType Ty = Expr->getType();
208 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
Mike Stump11289f42009-09-09 15:08:12 +0000209
Douglas Gregor8d9c5092009-05-01 20:41:21 +0000210 // C99 6.3.1.1p2:
211 //
212 // The following may be used in an expression wherever an int or
213 // unsigned int may be used:
214 // - an object or expression with an integer type whose integer
215 // conversion rank is less than or equal to the rank of int
216 // and unsigned int.
217 // - A bit-field of type _Bool, int, signed int, or unsigned int.
218 //
219 // If an int can represent all values of the original type, the
220 // value is converted to an int; otherwise, it is converted to an
221 // unsigned int. These are called the integer promotions. All
222 // other types are unchanged by the integer promotions.
Eli Friedman629ffb92009-08-20 04:21:42 +0000223 QualType PTy = Context.isPromotableBitField(Expr);
224 if (!PTy.isNull()) {
Eli Friedman06ed2a52009-10-20 08:27:19 +0000225 ImpCastExprToType(Expr, PTy, CastExpr::CK_IntegralCast);
Eli Friedman629ffb92009-08-20 04:21:42 +0000226 return Expr;
227 }
Douglas Gregor8d9c5092009-05-01 20:41:21 +0000228 if (Ty->isPromotableIntegerType()) {
Eli Friedman5ae98ee2009-08-19 07:44:53 +0000229 QualType PT = Context.getPromotedIntegerType(Ty);
Eli Friedman06ed2a52009-10-20 08:27:19 +0000230 ImpCastExprToType(Expr, PT, CastExpr::CK_IntegralCast);
Douglas Gregor8d9c5092009-05-01 20:41:21 +0000231 return Expr;
Eli Friedman629ffb92009-08-20 04:21:42 +0000232 }
233
Douglas Gregor8d9c5092009-05-01 20:41:21 +0000234 DefaultFunctionArrayConversion(Expr);
Chris Lattner513165e2008-07-25 21:10:04 +0000235 return Expr;
236}
237
Chris Lattner2ce500f2008-07-25 22:25:12 +0000238/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Mike Stump11289f42009-09-09 15:08:12 +0000239/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner2ce500f2008-07-25 22:25:12 +0000240/// double. All other argument types are converted by UsualUnaryConversions().
241void Sema::DefaultArgumentPromotion(Expr *&Expr) {
242 QualType Ty = Expr->getType();
243 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump11289f42009-09-09 15:08:12 +0000244
Chris Lattner2ce500f2008-07-25 22:25:12 +0000245 // If this is a 'float' (CVR qualified or typedef) promote to double.
John McCall9dd450b2009-09-21 23:43:11 +0000246 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
Chris Lattner2ce500f2008-07-25 22:25:12 +0000247 if (BT->getKind() == BuiltinType::Float)
Eli Friedman06ed2a52009-10-20 08:27:19 +0000248 return ImpCastExprToType(Expr, Context.DoubleTy,
249 CastExpr::CK_FloatingCast);
Mike Stump11289f42009-09-09 15:08:12 +0000250
Chris Lattner2ce500f2008-07-25 22:25:12 +0000251 UsualUnaryConversions(Expr);
252}
253
Chris Lattnera8a7d0f2009-04-12 08:11:20 +0000254/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
255/// will warn if the resulting type is not a POD type, and rejects ObjC
256/// interfaces passed by value. This returns true if the argument type is
257/// completely illegal.
258bool Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT) {
Anders Carlssona7d069d2009-01-16 16:48:51 +0000259 DefaultArgumentPromotion(Expr);
Mike Stump11289f42009-09-09 15:08:12 +0000260
Chris Lattnera8a7d0f2009-04-12 08:11:20 +0000261 if (Expr->getType()->isObjCInterfaceType()) {
262 Diag(Expr->getLocStart(),
263 diag::err_cannot_pass_objc_interface_to_vararg)
264 << Expr->getType() << CT;
265 return true;
Anders Carlssona7d069d2009-01-16 16:48:51 +0000266 }
Mike Stump11289f42009-09-09 15:08:12 +0000267
Chris Lattnera8a7d0f2009-04-12 08:11:20 +0000268 if (!Expr->getType()->isPODType())
269 Diag(Expr->getLocStart(), diag::warn_cannot_pass_non_pod_arg_to_vararg)
270 << Expr->getType() << CT;
271
272 return false;
Anders Carlssona7d069d2009-01-16 16:48:51 +0000273}
274
275
Chris Lattner513165e2008-07-25 21:10:04 +0000276/// UsualArithmeticConversions - Performs various conversions that are common to
277/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump11289f42009-09-09 15:08:12 +0000278/// routine returns the first non-arithmetic type found. The client is
Chris Lattner513165e2008-07-25 21:10:04 +0000279/// responsible for emitting appropriate error diagnostics.
280/// FIXME: verify the conversion rules for "complex int" are consistent with
281/// GCC.
282QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
283 bool isCompAssign) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +0000284 if (!isCompAssign)
Chris Lattner513165e2008-07-25 21:10:04 +0000285 UsualUnaryConversions(lhsExpr);
Eli Friedman8b7b1b12009-03-28 01:22:36 +0000286
287 UsualUnaryConversions(rhsExpr);
Douglas Gregora11693b2008-11-12 17:17:38 +0000288
Mike Stump11289f42009-09-09 15:08:12 +0000289 // For conversion purposes, we ignore any qualifiers.
Chris Lattner513165e2008-07-25 21:10:04 +0000290 // For example, "const float" and "float" are equivalent.
Chris Lattner574dee62008-07-26 22:17:49 +0000291 QualType lhs =
292 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +0000293 QualType rhs =
Chris Lattner574dee62008-07-26 22:17:49 +0000294 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +0000295
296 // If both types are identical, no conversion is needed.
297 if (lhs == rhs)
298 return lhs;
299
300 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
301 // The caller can deal with this (e.g. pointer + int).
302 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
303 return lhs;
304
Douglas Gregord2c2d172009-05-02 00:36:19 +0000305 // Perform bitfield promotions.
Eli Friedman629ffb92009-08-20 04:21:42 +0000306 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr);
Douglas Gregord2c2d172009-05-02 00:36:19 +0000307 if (!LHSBitfieldPromoteTy.isNull())
308 lhs = LHSBitfieldPromoteTy;
Eli Friedman629ffb92009-08-20 04:21:42 +0000309 QualType RHSBitfieldPromoteTy = Context.isPromotableBitField(rhsExpr);
Douglas Gregord2c2d172009-05-02 00:36:19 +0000310 if (!RHSBitfieldPromoteTy.isNull())
311 rhs = RHSBitfieldPromoteTy;
312
Eli Friedman5ae98ee2009-08-19 07:44:53 +0000313 QualType destType = Context.UsualArithmeticConversionsType(lhs, rhs);
Eli Friedman8b7b1b12009-03-28 01:22:36 +0000314 if (!isCompAssign)
Eli Friedman06ed2a52009-10-20 08:27:19 +0000315 ImpCastExprToType(lhsExpr, destType, CastExpr::CK_Unknown);
316 ImpCastExprToType(rhsExpr, destType, CastExpr::CK_Unknown);
Douglas Gregora11693b2008-11-12 17:17:38 +0000317 return destType;
318}
319
Chris Lattner513165e2008-07-25 21:10:04 +0000320//===----------------------------------------------------------------------===//
321// Semantic Analysis for various Expression Types
322//===----------------------------------------------------------------------===//
323
324
Steve Naroff83895f72007-09-16 03:34:24 +0000325/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner5b183d82006-11-10 05:03:26 +0000326/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
327/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
328/// multiple tokens. However, the common case is that StringToks points to one
329/// string.
Sebastian Redlffbcf962009-01-18 18:53:16 +0000330///
331Action::OwningExprResult
Steve Naroff83895f72007-09-16 03:34:24 +0000332Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner5b183d82006-11-10 05:03:26 +0000333 assert(NumStringToks && "Must have at least one string!");
334
Chris Lattner8a24e582009-01-16 18:51:42 +0000335 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Steve Naroff4f88b312007-03-13 22:37:02 +0000336 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +0000337 return ExprError();
Chris Lattner5b183d82006-11-10 05:03:26 +0000338
Chris Lattner23b7eb62007-06-15 23:05:46 +0000339 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
Chris Lattner5b183d82006-11-10 05:03:26 +0000340 for (unsigned i = 0; i != NumStringToks; ++i)
341 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattner36fc8792008-02-11 00:02:17 +0000342
Chris Lattner36fc8792008-02-11 00:02:17 +0000343 QualType StrTy = Context.CharTy;
Argyrios Kyrtzidiscbad7252008-08-09 17:20:01 +0000344 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattner36fc8792008-02-11 00:02:17 +0000345 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregoraa1e21d2008-09-12 00:47:35 +0000346
347 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
348 if (getLangOptions().CPlusPlus)
349 StrTy.addConst();
Sebastian Redlffbcf962009-01-18 18:53:16 +0000350
Chris Lattner36fc8792008-02-11 00:02:17 +0000351 // Get an array type for the string, according to C99 6.4.5. This includes
352 // the nul terminator character as well as the string length for pascal
353 // strings.
354 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerd42c29f2009-02-26 23:01:51 +0000355 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattner36fc8792008-02-11 00:02:17 +0000356 ArrayType::Normal, 0);
Mike Stump11289f42009-09-09 15:08:12 +0000357
Chris Lattner5b183d82006-11-10 05:03:26 +0000358 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Mike Stump11289f42009-09-09 15:08:12 +0000359 return Owned(StringLiteral::Create(Context, Literal.GetString(),
Chris Lattnerf83b5af2009-02-18 06:40:38 +0000360 Literal.GetStringLength(),
361 Literal.AnyWide, StrTy,
362 &StringTokLocs[0],
363 StringTokLocs.size()));
Chris Lattner5b183d82006-11-10 05:03:26 +0000364}
365
Chris Lattner2a9d9892008-10-20 05:16:36 +0000366/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
367/// CurBlock to VD should cause it to be snapshotted (as we do for auto
368/// variables defined outside the block) or false if this is not needed (e.g.
369/// for values inside the block or for globals).
370///
Chris Lattner497d7b02009-04-21 22:26:47 +0000371/// This also keeps the 'hasBlockDeclRefExprs' in the BlockSemaInfo records
372/// up-to-date.
373///
Chris Lattner2a9d9892008-10-20 05:16:36 +0000374static bool ShouldSnapshotBlockValueReference(BlockSemaInfo *CurBlock,
375 ValueDecl *VD) {
376 // If the value is defined inside the block, we couldn't snapshot it even if
377 // we wanted to.
378 if (CurBlock->TheDecl == VD->getDeclContext())
379 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000380
Chris Lattner2a9d9892008-10-20 05:16:36 +0000381 // If this is an enum constant or function, it is constant, don't snapshot.
382 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
383 return false;
384
385 // If this is a reference to an extern, static, or global variable, no need to
386 // snapshot it.
387 // FIXME: What about 'const' variables in C++?
388 if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
Chris Lattner497d7b02009-04-21 22:26:47 +0000389 if (!Var->hasLocalStorage())
390 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000391
Chris Lattner497d7b02009-04-21 22:26:47 +0000392 // Blocks that have these can't be constant.
393 CurBlock->hasBlockDeclRefExprs = true;
394
395 // If we have nested blocks, the decl may be declared in an outer block (in
396 // which case that outer block doesn't get "hasBlockDeclRefExprs") or it may
397 // be defined outside all of the current blocks (in which case the blocks do
398 // all get the bit). Walk the nesting chain.
399 for (BlockSemaInfo *NextBlock = CurBlock->PrevBlockInfo; NextBlock;
400 NextBlock = NextBlock->PrevBlockInfo) {
401 // If we found the defining block for the variable, don't mark the block as
402 // having a reference outside it.
403 if (NextBlock->TheDecl == VD->getDeclContext())
404 break;
Mike Stump11289f42009-09-09 15:08:12 +0000405
Chris Lattner497d7b02009-04-21 22:26:47 +0000406 // Otherwise, the DeclRef from the inner block causes the outer one to need
407 // a snapshot as well.
408 NextBlock->hasBlockDeclRefExprs = true;
409 }
Mike Stump11289f42009-09-09 15:08:12 +0000410
Chris Lattner2a9d9892008-10-20 05:16:36 +0000411 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000412}
413
Chris Lattner2a9d9892008-10-20 05:16:36 +0000414
415
Douglas Gregor4bd90e52009-10-23 18:54:35 +0000416/// BuildDeclRefExpr - Build a DeclRefExpr.
Anders Carlsson946b86d2009-06-24 00:10:43 +0000417Sema::OwningExprResult
Sebastian Redl3d3f75a2009-02-03 20:19:35 +0000418Sema::BuildDeclRefExpr(NamedDecl *D, QualType Ty, SourceLocation Loc,
Sebastian Redl3d3f75a2009-02-03 20:19:35 +0000419 const CXXScopeSpec *SS) {
Anders Carlsson364035d12009-06-26 19:16:07 +0000420 if (Context.getCanonicalType(Ty) == Context.UndeducedAutoTy) {
421 Diag(Loc,
Mike Stump11289f42009-09-09 15:08:12 +0000422 diag::err_auto_variable_cannot_appear_in_own_initializer)
Anders Carlsson364035d12009-06-26 19:16:07 +0000423 << D->getDeclName();
424 return ExprError();
425 }
Mike Stump11289f42009-09-09 15:08:12 +0000426
Anders Carlsson946b86d2009-06-24 00:10:43 +0000427 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
428 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
429 if (const FunctionDecl *FD = MD->getParent()->isLocalClass()) {
430 if (VD->hasLocalStorage() && VD->getDeclContext() != CurContext) {
Mike Stump11289f42009-09-09 15:08:12 +0000431 Diag(Loc, diag::err_reference_to_local_var_in_enclosing_function)
Anders Carlsson946b86d2009-06-24 00:10:43 +0000432 << D->getIdentifier() << FD->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +0000433 Diag(D->getLocation(), diag::note_local_variable_declared_here)
Anders Carlsson946b86d2009-06-24 00:10:43 +0000434 << D->getIdentifier();
435 return ExprError();
436 }
437 }
438 }
439 }
Mike Stump11289f42009-09-09 15:08:12 +0000440
Douglas Gregorc9c02ed2009-06-19 23:52:42 +0000441 MarkDeclarationReferenced(Loc, D);
Mike Stump11289f42009-09-09 15:08:12 +0000442
Douglas Gregor4bd90e52009-10-23 18:54:35 +0000443 return Owned(DeclRefExpr::Create(Context,
444 SS? (NestedNameSpecifier *)SS->getScopeRep() : 0,
445 SS? SS->getRange() : SourceRange(),
Douglas Gregored6c7442009-11-23 11:41:28 +0000446 D, Loc, Ty));
Douglas Gregorc7acfdf2009-01-06 05:10:23 +0000447}
448
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000449/// getObjectForAnonymousRecordDecl - Retrieve the (unnamed) field or
450/// variable corresponding to the anonymous union or struct whose type
451/// is Record.
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000452static Decl *getObjectForAnonymousRecordDecl(ASTContext &Context,
453 RecordDecl *Record) {
Mike Stump11289f42009-09-09 15:08:12 +0000454 assert(Record->isAnonymousStructOrUnion() &&
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000455 "Record must be an anonymous struct or union!");
Mike Stump11289f42009-09-09 15:08:12 +0000456
Mike Stump87c57ac2009-05-16 07:39:55 +0000457 // FIXME: Once Decls are directly linked together, this will be an O(1)
458 // operation rather than a slow walk through DeclContext's vector (which
459 // itself will be eliminated). DeclGroups might make this even better.
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000460 DeclContext *Ctx = Record->getDeclContext();
Mike Stump11289f42009-09-09 15:08:12 +0000461 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000462 DEnd = Ctx->decls_end();
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000463 D != DEnd; ++D) {
464 if (*D == Record) {
465 // The object for the anonymous struct/union directly
466 // follows its type in the list of declarations.
467 ++D;
468 assert(D != DEnd && "Missing object for anonymous record");
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000469 assert(!cast<NamedDecl>(*D)->getDeclName() && "Decl should be unnamed");
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000470 return *D;
471 }
472 }
473
474 assert(false && "Missing object for anonymous record");
475 return 0;
476}
477
Douglas Gregord5846a12009-04-15 06:41:24 +0000478/// \brief Given a field that represents a member of an anonymous
479/// struct/union, build the path from that field's context to the
480/// actual member.
481///
482/// Construct the sequence of field member references we'll have to
483/// perform to get to the field in the anonymous union/struct. The
484/// list of members is built from the field outward, so traverse it
485/// backwards to go from an object in the current context to the field
486/// we found.
487///
488/// \returns The variable from which the field access should begin,
489/// for an anonymous struct/union that is not a member of another
490/// class. Otherwise, returns NULL.
491VarDecl *Sema::BuildAnonymousStructUnionMemberPath(FieldDecl *Field,
492 llvm::SmallVectorImpl<FieldDecl *> &Path) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000493 assert(Field->getDeclContext()->isRecord() &&
494 cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion()
495 && "Field must be stored inside an anonymous struct or union");
496
Douglas Gregord5846a12009-04-15 06:41:24 +0000497 Path.push_back(Field);
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000498 VarDecl *BaseObject = 0;
499 DeclContext *Ctx = Field->getDeclContext();
500 do {
501 RecordDecl *Record = cast<RecordDecl>(Ctx);
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000502 Decl *AnonObject = getObjectForAnonymousRecordDecl(Context, Record);
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000503 if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject))
Douglas Gregord5846a12009-04-15 06:41:24 +0000504 Path.push_back(AnonField);
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000505 else {
506 BaseObject = cast<VarDecl>(AnonObject);
507 break;
508 }
509 Ctx = Ctx->getParent();
Mike Stump11289f42009-09-09 15:08:12 +0000510 } while (Ctx->isRecord() &&
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000511 cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion());
Douglas Gregord5846a12009-04-15 06:41:24 +0000512
513 return BaseObject;
514}
515
516Sema::OwningExprResult
517Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
518 FieldDecl *Field,
519 Expr *BaseObjectExpr,
520 SourceLocation OpLoc) {
521 llvm::SmallVector<FieldDecl *, 4> AnonFields;
Mike Stump11289f42009-09-09 15:08:12 +0000522 VarDecl *BaseObject = BuildAnonymousStructUnionMemberPath(Field,
Douglas Gregord5846a12009-04-15 06:41:24 +0000523 AnonFields);
524
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000525 // Build the expression that refers to the base object, from
526 // which we will build a sequence of member references to each
527 // of the anonymous union objects and, eventually, the field we
528 // found via name lookup.
529 bool BaseObjectIsPointer = false;
John McCall8ccfcb52009-09-24 19:53:00 +0000530 Qualifiers BaseQuals;
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000531 if (BaseObject) {
532 // BaseObject is an anonymous struct/union variable (and is,
533 // therefore, not part of another non-anonymous record).
Ted Kremenek5a201952009-02-07 01:47:29 +0000534 if (BaseObjectExpr) BaseObjectExpr->Destroy(Context);
Douglas Gregorc9c02ed2009-06-19 23:52:42 +0000535 MarkDeclarationReferenced(Loc, BaseObject);
Steve Narofff6009ed2009-01-21 00:14:39 +0000536 BaseObjectExpr = new (Context) DeclRefExpr(BaseObject,BaseObject->getType(),
Mike Stump4e1f26a2009-02-19 03:04:26 +0000537 SourceLocation());
John McCall8ccfcb52009-09-24 19:53:00 +0000538 BaseQuals
539 = Context.getCanonicalType(BaseObject->getType()).getQualifiers();
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000540 } else if (BaseObjectExpr) {
541 // The caller provided the base object expression. Determine
542 // whether its a pointer and whether it adds any qualifiers to the
543 // anonymous struct/union fields we're looking into.
544 QualType ObjectType = BaseObjectExpr->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000545 if (const PointerType *ObjectPtr = ObjectType->getAs<PointerType>()) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000546 BaseObjectIsPointer = true;
547 ObjectType = ObjectPtr->getPointeeType();
548 }
John McCall8ccfcb52009-09-24 19:53:00 +0000549 BaseQuals
550 = Context.getCanonicalType(ObjectType).getQualifiers();
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000551 } else {
552 // We've found a member of an anonymous struct/union that is
553 // inside a non-anonymous struct/union, so in a well-formed
554 // program our base object expression is "this".
555 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
556 if (!MD->isStatic()) {
Mike Stump11289f42009-09-09 15:08:12 +0000557 QualType AnonFieldType
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000558 = Context.getTagDeclType(
559 cast<RecordDecl>(AnonFields.back()->getDeclContext()));
560 QualType ThisType = Context.getTagDeclType(MD->getParent());
Mike Stump11289f42009-09-09 15:08:12 +0000561 if ((Context.getCanonicalType(AnonFieldType)
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000562 == Context.getCanonicalType(ThisType)) ||
563 IsDerivedFrom(ThisType, AnonFieldType)) {
564 // Our base object expression is "this".
Steve Narofff6009ed2009-01-21 00:14:39 +0000565 BaseObjectExpr = new (Context) CXXThisExpr(SourceLocation(),
Mike Stump4e1f26a2009-02-19 03:04:26 +0000566 MD->getThisType(Context));
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000567 BaseObjectIsPointer = true;
568 }
569 } else {
Sebastian Redlffbcf962009-01-18 18:53:16 +0000570 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
571 << Field->getDeclName());
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000572 }
John McCall8ccfcb52009-09-24 19:53:00 +0000573 BaseQuals = Qualifiers::fromCVRMask(MD->getTypeQualifiers());
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000574 }
575
Mike Stump11289f42009-09-09 15:08:12 +0000576 if (!BaseObjectExpr)
Sebastian Redlffbcf962009-01-18 18:53:16 +0000577 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
578 << Field->getDeclName());
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000579 }
580
581 // Build the implicit member references to the field of the
582 // anonymous struct/union.
583 Expr *Result = BaseObjectExpr;
John McCall8ccfcb52009-09-24 19:53:00 +0000584 Qualifiers ResultQuals = BaseQuals;
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000585 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
586 FI = AnonFields.rbegin(), FIEnd = AnonFields.rend();
587 FI != FIEnd; ++FI) {
588 QualType MemberType = (*FI)->getType();
John McCall8ccfcb52009-09-24 19:53:00 +0000589 Qualifiers MemberTypeQuals =
590 Context.getCanonicalType(MemberType).getQualifiers();
591
592 // CVR attributes from the base are picked up by members,
593 // except that 'mutable' members don't pick up 'const'.
594 if ((*FI)->isMutable())
595 ResultQuals.removeConst();
596
597 // GC attributes are never picked up by members.
598 ResultQuals.removeObjCGCAttr();
599
600 // TR 18037 does not allow fields to be declared with address spaces.
601 assert(!MemberTypeQuals.hasAddressSpace());
602
603 Qualifiers NewQuals = ResultQuals + MemberTypeQuals;
604 if (NewQuals != MemberTypeQuals)
605 MemberType = Context.getQualifiedType(MemberType, NewQuals);
606
Douglas Gregorc9c02ed2009-06-19 23:52:42 +0000607 MarkDeclarationReferenced(Loc, *FI);
Eli Friedman78cde142009-12-04 07:18:51 +0000608 PerformObjectMemberConversion(Result, *FI);
Douglas Gregorc1905232009-08-26 22:36:53 +0000609 // FIXME: Might this end up being a qualified name?
Steve Narofff6009ed2009-01-21 00:14:39 +0000610 Result = new (Context) MemberExpr(Result, BaseObjectIsPointer, *FI,
611 OpLoc, MemberType);
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000612 BaseObjectIsPointer = false;
John McCall8ccfcb52009-09-24 19:53:00 +0000613 ResultQuals = NewQuals;
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000614 }
615
Sebastian Redlffbcf962009-01-18 18:53:16 +0000616 return Owned(Result);
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000617}
618
John McCall10eae182009-11-30 22:42:35 +0000619/// Decomposes the given name into a DeclarationName, its location, and
620/// possibly a list of template arguments.
621///
622/// If this produces template arguments, it is permitted to call
623/// DecomposeTemplateName.
624///
625/// This actually loses a lot of source location information for
626/// non-standard name kinds; we should consider preserving that in
627/// some way.
628static void DecomposeUnqualifiedId(Sema &SemaRef,
629 const UnqualifiedId &Id,
630 TemplateArgumentListInfo &Buffer,
631 DeclarationName &Name,
632 SourceLocation &NameLoc,
633 const TemplateArgumentListInfo *&TemplateArgs) {
634 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
635 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
636 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
637
638 ASTTemplateArgsPtr TemplateArgsPtr(SemaRef,
639 Id.TemplateId->getTemplateArgs(),
640 Id.TemplateId->NumArgs);
641 SemaRef.translateTemplateArguments(TemplateArgsPtr, Buffer);
642 TemplateArgsPtr.release();
643
644 TemplateName TName =
645 Sema::TemplateTy::make(Id.TemplateId->Template).getAsVal<TemplateName>();
646
647 Name = SemaRef.Context.getNameForTemplate(TName);
648 NameLoc = Id.TemplateId->TemplateNameLoc;
649 TemplateArgs = &Buffer;
650 } else {
651 Name = SemaRef.GetNameFromUnqualifiedId(Id);
652 NameLoc = Id.StartLocation;
653 TemplateArgs = 0;
654 }
655}
656
657/// Decompose the given template name into a list of lookup results.
658///
659/// The unqualified ID must name a non-dependent template, which can
660/// be more easily tested by checking whether DecomposeUnqualifiedId
661/// found template arguments.
662static void DecomposeTemplateName(LookupResult &R, const UnqualifiedId &Id) {
663 assert(Id.getKind() == UnqualifiedId::IK_TemplateId);
664 TemplateName TName =
665 Sema::TemplateTy::make(Id.TemplateId->Template).getAsVal<TemplateName>();
666
John McCalle66edc12009-11-24 19:00:30 +0000667 if (TemplateDecl *TD = TName.getAsTemplateDecl())
668 R.addDecl(TD);
John McCalld28ae272009-12-02 08:04:21 +0000669 else if (OverloadedTemplateStorage *OT = TName.getAsOverloadedTemplate())
670 for (OverloadedTemplateStorage::iterator I = OT->begin(), E = OT->end();
671 I != E; ++I)
John McCalle66edc12009-11-24 19:00:30 +0000672 R.addDecl(*I);
John McCalla9ee3252009-11-22 02:49:43 +0000673
John McCalle66edc12009-11-24 19:00:30 +0000674 R.resolveKind();
Douglas Gregora121b752009-11-03 16:56:39 +0000675}
676
John McCall10eae182009-11-30 22:42:35 +0000677static bool IsFullyFormedScope(Sema &SemaRef, CXXRecordDecl *Record) {
678 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
679 E = Record->bases_end(); I != E; ++I) {
680 CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
681 CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
682 if (!BaseRT) return false;
683
684 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
685 if (!BaseRecord->isDefinition() ||
686 !IsFullyFormedScope(SemaRef, BaseRecord))
687 return false;
688 }
689
690 return true;
691}
692
John McCallf786fb12009-11-30 23:50:49 +0000693/// Determines whether we can lookup this id-expression now or whether
694/// we have to wait until template instantiation is complete.
695static bool IsDependentIdExpression(Sema &SemaRef, const CXXScopeSpec &SS) {
John McCall10eae182009-11-30 22:42:35 +0000696 DeclContext *DC = SemaRef.computeDeclContext(SS, false);
John McCall10eae182009-11-30 22:42:35 +0000697
John McCallf786fb12009-11-30 23:50:49 +0000698 // If the qualifier scope isn't computable, it's definitely dependent.
699 if (!DC) return true;
700
701 // If the qualifier scope doesn't name a record, we can always look into it.
702 if (!isa<CXXRecordDecl>(DC)) return false;
703
704 // We can't look into record types unless they're fully-formed.
705 if (!IsFullyFormedScope(SemaRef, cast<CXXRecordDecl>(DC))) return true;
706
John McCall2d74de92009-12-01 22:10:20 +0000707 return false;
708}
John McCallf786fb12009-11-30 23:50:49 +0000709
John McCall2d74de92009-12-01 22:10:20 +0000710/// Determines if the given class is provably not derived from all of
711/// the prospective base classes.
712static bool IsProvablyNotDerivedFrom(Sema &SemaRef,
713 CXXRecordDecl *Record,
714 const llvm::SmallPtrSet<CXXRecordDecl*, 4> &Bases) {
John McCalla6d407c2009-12-01 22:28:41 +0000715 if (Bases.count(Record->getCanonicalDecl()))
John McCall2d74de92009-12-01 22:10:20 +0000716 return false;
717
John McCalla6d407c2009-12-01 22:28:41 +0000718 RecordDecl *RD = Record->getDefinition(SemaRef.Context);
719 if (!RD) return false;
720 Record = cast<CXXRecordDecl>(RD);
721
John McCall2d74de92009-12-01 22:10:20 +0000722 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
723 E = Record->bases_end(); I != E; ++I) {
724 CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
725 CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
726 if (!BaseRT) return false;
727
728 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall2d74de92009-12-01 22:10:20 +0000729 if (!IsProvablyNotDerivedFrom(SemaRef, BaseRecord, Bases))
730 return false;
731 }
732
733 return true;
734}
735
John McCall5af04502009-12-02 20:26:00 +0000736/// Determines if this a C++ class member.
737static bool IsClassMember(NamedDecl *D) {
738 DeclContext *DC = D->getDeclContext();
John McCall1a49e9d2009-12-02 19:59:55 +0000739
John McCall5af04502009-12-02 20:26:00 +0000740 // C++0x [class.mem]p1:
741 // The enumerators of an unscoped enumeration defined in
742 // the class are members of the class.
743 // FIXME: support C++0x scoped enumerations.
744 if (isa<EnumDecl>(DC))
745 DC = DC->getParent();
746
747 return DC->isRecord();
748}
749
750/// Determines if this is an instance member of a class.
751static bool IsInstanceMember(NamedDecl *D) {
752 assert(IsClassMember(D) &&
John McCall2d74de92009-12-01 22:10:20 +0000753 "checking whether non-member is instance member");
754
755 if (isa<FieldDecl>(D)) return true;
756
757 if (isa<CXXMethodDecl>(D))
758 return !cast<CXXMethodDecl>(D)->isStatic();
759
760 if (isa<FunctionTemplateDecl>(D)) {
761 D = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
762 return !cast<CXXMethodDecl>(D)->isStatic();
763 }
764
765 return false;
766}
767
768enum IMAKind {
769 /// The reference is definitely not an instance member access.
770 IMA_Static,
771
772 /// The reference may be an implicit instance member access.
773 IMA_Mixed,
774
775 /// The reference may be to an instance member, but it is invalid if
776 /// so, because the context is not an instance method.
777 IMA_Mixed_StaticContext,
778
779 /// The reference may be to an instance member, but it is invalid if
780 /// so, because the context is from an unrelated class.
781 IMA_Mixed_Unrelated,
782
783 /// The reference is definitely an implicit instance member access.
784 IMA_Instance,
785
786 /// The reference may be to an unresolved using declaration.
787 IMA_Unresolved,
788
789 /// The reference may be to an unresolved using declaration and the
790 /// context is not an instance method.
791 IMA_Unresolved_StaticContext,
792
793 /// The reference is to a member of an anonymous structure in a
794 /// non-class context.
795 IMA_AnonymousMember,
796
797 /// All possible referrents are instance members and the current
798 /// context is not an instance method.
799 IMA_Error_StaticContext,
800
801 /// All possible referrents are instance members of an unrelated
802 /// class.
803 IMA_Error_Unrelated
804};
805
806/// The given lookup names class member(s) and is not being used for
807/// an address-of-member expression. Classify the type of access
808/// according to whether it's possible that this reference names an
809/// instance member. This is best-effort; it is okay to
810/// conservatively answer "yes", in which case some errors will simply
811/// not be caught until template-instantiation.
812static IMAKind ClassifyImplicitMemberAccess(Sema &SemaRef,
813 const LookupResult &R) {
John McCall5af04502009-12-02 20:26:00 +0000814 assert(!R.empty() && IsClassMember(*R.begin()));
John McCall2d74de92009-12-01 22:10:20 +0000815
816 bool isStaticContext =
817 (!isa<CXXMethodDecl>(SemaRef.CurContext) ||
818 cast<CXXMethodDecl>(SemaRef.CurContext)->isStatic());
819
820 if (R.isUnresolvableResult())
821 return isStaticContext ? IMA_Unresolved_StaticContext : IMA_Unresolved;
822
823 // Collect all the declaring classes of instance members we find.
824 bool hasNonInstance = false;
825 llvm::SmallPtrSet<CXXRecordDecl*, 4> Classes;
826 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
827 NamedDecl *D = (*I)->getUnderlyingDecl();
828 if (IsInstanceMember(D)) {
829 CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext());
830
831 // If this is a member of an anonymous record, move out to the
832 // innermost non-anonymous struct or union. If there isn't one,
833 // that's a special case.
834 while (R->isAnonymousStructOrUnion()) {
835 R = dyn_cast<CXXRecordDecl>(R->getParent());
836 if (!R) return IMA_AnonymousMember;
837 }
838 Classes.insert(R->getCanonicalDecl());
839 }
840 else
841 hasNonInstance = true;
842 }
843
844 // If we didn't find any instance members, it can't be an implicit
845 // member reference.
846 if (Classes.empty())
847 return IMA_Static;
848
849 // If the current context is not an instance method, it can't be
850 // an implicit member reference.
851 if (isStaticContext)
852 return (hasNonInstance ? IMA_Mixed_StaticContext : IMA_Error_StaticContext);
853
854 // If we can prove that the current context is unrelated to all the
855 // declaring classes, it can't be an implicit member reference (in
856 // which case it's an error if any of those members are selected).
857 if (IsProvablyNotDerivedFrom(SemaRef,
858 cast<CXXMethodDecl>(SemaRef.CurContext)->getParent(),
859 Classes))
860 return (hasNonInstance ? IMA_Mixed_Unrelated : IMA_Error_Unrelated);
861
862 return (hasNonInstance ? IMA_Mixed : IMA_Instance);
863}
864
865/// Diagnose a reference to a field with no object available.
866static void DiagnoseInstanceReference(Sema &SemaRef,
867 const CXXScopeSpec &SS,
868 const LookupResult &R) {
869 SourceLocation Loc = R.getNameLoc();
870 SourceRange Range(Loc);
871 if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
872
873 if (R.getAsSingle<FieldDecl>()) {
874 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(SemaRef.CurContext)) {
875 if (MD->isStatic()) {
876 // "invalid use of member 'x' in static member function"
877 SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method)
878 << Range << R.getLookupName();
879 return;
880 }
881 }
882
883 SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
884 << R.getLookupName() << Range;
885 return;
886 }
887
888 SemaRef.Diag(Loc, diag::err_member_call_without_object) << Range;
John McCall10eae182009-11-30 22:42:35 +0000889}
890
John McCalle66edc12009-11-24 19:00:30 +0000891Sema::OwningExprResult Sema::ActOnIdExpression(Scope *S,
892 const CXXScopeSpec &SS,
893 UnqualifiedId &Id,
894 bool HasTrailingLParen,
895 bool isAddressOfOperand) {
896 assert(!(isAddressOfOperand && HasTrailingLParen) &&
897 "cannot be direct & operand and have a trailing lparen");
898
899 if (SS.isInvalid())
Douglas Gregored8f2882009-01-30 01:04:22 +0000900 return ExprError();
Douglas Gregor90a1a652009-03-19 17:26:29 +0000901
John McCall10eae182009-11-30 22:42:35 +0000902 TemplateArgumentListInfo TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +0000903
904 // Decompose the UnqualifiedId into the following data.
905 DeclarationName Name;
906 SourceLocation NameLoc;
907 const TemplateArgumentListInfo *TemplateArgs;
John McCall10eae182009-11-30 22:42:35 +0000908 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer,
909 Name, NameLoc, TemplateArgs);
Douglas Gregor90a1a652009-03-19 17:26:29 +0000910
Douglas Gregor4ea80432008-11-18 15:03:34 +0000911 IdentifierInfo *II = Name.getAsIdentifierInfo();
John McCalld14a8642009-11-21 08:51:07 +0000912
John McCalle66edc12009-11-24 19:00:30 +0000913 // C++ [temp.dep.expr]p3:
914 // An id-expression is type-dependent if it contains:
915 // -- a nested-name-specifier that contains a class-name that
916 // names a dependent type.
917 // Determine whether this is a member of an unknown specialization;
918 // we need to handle these differently.
John McCallf786fb12009-11-30 23:50:49 +0000919 if (SS.isSet() && IsDependentIdExpression(*this, SS)) {
John McCalle66edc12009-11-24 19:00:30 +0000920 return ActOnDependentIdExpression(SS, Name, NameLoc,
John McCallcd4b4772009-12-02 03:53:29 +0000921 isAddressOfOperand,
John McCalle66edc12009-11-24 19:00:30 +0000922 TemplateArgs);
923 }
John McCalld14a8642009-11-21 08:51:07 +0000924
John McCalle66edc12009-11-24 19:00:30 +0000925 // Perform the required lookup.
926 LookupResult R(*this, Name, NameLoc, LookupOrdinaryName);
927 if (TemplateArgs) {
John McCalle66edc12009-11-24 19:00:30 +0000928 // Just re-use the lookup done by isTemplateName.
John McCall10eae182009-11-30 22:42:35 +0000929 DecomposeTemplateName(R, Id);
John McCalle66edc12009-11-24 19:00:30 +0000930 } else {
931 LookupParsedName(R, S, &SS, true);
Mike Stump11289f42009-09-09 15:08:12 +0000932
John McCalle66edc12009-11-24 19:00:30 +0000933 // If this reference is in an Objective-C method, then we need to do
934 // some special Objective-C lookup, too.
935 if (!SS.isSet() && II && getCurMethodDecl()) {
936 OwningExprResult E(LookupInObjCMethod(R, S, II));
937 if (E.isInvalid())
938 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +0000939
John McCalle66edc12009-11-24 19:00:30 +0000940 Expr *Ex = E.takeAs<Expr>();
941 if (Ex) return Owned(Ex);
Steve Naroffebf4cb42008-06-02 23:03:37 +0000942 }
Chris Lattner59a25942008-03-31 00:36:02 +0000943 }
Douglas Gregorf15f5d32009-02-16 19:28:42 +0000944
John McCalle66edc12009-11-24 19:00:30 +0000945 if (R.isAmbiguous())
946 return ExprError();
947
Douglas Gregor171c45a2009-02-18 21:56:37 +0000948 // Determine whether this name might be a candidate for
949 // argument-dependent lookup.
John McCalle66edc12009-11-24 19:00:30 +0000950 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor171c45a2009-02-18 21:56:37 +0000951
John McCalle66edc12009-11-24 19:00:30 +0000952 if (R.empty() && !ADL) {
Bill Wendling4073ed52007-02-13 01:51:42 +0000953 // Otherwise, this could be an implicitly declared function reference (legal
John McCalle66edc12009-11-24 19:00:30 +0000954 // in C90, extension in C99, forbidden in C++).
955 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
956 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
957 if (D) R.addDecl(D);
958 }
959
960 // If this name wasn't predeclared and if this is not a function
961 // call, diagnose the problem.
962 if (R.empty()) {
963 if (!SS.isEmpty())
964 return ExprError(Diag(NameLoc, diag::err_no_member)
965 << Name << computeDeclContext(SS, false)
966 << SS.getRange());
Douglas Gregore40876a2009-10-13 21:16:44 +0000967 else if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
Alexis Hunt3d221f22009-11-29 07:34:05 +0000968 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregor4ea80432008-11-18 15:03:34 +0000969 Name.getNameKind() == DeclarationName::CXXConversionFunctionName)
John McCalle66edc12009-11-24 19:00:30 +0000970 return ExprError(Diag(NameLoc, diag::err_undeclared_use)
971 << Name);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000972 else
John McCalle66edc12009-11-24 19:00:30 +0000973 return ExprError(Diag(NameLoc, diag::err_undeclared_var_use) << Name);
Steve Naroff92e30f82007-04-02 22:35:25 +0000974 }
Chris Lattner17ed4872006-11-20 04:58:19 +0000975 }
Mike Stump11289f42009-09-09 15:08:12 +0000976
John McCalle66edc12009-11-24 19:00:30 +0000977 // This is guaranteed from this point on.
978 assert(!R.empty() || ADL);
979
980 if (VarDecl *Var = R.getAsSingle<VarDecl>()) {
Douglas Gregor3256d042009-06-30 15:47:41 +0000981 // Warn about constructs like:
982 // if (void *X = foo()) { ... } else { X }.
983 // In the else block, the pointer is always false.
Mike Stump11289f42009-09-09 15:08:12 +0000984
Douglas Gregor3256d042009-06-30 15:47:41 +0000985 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
986 Scope *CheckS = S;
Douglas Gregor13a2c032009-11-05 17:49:26 +0000987 while (CheckS && CheckS->getControlParent()) {
Mike Stump11289f42009-09-09 15:08:12 +0000988 if (CheckS->isWithinElse() &&
Douglas Gregor3256d042009-06-30 15:47:41 +0000989 CheckS->getControlParent()->isDeclScope(DeclPtrTy::make(Var))) {
John McCalle66edc12009-11-24 19:00:30 +0000990 ExprError(Diag(NameLoc, diag::warn_value_always_zero)
Douglas Gregor13a2c032009-11-05 17:49:26 +0000991 << Var->getDeclName()
992 << (Var->getType()->isPointerType()? 2 :
993 Var->getType()->isBooleanType()? 1 : 0));
Douglas Gregor3256d042009-06-30 15:47:41 +0000994 break;
995 }
Mike Stump11289f42009-09-09 15:08:12 +0000996
Douglas Gregor13a2c032009-11-05 17:49:26 +0000997 // Move to the parent of this scope.
998 CheckS = CheckS->getParent();
Douglas Gregor3256d042009-06-30 15:47:41 +0000999 }
1000 }
John McCalle66edc12009-11-24 19:00:30 +00001001 } else if (FunctionDecl *Func = R.getAsSingle<FunctionDecl>()) {
Douglas Gregor3256d042009-06-30 15:47:41 +00001002 if (!getLangOptions().CPlusPlus && !Func->hasPrototype()) {
1003 // C99 DR 316 says that, if a function type comes from a
1004 // function definition (without a prototype), that type is only
1005 // used for checking compatibility. Therefore, when referencing
1006 // the function, we pretend that we don't have the full function
1007 // type.
John McCalle66edc12009-11-24 19:00:30 +00001008 if (DiagnoseUseOfDecl(Func, NameLoc))
Douglas Gregor3256d042009-06-30 15:47:41 +00001009 return ExprError();
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001010
Douglas Gregor3256d042009-06-30 15:47:41 +00001011 QualType T = Func->getType();
1012 QualType NoProtoType = T;
John McCall9dd450b2009-09-21 23:43:11 +00001013 if (const FunctionProtoType *Proto = T->getAs<FunctionProtoType>())
Douglas Gregor3256d042009-06-30 15:47:41 +00001014 NoProtoType = Context.getFunctionNoProtoType(Proto->getResultType());
John McCalle66edc12009-11-24 19:00:30 +00001015 return BuildDeclRefExpr(Func, NoProtoType, NameLoc, &SS);
Douglas Gregor3256d042009-06-30 15:47:41 +00001016 }
1017 }
Mike Stump11289f42009-09-09 15:08:12 +00001018
John McCall2d74de92009-12-01 22:10:20 +00001019 // Check whether this might be a C++ implicit instance member access.
1020 // C++ [expr.prim.general]p6:
1021 // Within the definition of a non-static member function, an
1022 // identifier that names a non-static member is transformed to a
1023 // class member access expression.
1024 // But note that &SomeClass::foo is grammatically distinct, even
1025 // though we don't parse it that way.
John McCall5af04502009-12-02 20:26:00 +00001026 if (!R.empty() && IsClassMember(*R.begin())) {
John McCalle66edc12009-11-24 19:00:30 +00001027 bool isAbstractMemberPointer = (isAddressOfOperand && !SS.isEmpty());
John McCallb53bbd42009-11-22 01:44:31 +00001028
John McCall2d74de92009-12-01 22:10:20 +00001029 if (!isAbstractMemberPointer) {
1030 switch (ClassifyImplicitMemberAccess(*this, R)) {
1031 case IMA_Instance:
1032 return BuildImplicitMemberExpr(SS, R, TemplateArgs, true);
1033
1034 case IMA_AnonymousMember:
1035 assert(R.isSingleResult());
1036 return BuildAnonymousStructUnionMemberReference(R.getNameLoc(),
1037 R.getAsSingle<FieldDecl>());
1038
1039 case IMA_Mixed:
1040 case IMA_Mixed_Unrelated:
1041 case IMA_Unresolved:
1042 return BuildImplicitMemberExpr(SS, R, TemplateArgs, false);
1043
1044 case IMA_Static:
1045 case IMA_Mixed_StaticContext:
1046 case IMA_Unresolved_StaticContext:
1047 break;
1048
1049 case IMA_Error_StaticContext:
1050 case IMA_Error_Unrelated:
1051 DiagnoseInstanceReference(*this, SS, R);
1052 return ExprError();
1053 }
John McCallb53bbd42009-11-22 01:44:31 +00001054 }
1055 }
1056
John McCalle66edc12009-11-24 19:00:30 +00001057 if (TemplateArgs)
1058 return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001059
John McCalle66edc12009-11-24 19:00:30 +00001060 return BuildDeclarationNameExpr(SS, R, ADL);
1061}
1062
John McCall10eae182009-11-30 22:42:35 +00001063/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1064/// declaration name, generally during template instantiation.
1065/// There's a large number of things which don't need to be done along
1066/// this path.
John McCalle66edc12009-11-24 19:00:30 +00001067Sema::OwningExprResult
1068Sema::BuildQualifiedDeclarationNameExpr(const CXXScopeSpec &SS,
1069 DeclarationName Name,
1070 SourceLocation NameLoc) {
1071 DeclContext *DC;
1072 if (!(DC = computeDeclContext(SS, false)) ||
1073 DC->isDependentContext() ||
1074 RequireCompleteDeclContext(SS))
1075 return BuildDependentDeclRefExpr(SS, Name, NameLoc, 0);
1076
1077 LookupResult R(*this, Name, NameLoc, LookupOrdinaryName);
1078 LookupQualifiedName(R, DC);
1079
1080 if (R.isAmbiguous())
1081 return ExprError();
1082
1083 if (R.empty()) {
1084 Diag(NameLoc, diag::err_no_member) << Name << DC << SS.getRange();
1085 return ExprError();
1086 }
1087
1088 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1089}
1090
1091/// LookupInObjCMethod - The parser has read a name in, and Sema has
1092/// detected that we're currently inside an ObjC method. Perform some
1093/// additional lookup.
1094///
1095/// Ideally, most of this would be done by lookup, but there's
1096/// actually quite a lot of extra work involved.
1097///
1098/// Returns a null sentinel to indicate trivial success.
1099Sema::OwningExprResult
1100Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
1101 IdentifierInfo *II) {
1102 SourceLocation Loc = Lookup.getNameLoc();
1103
1104 // There are two cases to handle here. 1) scoped lookup could have failed,
1105 // in which case we should look for an ivar. 2) scoped lookup could have
1106 // found a decl, but that decl is outside the current instance method (i.e.
1107 // a global variable). In these two cases, we do a lookup for an ivar with
1108 // this name, if the lookup sucedes, we replace it our current decl.
1109
1110 // If we're in a class method, we don't normally want to look for
1111 // ivars. But if we don't find anything else, and there's an
1112 // ivar, that's an error.
1113 bool IsClassMethod = getCurMethodDecl()->isClassMethod();
1114
1115 bool LookForIvars;
1116 if (Lookup.empty())
1117 LookForIvars = true;
1118 else if (IsClassMethod)
1119 LookForIvars = false;
1120 else
1121 LookForIvars = (Lookup.isSingleResult() &&
1122 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
1123
1124 if (LookForIvars) {
1125 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
1126 ObjCInterfaceDecl *ClassDeclared;
1127 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1128 // Diagnose using an ivar in a class method.
1129 if (IsClassMethod)
1130 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1131 << IV->getDeclName());
1132
1133 // If we're referencing an invalid decl, just return this as a silent
1134 // error node. The error diagnostic was already emitted on the decl.
1135 if (IV->isInvalidDecl())
1136 return ExprError();
1137
1138 // Check if referencing a field with __attribute__((deprecated)).
1139 if (DiagnoseUseOfDecl(IV, Loc))
1140 return ExprError();
1141
1142 // Diagnose the use of an ivar outside of the declaring class.
1143 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
1144 ClassDeclared != IFace)
1145 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1146
1147 // FIXME: This should use a new expr for a direct reference, don't
1148 // turn this into Self->ivar, just return a BareIVarExpr or something.
1149 IdentifierInfo &II = Context.Idents.get("self");
1150 UnqualifiedId SelfName;
1151 SelfName.setIdentifier(&II, SourceLocation());
1152 CXXScopeSpec SelfScopeSpec;
1153 OwningExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
1154 SelfName, false, false);
1155 MarkDeclarationReferenced(Loc, IV);
1156 return Owned(new (Context)
1157 ObjCIvarRefExpr(IV, IV->getType(), Loc,
1158 SelfExpr.takeAs<Expr>(), true, true));
1159 }
1160 } else if (getCurMethodDecl()->isInstanceMethod()) {
1161 // We should warn if a local variable hides an ivar.
1162 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
1163 ObjCInterfaceDecl *ClassDeclared;
1164 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1165 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
1166 IFace == ClassDeclared)
1167 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
1168 }
1169 }
1170
1171 // Needed to implement property "super.method" notation.
1172 if (Lookup.empty() && II->isStr("super")) {
1173 QualType T;
1174
1175 if (getCurMethodDecl()->isInstanceMethod())
1176 T = Context.getObjCObjectPointerType(Context.getObjCInterfaceType(
1177 getCurMethodDecl()->getClassInterface()));
1178 else
1179 T = Context.getObjCClassType();
1180 return Owned(new (Context) ObjCSuperExpr(Loc, T));
1181 }
1182
1183 // Sentinel value saying that we didn't do anything special.
1184 return Owned((Expr*) 0);
Douglas Gregor3256d042009-06-30 15:47:41 +00001185}
John McCalld14a8642009-11-21 08:51:07 +00001186
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001187/// \brief Cast member's object to its own class if necessary.
Fariborz Jahanian3f150832009-07-29 19:40:11 +00001188bool
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001189Sema::PerformObjectMemberConversion(Expr *&From, NamedDecl *Member) {
1190 if (FieldDecl *FD = dyn_cast<FieldDecl>(Member))
Mike Stump11289f42009-09-09 15:08:12 +00001191 if (CXXRecordDecl *RD =
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001192 dyn_cast<CXXRecordDecl>(FD->getDeclContext())) {
Mike Stump11289f42009-09-09 15:08:12 +00001193 QualType DestType =
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001194 Context.getCanonicalType(Context.getTypeDeclType(RD));
Fariborz Jahanian4b12ed12009-07-29 20:41:46 +00001195 if (DestType->isDependentType() || From->getType()->isDependentType())
1196 return false;
1197 QualType FromRecordType = From->getType();
1198 QualType DestRecordType = DestType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001199 if (FromRecordType->getAs<PointerType>()) {
Fariborz Jahanian4b12ed12009-07-29 20:41:46 +00001200 DestType = Context.getPointerType(DestType);
1201 FromRecordType = FromRecordType->getPointeeType();
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001202 }
Fariborz Jahanian4b12ed12009-07-29 20:41:46 +00001203 if (!Context.hasSameUnqualifiedType(FromRecordType, DestRecordType) &&
1204 CheckDerivedToBaseConversion(FromRecordType,
1205 DestRecordType,
1206 From->getSourceRange().getBegin(),
1207 From->getSourceRange()))
1208 return true;
Anders Carlssona076d142009-07-31 01:23:52 +00001209 ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
1210 /*isLvalue=*/true);
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001211 }
Fariborz Jahanian3f150832009-07-29 19:40:11 +00001212 return false;
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001213}
Douglas Gregor3256d042009-06-30 15:47:41 +00001214
Douglas Gregorf405d7e2009-08-31 23:41:50 +00001215/// \brief Build a MemberExpr AST node.
Mike Stump11289f42009-09-09 15:08:12 +00001216static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow,
Eli Friedman2cfcef62009-12-04 06:40:45 +00001217 const CXXScopeSpec &SS, ValueDecl *Member,
John McCalle66edc12009-11-24 19:00:30 +00001218 SourceLocation Loc, QualType Ty,
1219 const TemplateArgumentListInfo *TemplateArgs = 0) {
1220 NestedNameSpecifier *Qualifier = 0;
1221 SourceRange QualifierRange;
John McCall10eae182009-11-30 22:42:35 +00001222 if (SS.isSet()) {
1223 Qualifier = (NestedNameSpecifier *) SS.getScopeRep();
1224 QualifierRange = SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00001225 }
Mike Stump11289f42009-09-09 15:08:12 +00001226
John McCalle66edc12009-11-24 19:00:30 +00001227 return MemberExpr::Create(C, Base, isArrow, Qualifier, QualifierRange,
1228 Member, Loc, TemplateArgs, Ty);
Douglas Gregorc1905232009-08-26 22:36:53 +00001229}
1230
John McCall2d74de92009-12-01 22:10:20 +00001231/// Builds an implicit member access expression. The current context
1232/// is known to be an instance method, and the given unqualified lookup
1233/// set is known to contain only instance members, at least one of which
1234/// is from an appropriate type.
John McCallb53bbd42009-11-22 01:44:31 +00001235Sema::OwningExprResult
John McCall2d74de92009-12-01 22:10:20 +00001236Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
1237 LookupResult &R,
1238 const TemplateArgumentListInfo *TemplateArgs,
1239 bool IsKnownInstance) {
John McCalle66edc12009-11-24 19:00:30 +00001240 assert(!R.empty() && !R.isAmbiguous());
1241
John McCalld14a8642009-11-21 08:51:07 +00001242 SourceLocation Loc = R.getNameLoc();
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00001243
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001244 // We may have found a field within an anonymous union or struct
1245 // (C++ [class.union]).
Douglas Gregor6493d9c2009-10-22 07:08:30 +00001246 // FIXME: This needs to happen post-isImplicitMemberReference?
John McCalle66edc12009-11-24 19:00:30 +00001247 // FIXME: template-ids inside anonymous structs?
John McCall10eae182009-11-30 22:42:35 +00001248 if (FieldDecl *FD = R.getAsSingle<FieldDecl>())
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001249 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
John McCallb53bbd42009-11-22 01:44:31 +00001250 return BuildAnonymousStructUnionMemberReference(Loc, FD);
Sebastian Redlffbcf962009-01-18 18:53:16 +00001251
John McCall2d74de92009-12-01 22:10:20 +00001252 // If this is known to be an instance access, go ahead and build a
1253 // 'this' expression now.
1254 QualType ThisType = cast<CXXMethodDecl>(CurContext)->getThisType(Context);
1255 Expr *This = 0; // null signifies implicit access
1256 if (IsKnownInstance) {
1257 This = new (Context) CXXThisExpr(SourceLocation(), ThisType);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00001258 }
1259
John McCall2d74de92009-12-01 22:10:20 +00001260 return BuildMemberReferenceExpr(ExprArg(*this, This), ThisType,
1261 /*OpLoc*/ SourceLocation(),
1262 /*IsArrow*/ true,
1263 SS, R, TemplateArgs);
John McCalld14a8642009-11-21 08:51:07 +00001264}
1265
John McCalle66edc12009-11-24 19:00:30 +00001266bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00001267 const LookupResult &R,
1268 bool HasTrailingLParen) {
John McCalld14a8642009-11-21 08:51:07 +00001269 // Only when used directly as the postfix-expression of a call.
1270 if (!HasTrailingLParen)
1271 return false;
1272
1273 // Never if a scope specifier was provided.
John McCalle66edc12009-11-24 19:00:30 +00001274 if (SS.isSet())
John McCalld14a8642009-11-21 08:51:07 +00001275 return false;
1276
1277 // Only in C++ or ObjC++.
John McCallb53bbd42009-11-22 01:44:31 +00001278 if (!getLangOptions().CPlusPlus)
John McCalld14a8642009-11-21 08:51:07 +00001279 return false;
1280
1281 // Turn off ADL when we find certain kinds of declarations during
1282 // normal lookup:
1283 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
1284 NamedDecl *D = *I;
1285
1286 // C++0x [basic.lookup.argdep]p3:
1287 // -- a declaration of a class member
1288 // Since using decls preserve this property, we check this on the
1289 // original decl.
John McCall5af04502009-12-02 20:26:00 +00001290 if (IsClassMember(D))
John McCalld14a8642009-11-21 08:51:07 +00001291 return false;
1292
1293 // C++0x [basic.lookup.argdep]p3:
1294 // -- a block-scope function declaration that is not a
1295 // using-declaration
1296 // NOTE: we also trigger this for function templates (in fact, we
1297 // don't check the decl type at all, since all other decl types
1298 // turn off ADL anyway).
1299 if (isa<UsingShadowDecl>(D))
1300 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1301 else if (D->getDeclContext()->isFunctionOrMethod())
1302 return false;
1303
1304 // C++0x [basic.lookup.argdep]p3:
1305 // -- a declaration that is neither a function or a function
1306 // template
1307 // And also for builtin functions.
1308 if (isa<FunctionDecl>(D)) {
1309 FunctionDecl *FDecl = cast<FunctionDecl>(D);
1310
1311 // But also builtin functions.
1312 if (FDecl->getBuiltinID() && FDecl->isImplicit())
1313 return false;
1314 } else if (!isa<FunctionTemplateDecl>(D))
1315 return false;
1316 }
1317
1318 return true;
1319}
1320
1321
John McCalld14a8642009-11-21 08:51:07 +00001322/// Diagnoses obvious problems with the use of the given declaration
1323/// as an expression. This is only actually called for lookups that
1324/// were not overloaded, and it doesn't promise that the declaration
1325/// will in fact be used.
1326static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
1327 if (isa<TypedefDecl>(D)) {
1328 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
1329 return true;
1330 }
1331
1332 if (isa<ObjCInterfaceDecl>(D)) {
1333 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
1334 return true;
1335 }
1336
1337 if (isa<NamespaceDecl>(D)) {
1338 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
1339 return true;
1340 }
1341
1342 return false;
1343}
1344
1345Sema::OwningExprResult
John McCalle66edc12009-11-24 19:00:30 +00001346Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00001347 LookupResult &R,
1348 bool NeedsADL) {
John McCalle66edc12009-11-24 19:00:30 +00001349 // If this isn't an overloaded result and we don't need ADL, just
1350 // build an ordinary singleton decl ref.
John McCallb53bbd42009-11-22 01:44:31 +00001351 if (!NeedsADL && !R.isOverloadedResult())
1352 return BuildDeclarationNameExpr(SS, R.getNameLoc(), R.getFoundDecl());
John McCalld14a8642009-11-21 08:51:07 +00001353
1354 // We only need to check the declaration if there's exactly one
1355 // result, because in the overloaded case the results can only be
1356 // functions and function templates.
John McCallb53bbd42009-11-22 01:44:31 +00001357 if (R.isSingleResult() &&
1358 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCalld14a8642009-11-21 08:51:07 +00001359 return ExprError();
1360
John McCalle66edc12009-11-24 19:00:30 +00001361 bool Dependent
1362 = UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(), 0);
John McCalld14a8642009-11-21 08:51:07 +00001363 UnresolvedLookupExpr *ULE
John McCalle66edc12009-11-24 19:00:30 +00001364 = UnresolvedLookupExpr::Create(Context, Dependent,
1365 (NestedNameSpecifier*) SS.getScopeRep(),
1366 SS.getRange(),
John McCallb53bbd42009-11-22 01:44:31 +00001367 R.getLookupName(), R.getNameLoc(),
1368 NeedsADL, R.isOverloadedResult());
1369 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1370 ULE->addDecl(*I);
John McCalld14a8642009-11-21 08:51:07 +00001371
1372 return Owned(ULE);
1373}
1374
1375
1376/// \brief Complete semantic analysis for a reference to the given declaration.
1377Sema::OwningExprResult
John McCalle66edc12009-11-24 19:00:30 +00001378Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCalld14a8642009-11-21 08:51:07 +00001379 SourceLocation Loc, NamedDecl *D) {
1380 assert(D && "Cannot refer to a NULL declaration");
John McCall283b9012009-11-22 00:44:51 +00001381 assert(!isa<FunctionTemplateDecl>(D) &&
1382 "Cannot refer unambiguously to a function template");
John McCalld14a8642009-11-21 08:51:07 +00001383 DeclarationName Name = D->getDeclName();
1384
1385 if (CheckDeclInExpr(*this, Loc, D))
1386 return ExprError();
Steve Narofff1e53692007-03-23 22:27:02 +00001387
Douglas Gregore7488b92009-12-01 16:58:18 +00001388 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
1389 // Specifically diagnose references to class templates that are missing
1390 // a template argument list.
1391 Diag(Loc, diag::err_template_decl_ref)
1392 << Template << SS.getRange();
1393 Diag(Template->getLocation(), diag::note_template_decl_here);
1394 return ExprError();
1395 }
1396
1397 // Make sure that we're referring to a value.
1398 ValueDecl *VD = dyn_cast<ValueDecl>(D);
1399 if (!VD) {
1400 Diag(Loc, diag::err_ref_non_value)
1401 << D << SS.getRange();
1402 Diag(D->getLocation(), diag::note_previous_decl);
1403 return ExprError();
1404 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00001405
Douglas Gregor171c45a2009-02-18 21:56:37 +00001406 // Check whether this declaration can be used. Note that we suppress
1407 // this check when we're going to perform argument-dependent lookup
1408 // on this function name, because this might not be the function
1409 // that overload resolution actually selects.
John McCalld14a8642009-11-21 08:51:07 +00001410 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor171c45a2009-02-18 21:56:37 +00001411 return ExprError();
1412
Steve Naroff8de9c3a2008-09-05 22:11:13 +00001413 // Only create DeclRefExpr's for valid Decl's.
1414 if (VD->isInvalidDecl())
Sebastian Redlffbcf962009-01-18 18:53:16 +00001415 return ExprError();
1416
Chris Lattner2a9d9892008-10-20 05:16:36 +00001417 // If the identifier reference is inside a block, and it refers to a value
1418 // that is outside the block, create a BlockDeclRefExpr instead of a
1419 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
1420 // the block is formed.
Steve Naroff8de9c3a2008-09-05 22:11:13 +00001421 //
Chris Lattner2a9d9892008-10-20 05:16:36 +00001422 // We do not do this for things like enum constants, global variables, etc,
1423 // as they do not get snapshotted.
1424 //
1425 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00001426 MarkDeclarationReferenced(Loc, VD);
Eli Friedman7fa3faa2009-03-22 23:00:19 +00001427 QualType ExprTy = VD->getType().getNonReferenceType();
Steve Naroff1d95e5a2008-10-10 01:28:17 +00001428 // The BlocksAttr indicates the variable is bound by-reference.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001429 if (VD->getAttr<BlocksAttr>())
Eli Friedman7fa3faa2009-03-22 23:00:19 +00001430 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, true));
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00001431 // This is to record that a 'const' was actually synthesize and added.
1432 bool constAdded = !ExprTy.isConstQualified();
Steve Naroff1d95e5a2008-10-10 01:28:17 +00001433 // Variable will be bound by-copy, make it const within the closure.
Mike Stump11289f42009-09-09 15:08:12 +00001434
Eli Friedman7fa3faa2009-03-22 23:00:19 +00001435 ExprTy.addConst();
Mike Stump11289f42009-09-09 15:08:12 +00001436 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, false,
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00001437 constAdded));
Steve Naroff1d95e5a2008-10-10 01:28:17 +00001438 }
1439 // If this reference is not in a block or if the referenced variable is
1440 // within the block, create a normal DeclRefExpr.
Douglas Gregor4619e432008-12-05 23:32:09 +00001441
John McCalle66edc12009-11-24 19:00:30 +00001442 return BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc, &SS);
Chris Lattner17ed4872006-11-20 04:58:19 +00001443}
Chris Lattnere168f762006-11-10 05:29:30 +00001444
Sebastian Redlffbcf962009-01-18 18:53:16 +00001445Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
1446 tok::TokenKind Kind) {
Chris Lattner6307f192008-08-10 01:53:14 +00001447 PredefinedExpr::IdentType IT;
Sebastian Redlffbcf962009-01-18 18:53:16 +00001448
Chris Lattnere168f762006-11-10 05:29:30 +00001449 switch (Kind) {
Chris Lattner317e6ba2008-01-12 18:39:25 +00001450 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner6307f192008-08-10 01:53:14 +00001451 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
1452 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
1453 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattnere168f762006-11-10 05:29:30 +00001454 }
Chris Lattner317e6ba2008-01-12 18:39:25 +00001455
Chris Lattnera81a0272008-01-12 08:14:25 +00001456 // Pre-defined identifiers are of type char[x], where x is the length of the
1457 // string.
Mike Stump11289f42009-09-09 15:08:12 +00001458
Anders Carlsson2fb08242009-09-08 18:24:21 +00001459 Decl *currentDecl = getCurFunctionOrMethodDecl();
1460 if (!currentDecl) {
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00001461 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson2fb08242009-09-08 18:24:21 +00001462 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00001463 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00001464
Anders Carlsson0b209a82009-09-11 01:22:35 +00001465 QualType ResTy;
1466 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
1467 ResTy = Context.DependentTy;
1468 } else {
1469 unsigned Length =
1470 PredefinedExpr::ComputeName(Context, IT, currentDecl).length();
Sebastian Redlffbcf962009-01-18 18:53:16 +00001471
Anders Carlsson0b209a82009-09-11 01:22:35 +00001472 llvm::APInt LengthI(32, Length + 1);
John McCall8ccfcb52009-09-24 19:53:00 +00001473 ResTy = Context.CharTy.withConst();
Anders Carlsson0b209a82009-09-11 01:22:35 +00001474 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
1475 }
Steve Narofff6009ed2009-01-21 00:14:39 +00001476 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattnere168f762006-11-10 05:29:30 +00001477}
1478
Sebastian Redlffbcf962009-01-18 18:53:16 +00001479Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00001480 llvm::SmallString<16> CharBuffer;
Steve Naroffae4143e2007-04-26 20:39:23 +00001481 CharBuffer.resize(Tok.getLength());
1482 const char *ThisTokBegin = &CharBuffer[0];
1483 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlffbcf962009-01-18 18:53:16 +00001484
Steve Naroffae4143e2007-04-26 20:39:23 +00001485 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1486 Tok.getLocation(), PP);
1487 if (Literal.hadError())
Sebastian Redlffbcf962009-01-18 18:53:16 +00001488 return ExprError();
Chris Lattneref24b382008-03-01 08:32:21 +00001489
1490 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
1491
Sebastian Redl20614a72009-01-20 22:23:13 +00001492 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
1493 Literal.isWide(),
1494 type, Tok.getLocation()));
Steve Naroffae4143e2007-04-26 20:39:23 +00001495}
1496
Sebastian Redlffbcf962009-01-18 18:53:16 +00001497Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
1498 // Fast path for a single digit (which is quite common). A single digit
Steve Narofff2fb89e2007-03-13 20:29:44 +00001499 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
1500 if (Tok.getLength() == 1) {
Chris Lattner9240b3e2009-01-26 22:36:52 +00001501 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattnerc4c18192009-01-16 07:10:29 +00001502 unsigned IntSize = Context.Target.getIntWidth();
Steve Narofff6009ed2009-01-21 00:14:39 +00001503 return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
Steve Naroff5faaef72009-01-20 19:53:53 +00001504 Context.IntTy, Tok.getLocation()));
Steve Narofff2fb89e2007-03-13 20:29:44 +00001505 }
Ted Kremeneke9814182009-01-13 23:19:12 +00001506
Chris Lattner23b7eb62007-06-15 23:05:46 +00001507 llvm::SmallString<512> IntegerBuffer;
Chris Lattnera1cf5f92008-09-30 20:53:45 +00001508 // Add padding so that NumericLiteralParser can overread by one character.
1509 IntegerBuffer.resize(Tok.getLength()+1);
Steve Naroff8160ea22007-03-06 01:09:46 +00001510 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlffbcf962009-01-18 18:53:16 +00001511
Chris Lattner67ca9252007-05-21 01:08:44 +00001512 // Get the spelling of the token, which eliminates trigraphs, etc.
Steve Naroff8160ea22007-03-06 01:09:46 +00001513 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlffbcf962009-01-18 18:53:16 +00001514
Mike Stump11289f42009-09-09 15:08:12 +00001515 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Steve Naroff451d8f162007-03-12 23:22:38 +00001516 Tok.getLocation(), PP);
Steve Narofff2fb89e2007-03-13 20:29:44 +00001517 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +00001518 return ExprError();
1519
Chris Lattner1c20a172007-08-26 03:42:43 +00001520 Expr *Res;
Sebastian Redlffbcf962009-01-18 18:53:16 +00001521
Chris Lattner1c20a172007-08-26 03:42:43 +00001522 if (Literal.isFloatingLiteral()) {
Chris Lattnerec0a6d92007-09-22 18:29:59 +00001523 QualType Ty;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001524 if (Literal.isFloat)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00001525 Ty = Context.FloatTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001526 else if (!Literal.isLong)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00001527 Ty = Context.DoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001528 else
Chris Lattner7570e9c2008-03-08 08:52:55 +00001529 Ty = Context.LongDoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001530
1531 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
1532
Ted Kremenek3a2c9502007-11-29 00:56:49 +00001533 // isExact will be set by GetFloatValue().
1534 bool isExact = false;
Chris Lattnere4edb8e2009-06-29 17:34:55 +00001535 llvm::APFloat Val = Literal.GetFloatValue(Format, &isExact);
1536 Res = new (Context) FloatingLiteral(Val, isExact, Ty, Tok.getLocation());
Sebastian Redlffbcf962009-01-18 18:53:16 +00001537
Chris Lattner1c20a172007-08-26 03:42:43 +00001538 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00001539 return ExprError();
Chris Lattner1c20a172007-08-26 03:42:43 +00001540 } else {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001541 QualType Ty;
Chris Lattner67ca9252007-05-21 01:08:44 +00001542
Neil Boothac582c52007-08-29 22:00:19 +00001543 // long long is a C99 feature.
1544 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth4a1ee052007-08-29 22:13:52 +00001545 Literal.isLongLong)
Neil Boothac582c52007-08-29 22:00:19 +00001546 Diag(Tok.getLocation(), diag::ext_longlong);
1547
Chris Lattner67ca9252007-05-21 01:08:44 +00001548 // Get the value in the widest-possible width.
Chris Lattner37e05872008-03-05 18:54:05 +00001549 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlffbcf962009-01-18 18:53:16 +00001550
Chris Lattner67ca9252007-05-21 01:08:44 +00001551 if (Literal.GetIntegerValue(ResultVal)) {
1552 // If this value didn't fit into uintmax_t, warn and force to ull.
1553 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001554 Ty = Context.UnsignedLongLongTy;
1555 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner37e05872008-03-05 18:54:05 +00001556 "long long is not intmax_t?");
Steve Naroff09ef4742007-03-09 23:16:33 +00001557 } else {
Chris Lattner67ca9252007-05-21 01:08:44 +00001558 // If this value fits into a ULL, try to figure out what else it fits into
1559 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlffbcf962009-01-18 18:53:16 +00001560
Chris Lattner67ca9252007-05-21 01:08:44 +00001561 // Octal, Hexadecimal, and integers with a U suffix are allowed to
1562 // be an unsigned int.
1563 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
1564
1565 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner55258cf2008-05-09 05:59:00 +00001566 unsigned Width = 0;
Chris Lattner7b939cf2007-08-23 21:58:08 +00001567 if (!Literal.isLong && !Literal.isLongLong) {
1568 // Are int/unsigned possibilities?
Chris Lattner55258cf2008-05-09 05:59:00 +00001569 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00001570
Chris Lattner67ca9252007-05-21 01:08:44 +00001571 // Does it fit in a unsigned int?
1572 if (ResultVal.isIntN(IntSize)) {
1573 // Does it fit in a signed int?
1574 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001575 Ty = Context.IntTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00001576 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001577 Ty = Context.UnsignedIntTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00001578 Width = IntSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00001579 }
Chris Lattner67ca9252007-05-21 01:08:44 +00001580 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00001581
Chris Lattner67ca9252007-05-21 01:08:44 +00001582 // Are long/unsigned long possibilities?
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001583 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner55258cf2008-05-09 05:59:00 +00001584 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00001585
Chris Lattner67ca9252007-05-21 01:08:44 +00001586 // Does it fit in a unsigned long?
1587 if (ResultVal.isIntN(LongSize)) {
1588 // Does it fit in a signed long?
1589 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001590 Ty = Context.LongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00001591 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001592 Ty = Context.UnsignedLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00001593 Width = LongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00001594 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00001595 }
1596
Chris Lattner67ca9252007-05-21 01:08:44 +00001597 // Finally, check long long if needed.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001598 if (Ty.isNull()) {
Chris Lattner55258cf2008-05-09 05:59:00 +00001599 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00001600
Chris Lattner67ca9252007-05-21 01:08:44 +00001601 // Does it fit in a unsigned long long?
1602 if (ResultVal.isIntN(LongLongSize)) {
1603 // Does it fit in a signed long long?
1604 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001605 Ty = Context.LongLongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00001606 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001607 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00001608 Width = LongLongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00001609 }
1610 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00001611
Chris Lattner67ca9252007-05-21 01:08:44 +00001612 // If we still couldn't decide a type, we probably have something that
1613 // does not fit in a signed long long, but has no U suffix.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001614 if (Ty.isNull()) {
Chris Lattner67ca9252007-05-21 01:08:44 +00001615 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001616 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00001617 Width = Context.Target.getLongLongWidth();
Chris Lattner67ca9252007-05-21 01:08:44 +00001618 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00001619
Chris Lattner55258cf2008-05-09 05:59:00 +00001620 if (ResultVal.getBitWidth() != Width)
1621 ResultVal.trunc(Width);
Steve Naroff09ef4742007-03-09 23:16:33 +00001622 }
Sebastian Redl20614a72009-01-20 22:23:13 +00001623 Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Steve Naroff09ef4742007-03-09 23:16:33 +00001624 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00001625
Chris Lattner1c20a172007-08-26 03:42:43 +00001626 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
1627 if (Literal.isImaginary)
Mike Stump11289f42009-09-09 15:08:12 +00001628 Res = new (Context) ImaginaryLiteral(Res,
Steve Narofff6009ed2009-01-21 00:14:39 +00001629 Context.getComplexType(Res->getType()));
Sebastian Redlffbcf962009-01-18 18:53:16 +00001630
1631 return Owned(Res);
Chris Lattnere168f762006-11-10 05:29:30 +00001632}
1633
Sebastian Redlffbcf962009-01-18 18:53:16 +00001634Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1635 SourceLocation R, ExprArg Val) {
Anders Carlssonb781bcd2009-05-01 19:49:17 +00001636 Expr *E = Val.takeAs<Expr>();
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001637 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Narofff6009ed2009-01-21 00:14:39 +00001638 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattnere168f762006-11-10 05:29:30 +00001639}
1640
Steve Naroff71b59a92007-06-04 22:22:31 +00001641/// The UsualUnaryConversions() function is *not* called by this routine.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00001642/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001643bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Sebastian Redl6f282892008-11-11 17:56:53 +00001644 SourceLocation OpLoc,
1645 const SourceRange &ExprRange,
1646 bool isSizeof) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001647 if (exprType->isDependentType())
1648 return false;
1649
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001650 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
1651 // the result is the size of the referenced type."
1652 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
1653 // result shall be the alignment of the referenced type."
1654 if (const ReferenceType *Ref = exprType->getAs<ReferenceType>())
1655 exprType = Ref->getPointeeType();
1656
Steve Naroff043d45d2007-05-15 02:32:35 +00001657 // C99 6.5.3.4p1:
John McCall4c98fd82009-11-04 07:28:41 +00001658 if (exprType->isFunctionType()) {
Chris Lattner62975a72009-04-24 00:30:45 +00001659 // alignof(function) is allowed as an extension.
Chris Lattnerb1355b12009-01-24 19:46:37 +00001660 if (isSizeof)
1661 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
1662 return false;
1663 }
Mike Stump11289f42009-09-09 15:08:12 +00001664
Chris Lattner62975a72009-04-24 00:30:45 +00001665 // Allow sizeof(void)/alignof(void) as an extension.
Chris Lattnerb1355b12009-01-24 19:46:37 +00001666 if (exprType->isVoidType()) {
Chris Lattner3b054132008-11-19 05:08:23 +00001667 Diag(OpLoc, diag::ext_sizeof_void_type)
1668 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattnerb1355b12009-01-24 19:46:37 +00001669 return false;
1670 }
Mike Stump11289f42009-09-09 15:08:12 +00001671
Chris Lattner62975a72009-04-24 00:30:45 +00001672 if (RequireCompleteType(OpLoc, exprType,
Mike Stump11289f42009-09-09 15:08:12 +00001673 isSizeof ? diag::err_sizeof_incomplete_type :
Anders Carlssond624e162009-08-26 23:45:07 +00001674 PDiag(diag::err_alignof_incomplete_type)
1675 << ExprRange))
Chris Lattner62975a72009-04-24 00:30:45 +00001676 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001677
Chris Lattner62975a72009-04-24 00:30:45 +00001678 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
Fariborz Jahanian1dcb3222009-04-24 17:34:33 +00001679 if (LangOpts.ObjCNonFragileABI && exprType->isObjCInterfaceType()) {
Chris Lattner62975a72009-04-24 00:30:45 +00001680 Diag(OpLoc, diag::err_sizeof_nonfragile_interface)
Chris Lattnercd2a8c52009-04-24 22:30:50 +00001681 << exprType << isSizeof << ExprRange;
1682 return true;
Chris Lattner37920f52009-04-21 19:55:16 +00001683 }
Mike Stump11289f42009-09-09 15:08:12 +00001684
Chris Lattner62975a72009-04-24 00:30:45 +00001685 return false;
Steve Naroff043d45d2007-05-15 02:32:35 +00001686}
1687
Chris Lattner8dff0172009-01-24 20:17:12 +00001688bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
1689 const SourceRange &ExprRange) {
1690 E = E->IgnoreParens();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001691
Mike Stump11289f42009-09-09 15:08:12 +00001692 // alignof decl is always ok.
Chris Lattner8dff0172009-01-24 20:17:12 +00001693 if (isa<DeclRefExpr>(E))
1694 return false;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001695
1696 // Cannot know anything else if the expression is dependent.
1697 if (E->isTypeDependent())
1698 return false;
1699
Douglas Gregor71235ec2009-05-02 02:18:30 +00001700 if (E->getBitField()) {
1701 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
1702 return true;
Chris Lattner8dff0172009-01-24 20:17:12 +00001703 }
Douglas Gregor71235ec2009-05-02 02:18:30 +00001704
1705 // Alignment of a field access is always okay, so long as it isn't a
1706 // bit-field.
1707 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump212005c2009-07-22 18:58:19 +00001708 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor71235ec2009-05-02 02:18:30 +00001709 return false;
1710
Chris Lattner8dff0172009-01-24 20:17:12 +00001711 return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
1712}
1713
Douglas Gregor0950e412009-03-13 21:01:28 +00001714/// \brief Build a sizeof or alignof expression given a type operand.
Mike Stump11289f42009-09-09 15:08:12 +00001715Action::OwningExprResult
John McCallbcd03502009-12-07 02:54:59 +00001716Sema::CreateSizeOfAlignOfExpr(TypeSourceInfo *TInfo,
John McCall4c98fd82009-11-04 07:28:41 +00001717 SourceLocation OpLoc,
Douglas Gregor0950e412009-03-13 21:01:28 +00001718 bool isSizeOf, SourceRange R) {
John McCallbcd03502009-12-07 02:54:59 +00001719 if (!TInfo)
Douglas Gregor0950e412009-03-13 21:01:28 +00001720 return ExprError();
1721
John McCallbcd03502009-12-07 02:54:59 +00001722 QualType T = TInfo->getType();
John McCall4c98fd82009-11-04 07:28:41 +00001723
Douglas Gregor0950e412009-03-13 21:01:28 +00001724 if (!T->isDependentType() &&
1725 CheckSizeOfAlignOfOperand(T, OpLoc, R, isSizeOf))
1726 return ExprError();
1727
1728 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
John McCallbcd03502009-12-07 02:54:59 +00001729 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, TInfo,
Douglas Gregor0950e412009-03-13 21:01:28 +00001730 Context.getSizeType(), OpLoc,
1731 R.getEnd()));
1732}
1733
1734/// \brief Build a sizeof or alignof expression given an expression
1735/// operand.
Mike Stump11289f42009-09-09 15:08:12 +00001736Action::OwningExprResult
1737Sema::CreateSizeOfAlignOfExpr(Expr *E, SourceLocation OpLoc,
Douglas Gregor0950e412009-03-13 21:01:28 +00001738 bool isSizeOf, SourceRange R) {
1739 // Verify that the operand is valid.
1740 bool isInvalid = false;
1741 if (E->isTypeDependent()) {
1742 // Delay type-checking for type-dependent expressions.
1743 } else if (!isSizeOf) {
1744 isInvalid = CheckAlignOfExpr(E, OpLoc, R);
Douglas Gregor71235ec2009-05-02 02:18:30 +00001745 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Douglas Gregor0950e412009-03-13 21:01:28 +00001746 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
1747 isInvalid = true;
1748 } else {
1749 isInvalid = CheckSizeOfAlignOfOperand(E->getType(), OpLoc, R, true);
1750 }
1751
1752 if (isInvalid)
1753 return ExprError();
1754
1755 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1756 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, E,
1757 Context.getSizeType(), OpLoc,
1758 R.getEnd()));
1759}
1760
Sebastian Redl6f282892008-11-11 17:56:53 +00001761/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1762/// the same for @c alignof and @c __alignof
1763/// Note that the ArgRange is invalid if isType is false.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001764Action::OwningExprResult
Sebastian Redl6f282892008-11-11 17:56:53 +00001765Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1766 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner0d8b1a12006-11-20 04:34:45 +00001767 // If error parsing type, ignore.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001768 if (TyOrEx == 0) return ExprError();
Steve Naroff043d45d2007-05-15 02:32:35 +00001769
Sebastian Redl6f282892008-11-11 17:56:53 +00001770 if (isType) {
John McCallbcd03502009-12-07 02:54:59 +00001771 TypeSourceInfo *TInfo;
1772 (void) GetTypeFromParser(TyOrEx, &TInfo);
1773 return CreateSizeOfAlignOfExpr(TInfo, OpLoc, isSizeof, ArgRange);
Mike Stump11289f42009-09-09 15:08:12 +00001774 }
Sebastian Redl6f282892008-11-11 17:56:53 +00001775
Douglas Gregor0950e412009-03-13 21:01:28 +00001776 Expr *ArgEx = (Expr *)TyOrEx;
1777 Action::OwningExprResult Result
1778 = CreateSizeOfAlignOfExpr(ArgEx, OpLoc, isSizeof, ArgEx->getSourceRange());
1779
1780 if (Result.isInvalid())
1781 DeleteExpr(ArgEx);
1782
1783 return move(Result);
Chris Lattnere168f762006-11-10 05:29:30 +00001784}
1785
Chris Lattner709322b2009-02-17 08:12:06 +00001786QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc, bool isReal) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001787 if (V->isTypeDependent())
1788 return Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00001789
Chris Lattnere267f5d2007-08-26 05:39:26 +00001790 // These operators return the element type of a complex type.
John McCall9dd450b2009-09-21 23:43:11 +00001791 if (const ComplexType *CT = V->getType()->getAs<ComplexType>())
Chris Lattner30b5dd02007-08-24 21:16:53 +00001792 return CT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00001793
Chris Lattnere267f5d2007-08-26 05:39:26 +00001794 // Otherwise they pass through real integer and floating point types here.
1795 if (V->getType()->isArithmeticType())
1796 return V->getType();
Mike Stump11289f42009-09-09 15:08:12 +00001797
Chris Lattnere267f5d2007-08-26 05:39:26 +00001798 // Reject anything else.
Chris Lattner709322b2009-02-17 08:12:06 +00001799 Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
1800 << (isReal ? "__real" : "__imag");
Chris Lattnere267f5d2007-08-26 05:39:26 +00001801 return QualType();
Chris Lattner30b5dd02007-08-24 21:16:53 +00001802}
1803
1804
Chris Lattnere168f762006-11-10 05:29:30 +00001805
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001806Action::OwningExprResult
1807Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
1808 tok::TokenKind Kind, ExprArg Input) {
Chris Lattnere168f762006-11-10 05:29:30 +00001809 UnaryOperator::Opcode Opc;
1810 switch (Kind) {
1811 default: assert(0 && "Unknown unary op!");
1812 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
1813 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1814 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001815
Eli Friedmancfdd40c2009-11-18 03:38:04 +00001816 return BuildUnaryOp(S, OpLoc, Opc, move(Input));
Chris Lattnere168f762006-11-10 05:29:30 +00001817}
1818
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001819Action::OwningExprResult
1820Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
1821 ExprArg Idx, SourceLocation RLoc) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00001822 // Since this might be a postfix expression, get rid of ParenListExprs.
1823 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
1824
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001825 Expr *LHSExp = static_cast<Expr*>(Base.get()),
1826 *RHSExp = static_cast<Expr*>(Idx.get());
Mike Stump11289f42009-09-09 15:08:12 +00001827
Douglas Gregor40412ac2008-11-19 17:17:41 +00001828 if (getLangOptions().CPlusPlus &&
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00001829 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
1830 Base.release();
1831 Idx.release();
1832 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
1833 Context.DependentTy, RLoc));
1834 }
1835
Mike Stump11289f42009-09-09 15:08:12 +00001836 if (getLangOptions().CPlusPlus &&
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001837 (LHSExp->getType()->isRecordType() ||
Eli Friedman254a1a22008-12-15 22:34:21 +00001838 LHSExp->getType()->isEnumeralType() ||
1839 RHSExp->getType()->isRecordType() ||
1840 RHSExp->getType()->isEnumeralType())) {
Sebastian Redladba46e2009-10-29 20:17:01 +00001841 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, move(Base),move(Idx));
Douglas Gregor40412ac2008-11-19 17:17:41 +00001842 }
1843
Sebastian Redladba46e2009-10-29 20:17:01 +00001844 return CreateBuiltinArraySubscriptExpr(move(Base), LLoc, move(Idx), RLoc);
1845}
1846
1847
1848Action::OwningExprResult
1849Sema::CreateBuiltinArraySubscriptExpr(ExprArg Base, SourceLocation LLoc,
1850 ExprArg Idx, SourceLocation RLoc) {
1851 Expr *LHSExp = static_cast<Expr*>(Base.get());
1852 Expr *RHSExp = static_cast<Expr*>(Idx.get());
1853
Chris Lattner36d572b2007-07-16 00:14:47 +00001854 // Perform default conversions.
1855 DefaultFunctionArrayConversion(LHSExp);
1856 DefaultFunctionArrayConversion(RHSExp);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001857
Chris Lattner36d572b2007-07-16 00:14:47 +00001858 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
Steve Narofff1e53692007-03-23 22:27:02 +00001859
Steve Naroffc1aadb12007-03-28 21:49:40 +00001860 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattnerf17bd422007-08-30 17:45:32 +00001861 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stump4e1f26a2009-02-19 03:04:26 +00001862 // in the subscript position. As a result, we need to derive the array base
Steve Narofff1e53692007-03-23 22:27:02 +00001863 // and index from the expression types.
Chris Lattner36d572b2007-07-16 00:14:47 +00001864 Expr *BaseExpr, *IndexExpr;
1865 QualType ResultType;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001866 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
1867 BaseExpr = LHSExp;
1868 IndexExpr = RHSExp;
1869 ResultType = Context.DependentTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001870 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner36d572b2007-07-16 00:14:47 +00001871 BaseExpr = LHSExp;
1872 IndexExpr = RHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00001873 ResultType = PTy->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001874 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattneraee0cfd2007-07-16 00:23:25 +00001875 // Handle the uncommon case of "123[Ptr]".
Chris Lattner36d572b2007-07-16 00:14:47 +00001876 BaseExpr = RHSExp;
1877 IndexExpr = LHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00001878 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00001879 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00001880 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001881 BaseExpr = LHSExp;
1882 IndexExpr = RHSExp;
1883 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00001884 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00001885 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001886 // Handle the uncommon case of "123[Ptr]".
1887 BaseExpr = RHSExp;
1888 IndexExpr = LHSExp;
1889 ResultType = PTy->getPointeeType();
John McCall9dd450b2009-09-21 23:43:11 +00001890 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattner41977962007-07-31 19:29:30 +00001891 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner36d572b2007-07-16 00:14:47 +00001892 IndexExpr = RHSExp;
Nate Begemanc1bf0612009-01-18 00:45:31 +00001893
Chris Lattner36d572b2007-07-16 00:14:47 +00001894 // FIXME: need to deal with const...
1895 ResultType = VTy->getElementType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00001896 } else if (LHSTy->isArrayType()) {
1897 // If we see an array that wasn't promoted by
1898 // DefaultFunctionArrayConversion, it must be an array that
1899 // wasn't promoted because of the C90 rule that doesn't
1900 // allow promoting non-lvalue arrays. Warn, then
1901 // force the promotion here.
1902 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
1903 LHSExp->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00001904 ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
1905 CastExpr::CK_ArrayToPointerDecay);
Eli Friedmanab2784f2009-04-25 23:46:54 +00001906 LHSTy = LHSExp->getType();
1907
1908 BaseExpr = LHSExp;
1909 IndexExpr = RHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001910 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00001911 } else if (RHSTy->isArrayType()) {
1912 // Same as previous, except for 123[f().a] case
1913 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
1914 RHSExp->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00001915 ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
1916 CastExpr::CK_ArrayToPointerDecay);
Eli Friedmanab2784f2009-04-25 23:46:54 +00001917 RHSTy = RHSExp->getType();
1918
1919 BaseExpr = RHSExp;
1920 IndexExpr = LHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001921 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroffb3096442007-06-09 03:47:53 +00001922 } else {
Chris Lattner003af242009-04-25 22:50:55 +00001923 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
1924 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001925 }
Steve Naroffc1aadb12007-03-28 21:49:40 +00001926 // C99 6.5.2.1p1
Nate Begeman5ec4b312009-08-10 23:49:36 +00001927 if (!(IndexExpr->getType()->isIntegerType() &&
1928 IndexExpr->getType()->isScalarType()) && !IndexExpr->isTypeDependent())
Chris Lattner003af242009-04-25 22:50:55 +00001929 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
1930 << IndexExpr->getSourceRange());
Steve Naroffb29cdd52007-07-10 18:23:31 +00001931
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00001932 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinigb7608d72009-09-14 20:14:57 +00001933 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
1934 && !IndexExpr->isTypeDependent())
Sam Weinig914244e2009-09-14 01:58:58 +00001935 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
1936
Douglas Gregorac1fb652009-03-24 19:52:54 +00001937 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump11289f42009-09-09 15:08:12 +00001938 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
1939 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregorac1fb652009-03-24 19:52:54 +00001940 // incomplete types are not object types.
1941 if (ResultType->isFunctionType()) {
1942 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
1943 << ResultType << BaseExpr->getSourceRange();
1944 return ExprError();
1945 }
Mike Stump11289f42009-09-09 15:08:12 +00001946
Douglas Gregorac1fb652009-03-24 19:52:54 +00001947 if (!ResultType->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00001948 RequireCompleteType(LLoc, ResultType,
Anders Carlssond624e162009-08-26 23:45:07 +00001949 PDiag(diag::err_subscript_incomplete_type)
1950 << BaseExpr->getSourceRange()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00001951 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001952
Chris Lattner62975a72009-04-24 00:30:45 +00001953 // Diagnose bad cases where we step over interface counts.
1954 if (ResultType->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
1955 Diag(LLoc, diag::err_subscript_nonfragile_interface)
1956 << ResultType << BaseExpr->getSourceRange();
1957 return ExprError();
1958 }
Mike Stump11289f42009-09-09 15:08:12 +00001959
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001960 Base.release();
1961 Idx.release();
Mike Stump4e1f26a2009-02-19 03:04:26 +00001962 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
Steve Narofff6009ed2009-01-21 00:14:39 +00001963 ResultType, RLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00001964}
1965
Steve Narofff8fd09e2007-07-27 22:15:19 +00001966QualType Sema::
Nate Begemance4d7fc2008-04-18 23:10:10 +00001967CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001968 const IdentifierInfo *CompName,
Anders Carlssonf571c112009-08-26 18:25:21 +00001969 SourceLocation CompLoc) {
Daniel Dunbarc0429402009-10-18 02:09:38 +00001970 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
1971 // see FIXME there.
1972 //
1973 // FIXME: This logic can be greatly simplified by splitting it along
1974 // halving/not halving and reworking the component checking.
John McCall9dd450b2009-09-21 23:43:11 +00001975 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
Nate Begemanf322eab2008-05-09 06:41:27 +00001976
Steve Narofff8fd09e2007-07-27 22:15:19 +00001977 // The vector accessor can't exceed the number of elements.
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00001978 const char *compStr = CompName->getNameStart();
Nate Begemanbb70bf62009-01-18 01:47:54 +00001979
Mike Stump4e1f26a2009-02-19 03:04:26 +00001980 // This flag determines whether or not the component is one of the four
Nate Begemanbb70bf62009-01-18 01:47:54 +00001981 // special names that indicate a subset of exactly half the elements are
1982 // to be selected.
1983 bool HalvingSwizzle = false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00001984
Nate Begemanbb70bf62009-01-18 01:47:54 +00001985 // This flag determines whether or not CompName has an 's' char prefix,
1986 // indicating that it is a string of hex values to be used as vector indices.
Nate Begeman0359e122009-06-25 21:06:09 +00001987 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
Nate Begemanf322eab2008-05-09 06:41:27 +00001988
1989 // Check that we've found one of the special components, or that the component
1990 // names must come from the same set.
Mike Stump4e1f26a2009-02-19 03:04:26 +00001991 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begemanbb70bf62009-01-18 01:47:54 +00001992 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
1993 HalvingSwizzle = true;
Nate Begemanf322eab2008-05-09 06:41:27 +00001994 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner7e152db2007-08-02 22:33:49 +00001995 do
1996 compStr++;
1997 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
Nate Begemanbb70bf62009-01-18 01:47:54 +00001998 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
Chris Lattner7e152db2007-08-02 22:33:49 +00001999 do
2000 compStr++;
Nate Begemanbb70bf62009-01-18 01:47:54 +00002001 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
Chris Lattner7e152db2007-08-02 22:33:49 +00002002 }
Nate Begemanbb70bf62009-01-18 01:47:54 +00002003
Mike Stump4e1f26a2009-02-19 03:04:26 +00002004 if (!HalvingSwizzle && *compStr) {
Steve Narofff8fd09e2007-07-27 22:15:19 +00002005 // We didn't get to the end of the string. This means the component names
2006 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattner3b054132008-11-19 05:08:23 +00002007 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
2008 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Narofff8fd09e2007-07-27 22:15:19 +00002009 return QualType();
2010 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00002011
Nate Begemanbb70bf62009-01-18 01:47:54 +00002012 // Ensure no component accessor exceeds the width of the vector type it
2013 // operates on.
2014 if (!HalvingSwizzle) {
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002015 compStr = CompName->getNameStart();
Nate Begemanbb70bf62009-01-18 01:47:54 +00002016
2017 if (HexSwizzle)
Steve Narofff8fd09e2007-07-27 22:15:19 +00002018 compStr++;
Nate Begemanbb70bf62009-01-18 01:47:54 +00002019
2020 while (*compStr) {
2021 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
2022 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
2023 << baseType << SourceRange(CompLoc);
2024 return QualType();
2025 }
2026 }
Steve Narofff8fd09e2007-07-27 22:15:19 +00002027 }
Nate Begemanf322eab2008-05-09 06:41:27 +00002028
Nate Begemanbb70bf62009-01-18 01:47:54 +00002029 // If this is a halving swizzle, verify that the base type has an even
2030 // number of elements.
2031 if (HalvingSwizzle && (vecType->getNumElements() & 1U)) {
Chris Lattner3b054132008-11-19 05:08:23 +00002032 Diag(OpLoc, diag::err_ext_vector_component_requires_even)
Chris Lattner1e5665e2008-11-24 06:25:27 +00002033 << baseType << SourceRange(CompLoc);
Nate Begemanf322eab2008-05-09 06:41:27 +00002034 return QualType();
2035 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00002036
Steve Narofff8fd09e2007-07-27 22:15:19 +00002037 // The component accessor looks fine - now we need to compute the actual type.
Mike Stump4e1f26a2009-02-19 03:04:26 +00002038 // The vector type is implied by the component accessor. For example,
Steve Narofff8fd09e2007-07-27 22:15:19 +00002039 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begemanbb70bf62009-01-18 01:47:54 +00002040 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begemanf322eab2008-05-09 06:41:27 +00002041 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begemanbb70bf62009-01-18 01:47:54 +00002042 unsigned CompSize = HalvingSwizzle ? vecType->getNumElements() / 2
Anders Carlssonf571c112009-08-26 18:25:21 +00002043 : CompName->getLength();
Nate Begemanbb70bf62009-01-18 01:47:54 +00002044 if (HexSwizzle)
2045 CompSize--;
2046
Steve Narofff8fd09e2007-07-27 22:15:19 +00002047 if (CompSize == 1)
2048 return vecType->getElementType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00002049
Nate Begemance4d7fc2008-04-18 23:10:10 +00002050 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stump4e1f26a2009-02-19 03:04:26 +00002051 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemance4d7fc2008-04-18 23:10:10 +00002052 // diagostics look bad. We want extended vector types to appear built-in.
2053 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
2054 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
2055 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroffddf5a1d2007-07-29 16:33:31 +00002056 }
2057 return VT; // should never get here (a typedef type should always be found).
Steve Narofff8fd09e2007-07-27 22:15:19 +00002058}
2059
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002060static Decl *FindGetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
Anders Carlssonf571c112009-08-26 18:25:21 +00002061 IdentifierInfo *Member,
Douglas Gregorbcced4e2009-04-09 21:40:53 +00002062 const Selector &Sel,
2063 ASTContext &Context) {
Mike Stump11289f42009-09-09 15:08:12 +00002064
Anders Carlssonf571c112009-08-26 18:25:21 +00002065 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002066 return PD;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002067 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002068 return OMD;
Mike Stump11289f42009-09-09 15:08:12 +00002069
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002070 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
2071 E = PDecl->protocol_end(); I != E; ++I) {
Mike Stump11289f42009-09-09 15:08:12 +00002072 if (Decl *D = FindGetterNameDeclFromProtocolList(*I, Member, Sel,
Douglas Gregorbcced4e2009-04-09 21:40:53 +00002073 Context))
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002074 return D;
2075 }
2076 return 0;
2077}
2078
Steve Narofffb4330f2009-06-17 22:40:22 +00002079static Decl *FindGetterNameDecl(const ObjCObjectPointerType *QIdTy,
Anders Carlssonf571c112009-08-26 18:25:21 +00002080 IdentifierInfo *Member,
Douglas Gregorbcced4e2009-04-09 21:40:53 +00002081 const Selector &Sel,
2082 ASTContext &Context) {
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002083 // Check protocols on qualified interfaces.
2084 Decl *GDecl = 0;
Steve Narofffb4330f2009-06-17 22:40:22 +00002085 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002086 E = QIdTy->qual_end(); I != E; ++I) {
Anders Carlssonf571c112009-08-26 18:25:21 +00002087 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002088 GDecl = PD;
2089 break;
2090 }
2091 // Also must look for a getter name which uses property syntax.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002092 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002093 GDecl = OMD;
2094 break;
2095 }
2096 }
2097 if (!GDecl) {
Steve Narofffb4330f2009-06-17 22:40:22 +00002098 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002099 E = QIdTy->qual_end(); I != E; ++I) {
2100 // Search in the protocol-qualifier list of current protocol.
Douglas Gregorbcced4e2009-04-09 21:40:53 +00002101 GDecl = FindGetterNameDeclFromProtocolList(*I, Member, Sel, Context);
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002102 if (GDecl)
2103 return GDecl;
2104 }
2105 }
2106 return GDecl;
2107}
Chris Lattner4bf74fd2009-02-15 22:43:40 +00002108
John McCall10eae182009-11-30 22:42:35 +00002109Sema::OwningExprResult
John McCall2d74de92009-12-01 22:10:20 +00002110Sema::ActOnDependentMemberExpr(ExprArg Base, QualType BaseType,
2111 bool IsArrow, SourceLocation OpLoc,
John McCall10eae182009-11-30 22:42:35 +00002112 const CXXScopeSpec &SS,
2113 NamedDecl *FirstQualifierInScope,
2114 DeclarationName Name, SourceLocation NameLoc,
2115 const TemplateArgumentListInfo *TemplateArgs) {
2116 Expr *BaseExpr = Base.takeAs<Expr>();
2117
2118 // Even in dependent contexts, try to diagnose base expressions with
2119 // obviously wrong types, e.g.:
2120 //
2121 // T* t;
2122 // t.f;
2123 //
2124 // In Obj-C++, however, the above expression is valid, since it could be
2125 // accessing the 'f' property if T is an Obj-C interface. The extra check
2126 // allows this, while still reporting an error if T is a struct pointer.
2127 if (!IsArrow) {
John McCall2d74de92009-12-01 22:10:20 +00002128 const PointerType *PT = BaseType->getAs<PointerType>();
John McCall10eae182009-11-30 22:42:35 +00002129 if (PT && (!getLangOptions().ObjC1 ||
2130 PT->getPointeeType()->isRecordType())) {
John McCall2d74de92009-12-01 22:10:20 +00002131 assert(BaseExpr && "cannot happen with implicit member accesses");
John McCall10eae182009-11-30 22:42:35 +00002132 Diag(NameLoc, diag::err_typecheck_member_reference_struct_union)
John McCall2d74de92009-12-01 22:10:20 +00002133 << BaseType << BaseExpr->getSourceRange();
John McCall10eae182009-11-30 22:42:35 +00002134 return ExprError();
2135 }
2136 }
2137
John McCall2d74de92009-12-01 22:10:20 +00002138 assert(BaseType->isDependentType());
John McCall10eae182009-11-30 22:42:35 +00002139
2140 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
2141 // must have pointer type, and the accessed type is the pointee.
John McCall2d74de92009-12-01 22:10:20 +00002142 return Owned(CXXDependentScopeMemberExpr::Create(Context, BaseExpr, BaseType,
John McCall10eae182009-11-30 22:42:35 +00002143 IsArrow, OpLoc,
2144 static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
2145 SS.getRange(),
2146 FirstQualifierInScope,
2147 Name, NameLoc,
2148 TemplateArgs));
2149}
2150
2151/// We know that the given qualified member reference points only to
2152/// declarations which do not belong to the static type of the base
2153/// expression. Diagnose the problem.
2154static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
2155 Expr *BaseExpr,
2156 QualType BaseType,
John McCallcd4b4772009-12-02 03:53:29 +00002157 const CXXScopeSpec &SS,
John McCall10eae182009-11-30 22:42:35 +00002158 const LookupResult &R) {
John McCallcd4b4772009-12-02 03:53:29 +00002159 // If this is an implicit member access, use a different set of
2160 // diagnostics.
2161 if (!BaseExpr)
2162 return DiagnoseInstanceReference(SemaRef, SS, R);
John McCall10eae182009-11-30 22:42:35 +00002163
2164 // FIXME: this is an exceedingly lame diagnostic for some of the more
2165 // complicated cases here.
John McCallcd4b4772009-12-02 03:53:29 +00002166 DeclContext *DC = R.getRepresentativeDecl()->getDeclContext();
John McCall10eae182009-11-30 22:42:35 +00002167 SemaRef.Diag(R.getNameLoc(), diag::err_not_direct_base_or_virtual)
John McCallcd4b4772009-12-02 03:53:29 +00002168 << SS.getRange() << DC << BaseType;
John McCall10eae182009-11-30 22:42:35 +00002169}
2170
2171// Check whether the declarations we found through a nested-name
2172// specifier in a member expression are actually members of the base
2173// type. The restriction here is:
2174//
2175// C++ [expr.ref]p2:
2176// ... In these cases, the id-expression shall name a
2177// member of the class or of one of its base classes.
2178//
2179// So it's perfectly legitimate for the nested-name specifier to name
2180// an unrelated class, and for us to find an overload set including
2181// decls from classes which are not superclasses, as long as the decl
2182// we actually pick through overload resolution is from a superclass.
2183bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
2184 QualType BaseType,
John McCallcd4b4772009-12-02 03:53:29 +00002185 const CXXScopeSpec &SS,
John McCall10eae182009-11-30 22:42:35 +00002186 const LookupResult &R) {
John McCall2d74de92009-12-01 22:10:20 +00002187 const RecordType *BaseRT = BaseType->getAs<RecordType>();
2188 if (!BaseRT) {
2189 // We can't check this yet because the base type is still
2190 // dependent.
2191 assert(BaseType->isDependentType());
2192 return false;
2193 }
2194 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall10eae182009-11-30 22:42:35 +00002195
2196 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
John McCall2d74de92009-12-01 22:10:20 +00002197 // If this is an implicit member reference and we find a
2198 // non-instance member, it's not an error.
2199 if (!BaseExpr && !IsInstanceMember((*I)->getUnderlyingDecl()))
2200 return false;
John McCall10eae182009-11-30 22:42:35 +00002201
John McCall2d74de92009-12-01 22:10:20 +00002202 // Note that we use the DC of the decl, not the underlying decl.
2203 CXXRecordDecl *RecordD = cast<CXXRecordDecl>((*I)->getDeclContext());
2204 while (RecordD->isAnonymousStructOrUnion())
2205 RecordD = cast<CXXRecordDecl>(RecordD->getParent());
2206
2207 llvm::SmallPtrSet<CXXRecordDecl*,4> MemberRecord;
2208 MemberRecord.insert(RecordD->getCanonicalDecl());
2209
2210 if (!IsProvablyNotDerivedFrom(*this, BaseRecord, MemberRecord))
2211 return false;
2212 }
2213
John McCallcd4b4772009-12-02 03:53:29 +00002214 DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS, R);
John McCall2d74de92009-12-01 22:10:20 +00002215 return true;
2216}
2217
2218static bool
2219LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
2220 SourceRange BaseRange, const RecordType *RTy,
2221 SourceLocation OpLoc, const CXXScopeSpec &SS) {
2222 RecordDecl *RDecl = RTy->getDecl();
2223 if (SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
2224 PDiag(diag::err_typecheck_incomplete_tag)
2225 << BaseRange))
2226 return true;
2227
2228 DeclContext *DC = RDecl;
2229 if (SS.isSet()) {
2230 // If the member name was a qualified-id, look into the
2231 // nested-name-specifier.
2232 DC = SemaRef.computeDeclContext(SS, false);
2233
John McCallcd4b4772009-12-02 03:53:29 +00002234 if (SemaRef.RequireCompleteDeclContext(SS)) {
2235 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
2236 << SS.getRange() << DC;
2237 return true;
2238 }
2239
John McCall2d74de92009-12-01 22:10:20 +00002240 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
2241
2242 if (!isa<TypeDecl>(DC)) {
2243 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
2244 << DC << SS.getRange();
2245 return true;
John McCall10eae182009-11-30 22:42:35 +00002246 }
2247 }
2248
John McCall2d74de92009-12-01 22:10:20 +00002249 // The record definition is complete, now look up the member.
2250 SemaRef.LookupQualifiedName(R, DC);
John McCall10eae182009-11-30 22:42:35 +00002251
2252 return false;
2253}
2254
2255Sema::OwningExprResult
John McCall2d74de92009-12-01 22:10:20 +00002256Sema::BuildMemberReferenceExpr(ExprArg BaseArg, QualType BaseType,
John McCall10eae182009-11-30 22:42:35 +00002257 SourceLocation OpLoc, bool IsArrow,
2258 const CXXScopeSpec &SS,
2259 NamedDecl *FirstQualifierInScope,
2260 DeclarationName Name, SourceLocation NameLoc,
2261 const TemplateArgumentListInfo *TemplateArgs) {
2262 Expr *Base = BaseArg.takeAs<Expr>();
2263
John McCallcd4b4772009-12-02 03:53:29 +00002264 if (BaseType->isDependentType() ||
2265 (SS.isSet() && isDependentScopeSpecifier(SS)))
John McCall2d74de92009-12-01 22:10:20 +00002266 return ActOnDependentMemberExpr(ExprArg(*this, Base), BaseType,
John McCall10eae182009-11-30 22:42:35 +00002267 IsArrow, OpLoc,
2268 SS, FirstQualifierInScope,
2269 Name, NameLoc,
2270 TemplateArgs);
2271
2272 LookupResult R(*this, Name, NameLoc, LookupMemberName);
John McCall10eae182009-11-30 22:42:35 +00002273
John McCall2d74de92009-12-01 22:10:20 +00002274 // Implicit member accesses.
2275 if (!Base) {
2276 QualType RecordTy = BaseType;
2277 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
2278 if (LookupMemberExprInRecord(*this, R, SourceRange(),
2279 RecordTy->getAs<RecordType>(),
2280 OpLoc, SS))
2281 return ExprError();
2282
2283 // Explicit member accesses.
2284 } else {
2285 OwningExprResult Result =
2286 LookupMemberExpr(R, Base, IsArrow, OpLoc,
2287 SS, FirstQualifierInScope,
2288 /*ObjCImpDecl*/ DeclPtrTy());
2289
2290 if (Result.isInvalid()) {
2291 Owned(Base);
2292 return ExprError();
2293 }
2294
2295 if (Result.get())
2296 return move(Result);
John McCall10eae182009-11-30 22:42:35 +00002297 }
2298
John McCall2d74de92009-12-01 22:10:20 +00002299 return BuildMemberReferenceExpr(ExprArg(*this, Base), BaseType,
2300 OpLoc, IsArrow, SS, R, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00002301}
2302
2303Sema::OwningExprResult
John McCall2d74de92009-12-01 22:10:20 +00002304Sema::BuildMemberReferenceExpr(ExprArg Base, QualType BaseExprType,
2305 SourceLocation OpLoc, bool IsArrow,
2306 const CXXScopeSpec &SS,
John McCall10eae182009-11-30 22:42:35 +00002307 LookupResult &R,
2308 const TemplateArgumentListInfo *TemplateArgs) {
2309 Expr *BaseExpr = Base.takeAs<Expr>();
John McCall2d74de92009-12-01 22:10:20 +00002310 QualType BaseType = BaseExprType;
John McCall10eae182009-11-30 22:42:35 +00002311 if (IsArrow) {
2312 assert(BaseType->isPointerType());
2313 BaseType = BaseType->getAs<PointerType>()->getPointeeType();
2314 }
2315
2316 NestedNameSpecifier *Qualifier =
2317 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
2318 DeclarationName MemberName = R.getLookupName();
2319 SourceLocation MemberLoc = R.getNameLoc();
2320
2321 if (R.isAmbiguous())
Douglas Gregord8061562009-08-06 03:17:00 +00002322 return ExprError();
2323
John McCall10eae182009-11-30 22:42:35 +00002324 if (R.empty()) {
2325 // Rederive where we looked up.
2326 DeclContext *DC = (SS.isSet()
2327 ? computeDeclContext(SS, false)
2328 : BaseType->getAs<RecordType>()->getDecl());
Nate Begeman5ec4b312009-08-10 23:49:36 +00002329
John McCall10eae182009-11-30 22:42:35 +00002330 Diag(R.getNameLoc(), diag::err_no_member)
John McCall2d74de92009-12-01 22:10:20 +00002331 << MemberName << DC
2332 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
John McCall10eae182009-11-30 22:42:35 +00002333 return ExprError();
2334 }
2335
John McCallcd4b4772009-12-02 03:53:29 +00002336 // Diagnose qualified lookups that find only declarations from a
2337 // non-base type. Note that it's okay for lookup to find
2338 // declarations from a non-base type as long as those aren't the
2339 // ones picked by overload resolution.
2340 if (SS.isSet() && CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
John McCall10eae182009-11-30 22:42:35 +00002341 return ExprError();
2342
2343 // Construct an unresolved result if we in fact got an unresolved
2344 // result.
2345 if (R.isOverloadedResult() || R.isUnresolvableResult()) {
John McCall2d74de92009-12-01 22:10:20 +00002346 bool Dependent =
2347 R.isUnresolvableResult() ||
2348 UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(), TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00002349
2350 UnresolvedMemberExpr *MemExpr
2351 = UnresolvedMemberExpr::Create(Context, Dependent,
2352 R.isUnresolvableResult(),
John McCall2d74de92009-12-01 22:10:20 +00002353 BaseExpr, BaseExprType,
2354 IsArrow, OpLoc,
John McCall10eae182009-11-30 22:42:35 +00002355 Qualifier, SS.getRange(),
2356 MemberName, MemberLoc,
2357 TemplateArgs);
2358 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
2359 MemExpr->addDecl(*I);
2360
2361 return Owned(MemExpr);
2362 }
2363
2364 assert(R.isSingleResult());
2365 NamedDecl *MemberDecl = R.getFoundDecl();
2366
2367 // FIXME: diagnose the presence of template arguments now.
2368
2369 // If the decl being referenced had an error, return an error for this
2370 // sub-expr without emitting another error, in order to avoid cascading
2371 // error cases.
2372 if (MemberDecl->isInvalidDecl())
2373 return ExprError();
2374
John McCall2d74de92009-12-01 22:10:20 +00002375 // Handle the implicit-member-access case.
2376 if (!BaseExpr) {
2377 // If this is not an instance member, convert to a non-member access.
2378 if (!IsInstanceMember(MemberDecl))
2379 return BuildDeclarationNameExpr(SS, R.getNameLoc(), MemberDecl);
2380
2381 BaseExpr = new (Context) CXXThisExpr(SourceLocation(), BaseExprType);
2382 }
2383
John McCall10eae182009-11-30 22:42:35 +00002384 bool ShouldCheckUse = true;
2385 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
2386 // Don't diagnose the use of a virtual member function unless it's
2387 // explicitly qualified.
2388 if (MD->isVirtual() && !SS.isSet())
2389 ShouldCheckUse = false;
2390 }
2391
2392 // Check the use of this member.
2393 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc)) {
2394 Owned(BaseExpr);
2395 return ExprError();
2396 }
2397
2398 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
2399 // We may have found a field within an anonymous union or struct
2400 // (C++ [class.union]).
Eli Friedman78cde142009-12-04 07:18:51 +00002401 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion() &&
2402 !BaseType->getAs<RecordType>()->getDecl()->isAnonymousStructOrUnion())
John McCall10eae182009-11-30 22:42:35 +00002403 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
2404 BaseExpr, OpLoc);
2405
2406 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
2407 QualType MemberType = FD->getType();
2408 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>())
2409 MemberType = Ref->getPointeeType();
2410 else {
2411 Qualifiers BaseQuals = BaseType.getQualifiers();
2412 BaseQuals.removeObjCGCAttr();
2413 if (FD->isMutable()) BaseQuals.removeConst();
2414
2415 Qualifiers MemberQuals
2416 = Context.getCanonicalType(MemberType).getQualifiers();
2417
2418 Qualifiers Combined = BaseQuals + MemberQuals;
2419 if (Combined != MemberQuals)
2420 MemberType = Context.getQualifiedType(MemberType, Combined);
2421 }
2422
2423 MarkDeclarationReferenced(MemberLoc, FD);
2424 if (PerformObjectMemberConversion(BaseExpr, FD))
2425 return ExprError();
2426 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
2427 FD, MemberLoc, MemberType));
2428 }
2429
2430 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
2431 MarkDeclarationReferenced(MemberLoc, Var);
2432 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
2433 Var, MemberLoc,
2434 Var->getType().getNonReferenceType()));
2435 }
2436
2437 if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl)) {
2438 MarkDeclarationReferenced(MemberLoc, MemberDecl);
2439 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
2440 MemberFn, MemberLoc,
2441 MemberFn->getType()));
2442 }
2443
2444 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
2445 MarkDeclarationReferenced(MemberLoc, MemberDecl);
2446 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
2447 Enum, MemberLoc, Enum->getType()));
2448 }
2449
2450 Owned(BaseExpr);
2451
2452 if (isa<TypeDecl>(MemberDecl))
2453 return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
2454 << MemberName << int(IsArrow));
2455
2456 // We found a declaration kind that we didn't expect. This is a
2457 // generic error message that tells the user that she can't refer
2458 // to this member with '.' or '->'.
2459 return ExprError(Diag(MemberLoc,
2460 diag::err_typecheck_member_reference_unknown)
2461 << MemberName << int(IsArrow));
2462}
2463
2464/// Look up the given member of the given non-type-dependent
2465/// expression. This can return in one of two ways:
2466/// * If it returns a sentinel null-but-valid result, the caller will
2467/// assume that lookup was performed and the results written into
2468/// the provided structure. It will take over from there.
2469/// * Otherwise, the returned expression will be produced in place of
2470/// an ordinary member expression.
2471///
2472/// The ObjCImpDecl bit is a gross hack that will need to be properly
2473/// fixed for ObjC++.
2474Sema::OwningExprResult
2475Sema::LookupMemberExpr(LookupResult &R, Expr *&BaseExpr,
John McCalla928c652009-12-07 22:46:59 +00002476 bool &IsArrow, SourceLocation OpLoc,
John McCall10eae182009-11-30 22:42:35 +00002477 const CXXScopeSpec &SS,
2478 NamedDecl *FirstQualifierInScope,
2479 DeclPtrTy ObjCImpDecl) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00002480 assert(BaseExpr && "no base expression");
Mike Stump11289f42009-09-09 15:08:12 +00002481
Steve Naroffeaaae462007-12-16 21:42:28 +00002482 // Perform default conversions.
2483 DefaultFunctionArrayConversion(BaseExpr);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002484
Steve Naroff185616f2007-07-26 03:11:44 +00002485 QualType BaseType = BaseExpr->getType();
John McCall10eae182009-11-30 22:42:35 +00002486 assert(!BaseType->isDependentType());
2487
2488 DeclarationName MemberName = R.getLookupName();
2489 SourceLocation MemberLoc = R.getNameLoc();
Douglas Gregord82ae382009-11-06 06:30:47 +00002490
2491 // If the user is trying to apply -> or . to a function pointer
John McCall10eae182009-11-30 22:42:35 +00002492 // type, it's probably because they forgot parentheses to call that
Douglas Gregord82ae382009-11-06 06:30:47 +00002493 // function. Suggest the addition of those parentheses, build the
2494 // call, and continue on.
2495 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
2496 if (const FunctionProtoType *Fun
2497 = Ptr->getPointeeType()->getAs<FunctionProtoType>()) {
2498 QualType ResultTy = Fun->getResultType();
2499 if (Fun->getNumArgs() == 0 &&
John McCall10eae182009-11-30 22:42:35 +00002500 ((!IsArrow && ResultTy->isRecordType()) ||
2501 (IsArrow && ResultTy->isPointerType() &&
Douglas Gregord82ae382009-11-06 06:30:47 +00002502 ResultTy->getAs<PointerType>()->getPointeeType()
2503 ->isRecordType()))) {
2504 SourceLocation Loc = PP.getLocForEndOfToken(BaseExpr->getLocEnd());
2505 Diag(Loc, diag::err_member_reference_needs_call)
2506 << QualType(Fun, 0)
2507 << CodeModificationHint::CreateInsertion(Loc, "()");
2508
2509 OwningExprResult NewBase
John McCall10eae182009-11-30 22:42:35 +00002510 = ActOnCallExpr(0, ExprArg(*this, BaseExpr), Loc,
Douglas Gregord82ae382009-11-06 06:30:47 +00002511 MultiExprArg(*this, 0, 0), 0, Loc);
2512 if (NewBase.isInvalid())
John McCall10eae182009-11-30 22:42:35 +00002513 return ExprError();
Douglas Gregord82ae382009-11-06 06:30:47 +00002514
2515 BaseExpr = NewBase.takeAs<Expr>();
2516 DefaultFunctionArrayConversion(BaseExpr);
2517 BaseType = BaseExpr->getType();
2518 }
2519 }
2520 }
2521
David Chisnall9f57c292009-08-17 16:35:33 +00002522 // If this is an Objective-C pseudo-builtin and a definition is provided then
2523 // use that.
2524 if (BaseType->isObjCIdType()) {
Fariborz Jahanianc2949f92009-12-07 20:09:25 +00002525 if (IsArrow) {
2526 // Handle the following exceptional case PObj->isa.
2527 if (const ObjCObjectPointerType *OPT =
2528 BaseType->getAs<ObjCObjectPointerType>()) {
2529 if (OPT->getPointeeType()->isSpecificBuiltinType(BuiltinType::ObjCId) &&
2530 MemberName.getAsIdentifierInfo()->isStr("isa"))
2531 return Owned(new (Context) ObjCIsaExpr(BaseExpr, false, MemberLoc,
2532 Context.getObjCIdType()));
2533 }
2534 }
David Chisnall9f57c292009-08-17 16:35:33 +00002535 // We have an 'id' type. Rather than fall through, we check if this
2536 // is a reference to 'isa'.
2537 if (BaseType != Context.ObjCIdRedefinitionType) {
2538 BaseType = Context.ObjCIdRedefinitionType;
Eli Friedman06ed2a52009-10-20 08:27:19 +00002539 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
David Chisnall9f57c292009-08-17 16:35:33 +00002540 }
David Chisnall9f57c292009-08-17 16:35:33 +00002541 }
John McCall10eae182009-11-30 22:42:35 +00002542
Fariborz Jahanian04b258c2009-11-25 23:07:42 +00002543 // If this is an Objective-C pseudo-builtin and a definition is provided then
2544 // use that.
2545 if (Context.isObjCSelType(BaseType)) {
2546 // We have an 'SEL' type. Rather than fall through, we check if this
2547 // is a reference to 'sel_id'.
2548 if (BaseType != Context.ObjCSelRedefinitionType) {
2549 BaseType = Context.ObjCSelRedefinitionType;
2550 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
2551 }
2552 }
John McCall10eae182009-11-30 22:42:35 +00002553
Steve Naroff185616f2007-07-26 03:11:44 +00002554 assert(!BaseType.isNull() && "no type for member expression");
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002555
Fariborz Jahaniane983d172009-09-22 16:48:37 +00002556 // Handle properties on ObjC 'Class' types.
John McCall10eae182009-11-30 22:42:35 +00002557 if (!IsArrow && BaseType->isObjCClassType()) {
Fariborz Jahaniane983d172009-09-22 16:48:37 +00002558 // Also must look for a getter name which uses property syntax.
2559 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
2560 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
2561 if (ObjCMethodDecl *MD = getCurMethodDecl()) {
2562 ObjCInterfaceDecl *IFace = MD->getClassInterface();
2563 ObjCMethodDecl *Getter;
2564 // FIXME: need to also look locally in the implementation.
2565 if ((Getter = IFace->lookupClassMethod(Sel))) {
2566 // Check the use of this method.
2567 if (DiagnoseUseOfDecl(Getter, MemberLoc))
2568 return ExprError();
2569 }
2570 // If we found a getter then this may be a valid dot-reference, we
2571 // will look for the matching setter, in case it is needed.
2572 Selector SetterSel =
2573 SelectorTable::constructSetterName(PP.getIdentifierTable(),
2574 PP.getSelectorTable(), Member);
2575 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
2576 if (!Setter) {
2577 // If this reference is in an @implementation, also check for 'private'
2578 // methods.
Steve Naroffbb69c942009-10-01 23:46:04 +00002579 Setter = IFace->lookupPrivateInstanceMethod(SetterSel);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00002580 }
2581 // Look through local category implementations associated with the class.
2582 if (!Setter)
2583 Setter = IFace->getCategoryClassMethod(SetterSel);
2584
2585 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2586 return ExprError();
2587
2588 if (Getter || Setter) {
2589 QualType PType;
2590
2591 if (Getter)
2592 PType = Getter->getResultType();
2593 else
2594 // Get the expression type from Setter's incoming parameter.
2595 PType = (*(Setter->param_end() -1))->getType();
2596 // FIXME: we must check that the setter has property type.
2597 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter,
2598 PType,
2599 Setter, MemberLoc, BaseExpr));
2600 }
2601 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
2602 << MemberName << BaseType);
2603 }
2604 }
2605
2606 if (BaseType->isObjCClassType() &&
2607 BaseType != Context.ObjCClassRedefinitionType) {
2608 BaseType = Context.ObjCClassRedefinitionType;
Eli Friedman06ed2a52009-10-20 08:27:19 +00002609 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00002610 }
Mike Stump11289f42009-09-09 15:08:12 +00002611
John McCall10eae182009-11-30 22:42:35 +00002612 if (IsArrow) {
2613 if (const PointerType *PT = BaseType->getAs<PointerType>())
Steve Naroff185616f2007-07-26 03:11:44 +00002614 BaseType = PT->getPointeeType();
Steve Naroff7cae42b2009-07-10 23:34:53 +00002615 else if (BaseType->isObjCObjectPointerType())
2616 ;
John McCalla928c652009-12-07 22:46:59 +00002617 else if (BaseType->isRecordType()) {
2618 // Recover from arrow accesses to records, e.g.:
2619 // struct MyRecord foo;
2620 // foo->bar
2621 // This is actually well-formed in C++ if MyRecord has an
2622 // overloaded operator->, but that should have been dealt with
2623 // by now.
2624 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
2625 << BaseType << int(IsArrow) << BaseExpr->getSourceRange()
2626 << CodeModificationHint::CreateReplacement(OpLoc, ".");
2627 IsArrow = false;
2628 } else {
John McCall10eae182009-11-30 22:42:35 +00002629 Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
2630 << BaseType << BaseExpr->getSourceRange();
2631 return ExprError();
Anders Carlsson524d5a42009-05-16 20:31:20 +00002632 }
John McCalla928c652009-12-07 22:46:59 +00002633 } else {
2634 // Recover from dot accesses to pointers, e.g.:
2635 // type *foo;
2636 // foo.bar
2637 // This is actually well-formed in two cases:
2638 // - 'type' is an Objective C type
2639 // - 'bar' is a pseudo-destructor name which happens to refer to
2640 // the appropriate pointer type
2641 if (MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
2642 const PointerType *PT = BaseType->getAs<PointerType>();
2643 if (PT && PT->getPointeeType()->isRecordType()) {
2644 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
2645 << BaseType << int(IsArrow) << BaseExpr->getSourceRange()
2646 << CodeModificationHint::CreateReplacement(OpLoc, "->");
2647 BaseType = PT->getPointeeType();
2648 IsArrow = true;
2649 }
2650 }
John McCall10eae182009-11-30 22:42:35 +00002651 }
John McCalla928c652009-12-07 22:46:59 +00002652
John McCall10eae182009-11-30 22:42:35 +00002653 // Handle field access to simple records. This also handles access
2654 // to fields of the ObjC 'id' struct.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002655 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
John McCall2d74de92009-12-01 22:10:20 +00002656 if (LookupMemberExprInRecord(*this, R, BaseExpr->getSourceRange(),
2657 RTy, OpLoc, SS))
Douglas Gregordd430f72009-01-19 19:26:10 +00002658 return ExprError();
John McCall10eae182009-11-30 22:42:35 +00002659 return Owned((Expr*) 0);
Chris Lattnerb63a7452008-07-21 04:28:12 +00002660 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002661
Douglas Gregorad8a3362009-09-04 17:36:40 +00002662 // Handle pseudo-destructors (C++ [expr.pseudo]). Since anything referring
2663 // into a record type was handled above, any destructor we see here is a
2664 // pseudo-destructor.
2665 if (MemberName.getNameKind() == DeclarationName::CXXDestructorName) {
2666 // C++ [expr.pseudo]p2:
Mike Stump11289f42009-09-09 15:08:12 +00002667 // The left hand side of the dot operator shall be of scalar type. The
2668 // left hand side of the arrow operator shall be of pointer to scalar
Douglas Gregorad8a3362009-09-04 17:36:40 +00002669 // type.
2670 if (!BaseType->isScalarType())
2671 return Owned(Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
2672 << BaseType << BaseExpr->getSourceRange());
Mike Stump11289f42009-09-09 15:08:12 +00002673
Douglas Gregorad8a3362009-09-04 17:36:40 +00002674 // [...] The type designated by the pseudo-destructor-name shall be the
2675 // same as the object type.
2676 if (!MemberName.getCXXNameType()->isDependentType() &&
2677 !Context.hasSameUnqualifiedType(BaseType, MemberName.getCXXNameType()))
2678 return Owned(Diag(OpLoc, diag::err_pseudo_dtor_type_mismatch)
2679 << BaseType << MemberName.getCXXNameType()
2680 << BaseExpr->getSourceRange() << SourceRange(MemberLoc));
Mike Stump11289f42009-09-09 15:08:12 +00002681
2682 // [...] Furthermore, the two type-names in a pseudo-destructor-name of
Douglas Gregorad8a3362009-09-04 17:36:40 +00002683 // the form
2684 //
Mike Stump11289f42009-09-09 15:08:12 +00002685 // ::[opt] nested-name-specifier[opt] type-name :: ̃ type-name
2686 //
Douglas Gregorad8a3362009-09-04 17:36:40 +00002687 // shall designate the same scalar type.
2688 //
2689 // FIXME: DPG can't see any way to trigger this particular clause, so it
2690 // isn't checked here.
Mike Stump11289f42009-09-09 15:08:12 +00002691
Douglas Gregorad8a3362009-09-04 17:36:40 +00002692 // FIXME: We've lost the precise spelling of the type by going through
2693 // DeclarationName. Can we do better?
2694 return Owned(new (Context) CXXPseudoDestructorExpr(Context, BaseExpr,
John McCall10eae182009-11-30 22:42:35 +00002695 IsArrow, OpLoc,
2696 (NestedNameSpecifier *) SS.getScopeRep(),
2697 SS.getRange(),
Douglas Gregorad8a3362009-09-04 17:36:40 +00002698 MemberName.getCXXNameType(),
2699 MemberLoc));
2700 }
Mike Stump11289f42009-09-09 15:08:12 +00002701
Chris Lattnerdc420f42008-07-21 04:59:05 +00002702 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
2703 // (*Obj).ivar.
John McCall10eae182009-11-30 22:42:35 +00002704 if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
2705 (!IsArrow && BaseType->isObjCInterfaceType())) {
John McCall9dd450b2009-09-21 23:43:11 +00002706 const ObjCObjectPointerType *OPT = BaseType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00002707 const ObjCInterfaceType *IFaceT =
John McCall9dd450b2009-09-21 23:43:11 +00002708 OPT ? OPT->getInterfaceType() : BaseType->getAs<ObjCInterfaceType>();
Steve Naroffa057ba92009-07-16 00:25:06 +00002709 if (IFaceT) {
Anders Carlssonf571c112009-08-26 18:25:21 +00002710 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
2711
Steve Naroffa057ba92009-07-16 00:25:06 +00002712 ObjCInterfaceDecl *IDecl = IFaceT->getDecl();
2713 ObjCInterfaceDecl *ClassDeclared;
Anders Carlssonf571c112009-08-26 18:25:21 +00002714 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
Mike Stump11289f42009-09-09 15:08:12 +00002715
Steve Naroffa057ba92009-07-16 00:25:06 +00002716 if (IV) {
2717 // If the decl being referenced had an error, return an error for this
2718 // sub-expr without emitting another error, in order to avoid cascading
2719 // error cases.
2720 if (IV->isInvalidDecl())
2721 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00002722
Steve Naroffa057ba92009-07-16 00:25:06 +00002723 // Check whether we can reference this field.
2724 if (DiagnoseUseOfDecl(IV, MemberLoc))
2725 return ExprError();
2726 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
2727 IV->getAccessControl() != ObjCIvarDecl::Package) {
2728 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
2729 if (ObjCMethodDecl *MD = getCurMethodDecl())
2730 ClassOfMethodDecl = MD->getClassInterface();
2731 else if (ObjCImpDecl && getCurFunctionDecl()) {
2732 // Case of a c-function declared inside an objc implementation.
2733 // FIXME: For a c-style function nested inside an objc implementation
2734 // class, there is no implementation context available, so we pass
2735 // down the context as argument to this routine. Ideally, this context
2736 // need be passed down in the AST node and somehow calculated from the
2737 // AST for a function decl.
2738 Decl *ImplDecl = ObjCImpDecl.getAs<Decl>();
Mike Stump11289f42009-09-09 15:08:12 +00002739 if (ObjCImplementationDecl *IMPD =
Steve Naroffa057ba92009-07-16 00:25:06 +00002740 dyn_cast<ObjCImplementationDecl>(ImplDecl))
2741 ClassOfMethodDecl = IMPD->getClassInterface();
2742 else if (ObjCCategoryImplDecl* CatImplClass =
2743 dyn_cast<ObjCCategoryImplDecl>(ImplDecl))
2744 ClassOfMethodDecl = CatImplClass->getClassInterface();
2745 }
Mike Stump11289f42009-09-09 15:08:12 +00002746
2747 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
2748 if (ClassDeclared != IDecl ||
Steve Naroffa057ba92009-07-16 00:25:06 +00002749 ClassOfMethodDecl != ClassDeclared)
Mike Stump11289f42009-09-09 15:08:12 +00002750 Diag(MemberLoc, diag::error_private_ivar_access)
Steve Naroffa057ba92009-07-16 00:25:06 +00002751 << IV->getDeclName();
Mike Stump12b8ce12009-08-04 21:02:39 +00002752 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
2753 // @protected
Mike Stump11289f42009-09-09 15:08:12 +00002754 Diag(MemberLoc, diag::error_protected_ivar_access)
Steve Naroffa057ba92009-07-16 00:25:06 +00002755 << IV->getDeclName();
Steve Naroffd1b64be2009-03-04 18:34:24 +00002756 }
Steve Naroffa057ba92009-07-16 00:25:06 +00002757
2758 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
2759 MemberLoc, BaseExpr,
John McCall10eae182009-11-30 22:42:35 +00002760 IsArrow));
Fariborz Jahaniana458c4f2009-03-03 01:21:12 +00002761 }
Steve Naroffa057ba92009-07-16 00:25:06 +00002762 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
Anders Carlssonf571c112009-08-26 18:25:21 +00002763 << IDecl->getDeclName() << MemberName
Steve Naroffa057ba92009-07-16 00:25:06 +00002764 << BaseExpr->getSourceRange());
Fariborz Jahanianb1378f92008-12-13 22:20:28 +00002765 }
Chris Lattnerb63a7452008-07-21 04:28:12 +00002766 }
Steve Naroff1329fa02009-07-15 18:40:39 +00002767 // Handle properties on 'id' and qualified "id".
John McCall10eae182009-11-30 22:42:35 +00002768 if (!IsArrow && (BaseType->isObjCIdType() ||
2769 BaseType->isObjCQualifiedIdType())) {
John McCall9dd450b2009-09-21 23:43:11 +00002770 const ObjCObjectPointerType *QIdTy = BaseType->getAs<ObjCObjectPointerType>();
Anders Carlssonf571c112009-08-26 18:25:21 +00002771 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Mike Stump11289f42009-09-09 15:08:12 +00002772
Steve Naroff7cae42b2009-07-10 23:34:53 +00002773 // Check protocols on qualified interfaces.
Anders Carlssonf571c112009-08-26 18:25:21 +00002774 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002775 if (Decl *PMDecl = FindGetterNameDecl(QIdTy, Member, Sel, Context)) {
2776 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
2777 // Check the use of this declaration
2778 if (DiagnoseUseOfDecl(PD, MemberLoc))
2779 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00002780
Steve Naroff7cae42b2009-07-10 23:34:53 +00002781 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
2782 MemberLoc, BaseExpr));
2783 }
2784 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
2785 // Check the use of this method.
2786 if (DiagnoseUseOfDecl(OMD, MemberLoc))
2787 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00002788
Steve Naroff7cae42b2009-07-10 23:34:53 +00002789 return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel,
Mike Stump11289f42009-09-09 15:08:12 +00002790 OMD->getResultType(),
2791 OMD, OpLoc, MemberLoc,
Steve Naroff7cae42b2009-07-10 23:34:53 +00002792 NULL, 0));
2793 }
2794 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002795
Steve Naroff7cae42b2009-07-10 23:34:53 +00002796 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlssonf571c112009-08-26 18:25:21 +00002797 << MemberName << BaseType);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002798 }
Chris Lattnerdc420f42008-07-21 04:59:05 +00002799 // Handle Objective-C property access, which is "Obj.property" where Obj is a
2800 // pointer to a (potentially qualified) interface type.
Steve Naroff7cae42b2009-07-10 23:34:53 +00002801 const ObjCObjectPointerType *OPT;
John McCall10eae182009-11-30 22:42:35 +00002802 if (!IsArrow && (OPT = BaseType->getAsObjCInterfacePointerType())) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002803 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
2804 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
Anders Carlssonf571c112009-08-26 18:25:21 +00002805 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Mike Stump11289f42009-09-09 15:08:12 +00002806
Daniel Dunbaref89086c2008-09-03 01:05:41 +00002807 // Search for a declared property first.
Anders Carlssonf571c112009-08-26 18:25:21 +00002808 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00002809 // Check whether we can reference this property.
2810 if (DiagnoseUseOfDecl(PD, MemberLoc))
2811 return ExprError();
Fariborz Jahanianb2ab73d2009-05-08 19:36:34 +00002812 QualType ResTy = PD->getType();
Anders Carlssonf571c112009-08-26 18:25:21 +00002813 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002814 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Fariborz Jahanianfe9e3942009-05-08 20:20:55 +00002815 if (DiagnosePropertyAccessorMismatch(PD, Getter, MemberLoc))
2816 ResTy = Getter->getResultType();
Fariborz Jahanianb2ab73d2009-05-08 19:36:34 +00002817 return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
Chris Lattner43df5562009-02-16 18:35:08 +00002818 MemberLoc, BaseExpr));
2819 }
Daniel Dunbaref89086c2008-09-03 01:05:41 +00002820 // Check protocols on qualified interfaces.
Steve Naroffaccc4882009-07-20 17:56:53 +00002821 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
2822 E = OPT->qual_end(); I != E; ++I)
Anders Carlssonf571c112009-08-26 18:25:21 +00002823 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00002824 // Check whether we can reference this property.
2825 if (DiagnoseUseOfDecl(PD, MemberLoc))
2826 return ExprError();
Chris Lattner43df5562009-02-16 18:35:08 +00002827
Steve Narofff6009ed2009-01-21 00:14:39 +00002828 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner43df5562009-02-16 18:35:08 +00002829 MemberLoc, BaseExpr));
2830 }
Daniel Dunbaref89086c2008-09-03 01:05:41 +00002831 // If that failed, look for an "implicit" property by seeing if the nullary
2832 // selector is implemented.
2833
2834 // FIXME: The logic for looking up nullary and unary selectors should be
2835 // shared with the code in ActOnInstanceMessage.
2836
Anders Carlssonf571c112009-08-26 18:25:21 +00002837 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002838 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002839
Daniel Dunbaref89086c2008-09-03 01:05:41 +00002840 // If this reference is in an @implementation, check for 'private' methods.
2841 if (!Getter)
Steve Naroffbb69c942009-10-01 23:46:04 +00002842 Getter = IFace->lookupPrivateInstanceMethod(Sel);
Daniel Dunbaref89086c2008-09-03 01:05:41 +00002843
Steve Naroff1df62692008-10-22 19:16:27 +00002844 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1559d67b2009-07-21 00:06:20 +00002845 if (!Getter)
2846 Getter = IFace->getCategoryInstanceMethod(Sel);
Daniel Dunbaref89086c2008-09-03 01:05:41 +00002847 if (Getter) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00002848 // Check if we can reference this property.
2849 if (DiagnoseUseOfDecl(Getter, MemberLoc))
2850 return ExprError();
Steve Naroff1d984fe2009-03-11 13:48:17 +00002851 }
2852 // If we found a getter then this may be a valid dot-reference, we
2853 // will look for the matching setter, in case it is needed.
Mike Stump11289f42009-09-09 15:08:12 +00002854 Selector SetterSel =
2855 SelectorTable::constructSetterName(PP.getIdentifierTable(),
Anders Carlssonf571c112009-08-26 18:25:21 +00002856 PP.getSelectorTable(), Member);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002857 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
Steve Naroff1d984fe2009-03-11 13:48:17 +00002858 if (!Setter) {
2859 // If this reference is in an @implementation, also check for 'private'
2860 // methods.
Steve Naroffbb69c942009-10-01 23:46:04 +00002861 Setter = IFace->lookupPrivateInstanceMethod(SetterSel);
Steve Naroff1d984fe2009-03-11 13:48:17 +00002862 }
2863 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1559d67b2009-07-21 00:06:20 +00002864 if (!Setter)
2865 Setter = IFace->getCategoryInstanceMethod(SetterSel);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002866
Steve Naroff1d984fe2009-03-11 13:48:17 +00002867 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2868 return ExprError();
2869
2870 if (Getter || Setter) {
2871 QualType PType;
2872
2873 if (Getter)
2874 PType = Getter->getResultType();
Fariborz Jahanian88cc2342009-08-18 20:50:23 +00002875 else
2876 // Get the expression type from Setter's incoming parameter.
2877 PType = (*(Setter->param_end() -1))->getType();
Steve Naroff1d984fe2009-03-11 13:48:17 +00002878 // FIXME: we must check that the setter has property type.
Fariborz Jahanian9a846652009-08-20 17:02:02 +00002879 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter, PType,
Steve Naroff1d984fe2009-03-11 13:48:17 +00002880 Setter, MemberLoc, BaseExpr));
2881 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002882 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlssonf571c112009-08-26 18:25:21 +00002883 << MemberName << BaseType);
Fariborz Jahanian21f54ee2007-11-12 22:29:28 +00002884 }
Mike Stump11289f42009-09-09 15:08:12 +00002885
Steve Naroffe87026a2009-07-24 17:54:45 +00002886 // Handle the following exceptional case (*Obj).isa.
John McCall10eae182009-11-30 22:42:35 +00002887 if (!IsArrow &&
Steve Naroffe87026a2009-07-24 17:54:45 +00002888 BaseType->isSpecificBuiltinType(BuiltinType::ObjCId) &&
Anders Carlssonf571c112009-08-26 18:25:21 +00002889 MemberName.getAsIdentifierInfo()->isStr("isa"))
Steve Naroffe87026a2009-07-24 17:54:45 +00002890 return Owned(new (Context) ObjCIsaExpr(BaseExpr, false, MemberLoc,
2891 Context.getObjCIdType()));
2892
Chris Lattnerb63a7452008-07-21 04:28:12 +00002893 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner6c7ce102009-02-16 21:11:58 +00002894 if (BaseType->isExtVectorType()) {
Anders Carlssonf571c112009-08-26 18:25:21 +00002895 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Chris Lattnerb63a7452008-07-21 04:28:12 +00002896 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
2897 if (ret.isNull())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002898 return ExprError();
Anders Carlssonf571c112009-08-26 18:25:21 +00002899 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, *Member,
Steve Narofff6009ed2009-01-21 00:14:39 +00002900 MemberLoc));
Chris Lattnerb63a7452008-07-21 04:28:12 +00002901 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002902
Douglas Gregor0b08ba42009-03-27 06:00:30 +00002903 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
2904 << BaseType << BaseExpr->getSourceRange();
2905
Douglas Gregor0b08ba42009-03-27 06:00:30 +00002906 return ExprError();
Chris Lattnere168f762006-11-10 05:29:30 +00002907}
2908
John McCall10eae182009-11-30 22:42:35 +00002909static Sema::OwningExprResult DiagnoseDtorReference(Sema &SemaRef,
2910 SourceLocation NameLoc,
2911 Sema::ExprArg MemExpr) {
2912 Expr *E = (Expr *) MemExpr.get();
2913 SourceLocation ExpectedLParenLoc = SemaRef.PP.getLocForEndOfToken(NameLoc);
2914 SemaRef.Diag(E->getLocStart(), diag::err_dtor_expr_without_call)
Douglas Gregor30d60cb2009-11-03 19:44:04 +00002915 << isa<CXXPseudoDestructorExpr>(E)
2916 << CodeModificationHint::CreateInsertion(ExpectedLParenLoc, "()");
2917
John McCall10eae182009-11-30 22:42:35 +00002918 return SemaRef.ActOnCallExpr(/*Scope*/ 0,
2919 move(MemExpr),
2920 /*LPLoc*/ ExpectedLParenLoc,
2921 Sema::MultiExprArg(SemaRef, 0, 0),
2922 /*CommaLocs*/ 0,
2923 /*RPLoc*/ ExpectedLParenLoc);
2924}
2925
2926/// The main callback when the parser finds something like
2927/// expression . [nested-name-specifier] identifier
2928/// expression -> [nested-name-specifier] identifier
2929/// where 'identifier' encompasses a fairly broad spectrum of
2930/// possibilities, including destructor and operator references.
2931///
2932/// \param OpKind either tok::arrow or tok::period
2933/// \param HasTrailingLParen whether the next token is '(', which
2934/// is used to diagnose mis-uses of special members that can
2935/// only be called
2936/// \param ObjCImpDecl the current ObjC @implementation decl;
2937/// this is an ugly hack around the fact that ObjC @implementations
2938/// aren't properly put in the context chain
2939Sema::OwningExprResult Sema::ActOnMemberAccessExpr(Scope *S, ExprArg BaseArg,
2940 SourceLocation OpLoc,
2941 tok::TokenKind OpKind,
2942 const CXXScopeSpec &SS,
2943 UnqualifiedId &Id,
2944 DeclPtrTy ObjCImpDecl,
2945 bool HasTrailingLParen) {
2946 if (SS.isSet() && SS.isInvalid())
2947 return ExprError();
2948
2949 TemplateArgumentListInfo TemplateArgsBuffer;
2950
2951 // Decompose the name into its component parts.
2952 DeclarationName Name;
2953 SourceLocation NameLoc;
2954 const TemplateArgumentListInfo *TemplateArgs;
2955 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer,
2956 Name, NameLoc, TemplateArgs);
2957
2958 bool IsArrow = (OpKind == tok::arrow);
2959
2960 NamedDecl *FirstQualifierInScope
2961 = (!SS.isSet() ? 0 : FindFirstQualifierInScope(S,
2962 static_cast<NestedNameSpecifier*>(SS.getScopeRep())));
2963
2964 // This is a postfix expression, so get rid of ParenListExprs.
2965 BaseArg = MaybeConvertParenListExprToParenExpr(S, move(BaseArg));
2966
2967 Expr *Base = BaseArg.takeAs<Expr>();
2968 OwningExprResult Result(*this);
2969 if (Base->getType()->isDependentType()) {
John McCall2d74de92009-12-01 22:10:20 +00002970 Result = ActOnDependentMemberExpr(ExprArg(*this, Base), Base->getType(),
John McCall10eae182009-11-30 22:42:35 +00002971 IsArrow, OpLoc,
2972 SS, FirstQualifierInScope,
2973 Name, NameLoc,
2974 TemplateArgs);
2975 } else {
2976 LookupResult R(*this, Name, NameLoc, LookupMemberName);
2977 if (TemplateArgs) {
2978 // Re-use the lookup done for the template name.
2979 DecomposeTemplateName(R, Id);
2980 } else {
2981 Result = LookupMemberExpr(R, Base, IsArrow, OpLoc,
2982 SS, FirstQualifierInScope,
2983 ObjCImpDecl);
2984
2985 if (Result.isInvalid()) {
2986 Owned(Base);
2987 return ExprError();
2988 }
2989
2990 if (Result.get()) {
2991 // The only way a reference to a destructor can be used is to
2992 // immediately call it, which falls into this case. If the
2993 // next token is not a '(', produce a diagnostic and build the
2994 // call now.
2995 if (!HasTrailingLParen &&
2996 Id.getKind() == UnqualifiedId::IK_DestructorName)
2997 return DiagnoseDtorReference(*this, NameLoc, move(Result));
2998
2999 return move(Result);
3000 }
3001 }
3002
John McCall2d74de92009-12-01 22:10:20 +00003003 Result = BuildMemberReferenceExpr(ExprArg(*this, Base), Base->getType(),
3004 OpLoc, IsArrow, SS, R, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00003005 }
3006
3007 return move(Result);
Anders Carlssonf571c112009-08-26 18:25:21 +00003008}
3009
Anders Carlsson355933d2009-08-25 03:49:14 +00003010Sema::OwningExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
3011 FunctionDecl *FD,
3012 ParmVarDecl *Param) {
3013 if (Param->hasUnparsedDefaultArg()) {
3014 Diag (CallLoc,
3015 diag::err_use_of_default_argument_to_function_declared_later) <<
3016 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00003017 Diag(UnparsedDefaultArgLocs[Param],
Anders Carlsson355933d2009-08-25 03:49:14 +00003018 diag::note_default_argument_declared_here);
3019 } else {
3020 if (Param->hasUninstantiatedDefaultArg()) {
3021 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
3022
3023 // Instantiate the expression.
Douglas Gregor01afeef2009-08-28 20:31:08 +00003024 MultiLevelTemplateArgumentList ArgList = getTemplateInstantiationArgs(FD);
Anders Carlsson657bad42009-09-05 05:14:19 +00003025
Mike Stump11289f42009-09-09 15:08:12 +00003026 InstantiatingTemplate Inst(*this, CallLoc, Param,
3027 ArgList.getInnermost().getFlatArgumentList(),
Douglas Gregor01afeef2009-08-28 20:31:08 +00003028 ArgList.getInnermost().flat_size());
Anders Carlsson355933d2009-08-25 03:49:14 +00003029
John McCall76d824f2009-08-25 22:02:44 +00003030 OwningExprResult Result = SubstExpr(UninstExpr, ArgList);
Mike Stump11289f42009-09-09 15:08:12 +00003031 if (Result.isInvalid())
Anders Carlsson355933d2009-08-25 03:49:14 +00003032 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003033
3034 if (SetParamDefaultArgument(Param, move(Result),
Anders Carlsson355933d2009-08-25 03:49:14 +00003035 /*FIXME:EqualLoc*/
3036 UninstExpr->getSourceRange().getBegin()))
3037 return ExprError();
3038 }
Mike Stump11289f42009-09-09 15:08:12 +00003039
Anders Carlsson355933d2009-08-25 03:49:14 +00003040 Expr *DefaultExpr = Param->getDefaultArg();
Mike Stump11289f42009-09-09 15:08:12 +00003041
Anders Carlsson355933d2009-08-25 03:49:14 +00003042 // If the default expression creates temporaries, we need to
3043 // push them to the current stack of expression temporaries so they'll
3044 // be properly destroyed.
Mike Stump11289f42009-09-09 15:08:12 +00003045 if (CXXExprWithTemporaries *E
Anders Carlsson355933d2009-08-25 03:49:14 +00003046 = dyn_cast_or_null<CXXExprWithTemporaries>(DefaultExpr)) {
Mike Stump11289f42009-09-09 15:08:12 +00003047 assert(!E->shouldDestroyTemporaries() &&
Anders Carlsson355933d2009-08-25 03:49:14 +00003048 "Can't destroy temporaries in a default argument expr!");
3049 for (unsigned I = 0, N = E->getNumTemporaries(); I != N; ++I)
3050 ExprTemporaries.push_back(E->getTemporary(I));
3051 }
3052 }
3053
3054 // We already type-checked the argument, so we know it works.
3055 return Owned(CXXDefaultArgExpr::Create(Context, Param));
3056}
3057
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003058/// ConvertArgumentsForCall - Converts the arguments specified in
3059/// Args/NumArgs to the parameter types of the function FDecl with
3060/// function prototype Proto. Call is the call expression itself, and
3061/// Fn is the function expression. For a C++ member function, this
3062/// routine does not attempt to convert the object argument. Returns
3063/// true if the call is ill-formed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003064bool
3065Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003066 FunctionDecl *FDecl,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003067 const FunctionProtoType *Proto,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003068 Expr **Args, unsigned NumArgs,
3069 SourceLocation RParenLoc) {
Mike Stump4e1f26a2009-02-19 03:04:26 +00003070 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003071 // assignment, to the types of the corresponding parameter, ...
3072 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregorb6b99612009-01-23 21:30:56 +00003073 bool Invalid = false;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003074
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003075 // If too few arguments are available (and we don't have default
3076 // arguments for the remaining parameters), don't make the call.
3077 if (NumArgs < NumArgsInProto) {
3078 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
3079 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
3080 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
Ted Kremenek5a201952009-02-07 01:47:29 +00003081 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003082 }
3083
3084 // If too many are passed and not variadic, error on the extras and drop
3085 // them.
3086 if (NumArgs > NumArgsInProto) {
3087 if (!Proto->isVariadic()) {
3088 Diag(Args[NumArgsInProto]->getLocStart(),
3089 diag::err_typecheck_call_too_many_args)
3090 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
3091 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3092 Args[NumArgs-1]->getLocEnd());
3093 // This deletes the extra arguments.
Ted Kremenek5a201952009-02-07 01:47:29 +00003094 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003095 return true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003096 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003097 }
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003098 llvm::SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003099 VariadicCallType CallType =
3100 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
3101 if (Fn->getType()->isBlockPointerType())
3102 CallType = VariadicBlock; // Block
3103 else if (isa<MemberExpr>(Fn))
3104 CallType = VariadicMethod;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003105 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00003106 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003107 if (Invalid)
3108 return true;
3109 unsigned TotalNumArgs = AllArgs.size();
3110 for (unsigned i = 0; i < TotalNumArgs; ++i)
3111 Call->setArg(i, AllArgs[i]);
3112
3113 return false;
3114}
Mike Stump4e1f26a2009-02-19 03:04:26 +00003115
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003116bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
3117 FunctionDecl *FDecl,
3118 const FunctionProtoType *Proto,
3119 unsigned FirstProtoArg,
3120 Expr **Args, unsigned NumArgs,
3121 llvm::SmallVector<Expr *, 8> &AllArgs,
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003122 VariadicCallType CallType) {
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003123 unsigned NumArgsInProto = Proto->getNumArgs();
3124 unsigned NumArgsToCheck = NumArgs;
3125 bool Invalid = false;
3126 if (NumArgs != NumArgsInProto)
3127 // Use default arguments for missing arguments
3128 NumArgsToCheck = NumArgsInProto;
3129 unsigned ArgIx = 0;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003130 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003131 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003132 QualType ProtoArgType = Proto->getArgType(i);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003133
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003134 Expr *Arg;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003135 if (ArgIx < NumArgs) {
3136 Arg = Args[ArgIx++];
3137
Eli Friedman3164fb12009-03-22 22:00:50 +00003138 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3139 ProtoArgType,
Anders Carlssond624e162009-08-26 23:45:07 +00003140 PDiag(diag::err_call_incomplete_argument)
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003141 << Arg->getSourceRange()))
Eli Friedman3164fb12009-03-22 22:00:50 +00003142 return true;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003143
Douglas Gregor58354032008-12-24 00:01:03 +00003144 // Pass the argument.
3145 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
3146 return true;
Anders Carlsson78cfaa92009-11-13 04:34:45 +00003147
Anders Carlsson97df0b42009-11-13 17:04:35 +00003148 if (!ProtoArgType->isReferenceType())
3149 Arg = MaybeBindToTemporary(Arg).takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00003150 } else {
Anders Carlssonc80a1272009-08-25 02:29:20 +00003151 ParmVarDecl *Param = FDecl->getParamDecl(i);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003152
Mike Stump11289f42009-09-09 15:08:12 +00003153 OwningExprResult ArgExpr =
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003154 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson355933d2009-08-25 03:49:14 +00003155 if (ArgExpr.isInvalid())
3156 return true;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003157
Anders Carlsson355933d2009-08-25 03:49:14 +00003158 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00003159 }
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003160 AllArgs.push_back(Arg);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003161 }
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003162
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003163 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003164 if (CallType != VariadicDoesNotApply) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003165 // Promote the arguments (C99 6.5.2.2p7).
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003166 for (unsigned i = ArgIx; i < NumArgs; i++) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003167 Expr *Arg = Args[i];
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00003168 Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003169 AllArgs.push_back(Arg);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003170 }
3171 }
Douglas Gregorb6b99612009-01-23 21:30:56 +00003172 return Invalid;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003173}
3174
Douglas Gregorcabea402009-09-22 15:41:20 +00003175/// \brief "Deconstruct" the function argument of a call expression to find
3176/// the underlying declaration (if any), the name of the called function,
3177/// whether argument-dependent lookup is available, whether it has explicit
3178/// template arguments, etc.
3179void Sema::DeconstructCallFunction(Expr *FnExpr,
John McCalld14a8642009-11-21 08:51:07 +00003180 llvm::SmallVectorImpl<NamedDecl*> &Fns,
Douglas Gregorcabea402009-09-22 15:41:20 +00003181 DeclarationName &Name,
3182 NestedNameSpecifier *&Qualifier,
3183 SourceRange &QualifierRange,
3184 bool &ArgumentDependentLookup,
John McCall283b9012009-11-22 00:44:51 +00003185 bool &Overloaded,
Douglas Gregorcabea402009-09-22 15:41:20 +00003186 bool &HasExplicitTemplateArguments,
John McCall6b51f282009-11-23 01:53:49 +00003187 TemplateArgumentListInfo &ExplicitTemplateArgs) {
Douglas Gregorcabea402009-09-22 15:41:20 +00003188 // Set defaults for all of the output parameters.
Douglas Gregorcabea402009-09-22 15:41:20 +00003189 Name = DeclarationName();
3190 Qualifier = 0;
3191 QualifierRange = SourceRange();
John McCalle66edc12009-11-24 19:00:30 +00003192 ArgumentDependentLookup = false;
John McCall283b9012009-11-22 00:44:51 +00003193 Overloaded = false;
Douglas Gregorcabea402009-09-22 15:41:20 +00003194 HasExplicitTemplateArguments = false;
John McCall283b9012009-11-22 00:44:51 +00003195
Douglas Gregorcabea402009-09-22 15:41:20 +00003196 // If we're directly calling a function, get the appropriate declaration.
3197 // Also, in C++, keep track of whether we should perform argument-dependent
3198 // lookup and whether there were any explicitly-specified template arguments.
3199 while (true) {
3200 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(FnExpr))
3201 FnExpr = IcExpr->getSubExpr();
3202 else if (ParenExpr *PExpr = dyn_cast<ParenExpr>(FnExpr)) {
Douglas Gregorcabea402009-09-22 15:41:20 +00003203 FnExpr = PExpr->getSubExpr();
3204 } else if (isa<UnaryOperator>(FnExpr) &&
3205 cast<UnaryOperator>(FnExpr)->getOpcode()
3206 == UnaryOperator::AddrOf) {
3207 FnExpr = cast<UnaryOperator>(FnExpr)->getSubExpr();
Douglas Gregorcabea402009-09-22 15:41:20 +00003208 } else if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(FnExpr)) {
John McCalld14a8642009-11-21 08:51:07 +00003209 Fns.push_back(cast<NamedDecl>(DRExpr->getDecl()));
3210 ArgumentDependentLookup = false;
3211 if ((Qualifier = DRExpr->getQualifier()))
Douglas Gregor4bd90e52009-10-23 18:54:35 +00003212 QualifierRange = DRExpr->getQualifierRange();
Douglas Gregorcabea402009-09-22 15:41:20 +00003213 break;
John McCalld14a8642009-11-21 08:51:07 +00003214 } else if (UnresolvedLookupExpr *UnresLookup
3215 = dyn_cast<UnresolvedLookupExpr>(FnExpr)) {
3216 Name = UnresLookup->getName();
3217 Fns.append(UnresLookup->decls_begin(), UnresLookup->decls_end());
3218 ArgumentDependentLookup = UnresLookup->requiresADL();
John McCall283b9012009-11-22 00:44:51 +00003219 Overloaded = UnresLookup->isOverloaded();
John McCalld14a8642009-11-21 08:51:07 +00003220 if ((Qualifier = UnresLookup->getQualifier()))
3221 QualifierRange = UnresLookup->getQualifierRange();
John McCalle66edc12009-11-24 19:00:30 +00003222 if (UnresLookup->hasExplicitTemplateArgs()) {
3223 HasExplicitTemplateArguments = true;
3224 UnresLookup->copyTemplateArgumentsInto(ExplicitTemplateArgs);
Douglas Gregorcabea402009-09-22 15:41:20 +00003225 }
3226 break;
3227 } else {
Douglas Gregorcabea402009-09-22 15:41:20 +00003228 break;
3229 }
3230 }
3231}
3232
Steve Naroff83895f72007-09-16 03:34:24 +00003233/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattnere168f762006-11-10 05:29:30 +00003234/// This provides the location of the left/right parens and a list of comma
3235/// locations.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003236Action::OwningExprResult
3237Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
3238 MultiExprArg args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003239 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003240 unsigned NumArgs = args.size();
Nate Begeman5ec4b312009-08-10 23:49:36 +00003241
3242 // Since this might be a postfix expression, get rid of ParenListExprs.
3243 fn = MaybeConvertParenListExprToParenExpr(S, move(fn));
Mike Stump11289f42009-09-09 15:08:12 +00003244
Anders Carlsson3cbc8592009-05-01 19:30:39 +00003245 Expr *Fn = fn.takeAs<Expr>();
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003246 Expr **Args = reinterpret_cast<Expr**>(args.release());
Chris Lattner38dbdb22007-07-21 03:03:59 +00003247 assert(Fn && "no function call expression");
Mike Stump11289f42009-09-09 15:08:12 +00003248
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003249 if (getLangOptions().CPlusPlus) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00003250 // If this is a pseudo-destructor expression, build the call immediately.
3251 if (isa<CXXPseudoDestructorExpr>(Fn)) {
3252 if (NumArgs > 0) {
3253 // Pseudo-destructor calls should not have any arguments.
3254 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
3255 << CodeModificationHint::CreateRemoval(
3256 SourceRange(Args[0]->getLocStart(),
3257 Args[NumArgs-1]->getLocEnd()));
Mike Stump11289f42009-09-09 15:08:12 +00003258
Douglas Gregorad8a3362009-09-04 17:36:40 +00003259 for (unsigned I = 0; I != NumArgs; ++I)
3260 Args[I]->Destroy(Context);
Mike Stump11289f42009-09-09 15:08:12 +00003261
Douglas Gregorad8a3362009-09-04 17:36:40 +00003262 NumArgs = 0;
3263 }
Mike Stump11289f42009-09-09 15:08:12 +00003264
Douglas Gregorad8a3362009-09-04 17:36:40 +00003265 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
3266 RParenLoc));
3267 }
Mike Stump11289f42009-09-09 15:08:12 +00003268
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003269 // Determine whether this is a dependent call inside a C++ template,
Mike Stump4e1f26a2009-02-19 03:04:26 +00003270 // in which case we won't do any semantic analysis now.
Mike Stump87c57ac2009-05-16 07:39:55 +00003271 // FIXME: Will need to cache the results of name lookup (including ADL) in
3272 // Fn.
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003273 bool Dependent = false;
3274 if (Fn->isTypeDependent())
3275 Dependent = true;
3276 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
3277 Dependent = true;
3278
3279 if (Dependent)
Ted Kremenekd7b4f402009-02-09 20:51:47 +00003280 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003281 Context.DependentTy, RParenLoc));
3282
3283 // Determine whether this is a call to an object (C++ [over.call.object]).
3284 if (Fn->getType()->isRecordType())
3285 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
3286 CommaLocs, RParenLoc));
3287
John McCall10eae182009-11-30 22:42:35 +00003288 Expr *NakedFn = Fn->IgnoreParens();
3289
3290 // Determine whether this is a call to an unresolved member function.
3291 if (UnresolvedMemberExpr *MemE = dyn_cast<UnresolvedMemberExpr>(NakedFn)) {
3292 // If lookup was unresolved but not dependent (i.e. didn't find
3293 // an unresolved using declaration), it has to be an overloaded
3294 // function set, which means it must contain either multiple
3295 // declarations (all methods or method templates) or a single
3296 // method template.
3297 assert((MemE->getNumDecls() > 1) ||
3298 isa<FunctionTemplateDecl>(*MemE->decls_begin()));
Douglas Gregor8f184a32009-12-01 03:34:29 +00003299 (void)MemE;
John McCall10eae182009-11-30 22:42:35 +00003300
John McCall2d74de92009-12-01 22:10:20 +00003301 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
3302 CommaLocs, RParenLoc);
John McCall10eae182009-11-30 22:42:35 +00003303 }
3304
Douglas Gregore254f902009-02-04 00:32:51 +00003305 // Determine whether this is a call to a member function.
John McCall10eae182009-11-30 22:42:35 +00003306 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(NakedFn)) {
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003307 NamedDecl *MemDecl = MemExpr->getMemberDecl();
John McCall10eae182009-11-30 22:42:35 +00003308 if (isa<CXXMethodDecl>(MemDecl))
John McCall2d74de92009-12-01 22:10:20 +00003309 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
3310 CommaLocs, RParenLoc);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003311 }
Anders Carlsson61914b52009-10-03 17:40:22 +00003312
3313 // Determine whether this is a call to a pointer-to-member function.
John McCall10eae182009-11-30 22:42:35 +00003314 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(NakedFn)) {
Anders Carlsson61914b52009-10-03 17:40:22 +00003315 if (BO->getOpcode() == BinaryOperator::PtrMemD ||
3316 BO->getOpcode() == BinaryOperator::PtrMemI) {
Fariborz Jahanian42f66632009-10-28 16:49:46 +00003317 if (const FunctionProtoType *FPT =
3318 dyn_cast<FunctionProtoType>(BO->getType())) {
3319 QualType ResultTy = FPT->getResultType().getNonReferenceType();
Anders Carlsson61914b52009-10-03 17:40:22 +00003320
Fariborz Jahanian42f66632009-10-28 16:49:46 +00003321 ExprOwningPtr<CXXMemberCallExpr>
3322 TheCall(this, new (Context) CXXMemberCallExpr(Context, BO, Args,
3323 NumArgs, ResultTy,
3324 RParenLoc));
Anders Carlsson61914b52009-10-03 17:40:22 +00003325
Fariborz Jahanian42f66632009-10-28 16:49:46 +00003326 if (CheckCallReturnType(FPT->getResultType(),
3327 BO->getRHS()->getSourceRange().getBegin(),
3328 TheCall.get(), 0))
3329 return ExprError();
Anders Carlsson63dce022009-10-15 00:41:48 +00003330
Fariborz Jahanian42f66632009-10-28 16:49:46 +00003331 if (ConvertArgumentsForCall(&*TheCall, BO, 0, FPT, Args, NumArgs,
3332 RParenLoc))
3333 return ExprError();
Anders Carlsson61914b52009-10-03 17:40:22 +00003334
Fariborz Jahanian42f66632009-10-28 16:49:46 +00003335 return Owned(MaybeBindToTemporary(TheCall.release()).release());
3336 }
3337 return ExprError(Diag(Fn->getLocStart(),
3338 diag::err_typecheck_call_not_function)
3339 << Fn->getType() << Fn->getSourceRange());
Anders Carlsson61914b52009-10-03 17:40:22 +00003340 }
3341 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003342 }
3343
Douglas Gregore254f902009-02-04 00:32:51 +00003344 // If we're directly calling a function, get the appropriate declaration.
Mike Stump11289f42009-09-09 15:08:12 +00003345 // Also, in C++, keep track of whether we should perform argument-dependent
Douglas Gregor89026b52009-06-30 23:57:56 +00003346 // lookup and whether there were any explicitly-specified template arguments.
John McCalld14a8642009-11-21 08:51:07 +00003347 llvm::SmallVector<NamedDecl*,8> Fns;
3348 DeclarationName UnqualifiedName;
John McCall283b9012009-11-22 00:44:51 +00003349 bool Overloaded;
3350 bool ADL;
Douglas Gregor89026b52009-06-30 23:57:56 +00003351 bool HasExplicitTemplateArgs = 0;
John McCall6b51f282009-11-23 01:53:49 +00003352 TemplateArgumentListInfo ExplicitTemplateArgs;
Douglas Gregorcabea402009-09-22 15:41:20 +00003353 NestedNameSpecifier *Qualifier = 0;
3354 SourceRange QualifierRange;
John McCalld14a8642009-11-21 08:51:07 +00003355 DeconstructCallFunction(Fn, Fns, UnqualifiedName, Qualifier, QualifierRange,
John McCall283b9012009-11-22 00:44:51 +00003356 ADL, Overloaded, HasExplicitTemplateArgs,
John McCall6b51f282009-11-23 01:53:49 +00003357 ExplicitTemplateArgs);
Mike Stump4e1f26a2009-02-19 03:04:26 +00003358
John McCall283b9012009-11-22 00:44:51 +00003359 NamedDecl *NDecl; // the specific declaration we're calling, if applicable
3360 FunctionDecl *FDecl; // same, if it's known to be a function
John McCalld14a8642009-11-21 08:51:07 +00003361
John McCall283b9012009-11-22 00:44:51 +00003362 if (Overloaded || ADL) {
3363#ifndef NDEBUG
3364 if (ADL) {
3365 // To do ADL, we must have found an unqualified name.
3366 assert(UnqualifiedName && "found no unqualified name for ADL");
3367
3368 // We don't perform ADL for implicit declarations of builtins.
3369 // Verify that this was correctly set up.
3370 if (Fns.size() == 1 && (FDecl = dyn_cast<FunctionDecl>(Fns[0])) &&
3371 FDecl->getBuiltinID() && FDecl->isImplicit())
3372 assert(0 && "performing ADL for builtin");
3373
3374 // We don't perform ADL in C.
3375 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
3376 }
3377
3378 if (Overloaded) {
3379 // To be overloaded, we must either have multiple functions or
3380 // at least one function template (which is effectively an
3381 // infinite set of functions).
3382 assert((Fns.size() > 1 ||
3383 (Fns.size() == 1 &&
3384 isa<FunctionTemplateDecl>(Fns[0]->getUnderlyingDecl())))
3385 && "unrecognized overload situation");
3386 }
3387#endif
3388
3389 FDecl = ResolveOverloadedCallFn(Fn, Fns, UnqualifiedName,
John McCall6b51f282009-11-23 01:53:49 +00003390 (HasExplicitTemplateArgs ? &ExplicitTemplateArgs : 0),
John McCall283b9012009-11-22 00:44:51 +00003391 LParenLoc, Args, NumArgs, CommaLocs,
3392 RParenLoc, ADL);
3393 if (!FDecl)
3394 return ExprError();
3395
3396 Fn = FixOverloadedFunctionReference(Fn, FDecl);
3397
3398 NDecl = FDecl;
3399 } else {
3400 assert(Fns.size() <= 1 && "overloaded without Overloaded flag");
3401 if (Fns.empty())
John McCall2d74de92009-12-01 22:10:20 +00003402 NDecl = 0;
John McCall283b9012009-11-22 00:44:51 +00003403 else {
3404 NDecl = Fns[0];
Douglas Gregore254f902009-02-04 00:32:51 +00003405 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003406 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00003407
John McCall2d74de92009-12-01 22:10:20 +00003408 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc);
3409}
3410
3411/// BuildCallExpr - Build a call to a resolved expression, i.e. an
3412/// expression not of \p OverloadTy. The expression should
3413/// unary-convert to an expression of function-pointer or
3414/// block-pointer type.
3415///
3416/// \param NDecl the declaration being called, if available
3417Sema::OwningExprResult
3418Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
3419 SourceLocation LParenLoc,
3420 Expr **Args, unsigned NumArgs,
3421 SourceLocation RParenLoc) {
3422 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
3423
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00003424 // Promote the function operand.
3425 UsualUnaryConversions(Fn);
3426
Chris Lattner08464942007-12-28 05:29:59 +00003427 // Make the call expr early, before semantic checks. This guarantees cleanup
3428 // of arguments and function on error.
Ted Kremenekd7b4f402009-02-09 20:51:47 +00003429 ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
3430 Args, NumArgs,
3431 Context.BoolTy,
3432 RParenLoc));
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003433
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003434 const FunctionType *FuncT;
3435 if (!Fn->getType()->isBlockPointerType()) {
3436 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
3437 // have type pointer to function".
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003438 const PointerType *PT = Fn->getType()->getAs<PointerType>();
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003439 if (PT == 0)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003440 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3441 << Fn->getType() << Fn->getSourceRange());
John McCall9dd450b2009-09-21 23:43:11 +00003442 FuncT = PT->getPointeeType()->getAs<FunctionType>();
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003443 } else { // This is a block call.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003444 FuncT = Fn->getType()->getAs<BlockPointerType>()->getPointeeType()->
John McCall9dd450b2009-09-21 23:43:11 +00003445 getAs<FunctionType>();
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003446 }
Chris Lattner08464942007-12-28 05:29:59 +00003447 if (FuncT == 0)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003448 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3449 << Fn->getType() << Fn->getSourceRange());
3450
Eli Friedman3164fb12009-03-22 22:00:50 +00003451 // Check for a valid return type
Anders Carlsson7f84ed92009-10-09 23:51:55 +00003452 if (CheckCallReturnType(FuncT->getResultType(),
3453 Fn->getSourceRange().getBegin(), TheCall.get(),
3454 FDecl))
Eli Friedman3164fb12009-03-22 22:00:50 +00003455 return ExprError();
3456
Chris Lattner08464942007-12-28 05:29:59 +00003457 // We know the result type of the call, set it.
Douglas Gregor786ab212008-10-29 02:00:59 +00003458 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003459
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003460 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
Mike Stump4e1f26a2009-02-19 03:04:26 +00003461 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003462 RParenLoc))
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003463 return ExprError();
Chris Lattner08464942007-12-28 05:29:59 +00003464 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003465 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003466
Douglas Gregord8e97de2009-04-02 15:37:10 +00003467 if (FDecl) {
3468 // Check if we have too few/too many template arguments, based
3469 // on our knowledge of the function definition.
3470 const FunctionDecl *Def = 0;
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00003471 if (FDecl->getBody(Def) && NumArgs != Def->param_size()) {
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00003472 const FunctionProtoType *Proto =
John McCall9dd450b2009-09-21 23:43:11 +00003473 Def->getType()->getAs<FunctionProtoType>();
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00003474 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size())) {
3475 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
3476 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
3477 }
3478 }
Douglas Gregord8e97de2009-04-02 15:37:10 +00003479 }
3480
Steve Naroff0b661582007-08-28 23:30:39 +00003481 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner08464942007-12-28 05:29:59 +00003482 for (unsigned i = 0; i != NumArgs; i++) {
3483 Expr *Arg = Args[i];
3484 DefaultArgumentPromotion(Arg);
Eli Friedman3164fb12009-03-22 22:00:50 +00003485 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3486 Arg->getType(),
Anders Carlssond624e162009-08-26 23:45:07 +00003487 PDiag(diag::err_call_incomplete_argument)
3488 << Arg->getSourceRange()))
Eli Friedman3164fb12009-03-22 22:00:50 +00003489 return ExprError();
Chris Lattner08464942007-12-28 05:29:59 +00003490 TheCall->setArg(i, Arg);
Steve Naroff0b661582007-08-28 23:30:39 +00003491 }
Steve Naroffae4143e2007-04-26 20:39:23 +00003492 }
Chris Lattner08464942007-12-28 05:29:59 +00003493
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003494 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3495 if (!Method->isStatic())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003496 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
3497 << Fn->getSourceRange());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003498
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +00003499 // Check for sentinels
3500 if (NDecl)
3501 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump11289f42009-09-09 15:08:12 +00003502
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003503 // Do special checking on direct calls to functions.
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003504 if (FDecl) {
3505 if (CheckFunctionCall(FDecl, TheCall.get()))
3506 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003507
Douglas Gregor15fc9562009-09-12 00:22:50 +00003508 if (unsigned BuiltinID = FDecl->getBuiltinID())
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003509 return CheckBuiltinFunctionCall(BuiltinID, TheCall.take());
3510 } else if (NDecl) {
3511 if (CheckBlockCall(NDecl, TheCall.get()))
3512 return ExprError();
3513 }
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003514
Anders Carlssonf8984012009-08-16 03:06:32 +00003515 return MaybeBindToTemporary(TheCall.take());
Chris Lattnere168f762006-11-10 05:29:30 +00003516}
3517
Sebastian Redlb5d49352009-01-19 22:31:54 +00003518Action::OwningExprResult
3519Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
3520 SourceLocation RParenLoc, ExprArg InitExpr) {
Steve Naroff83895f72007-09-16 03:34:24 +00003521 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00003522 //FIXME: Preserve type source info.
3523 QualType literalType = GetTypeFromParser(Ty);
Steve Naroff57eb2c52007-07-19 21:32:11 +00003524 // FIXME: put back this assert when initializers are worked out.
Steve Naroff83895f72007-09-16 03:34:24 +00003525 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Sebastian Redlb5d49352009-01-19 22:31:54 +00003526 Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
Anders Carlsson2c1ec6d2007-12-05 07:24:19 +00003527
Eli Friedman37a186d2008-05-20 05:22:08 +00003528 if (literalType->isArrayType()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00003529 if (literalType->isVariableArrayType())
Sebastian Redlb5d49352009-01-19 22:31:54 +00003530 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
3531 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor1c37d9e2009-05-21 23:48:18 +00003532 } else if (!literalType->isDependentType() &&
3533 RequireCompleteType(LParenLoc, literalType,
Anders Carlssond624e162009-08-26 23:45:07 +00003534 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump11289f42009-09-09 15:08:12 +00003535 << SourceRange(LParenLoc,
Anders Carlssond624e162009-08-26 23:45:07 +00003536 literalExpr->getSourceRange().getEnd())))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003537 return ExprError();
Eli Friedman37a186d2008-05-20 05:22:08 +00003538
Sebastian Redlb5d49352009-01-19 22:31:54 +00003539 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003540 DeclarationName(), /*FIXME:DirectInit=*/false))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003541 return ExprError();
Steve Naroffd32419d2008-01-14 18:19:28 +00003542
Chris Lattner79413952008-12-04 23:50:19 +00003543 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffd32419d2008-01-14 18:19:28 +00003544 if (isFileScope) { // 6.5.2.5p3
Steve Naroff98f72032008-01-10 22:15:12 +00003545 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003546 return ExprError();
Steve Naroff98f72032008-01-10 22:15:12 +00003547 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00003548 InitExpr.release();
Mike Stump4e1f26a2009-02-19 03:04:26 +00003549 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType,
Steve Narofff6009ed2009-01-21 00:14:39 +00003550 literalExpr, isFileScope));
Steve Narofffbd09832007-07-19 01:06:55 +00003551}
3552
Sebastian Redlb5d49352009-01-19 22:31:54 +00003553Action::OwningExprResult
3554Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redlb5d49352009-01-19 22:31:54 +00003555 SourceLocation RBraceLoc) {
3556 unsigned NumInit = initlist.size();
3557 Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
Anders Carlsson4692db02007-08-31 04:56:16 +00003558
Steve Naroff30d242c2007-09-15 18:49:24 +00003559 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump4e1f26a2009-02-19 03:04:26 +00003560 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb5d49352009-01-19 22:31:54 +00003561
Mike Stump4e1f26a2009-02-19 03:04:26 +00003562 InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00003563 RBraceLoc);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003564 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb5d49352009-01-19 22:31:54 +00003565 return Owned(E);
Steve Narofffbd09832007-07-19 01:06:55 +00003566}
3567
Anders Carlsson094c4592009-10-18 18:12:03 +00003568static CastExpr::CastKind getScalarCastKind(ASTContext &Context,
3569 QualType SrcTy, QualType DestTy) {
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003570 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
Anders Carlsson094c4592009-10-18 18:12:03 +00003571 return CastExpr::CK_NoOp;
3572
3573 if (SrcTy->hasPointerRepresentation()) {
3574 if (DestTy->hasPointerRepresentation())
3575 return CastExpr::CK_BitCast;
3576 if (DestTy->isIntegerType())
3577 return CastExpr::CK_PointerToIntegral;
3578 }
3579
3580 if (SrcTy->isIntegerType()) {
3581 if (DestTy->isIntegerType())
3582 return CastExpr::CK_IntegralCast;
3583 if (DestTy->hasPointerRepresentation())
3584 return CastExpr::CK_IntegralToPointer;
3585 if (DestTy->isRealFloatingType())
3586 return CastExpr::CK_IntegralToFloating;
3587 }
3588
3589 if (SrcTy->isRealFloatingType()) {
3590 if (DestTy->isRealFloatingType())
3591 return CastExpr::CK_FloatingCast;
3592 if (DestTy->isIntegerType())
3593 return CastExpr::CK_FloatingToIntegral;
3594 }
3595
3596 // FIXME: Assert here.
3597 // assert(false && "Unhandled cast combination!");
3598 return CastExpr::CK_Unknown;
3599}
3600
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003601/// CheckCastTypes - Check type constraints for casting between types.
Sebastian Redl955a0672009-07-29 13:50:23 +00003602bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr,
Mike Stump11289f42009-09-09 15:08:12 +00003603 CastExpr::CastKind& Kind,
Fariborz Jahanian1cec0c42009-08-26 18:55:36 +00003604 CXXMethodDecl *& ConversionDecl,
3605 bool FunctionalStyle) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00003606 if (getLangOptions().CPlusPlus)
Fariborz Jahanian1cec0c42009-08-26 18:55:36 +00003607 return CXXCheckCStyleCast(TyR, castType, castExpr, Kind, FunctionalStyle,
3608 ConversionDecl);
Sebastian Redl9f831db2009-07-25 15:41:38 +00003609
Eli Friedmanda8d4de2009-08-15 19:02:19 +00003610 DefaultFunctionArrayConversion(castExpr);
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003611
3612 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
3613 // type needs to be scalar.
3614 if (castType->isVoidType()) {
3615 // Cast to void allows any expr type.
Anders Carlssonef918ac2009-10-16 02:35:04 +00003616 Kind = CastExpr::CK_ToVoid;
3617 return false;
3618 }
3619
3620 if (!castType->isScalarType() && !castType->isVectorType()) {
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003621 if (Context.hasSameUnqualifiedType(castType, castExpr->getType()) &&
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003622 (castType->isStructureType() || castType->isUnionType())) {
3623 // GCC struct/union extension: allow cast to self.
Eli Friedmanba961a92009-03-23 00:24:07 +00003624 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003625 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
3626 << castType << castExpr->getSourceRange();
Anders Carlssonec143772009-08-07 23:22:37 +00003627 Kind = CastExpr::CK_NoOp;
Anders Carlsson525b76b2009-10-16 02:48:28 +00003628 return false;
3629 }
3630
3631 if (castType->isUnionType()) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003632 // GCC cast to union extension
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003633 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003634 RecordDecl::field_iterator Field, FieldEnd;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003635 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003636 Field != FieldEnd; ++Field) {
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003637 if (Context.hasSameUnqualifiedType(Field->getType(),
3638 castExpr->getType())) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003639 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
3640 << castExpr->getSourceRange();
3641 break;
3642 }
3643 }
3644 if (Field == FieldEnd)
3645 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
3646 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlssonec143772009-08-07 23:22:37 +00003647 Kind = CastExpr::CK_ToUnion;
Anders Carlsson525b76b2009-10-16 02:48:28 +00003648 return false;
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003649 }
Anders Carlsson525b76b2009-10-16 02:48:28 +00003650
3651 // Reject any other conversions to non-scalar types.
3652 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
3653 << castType << castExpr->getSourceRange();
3654 }
3655
3656 if (!castExpr->getType()->isScalarType() &&
3657 !castExpr->getType()->isVectorType()) {
Chris Lattner3b054132008-11-19 05:08:23 +00003658 return Diag(castExpr->getLocStart(),
3659 diag::err_typecheck_expect_scalar_operand)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003660 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlsson525b76b2009-10-16 02:48:28 +00003661 }
3662
Anders Carlsson43d70f82009-10-16 05:23:41 +00003663 if (castType->isExtVectorType())
3664 return CheckExtVectorCast(TyR, castType, castExpr, Kind);
3665
Anders Carlsson525b76b2009-10-16 02:48:28 +00003666 if (castType->isVectorType())
3667 return CheckVectorCast(TyR, castType, castExpr->getType(), Kind);
3668 if (castExpr->getType()->isVectorType())
3669 return CheckVectorCast(TyR, castExpr->getType(), castType, Kind);
3670
3671 if (getLangOptions().ObjC1 && isa<ObjCSuperExpr>(castExpr))
Steve Naroffb47acdb2009-04-08 23:52:26 +00003672 return Diag(castExpr->getLocStart(), diag::err_illegal_super_cast) << TyR;
Anders Carlsson525b76b2009-10-16 02:48:28 +00003673
Anders Carlsson43d70f82009-10-16 05:23:41 +00003674 if (isa<ObjCSelectorExpr>(castExpr))
3675 return Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
3676
Anders Carlsson525b76b2009-10-16 02:48:28 +00003677 if (!castType->isArithmeticType()) {
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00003678 QualType castExprType = castExpr->getType();
3679 if (!castExprType->isIntegralType() && castExprType->isArithmeticType())
3680 return Diag(castExpr->getLocStart(),
3681 diag::err_cast_pointer_from_non_pointer_int)
3682 << castExprType << castExpr->getSourceRange();
3683 } else if (!castExpr->getType()->isArithmeticType()) {
3684 if (!castType->isIntegralType() && castType->isArithmeticType())
3685 return Diag(castExpr->getLocStart(),
3686 diag::err_cast_pointer_to_non_pointer_int)
3687 << castType << castExpr->getSourceRange();
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003688 }
Anders Carlsson094c4592009-10-18 18:12:03 +00003689
3690 Kind = getScalarCastKind(Context, castExpr->getType(), castType);
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003691 return false;
3692}
3693
Anders Carlsson525b76b2009-10-16 02:48:28 +00003694bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
3695 CastExpr::CastKind &Kind) {
Anders Carlssonde71adf2007-11-27 05:51:55 +00003696 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00003697
Anders Carlssonde71adf2007-11-27 05:51:55 +00003698 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner37e05872008-03-05 18:54:05 +00003699 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonde71adf2007-11-27 05:51:55 +00003700 return Diag(R.getBegin(),
Mike Stump4e1f26a2009-02-19 03:04:26 +00003701 Ty->isVectorType() ?
Anders Carlssonde71adf2007-11-27 05:51:55 +00003702 diag::err_invalid_conversion_between_vectors :
Chris Lattner3b054132008-11-19 05:08:23 +00003703 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003704 << VectorTy << Ty << R;
Anders Carlssonde71adf2007-11-27 05:51:55 +00003705 } else
3706 return Diag(R.getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00003707 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003708 << VectorTy << Ty << R;
Mike Stump4e1f26a2009-02-19 03:04:26 +00003709
Anders Carlsson525b76b2009-10-16 02:48:28 +00003710 Kind = CastExpr::CK_BitCast;
Anders Carlssonde71adf2007-11-27 05:51:55 +00003711 return false;
3712}
3713
Anders Carlsson43d70f82009-10-16 05:23:41 +00003714bool Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *&CastExpr,
3715 CastExpr::CastKind &Kind) {
Nate Begemanc69b7402009-06-26 00:50:28 +00003716 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Anders Carlsson43d70f82009-10-16 05:23:41 +00003717
3718 QualType SrcTy = CastExpr->getType();
3719
Nate Begemanc8961a42009-06-27 22:05:55 +00003720 // If SrcTy is a VectorType, the total size must match to explicitly cast to
3721 // an ExtVectorType.
Nate Begemanc69b7402009-06-26 00:50:28 +00003722 if (SrcTy->isVectorType()) {
3723 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
3724 return Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
3725 << DestTy << SrcTy << R;
Anders Carlsson43d70f82009-10-16 05:23:41 +00003726 Kind = CastExpr::CK_BitCast;
Nate Begemanc69b7402009-06-26 00:50:28 +00003727 return false;
3728 }
3729
Nate Begemanbd956c42009-06-28 02:36:38 +00003730 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begemanc69b7402009-06-26 00:50:28 +00003731 // conversion will take place first from scalar to elt type, and then
3732 // splat from elt type to vector.
Nate Begemanbd956c42009-06-28 02:36:38 +00003733 if (SrcTy->isPointerType())
3734 return Diag(R.getBegin(),
3735 diag::err_invalid_conversion_between_vector_and_scalar)
3736 << DestTy << SrcTy << R;
Eli Friedman06ed2a52009-10-20 08:27:19 +00003737
3738 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
3739 ImpCastExprToType(CastExpr, DestElemTy,
3740 getScalarCastKind(Context, SrcTy, DestElemTy));
Anders Carlsson43d70f82009-10-16 05:23:41 +00003741
3742 Kind = CastExpr::CK_VectorSplat;
Nate Begemanc69b7402009-06-26 00:50:28 +00003743 return false;
3744}
3745
Sebastian Redlb5d49352009-01-19 22:31:54 +00003746Action::OwningExprResult
Nate Begeman5ec4b312009-08-10 23:49:36 +00003747Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, TypeTy *Ty,
Sebastian Redlb5d49352009-01-19 22:31:54 +00003748 SourceLocation RParenLoc, ExprArg Op) {
Anders Carlssonf10e4142009-08-07 22:21:05 +00003749 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Mike Stump11289f42009-09-09 15:08:12 +00003750
Sebastian Redlb5d49352009-01-19 22:31:54 +00003751 assert((Ty != 0) && (Op.get() != 0) &&
3752 "ActOnCastExpr(): missing type or expr");
Steve Naroff1a2cf6b2007-07-16 23:25:18 +00003753
Nate Begeman5ec4b312009-08-10 23:49:36 +00003754 Expr *castExpr = (Expr *)Op.get();
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00003755 //FIXME: Preserve type source info.
3756 QualType castType = GetTypeFromParser(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00003757
Nate Begeman5ec4b312009-08-10 23:49:36 +00003758 // If the Expr being casted is a ParenListExpr, handle it specially.
3759 if (isa<ParenListExpr>(castExpr))
3760 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, move(Op),castType);
Anders Carlssone9766d52009-09-09 21:33:21 +00003761 CXXMethodDecl *Method = 0;
Mike Stump11289f42009-09-09 15:08:12 +00003762 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr,
Anders Carlssone9766d52009-09-09 21:33:21 +00003763 Kind, Method))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003764 return ExprError();
Anders Carlssone9766d52009-09-09 21:33:21 +00003765
3766 if (Method) {
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00003767 OwningExprResult CastArg = BuildCXXCastArgument(LParenLoc, castType, Kind,
Anders Carlssone9766d52009-09-09 21:33:21 +00003768 Method, move(Op));
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00003769
Anders Carlssone9766d52009-09-09 21:33:21 +00003770 if (CastArg.isInvalid())
3771 return ExprError();
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00003772
Anders Carlssone9766d52009-09-09 21:33:21 +00003773 castExpr = CastArg.takeAs<Expr>();
3774 } else {
3775 Op.release();
Fariborz Jahanian3df87672009-08-29 19:15:16 +00003776 }
Mike Stump11289f42009-09-09 15:08:12 +00003777
Sebastian Redl9f831db2009-07-25 15:41:38 +00003778 return Owned(new (Context) CStyleCastExpr(castType.getNonReferenceType(),
Mike Stump11289f42009-09-09 15:08:12 +00003779 Kind, castExpr, castType,
Anders Carlssonf10e4142009-08-07 22:21:05 +00003780 LParenLoc, RParenLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00003781}
3782
Nate Begeman5ec4b312009-08-10 23:49:36 +00003783/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
3784/// of comma binary operators.
3785Action::OwningExprResult
3786Sema::MaybeConvertParenListExprToParenExpr(Scope *S, ExprArg EA) {
3787 Expr *expr = EA.takeAs<Expr>();
3788 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
3789 if (!E)
3790 return Owned(expr);
Mike Stump11289f42009-09-09 15:08:12 +00003791
Nate Begeman5ec4b312009-08-10 23:49:36 +00003792 OwningExprResult Result(*this, E->getExpr(0));
Mike Stump11289f42009-09-09 15:08:12 +00003793
Nate Begeman5ec4b312009-08-10 23:49:36 +00003794 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
3795 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, move(Result),
3796 Owned(E->getExpr(i)));
Mike Stump11289f42009-09-09 15:08:12 +00003797
Nate Begeman5ec4b312009-08-10 23:49:36 +00003798 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), move(Result));
3799}
3800
3801Action::OwningExprResult
3802Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
3803 SourceLocation RParenLoc, ExprArg Op,
3804 QualType Ty) {
3805 ParenListExpr *PE = (ParenListExpr *)Op.get();
Mike Stump11289f42009-09-09 15:08:12 +00003806
3807 // If this is an altivec initializer, '(' type ')' '(' init, ..., init ')'
Nate Begeman5ec4b312009-08-10 23:49:36 +00003808 // then handle it as such.
3809 if (getLangOptions().AltiVec && Ty->isVectorType()) {
3810 if (PE->getNumExprs() == 0) {
3811 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
3812 return ExprError();
3813 }
3814
3815 llvm::SmallVector<Expr *, 8> initExprs;
3816 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
3817 initExprs.push_back(PE->getExpr(i));
3818
3819 // FIXME: This means that pretty-printing the final AST will produce curly
3820 // braces instead of the original commas.
3821 Op.release();
Mike Stump11289f42009-09-09 15:08:12 +00003822 InitListExpr *E = new (Context) InitListExpr(LParenLoc, &initExprs[0],
Nate Begeman5ec4b312009-08-10 23:49:36 +00003823 initExprs.size(), RParenLoc);
3824 E->setType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00003825 return ActOnCompoundLiteral(LParenLoc, Ty.getAsOpaquePtr(), RParenLoc,
Nate Begeman5ec4b312009-08-10 23:49:36 +00003826 Owned(E));
3827 } else {
Mike Stump11289f42009-09-09 15:08:12 +00003828 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
Nate Begeman5ec4b312009-08-10 23:49:36 +00003829 // sequence of BinOp comma operators.
3830 Op = MaybeConvertParenListExprToParenExpr(S, move(Op));
3831 return ActOnCastExpr(S, LParenLoc, Ty.getAsOpaquePtr(), RParenLoc,move(Op));
3832 }
3833}
3834
Fariborz Jahanian906d8712009-11-25 01:26:41 +00003835Action::OwningExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
Nate Begeman5ec4b312009-08-10 23:49:36 +00003836 SourceLocation R,
Fariborz Jahanian906d8712009-11-25 01:26:41 +00003837 MultiExprArg Val,
3838 TypeTy *TypeOfCast) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00003839 unsigned nexprs = Val.size();
3840 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanian906d8712009-11-25 01:26:41 +00003841 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
3842 Expr *expr;
3843 if (nexprs == 1 && TypeOfCast && !TypeIsVectorType(TypeOfCast))
3844 expr = new (Context) ParenExpr(L, R, exprs[0]);
3845 else
3846 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
Nate Begeman5ec4b312009-08-10 23:49:36 +00003847 return Owned(expr);
3848}
3849
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003850/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
3851/// In that case, lhs = cond.
Chris Lattner2c486602009-02-18 04:38:20 +00003852/// C99 6.5.15
3853QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
3854 SourceLocation QuestionLoc) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00003855 // C++ is sufficiently different to merit its own checker.
3856 if (getLangOptions().CPlusPlus)
3857 return CXXCheckConditionalOperands(Cond, LHS, RHS, QuestionLoc);
3858
John McCall1fa36b72009-11-05 09:23:39 +00003859 CheckSignCompare(LHS, RHS, QuestionLoc, diag::warn_mixed_sign_conditional);
3860
Chris Lattner432cff52009-02-18 04:28:32 +00003861 UsualUnaryConversions(Cond);
3862 UsualUnaryConversions(LHS);
3863 UsualUnaryConversions(RHS);
3864 QualType CondTy = Cond->getType();
3865 QualType LHSTy = LHS->getType();
3866 QualType RHSTy = RHS->getType();
Steve Naroff31090012007-07-16 21:54:35 +00003867
Steve Naroffa78fe7e2007-05-16 19:47:19 +00003868 // first, check the condition.
Sebastian Redl1a99f442009-04-16 17:51:27 +00003869 if (!CondTy->isScalarType()) { // C99 6.5.15p2
3870 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
3871 << CondTy;
3872 return QualType();
Steve Naroffa78fe7e2007-05-16 19:47:19 +00003873 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00003874
Chris Lattnere2949f42008-01-06 22:42:25 +00003875 // Now check the two expressions.
Nate Begeman5ec4b312009-08-10 23:49:36 +00003876 if (LHSTy->isVectorType() || RHSTy->isVectorType())
3877 return CheckVectorOperands(QuestionLoc, LHS, RHS);
Douglas Gregor4619e432008-12-05 23:32:09 +00003878
Chris Lattnere2949f42008-01-06 22:42:25 +00003879 // If both operands have arithmetic type, do the usual arithmetic conversions
3880 // to find a common type: C99 6.5.15p3,5.
Chris Lattner432cff52009-02-18 04:28:32 +00003881 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
3882 UsualArithmeticConversions(LHS, RHS);
3883 return LHS->getType();
Steve Naroffdbd9e892007-07-17 00:58:39 +00003884 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00003885
Chris Lattnere2949f42008-01-06 22:42:25 +00003886 // If both operands are the same structure or union type, the result is that
3887 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003888 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
3889 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattner2ab40a62007-11-26 01:40:58 +00003890 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump4e1f26a2009-02-19 03:04:26 +00003891 // "If both the operands have structure or union type, the result has
Chris Lattnere2949f42008-01-06 22:42:25 +00003892 // that type." This implies that CV qualifiers are dropped.
Chris Lattner432cff52009-02-18 04:28:32 +00003893 return LHSTy.getUnqualifiedType();
Eli Friedmanba961a92009-03-23 00:24:07 +00003894 // FIXME: Type of conditional expression must be complete in C mode.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00003895 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00003896
Chris Lattnere2949f42008-01-06 22:42:25 +00003897 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffbf1516c2008-05-12 21:44:38 +00003898 // The following || allows only one side to be void (a GCC-ism).
Chris Lattner432cff52009-02-18 04:28:32 +00003899 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
3900 if (!LHSTy->isVoidType())
3901 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
3902 << RHS->getSourceRange();
3903 if (!RHSTy->isVoidType())
3904 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
3905 << LHS->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00003906 ImpCastExprToType(LHS, Context.VoidTy, CastExpr::CK_ToVoid);
3907 ImpCastExprToType(RHS, Context.VoidTy, CastExpr::CK_ToVoid);
Eli Friedman3e1852f2008-06-04 19:47:51 +00003908 return Context.VoidTy;
Steve Naroffbf1516c2008-05-12 21:44:38 +00003909 }
Steve Naroff039ad3c2008-01-08 01:11:38 +00003910 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
3911 // the type of the other operand."
Steve Naroff6b712a72009-07-14 18:25:06 +00003912 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
Douglas Gregor56751b52009-09-25 04:25:58 +00003913 RHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00003914 // promote the null to a pointer.
3915 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_Unknown);
Chris Lattner432cff52009-02-18 04:28:32 +00003916 return LHSTy;
Steve Naroff039ad3c2008-01-08 01:11:38 +00003917 }
Steve Naroff6b712a72009-07-14 18:25:06 +00003918 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
Douglas Gregor56751b52009-09-25 04:25:58 +00003919 LHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00003920 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_Unknown);
Chris Lattner432cff52009-02-18 04:28:32 +00003921 return RHSTy;
Steve Naroff039ad3c2008-01-08 01:11:38 +00003922 }
David Chisnall9f57c292009-08-17 16:35:33 +00003923 // Handle things like Class and struct objc_class*. Here we case the result
3924 // to the pseudo-builtin, because that will be implicitly cast back to the
3925 // redefinition type if an attempt is made to access its fields.
3926 if (LHSTy->isObjCClassType() &&
3927 (RHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00003928 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
David Chisnall9f57c292009-08-17 16:35:33 +00003929 return LHSTy;
3930 }
3931 if (RHSTy->isObjCClassType() &&
3932 (LHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00003933 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
David Chisnall9f57c292009-08-17 16:35:33 +00003934 return RHSTy;
3935 }
3936 // And the same for struct objc_object* / id
3937 if (LHSTy->isObjCIdType() &&
3938 (RHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00003939 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
David Chisnall9f57c292009-08-17 16:35:33 +00003940 return LHSTy;
3941 }
3942 if (RHSTy->isObjCIdType() &&
3943 (LHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00003944 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
David Chisnall9f57c292009-08-17 16:35:33 +00003945 return RHSTy;
3946 }
Fariborz Jahanian04b258c2009-11-25 23:07:42 +00003947 // And the same for struct objc_selector* / SEL
3948 if (Context.isObjCSelType(LHSTy) &&
3949 (RHSTy.getDesugaredType() == Context.ObjCSelRedefinitionType)) {
3950 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
3951 return LHSTy;
3952 }
3953 if (Context.isObjCSelType(RHSTy) &&
3954 (LHSTy.getDesugaredType() == Context.ObjCSelRedefinitionType)) {
3955 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
3956 return RHSTy;
3957 }
Steve Naroff05efa972009-07-01 14:36:47 +00003958 // Handle block pointer types.
3959 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
3960 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
3961 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
3962 QualType destType = Context.getPointerType(Context.VoidTy);
Eli Friedman06ed2a52009-10-20 08:27:19 +00003963 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
3964 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00003965 return destType;
3966 }
3967 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3968 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3969 return QualType();
Mike Stump1b821b42009-05-07 03:14:14 +00003970 }
Steve Naroff05efa972009-07-01 14:36:47 +00003971 // We have 2 block pointer types.
3972 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3973 // Two identical block pointer types are always compatible.
Mike Stump1b821b42009-05-07 03:14:14 +00003974 return LHSTy;
3975 }
Steve Naroff05efa972009-07-01 14:36:47 +00003976 // The block pointer types aren't identical, continue checking.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003977 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
3978 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00003979
Steve Naroff05efa972009-07-01 14:36:47 +00003980 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
3981 rhptee.getUnqualifiedType())) {
Mike Stump1b821b42009-05-07 03:14:14 +00003982 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
3983 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3984 // In this situation, we assume void* type. No especially good
3985 // reason, but this is what gcc does, and we do have to pick
3986 // to get a consistent AST.
3987 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Eli Friedman06ed2a52009-10-20 08:27:19 +00003988 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
3989 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
Mike Stump1b821b42009-05-07 03:14:14 +00003990 return incompatTy;
Steve Naroffa78fe7e2007-05-16 19:47:19 +00003991 }
Steve Naroff05efa972009-07-01 14:36:47 +00003992 // The block pointer types are compatible.
Eli Friedman06ed2a52009-10-20 08:27:19 +00003993 ImpCastExprToType(LHS, LHSTy, CastExpr::CK_BitCast);
3994 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
Steve Naroffea4c7802009-04-08 17:05:15 +00003995 return LHSTy;
3996 }
Steve Naroff05efa972009-07-01 14:36:47 +00003997 // Check constraints for Objective-C object pointers types.
Steve Naroff7cae42b2009-07-10 23:34:53 +00003998 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003999
Steve Naroff05efa972009-07-01 14:36:47 +00004000 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4001 // Two identical object pointer types are always compatible.
4002 return LHSTy;
4003 }
John McCall9dd450b2009-09-21 23:43:11 +00004004 const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>();
4005 const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>();
Steve Naroff05efa972009-07-01 14:36:47 +00004006 QualType compositeType = LHSTy;
Mike Stump11289f42009-09-09 15:08:12 +00004007
Steve Naroff05efa972009-07-01 14:36:47 +00004008 // If both operands are interfaces and either operand can be
4009 // assigned to the other, use that type as the composite
4010 // type. This allows
4011 // xxx ? (A*) a : (B*) b
4012 // where B is a subclass of A.
4013 //
4014 // Additionally, as for assignment, if either type is 'id'
4015 // allow silent coercion. Finally, if the types are
4016 // incompatible then make sure to use 'id' as the composite
4017 // type so the result is acceptable for sending messages to.
4018
4019 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
4020 // It could return the composite type.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004021 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
Fariborz Jahaniana83c0162009-08-22 22:27:17 +00004022 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004023 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
Fariborz Jahaniana83c0162009-08-22 22:27:17 +00004024 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
Mike Stump11289f42009-09-09 15:08:12 +00004025 } else if ((LHSTy->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00004026 RHSTy->isObjCQualifiedIdType()) &&
Steve Naroff8e6aee52009-07-23 01:01:38 +00004027 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
Mike Stump11289f42009-09-09 15:08:12 +00004028 // Need to handle "id<xx>" explicitly.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004029 // GCC allows qualified id and any Objective-C type to devolve to
4030 // id. Currently localizing to here until clear this should be
4031 // part of ObjCQualifiedIdTypesAreCompatible.
4032 compositeType = Context.getObjCIdType();
4033 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
Steve Naroff05efa972009-07-01 14:36:47 +00004034 compositeType = Context.getObjCIdType();
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00004035 } else if (!(compositeType =
4036 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
4037 ;
4038 else {
Steve Naroff05efa972009-07-01 14:36:47 +00004039 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
4040 << LHSTy << RHSTy
4041 << LHS->getSourceRange() << RHS->getSourceRange();
4042 QualType incompatTy = Context.getObjCIdType();
Eli Friedman06ed2a52009-10-20 08:27:19 +00004043 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
4044 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004045 return incompatTy;
4046 }
4047 // The object pointer types are compatible.
Eli Friedman06ed2a52009-10-20 08:27:19 +00004048 ImpCastExprToType(LHS, compositeType, CastExpr::CK_BitCast);
4049 ImpCastExprToType(RHS, compositeType, CastExpr::CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004050 return compositeType;
4051 }
Steve Naroff85d97152009-07-29 15:09:39 +00004052 // Check Objective-C object pointer types and 'void *'
4053 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004054 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
John McCall9dd450b2009-09-21 23:43:11 +00004055 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
John McCall8ccfcb52009-09-24 19:53:00 +00004056 QualType destPointee
4057 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
Steve Naroff85d97152009-07-29 15:09:39 +00004058 QualType destType = Context.getPointerType(destPointee);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004059 // Add qualifiers if necessary.
4060 ImpCastExprToType(LHS, destType, CastExpr::CK_NoOp);
4061 // Promote to void*.
4062 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
Steve Naroff85d97152009-07-29 15:09:39 +00004063 return destType;
4064 }
4065 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
John McCall9dd450b2009-09-21 23:43:11 +00004066 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004067 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
John McCall8ccfcb52009-09-24 19:53:00 +00004068 QualType destPointee
4069 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
Steve Naroff85d97152009-07-29 15:09:39 +00004070 QualType destType = Context.getPointerType(destPointee);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004071 // Add qualifiers if necessary.
4072 ImpCastExprToType(RHS, destType, CastExpr::CK_NoOp);
4073 // Promote to void*.
4074 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
Steve Naroff85d97152009-07-29 15:09:39 +00004075 return destType;
4076 }
Steve Naroff05efa972009-07-01 14:36:47 +00004077 // Check constraints for C object pointers types (C99 6.5.15p3,6).
4078 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
4079 // get the "pointed to" types
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004080 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4081 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff05efa972009-07-01 14:36:47 +00004082
4083 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
4084 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
4085 // Figure out necessary qualifiers (C99 6.5.15p6)
John McCall8ccfcb52009-09-24 19:53:00 +00004086 QualType destPointee
4087 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
Steve Naroff05efa972009-07-01 14:36:47 +00004088 QualType destType = Context.getPointerType(destPointee);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004089 // Add qualifiers if necessary.
4090 ImpCastExprToType(LHS, destType, CastExpr::CK_NoOp);
4091 // Promote to void*.
4092 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004093 return destType;
4094 }
4095 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00004096 QualType destPointee
4097 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
Steve Naroff05efa972009-07-01 14:36:47 +00004098 QualType destType = Context.getPointerType(destPointee);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004099 // Add qualifiers if necessary.
Eli Friedmanb0bc5592009-11-17 01:22:05 +00004100 ImpCastExprToType(RHS, destType, CastExpr::CK_NoOp);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004101 // Promote to void*.
Eli Friedmanb0bc5592009-11-17 01:22:05 +00004102 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004103 return destType;
4104 }
4105
4106 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4107 // Two identical pointer types are always compatible.
4108 return LHSTy;
4109 }
4110 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
4111 rhptee.getUnqualifiedType())) {
4112 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
4113 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
4114 // In this situation, we assume void* type. No especially good
4115 // reason, but this is what gcc does, and we do have to pick
4116 // to get a consistent AST.
4117 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004118 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
4119 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004120 return incompatTy;
4121 }
4122 // The pointer types are compatible.
4123 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
4124 // differently qualified versions of compatible types, the result type is
4125 // a pointer to an appropriately qualified version of the *composite*
4126 // type.
4127 // FIXME: Need to calculate the composite type.
4128 // FIXME: Need to add qualifiers
Eli Friedman06ed2a52009-10-20 08:27:19 +00004129 ImpCastExprToType(LHS, LHSTy, CastExpr::CK_BitCast);
4130 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004131 return LHSTy;
4132 }
Mike Stump11289f42009-09-09 15:08:12 +00004133
Steve Naroff05efa972009-07-01 14:36:47 +00004134 // GCC compatibility: soften pointer/integer mismatch.
4135 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
4136 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4137 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00004138 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_IntegralToPointer);
Steve Naroff05efa972009-07-01 14:36:47 +00004139 return RHSTy;
4140 }
4141 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
4142 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4143 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00004144 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_IntegralToPointer);
Steve Naroff05efa972009-07-01 14:36:47 +00004145 return LHSTy;
4146 }
Daniel Dunbar484603b2008-09-11 23:12:46 +00004147
Chris Lattnere2949f42008-01-06 22:42:25 +00004148 // Otherwise, the operands are not compatible.
Chris Lattner432cff52009-02-18 04:28:32 +00004149 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
4150 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004151 return QualType();
Steve Narofff8a28c52007-05-15 20:29:32 +00004152}
4153
Steve Naroff83895f72007-09-16 03:34:24 +00004154/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattnere168f762006-11-10 05:29:30 +00004155/// in the case of a the GNU conditional expr extension.
Sebastian Redlb5d49352009-01-19 22:31:54 +00004156Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
4157 SourceLocation ColonLoc,
4158 ExprArg Cond, ExprArg LHS,
4159 ExprArg RHS) {
4160 Expr *CondExpr = (Expr *) Cond.get();
4161 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
Chris Lattner2ab40a62007-11-26 01:40:58 +00004162
4163 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
4164 // was the condition.
4165 bool isLHSNull = LHSExpr == 0;
4166 if (isLHSNull)
4167 LHSExpr = CondExpr;
Sebastian Redlb5d49352009-01-19 22:31:54 +00004168
4169 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
Chris Lattnerdaaa9f22007-07-16 21:39:03 +00004170 RHSExpr, QuestionLoc);
Steve Narofff8a28c52007-05-15 20:29:32 +00004171 if (result.isNull())
Sebastian Redlb5d49352009-01-19 22:31:54 +00004172 return ExprError();
4173
4174 Cond.release();
4175 LHS.release();
4176 RHS.release();
Douglas Gregor7e112b02009-08-26 14:37:04 +00004177 return Owned(new (Context) ConditionalOperator(CondExpr, QuestionLoc,
Steve Narofff6009ed2009-01-21 00:14:39 +00004178 isLHSNull ? 0 : LHSExpr,
Douglas Gregor7e112b02009-08-26 14:37:04 +00004179 ColonLoc, RHSExpr, result));
Chris Lattnere168f762006-11-10 05:29:30 +00004180}
4181
Steve Naroff3f597292007-05-11 22:18:03 +00004182// CheckPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump4e1f26a2009-02-19 03:04:26 +00004183// being closely modeled after the C99 spec:-). The odd characteristic of this
Steve Naroff3f597292007-05-11 22:18:03 +00004184// routine is it effectively iqnores the qualifiers on the top level pointee.
4185// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
4186// FIXME: add a couple examples in this comment.
Mike Stump4e1f26a2009-02-19 03:04:26 +00004187Sema::AssignConvertType
Steve Naroff98cf3e92007-06-06 18:38:38 +00004188Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
Steve Naroff3f597292007-05-11 22:18:03 +00004189 QualType lhptee, rhptee;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004190
David Chisnall9f57c292009-08-17 16:35:33 +00004191 if ((lhsType->isObjCClassType() &&
4192 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
4193 (rhsType->isObjCClassType() &&
4194 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
4195 return Compatible;
4196 }
4197
Steve Naroff1f4d7272007-05-11 04:00:31 +00004198 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004199 lhptee = lhsType->getAs<PointerType>()->getPointeeType();
4200 rhptee = rhsType->getAs<PointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004201
Steve Naroff1f4d7272007-05-11 04:00:31 +00004202 // make sure we operate on the canonical type
Chris Lattner574dee62008-07-26 22:17:49 +00004203 lhptee = Context.getCanonicalType(lhptee);
4204 rhptee = Context.getCanonicalType(rhptee);
Steve Naroff1f4d7272007-05-11 04:00:31 +00004205
Chris Lattner9bad62c2008-01-04 18:04:52 +00004206 AssignConvertType ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004207
4208 // C99 6.5.16.1p1: This following citation is common to constraints
4209 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
4210 // qualifiers of the type *pointed to* by the right;
Fariborz Jahanianece85822009-02-17 18:27:45 +00004211 // FIXME: Handle ExtQualType
Douglas Gregor9a657932008-10-21 23:43:52 +00004212 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner9bad62c2008-01-04 18:04:52 +00004213 ConvTy = CompatiblePointerDiscardsQualifiers;
Steve Naroff3f597292007-05-11 22:18:03 +00004214
Mike Stump4e1f26a2009-02-19 03:04:26 +00004215 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
4216 // incomplete type and the other is a pointer to a qualified or unqualified
Steve Naroff3f597292007-05-11 22:18:03 +00004217 // version of void...
Chris Lattner0a788432008-01-03 22:56:36 +00004218 if (lhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00004219 if (rhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00004220 return ConvTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004221
Chris Lattner0a788432008-01-03 22:56:36 +00004222 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00004223 assert(rhptee->isFunctionType());
4224 return FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00004225 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004226
Chris Lattner0a788432008-01-03 22:56:36 +00004227 if (rhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00004228 if (lhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00004229 return ConvTy;
Chris Lattner0a788432008-01-03 22:56:36 +00004230
4231 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00004232 assert(lhptee->isFunctionType());
4233 return FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00004234 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004235 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Steve Naroff3f597292007-05-11 22:18:03 +00004236 // unqualified versions of compatible types, ...
Eli Friedman80160bd2009-03-22 23:59:44 +00004237 lhptee = lhptee.getUnqualifiedType();
4238 rhptee = rhptee.getUnqualifiedType();
4239 if (!Context.typesAreCompatible(lhptee, rhptee)) {
4240 // Check if the pointee types are compatible ignoring the sign.
4241 // We explicitly check for char so that we catch "char" vs
4242 // "unsigned char" on systems where "char" is unsigned.
Chris Lattnerec3a1562009-10-17 20:33:28 +00004243 if (lhptee->isCharType())
Eli Friedman80160bd2009-03-22 23:59:44 +00004244 lhptee = Context.UnsignedCharTy;
Chris Lattnerec3a1562009-10-17 20:33:28 +00004245 else if (lhptee->isSignedIntegerType())
Eli Friedman80160bd2009-03-22 23:59:44 +00004246 lhptee = Context.getCorrespondingUnsignedType(lhptee);
Chris Lattnerec3a1562009-10-17 20:33:28 +00004247
4248 if (rhptee->isCharType())
Eli Friedman80160bd2009-03-22 23:59:44 +00004249 rhptee = Context.UnsignedCharTy;
Chris Lattnerec3a1562009-10-17 20:33:28 +00004250 else if (rhptee->isSignedIntegerType())
Eli Friedman80160bd2009-03-22 23:59:44 +00004251 rhptee = Context.getCorrespondingUnsignedType(rhptee);
Chris Lattnerec3a1562009-10-17 20:33:28 +00004252
Eli Friedman80160bd2009-03-22 23:59:44 +00004253 if (lhptee == rhptee) {
4254 // Types are compatible ignoring the sign. Qualifier incompatibility
4255 // takes priority over sign incompatibility because the sign
4256 // warning can be disabled.
4257 if (ConvTy != Compatible)
4258 return ConvTy;
4259 return IncompatiblePointerSign;
4260 }
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00004261
4262 // If we are a multi-level pointer, it's possible that our issue is simply
4263 // one of qualification - e.g. char ** -> const char ** is not allowed. If
4264 // the eventual target type is the same and the pointers have the same
4265 // level of indirection, this must be the issue.
4266 if (lhptee->isPointerType() && rhptee->isPointerType()) {
4267 do {
4268 lhptee = lhptee->getAs<PointerType>()->getPointeeType();
4269 rhptee = rhptee->getAs<PointerType>()->getPointeeType();
4270
4271 lhptee = Context.getCanonicalType(lhptee);
4272 rhptee = Context.getCanonicalType(rhptee);
4273 } while (lhptee->isPointerType() && rhptee->isPointerType());
4274
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004275 if (Context.hasSameUnqualifiedType(lhptee, rhptee))
Alexis Hunt6f3de502009-11-08 07:46:34 +00004276 return IncompatibleNestedPointerQualifiers;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00004277 }
4278
Eli Friedman80160bd2009-03-22 23:59:44 +00004279 // General pointer incompatibility takes priority over qualifiers.
Mike Stump11289f42009-09-09 15:08:12 +00004280 return IncompatiblePointer;
Eli Friedman80160bd2009-03-22 23:59:44 +00004281 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00004282 return ConvTy;
Steve Naroff1f4d7272007-05-11 04:00:31 +00004283}
4284
Steve Naroff081c7422008-09-04 15:10:53 +00004285/// CheckBlockPointerTypesForAssignment - This routine determines whether two
4286/// block pointer types are compatible or whether a block and normal pointer
4287/// are compatible. It is more restrict than comparing two function pointer
4288// types.
Mike Stump4e1f26a2009-02-19 03:04:26 +00004289Sema::AssignConvertType
4290Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
Steve Naroff081c7422008-09-04 15:10:53 +00004291 QualType rhsType) {
4292 QualType lhptee, rhptee;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004293
Steve Naroff081c7422008-09-04 15:10:53 +00004294 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004295 lhptee = lhsType->getAs<BlockPointerType>()->getPointeeType();
4296 rhptee = rhsType->getAs<BlockPointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004297
Steve Naroff081c7422008-09-04 15:10:53 +00004298 // make sure we operate on the canonical type
4299 lhptee = Context.getCanonicalType(lhptee);
4300 rhptee = Context.getCanonicalType(rhptee);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004301
Steve Naroff081c7422008-09-04 15:10:53 +00004302 AssignConvertType ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004303
Steve Naroff081c7422008-09-04 15:10:53 +00004304 // For blocks we enforce that qualifiers are identical.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004305 if (lhptee.getLocalCVRQualifiers() != rhptee.getLocalCVRQualifiers())
Steve Naroff081c7422008-09-04 15:10:53 +00004306 ConvTy = CompatiblePointerDiscardsQualifiers;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004307
Eli Friedmana6638ca2009-06-08 05:08:54 +00004308 if (!Context.typesAreCompatible(lhptee, rhptee))
Mike Stump4e1f26a2009-02-19 03:04:26 +00004309 return IncompatibleBlockPointer;
Steve Naroff081c7422008-09-04 15:10:53 +00004310 return ConvTy;
4311}
4312
Mike Stump4e1f26a2009-02-19 03:04:26 +00004313/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
4314/// has code to accommodate several GCC extensions when type checking
Steve Naroff17f76e02007-05-03 21:03:48 +00004315/// pointers. Here are some objectionable examples that GCC considers warnings:
4316///
4317/// int a, *pint;
4318/// short *pshort;
4319/// struct foo *pfoo;
4320///
4321/// pint = pshort; // warning: assignment from incompatible pointer type
4322/// a = pint; // warning: assignment makes integer from pointer without a cast
4323/// pint = a; // warning: assignment makes pointer from integer without a cast
4324/// pint = pfoo; // warning: assignment from incompatible pointer type
4325///
4326/// As a result, the code for dealing with pointers is more complex than the
Mike Stump4e1f26a2009-02-19 03:04:26 +00004327/// C99 spec dictates.
Steve Naroff17f76e02007-05-03 21:03:48 +00004328///
Chris Lattner9bad62c2008-01-04 18:04:52 +00004329Sema::AssignConvertType
Steve Naroff98cf3e92007-06-06 18:38:38 +00004330Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattnera52c2f22008-01-04 23:18:45 +00004331 // Get canonical types. We're not formatting these types, just comparing
4332 // them.
Chris Lattner574dee62008-07-26 22:17:49 +00004333 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
4334 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman3360d892008-05-30 18:07:22 +00004335
4336 if (lhsType == rhsType)
Chris Lattnerf5c973d2008-01-07 17:51:46 +00004337 return Compatible; // Common case: fast path an exact match.
Steve Naroff44fd8ff2007-07-24 21:46:40 +00004338
David Chisnall9f57c292009-08-17 16:35:33 +00004339 if ((lhsType->isObjCClassType() &&
4340 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
4341 (rhsType->isObjCClassType() &&
4342 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
4343 return Compatible;
4344 }
4345
Douglas Gregor6b754842008-10-28 00:22:11 +00004346 // If the left-hand side is a reference type, then we are in a
4347 // (rare!) case where we've allowed the use of references in C,
4348 // e.g., as a parameter type in a built-in function. In this case,
4349 // just make sure that the type referenced is compatible with the
4350 // right-hand side type. The caller is responsible for adjusting
4351 // lhsType so that the resulting expression does not have reference
4352 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004353 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
Douglas Gregor6b754842008-10-28 00:22:11 +00004354 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlsson24ebce62007-10-12 23:56:29 +00004355 return Compatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00004356 return Incompatible;
Fariborz Jahaniana1e34202007-12-19 17:45:58 +00004357 }
Nate Begemanbd956c42009-06-28 02:36:38 +00004358 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
4359 // to the same ExtVector type.
4360 if (lhsType->isExtVectorType()) {
4361 if (rhsType->isExtVectorType())
4362 return lhsType == rhsType ? Compatible : Incompatible;
4363 if (!rhsType->isVectorType() && rhsType->isArithmeticType())
4364 return Compatible;
4365 }
Mike Stump11289f42009-09-09 15:08:12 +00004366
Nate Begeman191a6b12008-07-14 18:02:46 +00004367 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begeman191a6b12008-07-14 18:02:46 +00004368 // If we are allowing lax vector conversions, and LHS and RHS are both
Mike Stump4e1f26a2009-02-19 03:04:26 +00004369 // vectors, the total size only needs to be the same. This is a bitcast;
Nate Begeman191a6b12008-07-14 18:02:46 +00004370 // no bits are changed but the result type is different.
Chris Lattner881a2122008-01-04 23:32:24 +00004371 if (getLangOptions().LaxVectorConversions &&
4372 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begeman191a6b12008-07-14 18:02:46 +00004373 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
Anders Carlssondb5a9b62009-01-30 23:17:46 +00004374 return IncompatibleVectors;
Chris Lattner881a2122008-01-04 23:32:24 +00004375 }
4376 return Incompatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004377 }
Eli Friedman3360d892008-05-30 18:07:22 +00004378
Chris Lattner881a2122008-01-04 23:32:24 +00004379 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Steve Naroff98cf3e92007-06-06 18:38:38 +00004380 return Compatible;
Eli Friedman3360d892008-05-30 18:07:22 +00004381
Chris Lattnerec646832008-04-07 06:49:41 +00004382 if (isa<PointerType>(lhsType)) {
Steve Naroff98cf3e92007-06-06 18:38:38 +00004383 if (rhsType->isIntegerType())
Chris Lattner940cfeb2008-01-04 18:22:42 +00004384 return IntToPointer;
Eli Friedman3360d892008-05-30 18:07:22 +00004385
Chris Lattnerec646832008-04-07 06:49:41 +00004386 if (isa<PointerType>(rhsType))
Steve Naroff98cf3e92007-06-06 18:38:38 +00004387 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004388
Steve Naroffaccc4882009-07-20 17:56:53 +00004389 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004390 if (isa<ObjCObjectPointerType>(rhsType)) {
Steve Naroffaccc4882009-07-20 17:56:53 +00004391 if (lhsType->isVoidPointerType()) // an exception to the rule.
4392 return Compatible;
4393 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004394 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004395 if (rhsType->getAs<BlockPointerType>()) {
4396 if (lhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregore7dd1452008-11-27 00:44:28 +00004397 return Compatible;
Steve Naroff32d072c2008-09-29 18:10:17 +00004398
4399 // Treat block pointers as objects.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004400 if (getLangOptions().ObjC1 && lhsType->isObjCIdType())
Steve Naroff32d072c2008-09-29 18:10:17 +00004401 return Compatible;
4402 }
Steve Naroff081c7422008-09-04 15:10:53 +00004403 return Incompatible;
4404 }
4405
4406 if (isa<BlockPointerType>(lhsType)) {
4407 if (rhsType->isIntegerType())
Eli Friedman8163b7a2009-02-25 04:20:42 +00004408 return IntToBlockPointer;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004409
Steve Naroff32d072c2008-09-29 18:10:17 +00004410 // Treat block pointers as objects.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004411 if (getLangOptions().ObjC1 && rhsType->isObjCIdType())
Steve Naroff32d072c2008-09-29 18:10:17 +00004412 return Compatible;
4413
Steve Naroff081c7422008-09-04 15:10:53 +00004414 if (rhsType->isBlockPointerType())
4415 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004416
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004417 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff081c7422008-09-04 15:10:53 +00004418 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregore7dd1452008-11-27 00:44:28 +00004419 return Compatible;
Steve Naroff081c7422008-09-04 15:10:53 +00004420 }
Chris Lattnera52c2f22008-01-04 23:18:45 +00004421 return Incompatible;
4422 }
4423
Steve Naroff7cae42b2009-07-10 23:34:53 +00004424 if (isa<ObjCObjectPointerType>(lhsType)) {
4425 if (rhsType->isIntegerType())
4426 return IntToPointer;
Mike Stump11289f42009-09-09 15:08:12 +00004427
Steve Naroffaccc4882009-07-20 17:56:53 +00004428 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004429 if (isa<PointerType>(rhsType)) {
Steve Naroffaccc4882009-07-20 17:56:53 +00004430 if (rhsType->isVoidPointerType()) // an exception to the rule.
4431 return Compatible;
4432 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004433 }
4434 if (rhsType->isObjCObjectPointerType()) {
Steve Naroff1329fa02009-07-15 18:40:39 +00004435 if (lhsType->isObjCBuiltinType() || rhsType->isObjCBuiltinType())
4436 return Compatible;
Steve Naroffaccc4882009-07-20 17:56:53 +00004437 if (Context.typesAreCompatible(lhsType, rhsType))
4438 return Compatible;
Steve Naroff8e6aee52009-07-23 01:01:38 +00004439 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
4440 return IncompatibleObjCQualifiedId;
Steve Naroffaccc4882009-07-20 17:56:53 +00004441 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004442 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004443 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004444 if (RHSPT->getPointeeType()->isVoidType())
4445 return Compatible;
4446 }
4447 // Treat block pointers as objects.
4448 if (rhsType->isBlockPointerType())
4449 return Compatible;
4450 return Incompatible;
4451 }
Chris Lattnerec646832008-04-07 06:49:41 +00004452 if (isa<PointerType>(rhsType)) {
Steve Naroff98cf3e92007-06-06 18:38:38 +00004453 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedman3360d892008-05-30 18:07:22 +00004454 if (lhsType == Context.BoolTy)
4455 return Compatible;
4456
4457 if (lhsType->isIntegerType())
Chris Lattner940cfeb2008-01-04 18:22:42 +00004458 return PointerToInt;
Steve Naroff98cf3e92007-06-06 18:38:38 +00004459
Mike Stump4e1f26a2009-02-19 03:04:26 +00004460 if (isa<PointerType>(lhsType))
Steve Naroff98cf3e92007-06-06 18:38:38 +00004461 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004462
4463 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004464 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregore7dd1452008-11-27 00:44:28 +00004465 return Compatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00004466 return Incompatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00004467 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00004468 if (isa<ObjCObjectPointerType>(rhsType)) {
4469 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
4470 if (lhsType == Context.BoolTy)
4471 return Compatible;
4472
4473 if (lhsType->isIntegerType())
4474 return PointerToInt;
4475
Steve Naroffaccc4882009-07-20 17:56:53 +00004476 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004477 if (isa<PointerType>(lhsType)) {
Steve Naroffaccc4882009-07-20 17:56:53 +00004478 if (lhsType->isVoidPointerType()) // an exception to the rule.
4479 return Compatible;
4480 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004481 }
4482 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004483 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00004484 return Compatible;
4485 return Incompatible;
4486 }
Eli Friedman3360d892008-05-30 18:07:22 +00004487
Chris Lattnera52c2f22008-01-04 23:18:45 +00004488 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattnerec646832008-04-07 06:49:41 +00004489 if (Context.typesAreCompatible(lhsType, rhsType))
Steve Naroff98cf3e92007-06-06 18:38:38 +00004490 return Compatible;
Bill Wendling216423b2007-05-30 06:30:29 +00004491 }
Steve Naroff98cf3e92007-06-06 18:38:38 +00004492 return Incompatible;
Steve Naroff9eb24652007-05-02 21:58:15 +00004493}
4494
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004495/// \brief Constructs a transparent union from an expression that is
4496/// used to initialize the transparent union.
Mike Stump11289f42009-09-09 15:08:12 +00004497static void ConstructTransparentUnion(ASTContext &C, Expr *&E,
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004498 QualType UnionType, FieldDecl *Field) {
4499 // Build an initializer list that designates the appropriate member
4500 // of the transparent union.
4501 InitListExpr *Initializer = new (C) InitListExpr(SourceLocation(),
4502 &E, 1,
4503 SourceLocation());
4504 Initializer->setType(UnionType);
4505 Initializer->setInitializedFieldInUnion(Field);
4506
4507 // Build a compound literal constructing a value of the transparent
4508 // union type from this initializer list.
4509 E = new (C) CompoundLiteralExpr(SourceLocation(), UnionType, Initializer,
4510 false);
4511}
4512
4513Sema::AssignConvertType
4514Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) {
4515 QualType FromType = rExpr->getType();
4516
Mike Stump11289f42009-09-09 15:08:12 +00004517 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004518 // transparent_union GCC extension.
4519 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004520 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004521 return Incompatible;
4522
4523 // The field to initialize within the transparent union.
4524 RecordDecl *UD = UT->getDecl();
4525 FieldDecl *InitField = 0;
4526 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004527 for (RecordDecl::field_iterator it = UD->field_begin(),
4528 itend = UD->field_end();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004529 it != itend; ++it) {
4530 if (it->getType()->isPointerType()) {
4531 // If the transparent union contains a pointer type, we allow:
4532 // 1) void pointer
4533 // 2) null pointer constant
4534 if (FromType->isPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004535 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004536 ImpCastExprToType(rExpr, it->getType(), CastExpr::CK_BitCast);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004537 InitField = *it;
4538 break;
4539 }
Mike Stump11289f42009-09-09 15:08:12 +00004540
Douglas Gregor56751b52009-09-25 04:25:58 +00004541 if (rExpr->isNullPointerConstant(Context,
4542 Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004543 ImpCastExprToType(rExpr, it->getType(), CastExpr::CK_IntegralToPointer);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004544 InitField = *it;
4545 break;
4546 }
4547 }
4548
4549 if (CheckAssignmentConstraints(it->getType(), rExpr->getType())
4550 == Compatible) {
4551 InitField = *it;
4552 break;
4553 }
4554 }
4555
4556 if (!InitField)
4557 return Incompatible;
4558
4559 ConstructTransparentUnion(Context, rExpr, ArgType, InitField);
4560 return Compatible;
4561}
4562
Chris Lattner9bad62c2008-01-04 18:04:52 +00004563Sema::AssignConvertType
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00004564Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor9a657932008-10-21 23:43:52 +00004565 if (getLangOptions().CPlusPlus) {
4566 if (!lhsType->isRecordType()) {
4567 // C++ 5.17p3: If the left operand is not of class type, the
4568 // expression is implicitly converted (C++ 4) to the
4569 // cv-unqualified type of the left operand.
Douglas Gregor47d3f272008-12-19 17:40:08 +00004570 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
4571 "assigning"))
Douglas Gregor9a657932008-10-21 23:43:52 +00004572 return Incompatible;
Chris Lattner0d5640c2009-04-12 09:02:39 +00004573 return Compatible;
Douglas Gregor9a657932008-10-21 23:43:52 +00004574 }
4575
4576 // FIXME: Currently, we fall through and treat C++ classes like C
4577 // structures.
4578 }
4579
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00004580 // C99 6.5.16.1p1: the left operand is a pointer and the right is
4581 // a null pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00004582 if ((lhsType->isPointerType() ||
4583 lhsType->isObjCObjectPointerType() ||
Mike Stump4e1f26a2009-02-19 03:04:26 +00004584 lhsType->isBlockPointerType())
Douglas Gregor56751b52009-09-25 04:25:58 +00004585 && rExpr->isNullPointerConstant(Context,
4586 Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004587 ImpCastExprToType(rExpr, lhsType, CastExpr::CK_Unknown);
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00004588 return Compatible;
4589 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004590
Chris Lattnere6dcd502007-10-16 02:55:40 +00004591 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00004592 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregora121b752009-11-03 16:56:39 +00004593 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00004594 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattnere6dcd502007-10-16 02:55:40 +00004595 //
Mike Stump4e1f26a2009-02-19 03:04:26 +00004596 // Suppress this for references: C++ 8.5.3p5.
Chris Lattnere6dcd502007-10-16 02:55:40 +00004597 if (!lhsType->isReferenceType())
4598 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00004599
Chris Lattner9bad62c2008-01-04 18:04:52 +00004600 Sema::AssignConvertType result =
4601 CheckAssignmentConstraints(lhsType, rExpr->getType());
Mike Stump4e1f26a2009-02-19 03:04:26 +00004602
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00004603 // C99 6.5.16.1p2: The value of the right operand is converted to the
4604 // type of the assignment expression.
Douglas Gregor6b754842008-10-28 00:22:11 +00004605 // CheckAssignmentConstraints allows the left-hand side to be a reference,
4606 // so that we can use references in built-in functions even in C.
4607 // The getNonReferenceType() call makes sure that the resulting expression
4608 // does not have reference type.
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004609 if (result != Incompatible && rExpr->getType() != lhsType)
Eli Friedman06ed2a52009-10-20 08:27:19 +00004610 ImpCastExprToType(rExpr, lhsType.getNonReferenceType(),
4611 CastExpr::CK_Unknown);
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00004612 return result;
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00004613}
4614
Chris Lattner326f7572008-11-18 01:30:42 +00004615QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattner377d1f82008-11-18 22:52:51 +00004616 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattner6a2ed6f2008-11-23 09:13:29 +00004617 << lex->getType() << rex->getType()
Chris Lattner377d1f82008-11-18 22:52:51 +00004618 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner5c11c412007-12-12 05:47:28 +00004619 return QualType();
Steve Naroff6f49f5d2007-05-29 14:23:36 +00004620}
4621
Mike Stump4e1f26a2009-02-19 03:04:26 +00004622inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Steve Naroff7a5af782007-07-13 16:58:59 +00004623 Expr *&rex) {
Mike Stump4e1f26a2009-02-19 03:04:26 +00004624 // For conversion purposes, we ignore any qualifiers.
Nate Begeman002e4bd2008-04-04 01:30:25 +00004625 // For example, "const float" and "float" are equivalent.
Chris Lattner574dee62008-07-26 22:17:49 +00004626 QualType lhsType =
4627 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
4628 QualType rhsType =
4629 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004630
Nate Begeman191a6b12008-07-14 18:02:46 +00004631 // If the vector types are identical, return.
Nate Begeman002e4bd2008-04-04 01:30:25 +00004632 if (lhsType == rhsType)
Steve Naroff84ff4b42007-07-09 21:31:10 +00004633 return lhsType;
Nate Begeman330aaa72007-12-30 02:59:45 +00004634
Nate Begeman191a6b12008-07-14 18:02:46 +00004635 // Handle the case of a vector & extvector type of the same size and element
4636 // type. It would be nice if we only had one vector type someday.
Anders Carlssondb5a9b62009-01-30 23:17:46 +00004637 if (getLangOptions().LaxVectorConversions) {
4638 // FIXME: Should we warn here?
John McCall9dd450b2009-09-21 23:43:11 +00004639 if (const VectorType *LV = lhsType->getAs<VectorType>()) {
4640 if (const VectorType *RV = rhsType->getAs<VectorType>())
Nate Begeman191a6b12008-07-14 18:02:46 +00004641 if (LV->getElementType() == RV->getElementType() &&
Anders Carlssondb5a9b62009-01-30 23:17:46 +00004642 LV->getNumElements() == RV->getNumElements()) {
Nate Begeman191a6b12008-07-14 18:02:46 +00004643 return lhsType->isExtVectorType() ? lhsType : rhsType;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00004644 }
4645 }
4646 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004647
Nate Begemanbd956c42009-06-28 02:36:38 +00004648 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
4649 // swap back (so that we don't reverse the inputs to a subtract, for instance.
4650 bool swapped = false;
4651 if (rhsType->isExtVectorType()) {
4652 swapped = true;
4653 std::swap(rex, lex);
4654 std::swap(rhsType, lhsType);
4655 }
Mike Stump11289f42009-09-09 15:08:12 +00004656
Nate Begeman886448d2009-06-28 19:12:57 +00004657 // Handle the case of an ext vector and scalar.
John McCall9dd450b2009-09-21 23:43:11 +00004658 if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) {
Nate Begemanbd956c42009-06-28 02:36:38 +00004659 QualType EltTy = LV->getElementType();
4660 if (EltTy->isIntegralType() && rhsType->isIntegralType()) {
4661 if (Context.getIntegerTypeOrder(EltTy, rhsType) >= 0) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004662 ImpCastExprToType(rex, lhsType, CastExpr::CK_IntegralCast);
Nate Begemanbd956c42009-06-28 02:36:38 +00004663 if (swapped) std::swap(rex, lex);
4664 return lhsType;
4665 }
4666 }
4667 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
4668 rhsType->isRealFloatingType()) {
4669 if (Context.getFloatingTypeOrder(EltTy, rhsType) >= 0) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004670 ImpCastExprToType(rex, lhsType, CastExpr::CK_FloatingCast);
Nate Begemanbd956c42009-06-28 02:36:38 +00004671 if (swapped) std::swap(rex, lex);
4672 return lhsType;
4673 }
Nate Begeman330aaa72007-12-30 02:59:45 +00004674 }
4675 }
Mike Stump11289f42009-09-09 15:08:12 +00004676
Nate Begeman886448d2009-06-28 19:12:57 +00004677 // Vectors of different size or scalar and non-ext-vector are errors.
Chris Lattner377d1f82008-11-18 22:52:51 +00004678 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004679 << lex->getType() << rex->getType()
Chris Lattner377d1f82008-11-18 22:52:51 +00004680 << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff84ff4b42007-07-09 21:31:10 +00004681 return QualType();
Sebastian Redl112a97662009-02-07 00:15:38 +00004682}
4683
Steve Naroff218bc2b2007-05-04 21:54:46 +00004684inline QualType Sema::CheckMultiplyDivideOperands(
Mike Stump11289f42009-09-09 15:08:12 +00004685 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Daniel Dunbar060d5e22009-01-05 22:42:10 +00004686 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner326f7572008-11-18 01:30:42 +00004687 return CheckVectorOperands(Loc, lex, rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004688
Steve Naroffbe4c4d12007-08-24 19:07:16 +00004689 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004690
Steve Naroffdbd9e892007-07-17 00:58:39 +00004691 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroffbe4c4d12007-08-24 19:07:16 +00004692 return compType;
Chris Lattner326f7572008-11-18 01:30:42 +00004693 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00004694}
4695
Steve Naroff218bc2b2007-05-04 21:54:46 +00004696inline QualType Sema::CheckRemainderOperands(
Mike Stump11289f42009-09-09 15:08:12 +00004697 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Daniel Dunbar0d2bfec2009-01-05 22:55:36 +00004698 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4699 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
4700 return CheckVectorOperands(Loc, lex, rex);
4701 return InvalidOperands(Loc, lex, rex);
4702 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00004703
Steve Naroffbe4c4d12007-08-24 19:07:16 +00004704 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004705
Steve Naroffdbd9e892007-07-17 00:58:39 +00004706 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroffbe4c4d12007-08-24 19:07:16 +00004707 return compType;
Chris Lattner326f7572008-11-18 01:30:42 +00004708 return InvalidOperands(Loc, lex, rex);
Steve Naroff218bc2b2007-05-04 21:54:46 +00004709}
4710
4711inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Mike Stump11289f42009-09-09 15:08:12 +00004712 Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004713 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4714 QualType compType = CheckVectorOperands(Loc, lex, rex);
4715 if (CompLHSTy) *CompLHSTy = compType;
4716 return compType;
4717 }
Steve Naroff7a5af782007-07-13 16:58:59 +00004718
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004719 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Eli Friedman8e122982008-05-18 18:08:51 +00004720
Steve Naroffe4718892007-04-27 18:30:00 +00004721 // handle the common case first (both operands are arithmetic).
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004722 if (lex->getType()->isArithmeticType() &&
4723 rex->getType()->isArithmeticType()) {
4724 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00004725 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004726 }
Steve Naroff218bc2b2007-05-04 21:54:46 +00004727
Eli Friedman8e122982008-05-18 18:08:51 +00004728 // Put any potential pointer into PExp
4729 Expr* PExp = lex, *IExp = rex;
Steve Naroff6b712a72009-07-14 18:25:06 +00004730 if (IExp->getType()->isAnyPointerType())
Eli Friedman8e122982008-05-18 18:08:51 +00004731 std::swap(PExp, IExp);
4732
Steve Naroff6b712a72009-07-14 18:25:06 +00004733 if (PExp->getType()->isAnyPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00004734
Eli Friedman8e122982008-05-18 18:08:51 +00004735 if (IExp->getType()->isIntegerType()) {
Steve Naroffaacd4cc2009-07-13 21:20:41 +00004736 QualType PointeeTy = PExp->getType()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00004737
Chris Lattner12bdebb2009-04-24 23:50:08 +00004738 // Check for arithmetic on pointers to incomplete types.
4739 if (PointeeTy->isVoidType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00004740 if (getLangOptions().CPlusPlus) {
4741 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
Chris Lattner3b054132008-11-19 05:08:23 +00004742 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregordd430f72009-01-19 19:26:10 +00004743 return QualType();
Eli Friedman8e122982008-05-18 18:08:51 +00004744 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00004745
4746 // GNU extension: arithmetic on pointer to void
4747 Diag(Loc, diag::ext_gnu_void_ptr)
4748 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner12bdebb2009-04-24 23:50:08 +00004749 } else if (PointeeTy->isFunctionType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00004750 if (getLangOptions().CPlusPlus) {
4751 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
4752 << lex->getType() << lex->getSourceRange();
4753 return QualType();
4754 }
4755
4756 // GNU extension: arithmetic on pointer to function
4757 Diag(Loc, diag::ext_gnu_ptr_func_arith)
4758 << lex->getType() << lex->getSourceRange();
Steve Naroffa63372d2009-07-13 21:32:29 +00004759 } else {
Steve Naroffaacd4cc2009-07-13 21:20:41 +00004760 // Check if we require a complete type.
Mike Stump11289f42009-09-09 15:08:12 +00004761 if (((PExp->getType()->isPointerType() &&
Steve Naroffa63372d2009-07-13 21:32:29 +00004762 !PExp->getType()->isDependentType()) ||
Steve Naroffaacd4cc2009-07-13 21:20:41 +00004763 PExp->getType()->isObjCObjectPointerType()) &&
4764 RequireCompleteType(Loc, PointeeTy,
Mike Stump11289f42009-09-09 15:08:12 +00004765 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
4766 << PExp->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00004767 << PExp->getType()))
Steve Naroffaacd4cc2009-07-13 21:20:41 +00004768 return QualType();
4769 }
Chris Lattner12bdebb2009-04-24 23:50:08 +00004770 // Diagnose bad cases where we step over interface counts.
4771 if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4772 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
4773 << PointeeTy << PExp->getSourceRange();
4774 return QualType();
4775 }
Mike Stump11289f42009-09-09 15:08:12 +00004776
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004777 if (CompLHSTy) {
Eli Friedman629ffb92009-08-20 04:21:42 +00004778 QualType LHSTy = Context.isPromotableBitField(lex);
4779 if (LHSTy.isNull()) {
4780 LHSTy = lex->getType();
4781 if (LHSTy->isPromotableIntegerType())
4782 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregord2c2d172009-05-02 00:36:19 +00004783 }
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004784 *CompLHSTy = LHSTy;
4785 }
Eli Friedman8e122982008-05-18 18:08:51 +00004786 return PExp->getType();
4787 }
4788 }
4789
Chris Lattner326f7572008-11-18 01:30:42 +00004790 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00004791}
4792
Chris Lattner2a3569b2008-04-07 05:30:13 +00004793// C99 6.5.6
4794QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004795 SourceLocation Loc, QualType* CompLHSTy) {
4796 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4797 QualType compType = CheckVectorOperands(Loc, lex, rex);
4798 if (CompLHSTy) *CompLHSTy = compType;
4799 return compType;
4800 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004801
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004802 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004803
Chris Lattner4d62f422007-12-09 21:53:25 +00004804 // Enforce type constraints: C99 6.5.6p3.
Mike Stump4e1f26a2009-02-19 03:04:26 +00004805
Chris Lattner4d62f422007-12-09 21:53:25 +00004806 // Handle the common case first (both operands are arithmetic).
Mike Stumpf70bcf72009-05-07 18:43:07 +00004807 if (lex->getType()->isArithmeticType()
4808 && rex->getType()->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004809 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00004810 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004811 }
Mike Stump11289f42009-09-09 15:08:12 +00004812
Chris Lattner4d62f422007-12-09 21:53:25 +00004813 // Either ptr - int or ptr - ptr.
Steve Naroff6b712a72009-07-14 18:25:06 +00004814 if (lex->getType()->isAnyPointerType()) {
Steve Naroff4eed7a12009-07-13 17:19:15 +00004815 QualType lpointee = lex->getType()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004816
Douglas Gregorac1fb652009-03-24 19:52:54 +00004817 // The LHS must be an completely-defined object type.
Douglas Gregorf6cd9282009-01-23 00:36:41 +00004818
Douglas Gregorac1fb652009-03-24 19:52:54 +00004819 bool ComplainAboutVoid = false;
4820 Expr *ComplainAboutFunc = 0;
4821 if (lpointee->isVoidType()) {
4822 if (getLangOptions().CPlusPlus) {
4823 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
4824 << lex->getSourceRange() << rex->getSourceRange();
4825 return QualType();
4826 }
4827
4828 // GNU C extension: arithmetic on pointer to void
4829 ComplainAboutVoid = true;
4830 } else if (lpointee->isFunctionType()) {
4831 if (getLangOptions().CPlusPlus) {
4832 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004833 << lex->getType() << lex->getSourceRange();
Chris Lattner4d62f422007-12-09 21:53:25 +00004834 return QualType();
4835 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00004836
4837 // GNU C extension: arithmetic on pointer to function
4838 ComplainAboutFunc = lex;
4839 } else if (!lpointee->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00004840 RequireCompleteType(Loc, lpointee,
Anders Carlsson029fc692009-08-26 22:59:12 +00004841 PDiag(diag::err_typecheck_sub_ptr_object)
Mike Stump11289f42009-09-09 15:08:12 +00004842 << lex->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00004843 << lex->getType()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00004844 return QualType();
Chris Lattner4d62f422007-12-09 21:53:25 +00004845
Chris Lattner12bdebb2009-04-24 23:50:08 +00004846 // Diagnose bad cases where we step over interface counts.
4847 if (lpointee->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4848 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
4849 << lpointee << lex->getSourceRange();
4850 return QualType();
4851 }
Mike Stump11289f42009-09-09 15:08:12 +00004852
Chris Lattner4d62f422007-12-09 21:53:25 +00004853 // The result type of a pointer-int computation is the pointer type.
Douglas Gregorac1fb652009-03-24 19:52:54 +00004854 if (rex->getType()->isIntegerType()) {
4855 if (ComplainAboutVoid)
4856 Diag(Loc, diag::ext_gnu_void_ptr)
4857 << lex->getSourceRange() << rex->getSourceRange();
4858 if (ComplainAboutFunc)
4859 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump11289f42009-09-09 15:08:12 +00004860 << ComplainAboutFunc->getType()
Douglas Gregorac1fb652009-03-24 19:52:54 +00004861 << ComplainAboutFunc->getSourceRange();
4862
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004863 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00004864 return lex->getType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00004865 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004866
Chris Lattner4d62f422007-12-09 21:53:25 +00004867 // Handle pointer-pointer subtractions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004868 if (const PointerType *RHSPTy = rex->getType()->getAs<PointerType>()) {
Eli Friedman1974e532008-02-08 01:19:44 +00004869 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004870
Douglas Gregorac1fb652009-03-24 19:52:54 +00004871 // RHS must be a completely-type object type.
4872 // Handle the GNU void* extension.
4873 if (rpointee->isVoidType()) {
4874 if (getLangOptions().CPlusPlus) {
4875 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
4876 << lex->getSourceRange() << rex->getSourceRange();
4877 return QualType();
4878 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004879
Douglas Gregorac1fb652009-03-24 19:52:54 +00004880 ComplainAboutVoid = true;
4881 } else if (rpointee->isFunctionType()) {
4882 if (getLangOptions().CPlusPlus) {
4883 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004884 << rex->getType() << rex->getSourceRange();
Chris Lattner4d62f422007-12-09 21:53:25 +00004885 return QualType();
4886 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00004887
4888 // GNU extension: arithmetic on pointer to function
4889 if (!ComplainAboutFunc)
4890 ComplainAboutFunc = rex;
4891 } else if (!rpointee->isDependentType() &&
4892 RequireCompleteType(Loc, rpointee,
Anders Carlsson029fc692009-08-26 22:59:12 +00004893 PDiag(diag::err_typecheck_sub_ptr_object)
4894 << rex->getSourceRange()
4895 << rex->getType()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00004896 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004897
Eli Friedman168fe152009-05-16 13:54:38 +00004898 if (getLangOptions().CPlusPlus) {
4899 // Pointee types must be the same: C++ [expr.add]
4900 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
4901 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
4902 << lex->getType() << rex->getType()
4903 << lex->getSourceRange() << rex->getSourceRange();
4904 return QualType();
4905 }
4906 } else {
4907 // Pointee types must be compatible C99 6.5.6p3
4908 if (!Context.typesAreCompatible(
4909 Context.getCanonicalType(lpointee).getUnqualifiedType(),
4910 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
4911 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
4912 << lex->getType() << rex->getType()
4913 << lex->getSourceRange() << rex->getSourceRange();
4914 return QualType();
4915 }
Chris Lattner4d62f422007-12-09 21:53:25 +00004916 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004917
Douglas Gregorac1fb652009-03-24 19:52:54 +00004918 if (ComplainAboutVoid)
4919 Diag(Loc, diag::ext_gnu_void_ptr)
4920 << lex->getSourceRange() << rex->getSourceRange();
4921 if (ComplainAboutFunc)
4922 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump11289f42009-09-09 15:08:12 +00004923 << ComplainAboutFunc->getType()
Douglas Gregorac1fb652009-03-24 19:52:54 +00004924 << ComplainAboutFunc->getSourceRange();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004925
4926 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00004927 return Context.getPointerDiffType();
4928 }
4929 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004930
Chris Lattner326f7572008-11-18 01:30:42 +00004931 return InvalidOperands(Loc, lex, rex);
Steve Naroff218bc2b2007-05-04 21:54:46 +00004932}
4933
Chris Lattner2a3569b2008-04-07 05:30:13 +00004934// C99 6.5.7
Chris Lattner326f7572008-11-18 01:30:42 +00004935QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattner2a3569b2008-04-07 05:30:13 +00004936 bool isCompAssign) {
Chris Lattner5c11c412007-12-12 05:47:28 +00004937 // C99 6.5.7p2: Each of the operands shall have integer type.
4938 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner326f7572008-11-18 01:30:42 +00004939 return InvalidOperands(Loc, lex, rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004940
Nate Begemane46ee9a2009-10-25 02:26:48 +00004941 // Vector shifts promote their scalar inputs to vector type.
4942 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
4943 return CheckVectorOperands(Loc, lex, rex);
4944
Chris Lattner5c11c412007-12-12 05:47:28 +00004945 // Shifts don't perform usual arithmetic conversions, they just do integer
4946 // promotions on each operand. C99 6.5.7p3
Eli Friedman629ffb92009-08-20 04:21:42 +00004947 QualType LHSTy = Context.isPromotableBitField(lex);
4948 if (LHSTy.isNull()) {
4949 LHSTy = lex->getType();
4950 if (LHSTy->isPromotableIntegerType())
4951 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregord2c2d172009-05-02 00:36:19 +00004952 }
Chris Lattner3c133402007-12-13 07:28:16 +00004953 if (!isCompAssign)
Eli Friedman06ed2a52009-10-20 08:27:19 +00004954 ImpCastExprToType(lex, LHSTy, CastExpr::CK_IntegralCast);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004955
Chris Lattner5c11c412007-12-12 05:47:28 +00004956 UsualUnaryConversions(rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004957
Ryan Flynnf53fab82009-08-07 16:20:20 +00004958 // Sanity-check shift operands
4959 llvm::APSInt Right;
4960 // Check right/shifter operand
Daniel Dunbar687fa862009-09-17 06:31:27 +00004961 if (!rex->isValueDependent() &&
4962 rex->isIntegerConstantExpr(Right, Context)) {
Ryan Flynn2f085712009-08-08 19:18:23 +00004963 if (Right.isNegative())
Ryan Flynnf53fab82009-08-07 16:20:20 +00004964 Diag(Loc, diag::warn_shift_negative) << rex->getSourceRange();
4965 else {
4966 llvm::APInt LeftBits(Right.getBitWidth(),
4967 Context.getTypeSize(lex->getType()));
4968 if (Right.uge(LeftBits))
4969 Diag(Loc, diag::warn_shift_gt_typewidth) << rex->getSourceRange();
4970 }
4971 }
4972
Chris Lattner5c11c412007-12-12 05:47:28 +00004973 // "The type of the result is that of the promoted left operand."
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004974 return LHSTy;
Steve Naroff26c8ea52007-03-21 21:08:52 +00004975}
4976
John McCall99ce6bf2009-11-06 08:49:08 +00004977/// \brief Implements -Wsign-compare.
4978///
4979/// \param lex the left-hand expression
4980/// \param rex the right-hand expression
4981/// \param OpLoc the location of the joining operator
John McCalle46fd852009-11-06 08:53:51 +00004982/// \param Equality whether this is an "equality-like" join, which
4983/// suppresses the warning in some cases
John McCall1fa36b72009-11-05 09:23:39 +00004984void Sema::CheckSignCompare(Expr *lex, Expr *rex, SourceLocation OpLoc,
John McCall99ce6bf2009-11-06 08:49:08 +00004985 const PartialDiagnostic &PD, bool Equality) {
John McCalle2c91e62009-11-06 18:16:06 +00004986 // Don't warn if we're in an unevaluated context.
Douglas Gregorff790f12009-11-26 00:44:06 +00004987 if (ExprEvalContexts.back().Context == Unevaluated)
John McCalle2c91e62009-11-06 18:16:06 +00004988 return;
4989
John McCall644a4182009-11-05 00:40:04 +00004990 QualType lt = lex->getType(), rt = rex->getType();
4991
4992 // Only warn if both operands are integral.
4993 if (!lt->isIntegerType() || !rt->isIntegerType())
4994 return;
4995
Sebastian Redl0b7c85f2009-11-05 21:09:23 +00004996 // If either expression is value-dependent, don't warn. We'll get another
4997 // chance at instantiation time.
4998 if (lex->isValueDependent() || rex->isValueDependent())
4999 return;
5000
John McCall644a4182009-11-05 00:40:04 +00005001 // The rule is that the signed operand becomes unsigned, so isolate the
5002 // signed operand.
John McCall99ce6bf2009-11-06 08:49:08 +00005003 Expr *signedOperand, *unsignedOperand;
John McCall644a4182009-11-05 00:40:04 +00005004 if (lt->isSignedIntegerType()) {
5005 if (rt->isSignedIntegerType()) return;
5006 signedOperand = lex;
John McCall99ce6bf2009-11-06 08:49:08 +00005007 unsignedOperand = rex;
John McCall644a4182009-11-05 00:40:04 +00005008 } else {
5009 if (!rt->isSignedIntegerType()) return;
5010 signedOperand = rex;
John McCall99ce6bf2009-11-06 08:49:08 +00005011 unsignedOperand = lex;
John McCall644a4182009-11-05 00:40:04 +00005012 }
5013
John McCall99ce6bf2009-11-06 08:49:08 +00005014 // If the unsigned type is strictly smaller than the signed type,
John McCalle46fd852009-11-06 08:53:51 +00005015 // then (1) the result type will be signed and (2) the unsigned
5016 // value will fit fully within the signed type, and thus the result
John McCall99ce6bf2009-11-06 08:49:08 +00005017 // of the comparison will be exact.
5018 if (Context.getIntWidth(signedOperand->getType()) >
5019 Context.getIntWidth(unsignedOperand->getType()))
5020 return;
5021
John McCall644a4182009-11-05 00:40:04 +00005022 // If the value is a non-negative integer constant, then the
5023 // signed->unsigned conversion won't change it.
5024 llvm::APSInt value;
John McCall1fa36b72009-11-05 09:23:39 +00005025 if (signedOperand->isIntegerConstantExpr(value, Context)) {
John McCall644a4182009-11-05 00:40:04 +00005026 assert(value.isSigned() && "result of signed expression not signed");
5027
5028 if (value.isNonNegative())
5029 return;
5030 }
5031
John McCall99ce6bf2009-11-06 08:49:08 +00005032 if (Equality) {
5033 // For (in)equality comparisons, if the unsigned operand is a
John McCalle46fd852009-11-06 08:53:51 +00005034 // constant which cannot collide with a overflowed signed operand,
5035 // then reinterpreting the signed operand as unsigned will not
5036 // change the result of the comparison.
John McCall99ce6bf2009-11-06 08:49:08 +00005037 if (unsignedOperand->isIntegerConstantExpr(value, Context)) {
5038 assert(!value.isSigned() && "result of unsigned expression is signed");
5039
5040 // 2's complement: test the top bit.
5041 if (value.isNonNegative())
5042 return;
5043 }
5044 }
5045
John McCall1fa36b72009-11-05 09:23:39 +00005046 Diag(OpLoc, PD)
John McCall644a4182009-11-05 00:40:04 +00005047 << lex->getType() << rex->getType()
5048 << lex->getSourceRange() << rex->getSourceRange();
5049}
5050
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00005051// C99 6.5.8, C++ [expr.rel]
Chris Lattner326f7572008-11-18 01:30:42 +00005052QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Douglas Gregor7a5bc762009-04-06 18:45:53 +00005053 unsigned OpaqueOpc, bool isRelational) {
5054 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)OpaqueOpc;
5055
Chris Lattner9a152e22009-12-05 05:40:13 +00005056 // Handle vector comparisons separately.
Nate Begeman191a6b12008-07-14 18:02:46 +00005057 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner326f7572008-11-18 01:30:42 +00005058 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005059
John McCall99ce6bf2009-11-06 08:49:08 +00005060 CheckSignCompare(lex, rex, Loc, diag::warn_mixed_sign_comparison,
5061 (Opc == BinaryOperator::EQ || Opc == BinaryOperator::NE));
John McCall644a4182009-11-05 00:40:04 +00005062
Chris Lattnerb620c342007-08-26 01:18:55 +00005063 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroff47fea352007-08-10 18:26:40 +00005064 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
5065 UsualArithmeticConversions(lex, rex);
5066 else {
5067 UsualUnaryConversions(lex);
5068 UsualUnaryConversions(rex);
5069 }
Steve Naroff31090012007-07-16 21:54:35 +00005070 QualType lType = lex->getType();
5071 QualType rType = rex->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005072
Mike Stumpf70bcf72009-05-07 18:43:07 +00005073 if (!lType->isFloatingType()
5074 && !(lType->isBlockPointerType() && isRelational)) {
Chris Lattner222b8bd2009-03-08 19:39:53 +00005075 // For non-floating point types, check for self-comparisons of the form
5076 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
5077 // often indicate logic errors in the program.
Mike Stump11289f42009-09-09 15:08:12 +00005078 // NOTE: Don't warn about comparisons of enum constants. These can arise
Ted Kremenekde9e9682009-03-20 19:57:37 +00005079 // from macro expansions, and are usually quite deliberate.
Chris Lattner222b8bd2009-03-08 19:39:53 +00005080 Expr *LHSStripped = lex->IgnoreParens();
5081 Expr *RHSStripped = rex->IgnoreParens();
5082 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped))
5083 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped))
Ted Kremenek9ffbe412009-03-20 18:35:45 +00005084 if (DRL->getDecl() == DRR->getDecl() &&
5085 !isa<EnumConstantDecl>(DRL->getDecl()))
Mike Stump4e1f26a2009-02-19 03:04:26 +00005086 Diag(Loc, diag::warn_selfcomparison);
Mike Stump11289f42009-09-09 15:08:12 +00005087
Chris Lattner222b8bd2009-03-08 19:39:53 +00005088 if (isa<CastExpr>(LHSStripped))
5089 LHSStripped = LHSStripped->IgnoreParenCasts();
5090 if (isa<CastExpr>(RHSStripped))
5091 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00005092
Chris Lattner222b8bd2009-03-08 19:39:53 +00005093 // Warn about comparisons against a string constant (unless the other
5094 // operand is null), the user probably wants strcmp.
Douglas Gregor7a5bc762009-04-06 18:45:53 +00005095 Expr *literalString = 0;
5096 Expr *literalStringStripped = 0;
Chris Lattner222b8bd2009-03-08 19:39:53 +00005097 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Douglas Gregor56751b52009-09-25 04:25:58 +00005098 !RHSStripped->isNullPointerConstant(Context,
5099 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregor7a5bc762009-04-06 18:45:53 +00005100 literalString = lex;
5101 literalStringStripped = LHSStripped;
Mike Stump12b8ce12009-08-04 21:02:39 +00005102 } else if ((isa<StringLiteral>(RHSStripped) ||
5103 isa<ObjCEncodeExpr>(RHSStripped)) &&
Douglas Gregor56751b52009-09-25 04:25:58 +00005104 !LHSStripped->isNullPointerConstant(Context,
5105 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregor7a5bc762009-04-06 18:45:53 +00005106 literalString = rex;
5107 literalStringStripped = RHSStripped;
5108 }
5109
5110 if (literalString) {
5111 std::string resultComparison;
5112 switch (Opc) {
5113 case BinaryOperator::LT: resultComparison = ") < 0"; break;
5114 case BinaryOperator::GT: resultComparison = ") > 0"; break;
5115 case BinaryOperator::LE: resultComparison = ") <= 0"; break;
5116 case BinaryOperator::GE: resultComparison = ") >= 0"; break;
5117 case BinaryOperator::EQ: resultComparison = ") == 0"; break;
5118 case BinaryOperator::NE: resultComparison = ") != 0"; break;
5119 default: assert(false && "Invalid comparison operator");
5120 }
5121 Diag(Loc, diag::warn_stringcompare)
5122 << isa<ObjCEncodeExpr>(literalStringStripped)
5123 << literalString->getSourceRange()
Douglas Gregor170512f2009-04-01 23:51:29 +00005124 << CodeModificationHint::CreateReplacement(SourceRange(Loc), ", ")
5125 << CodeModificationHint::CreateInsertion(lex->getLocStart(),
5126 "strcmp(")
5127 << CodeModificationHint::CreateInsertion(
5128 PP.getLocForEndOfToken(rex->getLocEnd()),
Douglas Gregor7a5bc762009-04-06 18:45:53 +00005129 resultComparison);
5130 }
Ted Kremeneke451eae2007-10-29 16:58:49 +00005131 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005132
Douglas Gregorca63811b2008-11-19 03:25:36 +00005133 // The result of comparisons is 'bool' in C++, 'int' in C.
Chris Lattner9a152e22009-12-05 05:40:13 +00005134 QualType ResultTy = getLangOptions().CPlusPlus ? Context.BoolTy:Context.IntTy;
Douglas Gregorca63811b2008-11-19 03:25:36 +00005135
Chris Lattnerb620c342007-08-26 01:18:55 +00005136 if (isRelational) {
5137 if (lType->isRealType() && rType->isRealType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00005138 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00005139 } else {
Ted Kremeneke2763b02007-10-29 17:13:39 +00005140 // Check for comparisons of floating point operands using != and ==.
Chris Lattner9a152e22009-12-05 05:40:13 +00005141 if (lType->isFloatingType() && rType->isFloatingType())
Chris Lattner326f7572008-11-18 01:30:42 +00005142 CheckFloatComparison(Loc,lex,rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005143
Chris Lattnerb620c342007-08-26 01:18:55 +00005144 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00005145 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00005146 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005147
Douglas Gregor56751b52009-09-25 04:25:58 +00005148 bool LHSIsNull = lex->isNullPointerConstant(Context,
5149 Expr::NPC_ValueDependentIsNull);
5150 bool RHSIsNull = rex->isNullPointerConstant(Context,
5151 Expr::NPC_ValueDependentIsNull);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005152
Chris Lattnerb620c342007-08-26 01:18:55 +00005153 // All of the following pointer related warnings are GCC extensions, except
5154 // when handling null pointer constants. One day, we can consider making them
5155 // errors (when -pedantic-errors is enabled).
Steve Naroff808eb8f2007-08-27 04:08:11 +00005156 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner3a0702e2008-04-03 05:07:25 +00005157 QualType LCanPointeeTy =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005158 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattner3a0702e2008-04-03 05:07:25 +00005159 QualType RCanPointeeTy =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005160 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stump4e1f26a2009-02-19 03:04:26 +00005161
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00005162 if (getLangOptions().CPlusPlus) {
Eli Friedman16c209612009-08-23 00:27:47 +00005163 if (LCanPointeeTy == RCanPointeeTy)
5164 return ResultTy;
5165
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00005166 // C++ [expr.rel]p2:
5167 // [...] Pointer conversions (4.10) and qualification
5168 // conversions (4.4) are performed on pointer operands (or on
5169 // a pointer operand and a null pointer constant) to bring
5170 // them to their composite pointer type. [...]
5171 //
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005172 // C++ [expr.eq]p1 uses the same notion for (in)equality
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00005173 // comparisons of pointers.
Douglas Gregorb8420462009-05-05 04:50:50 +00005174 QualType T = FindCompositePointerType(lex, rex);
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00005175 if (T.isNull()) {
5176 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
5177 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5178 return QualType();
5179 }
5180
Eli Friedman06ed2a52009-10-20 08:27:19 +00005181 ImpCastExprToType(lex, T, CastExpr::CK_BitCast);
5182 ImpCastExprToType(rex, T, CastExpr::CK_BitCast);
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00005183 return ResultTy;
5184 }
Eli Friedman16c209612009-08-23 00:27:47 +00005185 // C99 6.5.9p2 and C99 6.5.8p2
5186 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
5187 RCanPointeeTy.getUnqualifiedType())) {
5188 // Valid unless a relational comparison of function pointers
5189 if (isRelational && LCanPointeeTy->isFunctionType()) {
5190 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
5191 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5192 }
5193 } else if (!isRelational &&
5194 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
5195 // Valid unless comparison between non-null pointer and function pointer
5196 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
5197 && !LHSIsNull && !RHSIsNull) {
5198 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
5199 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5200 }
5201 } else {
5202 // Invalid
Chris Lattner377d1f82008-11-18 22:52:51 +00005203 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005204 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff75c17232007-06-13 21:41:08 +00005205 }
Eli Friedman16c209612009-08-23 00:27:47 +00005206 if (LCanPointeeTy != RCanPointeeTy)
Eli Friedman06ed2a52009-10-20 08:27:19 +00005207 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005208 return ResultTy;
Steve Naroffcdee44c2007-08-16 21:48:38 +00005209 }
Mike Stump11289f42009-09-09 15:08:12 +00005210
Sebastian Redl576fd422009-05-10 18:38:11 +00005211 if (getLangOptions().CPlusPlus) {
Mike Stump11289f42009-09-09 15:08:12 +00005212 // Comparison of pointers with null pointer constants and equality
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005213 // comparisons of member pointers to null pointer constants.
Mike Stump11289f42009-09-09 15:08:12 +00005214 if (RHSIsNull &&
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005215 (lType->isPointerType() ||
5216 (!isRelational && lType->isMemberPointerType()))) {
Anders Carlsson83133d92009-08-24 18:03:14 +00005217 ImpCastExprToType(rex, lType, CastExpr::CK_NullToMemberPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00005218 return ResultTy;
5219 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005220 if (LHSIsNull &&
5221 (rType->isPointerType() ||
5222 (!isRelational && rType->isMemberPointerType()))) {
Anders Carlsson83133d92009-08-24 18:03:14 +00005223 ImpCastExprToType(lex, rType, CastExpr::CK_NullToMemberPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00005224 return ResultTy;
5225 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005226
5227 // Comparison of member pointers.
Mike Stump11289f42009-09-09 15:08:12 +00005228 if (!isRelational &&
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005229 lType->isMemberPointerType() && rType->isMemberPointerType()) {
5230 // C++ [expr.eq]p2:
Mike Stump11289f42009-09-09 15:08:12 +00005231 // In addition, pointers to members can be compared, or a pointer to
5232 // member and a null pointer constant. Pointer to member conversions
5233 // (4.11) and qualification conversions (4.4) are performed to bring
5234 // them to a common type. If one operand is a null pointer constant,
5235 // the common type is the type of the other operand. Otherwise, the
5236 // common type is a pointer to member type similar (4.4) to the type
5237 // of one of the operands, with a cv-qualification signature (4.4)
5238 // that is the union of the cv-qualification signatures of the operand
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005239 // types.
5240 QualType T = FindCompositePointerType(lex, rex);
5241 if (T.isNull()) {
5242 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
5243 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5244 return QualType();
5245 }
Mike Stump11289f42009-09-09 15:08:12 +00005246
Eli Friedman06ed2a52009-10-20 08:27:19 +00005247 ImpCastExprToType(lex, T, CastExpr::CK_BitCast);
5248 ImpCastExprToType(rex, T, CastExpr::CK_BitCast);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005249 return ResultTy;
5250 }
Mike Stump11289f42009-09-09 15:08:12 +00005251
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005252 // Comparison of nullptr_t with itself.
Sebastian Redl576fd422009-05-10 18:38:11 +00005253 if (lType->isNullPtrType() && rType->isNullPtrType())
5254 return ResultTy;
5255 }
Mike Stump11289f42009-09-09 15:08:12 +00005256
Steve Naroff081c7422008-09-04 15:10:53 +00005257 // Handle block pointer types.
Mike Stump1b821b42009-05-07 03:14:14 +00005258 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005259 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
5260 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005261
Steve Naroff081c7422008-09-04 15:10:53 +00005262 if (!LHSIsNull && !RHSIsNull &&
Eli Friedmana6638ca2009-06-08 05:08:54 +00005263 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00005264 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005265 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff081c7422008-09-04 15:10:53 +00005266 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00005267 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005268 return ResultTy;
Steve Naroff081c7422008-09-04 15:10:53 +00005269 }
Steve Naroffe18f94c2008-09-28 01:11:11 +00005270 // Allow block pointers to be compared with null pointer constants.
Mike Stump1b821b42009-05-07 03:14:14 +00005271 if (!isRelational
5272 && ((lType->isBlockPointerType() && rType->isPointerType())
5273 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Naroffe18f94c2008-09-28 01:11:11 +00005274 if (!LHSIsNull && !RHSIsNull) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005275 if (!((rType->isPointerType() && rType->getAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00005276 ->getPointeeType()->isVoidType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005277 || (lType->isPointerType() && lType->getAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00005278 ->getPointeeType()->isVoidType())))
5279 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
5280 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroffe18f94c2008-09-28 01:11:11 +00005281 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00005282 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005283 return ResultTy;
Steve Naroffe18f94c2008-09-28 01:11:11 +00005284 }
Steve Naroff081c7422008-09-04 15:10:53 +00005285
Steve Naroff7cae42b2009-07-10 23:34:53 +00005286 if ((lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType())) {
Steve Naroff1d4a9a32008-10-27 10:33:19 +00005287 if (lType->isPointerType() || rType->isPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005288 const PointerType *LPT = lType->getAs<PointerType>();
5289 const PointerType *RPT = rType->getAs<PointerType>();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005290 bool LPtrToVoid = LPT ?
Steve Naroff753567f2008-11-17 19:49:16 +00005291 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005292 bool RPtrToVoid = RPT ?
Steve Naroff753567f2008-11-17 19:49:16 +00005293 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005294
Steve Naroff753567f2008-11-17 19:49:16 +00005295 if (!LPtrToVoid && !RPtrToVoid &&
5296 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00005297 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005298 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff1d4a9a32008-10-27 10:33:19 +00005299 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00005300 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005301 return ResultTy;
Steve Naroffea54d9e2008-10-20 18:19:10 +00005302 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00005303 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00005304 if (!Context.areComparableObjCPointerTypes(lType, rType))
Steve Naroff7cae42b2009-07-10 23:34:53 +00005305 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
5306 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00005307 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005308 return ResultTy;
Steve Naroffb788d9b2008-06-03 14:04:54 +00005309 }
Fariborz Jahanian134cbef2007-12-20 01:06:58 +00005310 }
Steve Naroff6b712a72009-07-14 18:25:06 +00005311 if (lType->isAnyPointerType() && rType->isIntegerType()) {
Chris Lattnerd99bd522009-08-23 00:03:44 +00005312 unsigned DiagID = 0;
5313 if (RHSIsNull) {
5314 if (isRelational)
5315 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
5316 } else if (isRelational)
5317 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
5318 else
5319 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump11289f42009-09-09 15:08:12 +00005320
Chris Lattnerd99bd522009-08-23 00:03:44 +00005321 if (DiagID) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00005322 Diag(Loc, DiagID)
Chris Lattnerd466ea12009-06-30 06:24:05 +00005323 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf8344db2009-08-22 18:58:31 +00005324 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00005325 ImpCastExprToType(rex, lType, CastExpr::CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005326 return ResultTy;
Steve Naroffcdee44c2007-08-16 21:48:38 +00005327 }
Steve Naroff6b712a72009-07-14 18:25:06 +00005328 if (lType->isIntegerType() && rType->isAnyPointerType()) {
Chris Lattnerd99bd522009-08-23 00:03:44 +00005329 unsigned DiagID = 0;
5330 if (LHSIsNull) {
5331 if (isRelational)
5332 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
5333 } else if (isRelational)
5334 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
5335 else
5336 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump11289f42009-09-09 15:08:12 +00005337
Chris Lattnerd99bd522009-08-23 00:03:44 +00005338 if (DiagID) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00005339 Diag(Loc, DiagID)
Chris Lattnerd466ea12009-06-30 06:24:05 +00005340 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf8344db2009-08-22 18:58:31 +00005341 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00005342 ImpCastExprToType(lex, rType, CastExpr::CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005343 return ResultTy;
Steve Naroff043d45d2007-05-15 02:32:35 +00005344 }
Steve Naroff4b191572008-09-04 16:56:14 +00005345 // Handle block pointers.
Mike Stumpf70bcf72009-05-07 18:43:07 +00005346 if (!isRelational && RHSIsNull
5347 && lType->isBlockPointerType() && rType->isIntegerType()) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00005348 ImpCastExprToType(rex, lType, CastExpr::CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005349 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00005350 }
Mike Stumpf70bcf72009-05-07 18:43:07 +00005351 if (!isRelational && LHSIsNull
5352 && lType->isIntegerType() && rType->isBlockPointerType()) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00005353 ImpCastExprToType(lex, rType, CastExpr::CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005354 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00005355 }
Chris Lattner326f7572008-11-18 01:30:42 +00005356 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00005357}
5358
Nate Begeman191a6b12008-07-14 18:02:46 +00005359/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump4e1f26a2009-02-19 03:04:26 +00005360/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begeman191a6b12008-07-14 18:02:46 +00005361/// like a scalar comparison, a vector comparison produces a vector of integer
5362/// types.
5363QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner326f7572008-11-18 01:30:42 +00005364 SourceLocation Loc,
Nate Begeman191a6b12008-07-14 18:02:46 +00005365 bool isRelational) {
5366 // Check to make sure we're operating on vectors of the same type and width,
5367 // Allowing one side to be a scalar of element type.
Chris Lattner326f7572008-11-18 01:30:42 +00005368 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begeman191a6b12008-07-14 18:02:46 +00005369 if (vType.isNull())
5370 return vType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005371
Nate Begeman191a6b12008-07-14 18:02:46 +00005372 QualType lType = lex->getType();
5373 QualType rType = rex->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005374
Nate Begeman191a6b12008-07-14 18:02:46 +00005375 // For non-floating point types, check for self-comparisons of the form
5376 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
5377 // often indicate logic errors in the program.
5378 if (!lType->isFloatingType()) {
5379 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
5380 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
5381 if (DRL->getDecl() == DRR->getDecl())
Mike Stump4e1f26a2009-02-19 03:04:26 +00005382 Diag(Loc, diag::warn_selfcomparison);
Nate Begeman191a6b12008-07-14 18:02:46 +00005383 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005384
Nate Begeman191a6b12008-07-14 18:02:46 +00005385 // Check for comparisons of floating point operands using != and ==.
5386 if (!isRelational && lType->isFloatingType()) {
5387 assert (rType->isFloatingType());
Chris Lattner326f7572008-11-18 01:30:42 +00005388 CheckFloatComparison(Loc,lex,rex);
Nate Begeman191a6b12008-07-14 18:02:46 +00005389 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005390
Nate Begeman191a6b12008-07-14 18:02:46 +00005391 // Return the type for the comparison, which is the same as vector type for
5392 // integer vectors, or an integer type of identical size and number of
5393 // elements for floating point vectors.
5394 if (lType->isIntegerType())
5395 return lType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005396
John McCall9dd450b2009-09-21 23:43:11 +00005397 const VectorType *VTy = lType->getAs<VectorType>();
Nate Begeman191a6b12008-07-14 18:02:46 +00005398 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005399 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begeman191a6b12008-07-14 18:02:46 +00005400 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattner5d688962009-03-31 07:46:52 +00005401 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005402 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
5403
Mike Stump4e1f26a2009-02-19 03:04:26 +00005404 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005405 "Unhandled vector element size in vector compare");
Nate Begeman191a6b12008-07-14 18:02:46 +00005406 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
5407}
5408
Steve Naroff218bc2b2007-05-04 21:54:46 +00005409inline QualType Sema::CheckBitwiseOperands(
Mike Stump11289f42009-09-09 15:08:12 +00005410 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Steve Naroff94a5aca2007-07-16 22:23:01 +00005411 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner326f7572008-11-18 01:30:42 +00005412 return CheckVectorOperands(Loc, lex, rex);
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005413
Steve Naroffbe4c4d12007-08-24 19:07:16 +00005414 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005415
Steve Naroffdbd9e892007-07-17 00:58:39 +00005416 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroffbe4c4d12007-08-24 19:07:16 +00005417 return compType;
Chris Lattner326f7572008-11-18 01:30:42 +00005418 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00005419}
5420
Steve Naroff218bc2b2007-05-04 21:54:46 +00005421inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Mike Stump11289f42009-09-09 15:08:12 +00005422 Expr *&lex, Expr *&rex, SourceLocation Loc) {
Anders Carlsson2e7bc112009-11-23 21:47:44 +00005423 if (!Context.getLangOptions().CPlusPlus) {
5424 UsualUnaryConversions(lex);
5425 UsualUnaryConversions(rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005426
Anders Carlsson2e7bc112009-11-23 21:47:44 +00005427 if (!lex->getType()->isScalarType() || !rex->getType()->isScalarType())
5428 return InvalidOperands(Loc, lex, rex);
Anders Carlsson35a99d92009-10-16 01:44:21 +00005429
Anders Carlsson2e7bc112009-11-23 21:47:44 +00005430 return Context.IntTy;
Anders Carlsson35a99d92009-10-16 01:44:21 +00005431 }
Anders Carlsson2e7bc112009-11-23 21:47:44 +00005432
5433 // C++ [expr.log.and]p1
5434 // C++ [expr.log.or]p1
5435 // The operands are both implicitly converted to type bool (clause 4).
5436 StandardConversionSequence LHS;
5437 if (!IsStandardConversion(lex, Context.BoolTy,
5438 /*InOverloadResolution=*/false, LHS))
5439 return InvalidOperands(Loc, lex, rex);
Anders Carlsson35a99d92009-10-16 01:44:21 +00005440
Anders Carlsson2e7bc112009-11-23 21:47:44 +00005441 if (PerformImplicitConversion(lex, Context.BoolTy, LHS,
5442 "passing", /*IgnoreBaseAccess=*/false))
5443 return InvalidOperands(Loc, lex, rex);
5444
5445 StandardConversionSequence RHS;
5446 if (!IsStandardConversion(rex, Context.BoolTy,
5447 /*InOverloadResolution=*/false, RHS))
5448 return InvalidOperands(Loc, lex, rex);
5449
5450 if (PerformImplicitConversion(rex, Context.BoolTy, RHS,
5451 "passing", /*IgnoreBaseAccess=*/false))
5452 return InvalidOperands(Loc, lex, rex);
5453
5454 // C++ [expr.log.and]p2
5455 // C++ [expr.log.or]p2
5456 // The result is a bool.
5457 return Context.BoolTy;
Steve Naroffae4143e2007-04-26 20:39:23 +00005458}
5459
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00005460/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
5461/// is a read-only property; return true if so. A readonly property expression
5462/// depends on various declarations and thus must be treated specially.
5463///
Mike Stump11289f42009-09-09 15:08:12 +00005464static bool IsReadonlyProperty(Expr *E, Sema &S) {
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00005465 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
5466 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
5467 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
5468 QualType BaseType = PropExpr->getBase()->getType();
Mike Stump11289f42009-09-09 15:08:12 +00005469 if (const ObjCObjectPointerType *OPT =
Steve Naroff7cae42b2009-07-10 23:34:53 +00005470 BaseType->getAsObjCInterfacePointerType())
5471 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
5472 if (S.isPropertyReadonly(PDecl, IFace))
5473 return true;
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00005474 }
5475 }
5476 return false;
5477}
5478
Chris Lattner30bd3272008-11-18 01:22:49 +00005479/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
5480/// emit an error and return true. If so, return false.
5481static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00005482 SourceLocation OrigLoc = Loc;
Mike Stump11289f42009-09-09 15:08:12 +00005483 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00005484 &Loc);
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00005485 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
5486 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattner30bd3272008-11-18 01:22:49 +00005487 if (IsLV == Expr::MLV_Valid)
5488 return false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005489
Chris Lattner30bd3272008-11-18 01:22:49 +00005490 unsigned Diag = 0;
5491 bool NeedType = false;
5492 switch (IsLV) { // C99 6.5.16p2
5493 default: assert(0 && "Unknown result from isModifiableLvalue!");
5494 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005495 case Expr::MLV_ArrayType:
Chris Lattner30bd3272008-11-18 01:22:49 +00005496 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
5497 NeedType = true;
5498 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005499 case Expr::MLV_NotObjectType:
Chris Lattner30bd3272008-11-18 01:22:49 +00005500 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
5501 NeedType = true;
5502 break;
Chris Lattner9b3bbe92008-11-17 19:51:54 +00005503 case Expr::MLV_LValueCast:
Chris Lattner30bd3272008-11-18 01:22:49 +00005504 Diag = diag::err_typecheck_lvalue_casts_not_supported;
5505 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00005506 case Expr::MLV_InvalidExpression:
Chris Lattner30bd3272008-11-18 01:22:49 +00005507 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
5508 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00005509 case Expr::MLV_IncompleteType:
5510 case Expr::MLV_IncompleteVoidType:
Douglas Gregored0cfbd2009-03-09 16:13:40 +00005511 return S.RequireCompleteType(Loc, E->getType(),
Anders Carlssond624e162009-08-26 23:45:07 +00005512 PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
5513 << E->getSourceRange());
Chris Lattner9bad62c2008-01-04 18:04:52 +00005514 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner30bd3272008-11-18 01:22:49 +00005515 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
5516 break;
Steve Naroffba756cb2008-09-26 14:41:28 +00005517 case Expr::MLV_NotBlockQualified:
Chris Lattner30bd3272008-11-18 01:22:49 +00005518 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
5519 break;
Fariborz Jahanian8a1810f2008-11-22 18:39:36 +00005520 case Expr::MLV_ReadonlyProperty:
5521 Diag = diag::error_readonly_property_assignment;
5522 break;
Fariborz Jahanian5118c412008-11-22 20:25:50 +00005523 case Expr::MLV_NoSetterProperty:
5524 Diag = diag::error_nosetter_property_assignment;
5525 break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00005526 }
Steve Naroffad373bd2007-07-31 12:34:36 +00005527
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00005528 SourceRange Assign;
5529 if (Loc != OrigLoc)
5530 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattner30bd3272008-11-18 01:22:49 +00005531 if (NeedType)
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00005532 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00005533 else
Mike Stump11289f42009-09-09 15:08:12 +00005534 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00005535 return true;
5536}
5537
5538
5539
5540// C99 6.5.16.1
Chris Lattner326f7572008-11-18 01:30:42 +00005541QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
5542 SourceLocation Loc,
5543 QualType CompoundType) {
5544 // Verify that LHS is a modifiable lvalue, and emit error if not.
5545 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner30bd3272008-11-18 01:22:49 +00005546 return QualType();
Chris Lattner326f7572008-11-18 01:30:42 +00005547
5548 QualType LHSType = LHS->getType();
5549 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005550
Chris Lattner9bad62c2008-01-04 18:04:52 +00005551 AssignConvertType ConvTy;
Chris Lattner326f7572008-11-18 01:30:42 +00005552 if (CompoundType.isNull()) {
Chris Lattnerea714382008-08-21 18:04:13 +00005553 // Simple assignment "x = y".
Chris Lattner326f7572008-11-18 01:30:42 +00005554 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Fariborz Jahanian255c0952009-01-13 23:34:40 +00005555 // Special case of NSObject attributes on c-style pointer types.
5556 if (ConvTy == IncompatiblePointer &&
5557 ((Context.isObjCNSObjectType(LHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00005558 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanian255c0952009-01-13 23:34:40 +00005559 (Context.isObjCNSObjectType(RHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00005560 LHSType->isObjCObjectPointerType())))
Fariborz Jahanian255c0952009-01-13 23:34:40 +00005561 ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005562
Chris Lattnerea714382008-08-21 18:04:13 +00005563 // If the RHS is a unary plus or minus, check to see if they = and + are
5564 // right next to each other. If so, the user may have typo'd "x =+ 4"
5565 // instead of "x += 4".
Chris Lattner326f7572008-11-18 01:30:42 +00005566 Expr *RHSCheck = RHS;
Chris Lattnerea714382008-08-21 18:04:13 +00005567 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
5568 RHSCheck = ICE->getSubExpr();
5569 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
5570 if ((UO->getOpcode() == UnaryOperator::Plus ||
5571 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner326f7572008-11-18 01:30:42 +00005572 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattnerea714382008-08-21 18:04:13 +00005573 // Only if the two operators are exactly adjacent.
Chris Lattner36c39c92009-03-08 06:51:10 +00005574 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
5575 // And there is a space or other character before the subexpr of the
5576 // unary +/-. We don't want to warn on "x=-1".
Chris Lattnered9f14c2009-03-09 07:11:10 +00005577 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
5578 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattner29e812b2008-11-20 06:06:08 +00005579 Diag(Loc, diag::warn_not_compound_assign)
5580 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
5581 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner36c39c92009-03-08 06:51:10 +00005582 }
Chris Lattnerea714382008-08-21 18:04:13 +00005583 }
5584 } else {
5585 // Compound assignment "x += y"
Eli Friedmanb05c41e2009-05-16 05:56:02 +00005586 ConvTy = CheckAssignmentConstraints(LHSType, RHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00005587 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00005588
Chris Lattner326f7572008-11-18 01:30:42 +00005589 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
5590 RHS, "assigning"))
Chris Lattner9bad62c2008-01-04 18:04:52 +00005591 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005592
Steve Naroff98cf3e92007-06-06 18:38:38 +00005593 // C99 6.5.16p3: The type of an assignment expression is the type of the
5594 // left operand unless the left operand has qualified type, in which case
Mike Stump4e1f26a2009-02-19 03:04:26 +00005595 // it is the unqualified version of the type of the left operand.
Steve Naroff98cf3e92007-06-06 18:38:38 +00005596 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
5597 // is converted to the type of the assignment expression (above).
Chris Lattnerf17bd422007-08-30 17:45:32 +00005598 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregord2c2d172009-05-02 00:36:19 +00005599 // operand.
Chris Lattner326f7572008-11-18 01:30:42 +00005600 return LHSType.getUnqualifiedType();
Steve Naroffae4143e2007-04-26 20:39:23 +00005601}
5602
Chris Lattner326f7572008-11-18 01:30:42 +00005603// C99 6.5.17
5604QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
Chris Lattnerf6e1e302008-07-25 20:54:07 +00005605 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner326f7572008-11-18 01:30:42 +00005606 DefaultFunctionArrayConversion(RHS);
Eli Friedmanba961a92009-03-23 00:24:07 +00005607
5608 // FIXME: Check that RHS type is complete in C mode (it's legal for it to be
5609 // incomplete in C++).
5610
Chris Lattner326f7572008-11-18 01:30:42 +00005611 return RHS->getType();
Steve Naroff95af0132007-03-30 23:47:58 +00005612}
5613
Steve Naroff7a5af782007-07-13 16:58:59 +00005614/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
5615/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redle10c2c32008-12-20 09:35:34 +00005616QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
5617 bool isInc) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005618 if (Op->isTypeDependent())
5619 return Context.DependentTy;
5620
Chris Lattner6b0cf142008-11-21 07:05:48 +00005621 QualType ResType = Op->getType();
5622 assert(!ResType.isNull() && "no type for increment/decrement expression");
Steve Naroffd50c88e2007-04-05 21:15:20 +00005623
Sebastian Redle10c2c32008-12-20 09:35:34 +00005624 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
5625 // Decrement of bool is not allowed.
5626 if (!isInc) {
5627 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
5628 return QualType();
5629 }
5630 // Increment of bool sets it to true, but is deprecated.
5631 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
5632 } else if (ResType->isRealType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00005633 // OK!
Steve Naroff6b712a72009-07-14 18:25:06 +00005634 } else if (ResType->isAnyPointerType()) {
5635 QualType PointeeTy = ResType->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00005636
Chris Lattner6b0cf142008-11-21 07:05:48 +00005637 // C99 6.5.2.4p2, 6.5.6p2
Steve Naroff7cae42b2009-07-10 23:34:53 +00005638 if (PointeeTy->isVoidType()) {
Douglas Gregorf6cd9282009-01-23 00:36:41 +00005639 if (getLangOptions().CPlusPlus) {
5640 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
5641 << Op->getSourceRange();
5642 return QualType();
5643 }
5644
5645 // Pointer to void is a GNU extension in C.
Chris Lattner6b0cf142008-11-21 07:05:48 +00005646 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005647 } else if (PointeeTy->isFunctionType()) {
Douglas Gregorf6cd9282009-01-23 00:36:41 +00005648 if (getLangOptions().CPlusPlus) {
5649 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
5650 << Op->getType() << Op->getSourceRange();
5651 return QualType();
5652 }
5653
5654 Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005655 << ResType << Op->getSourceRange();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005656 } else if (RequireCompleteType(OpLoc, PointeeTy,
Anders Carlsson029fc692009-08-26 22:59:12 +00005657 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
Mike Stump11289f42009-09-09 15:08:12 +00005658 << Op->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00005659 << ResType))
Douglas Gregordd430f72009-01-19 19:26:10 +00005660 return QualType();
Fariborz Jahanianca75db72009-07-16 17:59:14 +00005661 // Diagnose bad cases where we step over interface counts.
5662 else if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
5663 Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
5664 << PointeeTy << Op->getSourceRange();
5665 return QualType();
5666 }
Chris Lattner6b0cf142008-11-21 07:05:48 +00005667 } else if (ResType->isComplexType()) {
5668 // C99 does not support ++/-- on complex types, we allow as an extension.
5669 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005670 << ResType << Op->getSourceRange();
Chris Lattner6b0cf142008-11-21 07:05:48 +00005671 } else {
5672 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005673 << ResType << Op->getSourceRange();
Chris Lattner6b0cf142008-11-21 07:05:48 +00005674 return QualType();
Steve Naroff46ba1eb2007-04-03 23:13:13 +00005675 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005676 // At this point, we know we have a real, complex or pointer type.
Steve Naroff9e1e5512007-08-23 21:37:33 +00005677 // Now make sure the operand is a modifiable lvalue.
Chris Lattner6b0cf142008-11-21 07:05:48 +00005678 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Steve Naroff35d85152007-05-07 00:24:15 +00005679 return QualType();
Chris Lattner6b0cf142008-11-21 07:05:48 +00005680 return ResType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00005681}
5682
Anders Carlsson806700f2008-02-01 07:15:58 +00005683/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Steve Naroff47500512007-04-19 23:00:49 +00005684/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb692ef42008-08-04 20:02:37 +00005685/// where the declaration is needed for type checking. We only need to
5686/// handle cases when the expression references a function designator
5687/// or is an lvalue. Here are some examples:
5688/// - &(x) => x
5689/// - &*****f => f for f a function designator.
5690/// - &s.xx => s
5691/// - &s.zz[1].yy -> s, if zz is an array
5692/// - *(x + 1) -> x, if x is an array
5693/// - &"123"[2] -> 0
5694/// - & __real__ x -> x
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005695static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00005696 switch (E->getStmtClass()) {
Steve Naroff47500512007-04-19 23:00:49 +00005697 case Stmt::DeclRefExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00005698 return cast<DeclRefExpr>(E)->getDecl();
Steve Naroff47500512007-04-19 23:00:49 +00005699 case Stmt::MemberExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00005700 // If this is an arrow operator, the address is an offset from
5701 // the base's value, so the object the base refers to is
5702 // irrelevant.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00005703 if (cast<MemberExpr>(E)->isArrow())
Chris Lattner48d52842007-11-16 17:46:48 +00005704 return 0;
Eli Friedman3a1e6922009-04-20 08:23:18 +00005705 // Otherwise, the expression refers to a part of the base
Chris Lattner24d5bfe2008-04-02 04:24:33 +00005706 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson806700f2008-02-01 07:15:58 +00005707 case Stmt::ArraySubscriptExprClass: {
Mike Stump87c57ac2009-05-16 07:39:55 +00005708 // FIXME: This code shouldn't be necessary! We should catch the implicit
5709 // promotion of register arrays earlier.
Eli Friedman3a1e6922009-04-20 08:23:18 +00005710 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
5711 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
5712 if (ICE->getSubExpr()->getType()->isArrayType())
5713 return getPrimaryDecl(ICE->getSubExpr());
5714 }
5715 return 0;
Anders Carlsson806700f2008-02-01 07:15:58 +00005716 }
Daniel Dunbarb692ef42008-08-04 20:02:37 +00005717 case Stmt::UnaryOperatorClass: {
5718 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005719
Daniel Dunbarb692ef42008-08-04 20:02:37 +00005720 switch(UO->getOpcode()) {
Daniel Dunbarb692ef42008-08-04 20:02:37 +00005721 case UnaryOperator::Real:
5722 case UnaryOperator::Imag:
5723 case UnaryOperator::Extension:
5724 return getPrimaryDecl(UO->getSubExpr());
5725 default:
5726 return 0;
5727 }
5728 }
Steve Naroff47500512007-04-19 23:00:49 +00005729 case Stmt::ParenExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00005730 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattner48d52842007-11-16 17:46:48 +00005731 case Stmt::ImplicitCastExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00005732 // If the result of an implicit cast is an l-value, we care about
5733 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00005734 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Steve Naroff47500512007-04-19 23:00:49 +00005735 default:
5736 return 0;
5737 }
5738}
5739
5740/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump4e1f26a2009-02-19 03:04:26 +00005741/// designator or an lvalue designating an object. If it is an lvalue, the
Steve Naroff47500512007-04-19 23:00:49 +00005742/// object cannot be declared with storage class register or be a bit field.
Mike Stump4e1f26a2009-02-19 03:04:26 +00005743/// Note: The usual conversions are *not* applied to the operand of the &
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005744/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump4e1f26a2009-02-19 03:04:26 +00005745/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregorcd695e52008-11-10 20:40:00 +00005746/// we allow the '&' but retain the overloaded-function type.
Steve Naroff35d85152007-05-07 00:24:15 +00005747QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Eli Friedman3a1e6922009-04-20 08:23:18 +00005748 // Make sure to ignore parentheses in subsequent checks
5749 op = op->IgnoreParens();
5750
Douglas Gregor19b8c4f2008-12-17 22:52:20 +00005751 if (op->isTypeDependent())
5752 return Context.DependentTy;
5753
Steve Naroff826e91a2008-01-13 17:10:08 +00005754 if (getLangOptions().C99) {
5755 // Implement C99-only parts of addressof rules.
5756 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
5757 if (uOp->getOpcode() == UnaryOperator::Deref)
5758 // Per C99 6.5.3.2, the address of a deref always returns a valid result
5759 // (assuming the deref expression is valid).
5760 return uOp->getSubExpr()->getType();
5761 }
5762 // Technically, there should be a check for array subscript
5763 // expressions here, but the result of one is always an lvalue anyway.
5764 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005765 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner67315442008-07-26 21:30:36 +00005766 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes17f345f2008-12-16 22:59:47 +00005767
Eli Friedmance7f9002009-05-16 23:27:50 +00005768 if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
5769 // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00005770 // The operand must be either an l-value or a function designator
Eli Friedmance7f9002009-05-16 23:27:50 +00005771 if (!op->getType()->isFunctionType()) {
Chris Lattner48d52842007-11-16 17:46:48 +00005772 // FIXME: emit more specific diag...
Chris Lattnerf490e152008-11-19 05:27:50 +00005773 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
5774 << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00005775 return QualType();
5776 }
Douglas Gregor71235ec2009-05-02 02:18:30 +00005777 } else if (op->getBitField()) { // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00005778 // The operand cannot be a bit-field
5779 Diag(OpLoc, diag::err_typecheck_address_of)
5780 << "bit-field" << op->getSourceRange();
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00005781 return QualType();
Nate Begemana6b47a42009-02-15 22:45:20 +00005782 } else if (isa<ExtVectorElementExpr>(op) || (isa<ArraySubscriptExpr>(op) &&
5783 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType())){
Eli Friedman3a1e6922009-04-20 08:23:18 +00005784 // The operand cannot be an element of a vector
Chris Lattner29e812b2008-11-20 06:06:08 +00005785 Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemana6b47a42009-02-15 22:45:20 +00005786 << "vector element" << op->getSourceRange();
Steve Naroffb96e4ab62008-02-29 23:30:25 +00005787 return QualType();
Fariborz Jahanian385db802009-07-07 18:50:52 +00005788 } else if (isa<ObjCPropertyRefExpr>(op)) {
5789 // cannot take address of a property expression.
5790 Diag(OpLoc, diag::err_typecheck_address_of)
5791 << "property expression" << op->getSourceRange();
5792 return QualType();
Anders Carlsson3fa58d12009-09-14 23:15:26 +00005793 } else if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(op)) {
5794 // FIXME: Can LHS ever be null here?
Anders Carlsson01ccf992009-09-15 16:03:44 +00005795 if (!CheckAddressOfOperand(CO->getTrueExpr(), OpLoc).isNull())
5796 return CheckAddressOfOperand(CO->getFalseExpr(), OpLoc);
John McCalld14a8642009-11-21 08:51:07 +00005797 } else if (isa<UnresolvedLookupExpr>(op)) {
5798 return Context.OverloadTy;
Steve Naroffb96e4ab62008-02-29 23:30:25 +00005799 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump4e1f26a2009-02-19 03:04:26 +00005800 // We have an lvalue with a decl. Make sure the decl is not declared
Steve Naroff47500512007-04-19 23:00:49 +00005801 // with the register storage-class specifier.
5802 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Steve Naroff35d85152007-05-07 00:24:15 +00005803 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattner29e812b2008-11-20 06:06:08 +00005804 Diag(OpLoc, diag::err_typecheck_address_of)
5805 << "register variable" << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00005806 return QualType();
5807 }
John McCalld14a8642009-11-21 08:51:07 +00005808 } else if (isa<FunctionTemplateDecl>(dcl)) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00005809 return Context.OverloadTy;
Anders Carlsson0b675f52009-07-08 21:45:58 +00005810 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(dcl)) {
Douglas Gregor9aa8b552008-12-10 21:26:49 +00005811 // Okay: we can take the address of a field.
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00005812 // Could be a pointer to member, though, if there is an explicit
5813 // scope qualifier for the class.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00005814 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00005815 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlsson0b675f52009-07-08 21:45:58 +00005816 if (Ctx && Ctx->isRecord()) {
5817 if (FD->getType()->isReferenceType()) {
Mike Stump11289f42009-09-09 15:08:12 +00005818 Diag(OpLoc,
Anders Carlsson0b675f52009-07-08 21:45:58 +00005819 diag::err_cannot_form_pointer_to_member_of_reference_type)
5820 << FD->getDeclName() << FD->getType();
5821 return QualType();
5822 }
Mike Stump11289f42009-09-09 15:08:12 +00005823
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00005824 return Context.getMemberPointerType(op->getType(),
5825 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlsson0b675f52009-07-08 21:45:58 +00005826 }
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00005827 }
Anders Carlsson5b535762009-05-16 21:43:42 +00005828 } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(dcl)) {
Nuno Lopes5773a1b2008-12-16 22:58:26 +00005829 // Okay: we can take the address of a function.
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005830 // As above.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00005831 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier() &&
5832 MD->isInstance())
Anders Carlsson5b535762009-05-16 21:43:42 +00005833 return Context.getMemberPointerType(op->getType(),
5834 Context.getTypeDeclType(MD->getParent()).getTypePtr());
5835 } else if (!isa<FunctionDecl>(dcl))
Steve Narofff633d092007-04-25 19:01:39 +00005836 assert(0 && "Unknown/unexpected decl type");
Steve Naroff47500512007-04-19 23:00:49 +00005837 }
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005838
Eli Friedmance7f9002009-05-16 23:27:50 +00005839 if (lval == Expr::LV_IncompleteVoidType) {
5840 // Taking the address of a void variable is technically illegal, but we
5841 // allow it in cases which are otherwise valid.
5842 // Example: "extern void x; void* y = &x;".
5843 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
5844 }
5845
Steve Naroff47500512007-04-19 23:00:49 +00005846 // If the operand has type "type", the result has type "pointer to type".
Steve Naroff35d85152007-05-07 00:24:15 +00005847 return Context.getPointerType(op->getType());
Steve Naroff47500512007-04-19 23:00:49 +00005848}
5849
Chris Lattner6a2ed6f2008-11-23 09:13:29 +00005850QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005851 if (Op->isTypeDependent())
5852 return Context.DependentTy;
5853
Chris Lattner6a2ed6f2008-11-23 09:13:29 +00005854 UsualUnaryConversions(Op);
5855 QualType Ty = Op->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005856
Chris Lattner6a2ed6f2008-11-23 09:13:29 +00005857 // Note that per both C89 and C99, this is always legal, even if ptype is an
5858 // incomplete type or void. It would be possible to warn about dereferencing
5859 // a void pointer, but it's completely well-defined, and such a warning is
5860 // unlikely to catch any mistakes.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005861 if (const PointerType *PT = Ty->getAs<PointerType>())
Steve Naroff826e91a2008-01-13 17:10:08 +00005862 return PT->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005863
John McCall9dd450b2009-09-21 23:43:11 +00005864 if (const ObjCObjectPointerType *OPT = Ty->getAs<ObjCObjectPointerType>())
Fariborz Jahanianf15d4b62009-09-03 00:43:07 +00005865 return OPT->getPointeeType();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005866
Chris Lattner29e812b2008-11-20 06:06:08 +00005867 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner6a2ed6f2008-11-23 09:13:29 +00005868 << Ty << Op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00005869 return QualType();
Steve Naroff1926c832007-04-24 00:23:05 +00005870}
Steve Naroff218bc2b2007-05-04 21:54:46 +00005871
5872static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
5873 tok::TokenKind Kind) {
5874 BinaryOperator::Opcode Opc;
5875 switch (Kind) {
5876 default: assert(0 && "Unknown binop!");
Sebastian Redl112a97662009-02-07 00:15:38 +00005877 case tok::periodstar: Opc = BinaryOperator::PtrMemD; break;
5878 case tok::arrowstar: Opc = BinaryOperator::PtrMemI; break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00005879 case tok::star: Opc = BinaryOperator::Mul; break;
5880 case tok::slash: Opc = BinaryOperator::Div; break;
5881 case tok::percent: Opc = BinaryOperator::Rem; break;
5882 case tok::plus: Opc = BinaryOperator::Add; break;
5883 case tok::minus: Opc = BinaryOperator::Sub; break;
5884 case tok::lessless: Opc = BinaryOperator::Shl; break;
5885 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
5886 case tok::lessequal: Opc = BinaryOperator::LE; break;
5887 case tok::less: Opc = BinaryOperator::LT; break;
5888 case tok::greaterequal: Opc = BinaryOperator::GE; break;
5889 case tok::greater: Opc = BinaryOperator::GT; break;
5890 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
5891 case tok::equalequal: Opc = BinaryOperator::EQ; break;
5892 case tok::amp: Opc = BinaryOperator::And; break;
5893 case tok::caret: Opc = BinaryOperator::Xor; break;
5894 case tok::pipe: Opc = BinaryOperator::Or; break;
5895 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
5896 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
5897 case tok::equal: Opc = BinaryOperator::Assign; break;
5898 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
5899 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
5900 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
5901 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
5902 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
5903 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
5904 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
5905 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
5906 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
5907 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
5908 case tok::comma: Opc = BinaryOperator::Comma; break;
5909 }
5910 return Opc;
5911}
5912
Steve Naroff35d85152007-05-07 00:24:15 +00005913static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
5914 tok::TokenKind Kind) {
5915 UnaryOperator::Opcode Opc;
5916 switch (Kind) {
5917 default: assert(0 && "Unknown unary op!");
5918 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
5919 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
5920 case tok::amp: Opc = UnaryOperator::AddrOf; break;
5921 case tok::star: Opc = UnaryOperator::Deref; break;
5922 case tok::plus: Opc = UnaryOperator::Plus; break;
5923 case tok::minus: Opc = UnaryOperator::Minus; break;
5924 case tok::tilde: Opc = UnaryOperator::Not; break;
5925 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Steve Naroff35d85152007-05-07 00:24:15 +00005926 case tok::kw___real: Opc = UnaryOperator::Real; break;
5927 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
Chris Lattnerd0f76512007-06-08 22:16:53 +00005928 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
Steve Naroff35d85152007-05-07 00:24:15 +00005929 }
5930 return Opc;
5931}
5932
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00005933/// CreateBuiltinBinOp - Creates a new built-in binary operation with
5934/// operator @p Opc at location @c TokLoc. This routine only supports
5935/// built-in operations; ActOnBinOp handles overloaded operators.
Sebastian Redlb5d49352009-01-19 22:31:54 +00005936Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
5937 unsigned Op,
5938 Expr *lhs, Expr *rhs) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005939 QualType ResultTy; // Result type of the binary operator.
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00005940 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005941 // The following two variables are used for compound assignment operators
5942 QualType CompLHSTy; // Type of LHS after promotions for computation
5943 QualType CompResultTy; // Type of computation result
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00005944
5945 switch (Opc) {
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00005946 case BinaryOperator::Assign:
5947 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
5948 break;
Sebastian Redl112a97662009-02-07 00:15:38 +00005949 case BinaryOperator::PtrMemD:
5950 case BinaryOperator::PtrMemI:
5951 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
5952 Opc == BinaryOperator::PtrMemI);
5953 break;
5954 case BinaryOperator::Mul:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00005955 case BinaryOperator::Div:
5956 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
5957 break;
5958 case BinaryOperator::Rem:
5959 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
5960 break;
5961 case BinaryOperator::Add:
5962 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
5963 break;
5964 case BinaryOperator::Sub:
5965 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
5966 break;
Sebastian Redl112a97662009-02-07 00:15:38 +00005967 case BinaryOperator::Shl:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00005968 case BinaryOperator::Shr:
5969 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
5970 break;
5971 case BinaryOperator::LE:
5972 case BinaryOperator::LT:
5973 case BinaryOperator::GE:
5974 case BinaryOperator::GT:
Douglas Gregor7a5bc762009-04-06 18:45:53 +00005975 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00005976 break;
5977 case BinaryOperator::EQ:
5978 case BinaryOperator::NE:
Douglas Gregor7a5bc762009-04-06 18:45:53 +00005979 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00005980 break;
5981 case BinaryOperator::And:
5982 case BinaryOperator::Xor:
5983 case BinaryOperator::Or:
5984 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
5985 break;
5986 case BinaryOperator::LAnd:
5987 case BinaryOperator::LOr:
5988 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
5989 break;
5990 case BinaryOperator::MulAssign:
5991 case BinaryOperator::DivAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005992 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
5993 CompLHSTy = CompResultTy;
5994 if (!CompResultTy.isNull())
5995 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00005996 break;
5997 case BinaryOperator::RemAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005998 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
5999 CompLHSTy = CompResultTy;
6000 if (!CompResultTy.isNull())
6001 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006002 break;
6003 case BinaryOperator::AddAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006004 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
6005 if (!CompResultTy.isNull())
6006 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006007 break;
6008 case BinaryOperator::SubAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006009 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
6010 if (!CompResultTy.isNull())
6011 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006012 break;
6013 case BinaryOperator::ShlAssign:
6014 case BinaryOperator::ShrAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006015 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
6016 CompLHSTy = CompResultTy;
6017 if (!CompResultTy.isNull())
6018 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006019 break;
6020 case BinaryOperator::AndAssign:
6021 case BinaryOperator::XorAssign:
6022 case BinaryOperator::OrAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006023 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
6024 CompLHSTy = CompResultTy;
6025 if (!CompResultTy.isNull())
6026 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006027 break;
6028 case BinaryOperator::Comma:
6029 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
6030 break;
6031 }
6032 if (ResultTy.isNull())
Sebastian Redlb5d49352009-01-19 22:31:54 +00006033 return ExprError();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006034 if (CompResultTy.isNull())
Steve Narofff6009ed2009-01-21 00:14:39 +00006035 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
6036 else
6037 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006038 CompLHSTy, CompResultTy,
6039 OpLoc));
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006040}
6041
Sebastian Redl44615072009-10-27 12:10:02 +00006042/// SuggestParentheses - Emit a diagnostic together with a fixit hint that wraps
6043/// ParenRange in parentheses.
Sebastian Redl4afb7c582009-10-26 17:01:32 +00006044static void SuggestParentheses(Sema &Self, SourceLocation Loc,
6045 const PartialDiagnostic &PD,
6046 SourceRange ParenRange)
6047{
6048 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
6049 if (!ParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
6050 // We can't display the parentheses, so just dig the
6051 // warning/error and return.
6052 Self.Diag(Loc, PD);
6053 return;
6054 }
6055
6056 Self.Diag(Loc, PD)
6057 << CodeModificationHint::CreateInsertion(ParenRange.getBegin(), "(")
6058 << CodeModificationHint::CreateInsertion(EndLoc, ")");
6059}
6060
Sebastian Redl44615072009-10-27 12:10:02 +00006061/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
6062/// operators are mixed in a way that suggests that the programmer forgot that
6063/// comparison operators have higher precedence. The most typical example of
6064/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
Sebastian Redl43028242009-10-26 15:24:15 +00006065static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperator::Opcode Opc,
6066 SourceLocation OpLoc,Expr *lhs,Expr *rhs){
Sebastian Redl44615072009-10-27 12:10:02 +00006067 typedef BinaryOperator BinOp;
6068 BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1),
6069 rhsopc = static_cast<BinOp::Opcode>(-1);
6070 if (BinOp *BO = dyn_cast<BinOp>(lhs))
Sebastian Redl43028242009-10-26 15:24:15 +00006071 lhsopc = BO->getOpcode();
Sebastian Redl44615072009-10-27 12:10:02 +00006072 if (BinOp *BO = dyn_cast<BinOp>(rhs))
Sebastian Redl43028242009-10-26 15:24:15 +00006073 rhsopc = BO->getOpcode();
6074
6075 // Subs are not binary operators.
6076 if (lhsopc == -1 && rhsopc == -1)
6077 return;
6078
6079 // Bitwise operations are sometimes used as eager logical ops.
6080 // Don't diagnose this.
Sebastian Redl44615072009-10-27 12:10:02 +00006081 if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) &&
6082 (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc)))
Sebastian Redl43028242009-10-26 15:24:15 +00006083 return;
6084
Sebastian Redl44615072009-10-27 12:10:02 +00006085 if (BinOp::isComparisonOp(lhsopc))
Sebastian Redl4afb7c582009-10-26 17:01:32 +00006086 SuggestParentheses(Self, OpLoc,
6087 PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redl44615072009-10-27 12:10:02 +00006088 << SourceRange(lhs->getLocStart(), OpLoc)
6089 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(lhsopc),
6090 SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(), rhs->getLocEnd()));
6091 else if (BinOp::isComparisonOp(rhsopc))
Sebastian Redl4afb7c582009-10-26 17:01:32 +00006092 SuggestParentheses(Self, OpLoc,
6093 PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redl44615072009-10-27 12:10:02 +00006094 << SourceRange(OpLoc, rhs->getLocEnd())
6095 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(rhsopc),
6096 SourceRange(lhs->getLocEnd(), cast<BinOp>(rhs)->getLHS()->getLocStart()));
Sebastian Redl43028242009-10-26 15:24:15 +00006097}
6098
6099/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
6100/// precedence. This currently diagnoses only "arg1 'bitwise' arg2 'eq' arg3".
6101/// But it could also warn about arg1 && arg2 || arg3, as GCC 4.3+ does.
6102static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperator::Opcode Opc,
6103 SourceLocation OpLoc, Expr *lhs, Expr *rhs){
Sebastian Redl44615072009-10-27 12:10:02 +00006104 if (BinaryOperator::isBitwiseOp(Opc))
Sebastian Redl43028242009-10-26 15:24:15 +00006105 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs);
6106}
6107
Steve Naroff218bc2b2007-05-04 21:54:46 +00006108// Binary Operators. 'Tok' is the token for the operator.
Sebastian Redlb5d49352009-01-19 22:31:54 +00006109Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
6110 tok::TokenKind Kind,
6111 ExprArg LHS, ExprArg RHS) {
Steve Naroff218bc2b2007-05-04 21:54:46 +00006112 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
Anders Carlssonb781bcd2009-05-01 19:49:17 +00006113 Expr *lhs = LHS.takeAs<Expr>(), *rhs = RHS.takeAs<Expr>();
Steve Naroff218bc2b2007-05-04 21:54:46 +00006114
Steve Naroff83895f72007-09-16 03:34:24 +00006115 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
6116 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Steve Naroff218bc2b2007-05-04 21:54:46 +00006117
Sebastian Redl43028242009-10-26 15:24:15 +00006118 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
6119 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs);
6120
Douglas Gregor5287f092009-11-05 00:51:44 +00006121 return BuildBinOp(S, TokLoc, Opc, lhs, rhs);
6122}
6123
6124Action::OwningExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
6125 BinaryOperator::Opcode Opc,
6126 Expr *lhs, Expr *rhs) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006127 if (getLangOptions().CPlusPlus &&
Mike Stump11289f42009-09-09 15:08:12 +00006128 (lhs->getType()->isOverloadableType() ||
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006129 rhs->getType()->isOverloadableType())) {
6130 // Find all of the overloaded operators visible from this
6131 // point. We perform both an operator-name lookup from the local
6132 // scope and an argument-dependent lookup based on the types of
6133 // the arguments.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00006134 FunctionSet Functions;
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006135 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
6136 if (OverOp != OO_None) {
Douglas Gregor5287f092009-11-05 00:51:44 +00006137 if (S)
6138 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
6139 Functions);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006140 Expr *Args[2] = { lhs, rhs };
Mike Stump11289f42009-09-09 15:08:12 +00006141 DeclarationName OpName
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006142 = Context.DeclarationNames.getCXXOperatorName(OverOp);
Sebastian Redlc057f422009-10-23 19:23:15 +00006143 ArgumentDependentLookup(OpName, /*Operator*/true, Args, 2, Functions);
Douglas Gregora11693b2008-11-12 17:17:38 +00006144 }
Douglas Gregor5287f092009-11-05 00:51:44 +00006145
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006146 // Build the (potentially-overloaded, potentially-dependent)
6147 // binary operation.
Douglas Gregor5287f092009-11-05 00:51:44 +00006148 return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs);
Sebastian Redlb5d49352009-01-19 22:31:54 +00006149 }
Douglas Gregor5287f092009-11-05 00:51:44 +00006150
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006151 // Build a built-in binary operation.
Douglas Gregor5287f092009-11-05 00:51:44 +00006152 return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs);
Steve Naroff218bc2b2007-05-04 21:54:46 +00006153}
6154
Douglas Gregor084d8552009-03-13 23:49:33 +00006155Action::OwningExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00006156 unsigned OpcIn,
Douglas Gregor084d8552009-03-13 23:49:33 +00006157 ExprArg InputArg) {
6158 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregord08452f2008-11-19 15:42:04 +00006159
Mike Stump87c57ac2009-05-16 07:39:55 +00006160 // FIXME: Input is modified below, but InputArg is not updated appropriately.
Douglas Gregor084d8552009-03-13 23:49:33 +00006161 Expr *Input = (Expr *)InputArg.get();
Steve Naroff35d85152007-05-07 00:24:15 +00006162 QualType resultType;
6163 switch (Opc) {
Douglas Gregor084d8552009-03-13 23:49:33 +00006164 case UnaryOperator::OffsetOf:
6165 assert(false && "Invalid unary operator");
6166 break;
6167
Steve Naroff35d85152007-05-07 00:24:15 +00006168 case UnaryOperator::PreInc:
6169 case UnaryOperator::PreDec:
Eli Friedman6aea5752009-07-22 22:25:00 +00006170 case UnaryOperator::PostInc:
6171 case UnaryOperator::PostDec:
Sebastian Redle10c2c32008-12-20 09:35:34 +00006172 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
Eli Friedman6aea5752009-07-22 22:25:00 +00006173 Opc == UnaryOperator::PreInc ||
6174 Opc == UnaryOperator::PostInc);
Steve Naroff35d85152007-05-07 00:24:15 +00006175 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006176 case UnaryOperator::AddrOf:
Chris Lattner86554282007-06-08 22:32:33 +00006177 resultType = CheckAddressOfOperand(Input, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00006178 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006179 case UnaryOperator::Deref:
Steve Naroffb7235642007-12-18 04:06:57 +00006180 DefaultFunctionArrayConversion(Input);
Chris Lattner86554282007-06-08 22:32:33 +00006181 resultType = CheckIndirectionOperand(Input, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00006182 break;
6183 case UnaryOperator::Plus:
6184 case UnaryOperator::Minus:
Steve Naroff31090012007-07-16 21:54:35 +00006185 UsualUnaryConversions(Input);
6186 resultType = Input->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006187 if (resultType->isDependentType())
6188 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00006189 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
6190 break;
6191 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
6192 resultType->isEnumeralType())
6193 break;
6194 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
6195 Opc == UnaryOperator::Plus &&
6196 resultType->isPointerType())
6197 break;
6198
Sebastian Redlc215cfc2009-01-19 00:08:26 +00006199 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
6200 << resultType << Input->getSourceRange());
Steve Naroff35d85152007-05-07 00:24:15 +00006201 case UnaryOperator::Not: // bitwise complement
Steve Naroff31090012007-07-16 21:54:35 +00006202 UsualUnaryConversions(Input);
6203 resultType = Input->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006204 if (resultType->isDependentType())
6205 break;
Chris Lattner0d707612008-07-25 23:52:49 +00006206 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
6207 if (resultType->isComplexType() || resultType->isComplexIntegerType())
6208 // C99 does not support '~' for complex conjugation.
Chris Lattner29e812b2008-11-20 06:06:08 +00006209 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006210 << resultType << Input->getSourceRange();
Chris Lattner0d707612008-07-25 23:52:49 +00006211 else if (!resultType->isIntegerType())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00006212 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
6213 << resultType << Input->getSourceRange());
Steve Naroff35d85152007-05-07 00:24:15 +00006214 break;
6215 case UnaryOperator::LNot: // logical negation
Steve Naroff71b59a92007-06-04 22:22:31 +00006216 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Steve Naroff31090012007-07-16 21:54:35 +00006217 DefaultFunctionArrayConversion(Input);
6218 resultType = Input->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006219 if (resultType->isDependentType())
6220 break;
Steve Naroff35d85152007-05-07 00:24:15 +00006221 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redlc215cfc2009-01-19 00:08:26 +00006222 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
6223 << resultType << Input->getSourceRange());
Chris Lattnerbe31ed82007-06-02 19:11:33 +00006224 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00006225 // In C++, it's bool. C++ 5.3.1p8
6226 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Steve Naroff35d85152007-05-07 00:24:15 +00006227 break;
Chris Lattner30b5dd02007-08-24 21:16:53 +00006228 case UnaryOperator::Real:
Chris Lattner30b5dd02007-08-24 21:16:53 +00006229 case UnaryOperator::Imag:
Chris Lattner709322b2009-02-17 08:12:06 +00006230 resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real);
Chris Lattner30b5dd02007-08-24 21:16:53 +00006231 break;
Chris Lattner86554282007-06-08 22:32:33 +00006232 case UnaryOperator::Extension:
Chris Lattner86554282007-06-08 22:32:33 +00006233 resultType = Input->getType();
Steve Naroff043d45d2007-05-15 02:32:35 +00006234 break;
Steve Naroff35d85152007-05-07 00:24:15 +00006235 }
6236 if (resultType.isNull())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00006237 return ExprError();
Douglas Gregor084d8552009-03-13 23:49:33 +00006238
6239 InputArg.release();
Steve Narofff6009ed2009-01-21 00:14:39 +00006240 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
Steve Naroff35d85152007-05-07 00:24:15 +00006241}
Chris Lattnereefa10e2007-05-28 06:56:27 +00006242
Douglas Gregor5287f092009-11-05 00:51:44 +00006243Action::OwningExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
6244 UnaryOperator::Opcode Opc,
6245 ExprArg input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00006246 Expr *Input = (Expr*)input.get();
Anders Carlsson461a2c02009-11-14 21:26:41 +00006247 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
6248 Opc != UnaryOperator::Extension) {
Douglas Gregor084d8552009-03-13 23:49:33 +00006249 // Find all of the overloaded operators visible from this
6250 // point. We perform both an operator-name lookup from the local
6251 // scope and an argument-dependent lookup based on the types of
6252 // the arguments.
6253 FunctionSet Functions;
6254 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
6255 if (OverOp != OO_None) {
Douglas Gregor5287f092009-11-05 00:51:44 +00006256 if (S)
6257 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
6258 Functions);
Mike Stump11289f42009-09-09 15:08:12 +00006259 DeclarationName OpName
Douglas Gregor084d8552009-03-13 23:49:33 +00006260 = Context.DeclarationNames.getCXXOperatorName(OverOp);
Sebastian Redlc057f422009-10-23 19:23:15 +00006261 ArgumentDependentLookup(OpName, /*Operator*/true, &Input, 1, Functions);
Douglas Gregor084d8552009-03-13 23:49:33 +00006262 }
Douglas Gregor5287f092009-11-05 00:51:44 +00006263
Douglas Gregor084d8552009-03-13 23:49:33 +00006264 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, move(input));
6265 }
Douglas Gregor5287f092009-11-05 00:51:44 +00006266
Douglas Gregor084d8552009-03-13 23:49:33 +00006267 return CreateBuiltinUnaryOp(OpLoc, Opc, move(input));
6268}
6269
Douglas Gregor5287f092009-11-05 00:51:44 +00006270// Unary Operators. 'Tok' is the token for the operator.
6271Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
6272 tok::TokenKind Op, ExprArg input) {
6273 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), move(input));
6274}
6275
Steve Naroff66356bd2007-09-16 14:56:35 +00006276/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006277Sema::OwningExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
6278 SourceLocation LabLoc,
6279 IdentifierInfo *LabelII) {
Chris Lattnereefa10e2007-05-28 06:56:27 +00006280 // Look up the record for this label identifier.
Chris Lattner3318e862009-04-18 20:01:55 +00006281 LabelStmt *&LabelDecl = getLabelMap()[LabelII];
Mike Stump4e1f26a2009-02-19 03:04:26 +00006282
Daniel Dunbar88402ce2008-08-04 16:51:22 +00006283 // If we haven't seen this label yet, create a forward reference. It
6284 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Steve Naroff846b1ec2009-03-13 15:38:40 +00006285 if (LabelDecl == 0)
Steve Narofff6009ed2009-01-21 00:14:39 +00006286 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006287
Chris Lattnereefa10e2007-05-28 06:56:27 +00006288 // Create the AST node. The address of a label always has type 'void*'.
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006289 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
6290 Context.getPointerType(Context.VoidTy)));
Chris Lattnereefa10e2007-05-28 06:56:27 +00006291}
6292
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006293Sema::OwningExprResult
6294Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtArg substmt,
6295 SourceLocation RPLoc) { // "({..})"
6296 Stmt *SubStmt = static_cast<Stmt*>(substmt.get());
Chris Lattner366727f2007-07-24 16:58:17 +00006297 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
6298 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
6299
Eli Friedman52cc0162009-01-24 23:09:00 +00006300 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Chris Lattnera69b0762009-04-25 19:11:05 +00006301 if (isFileScope)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006302 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedman52cc0162009-01-24 23:09:00 +00006303
Chris Lattner366727f2007-07-24 16:58:17 +00006304 // FIXME: there are a variety of strange constraints to enforce here, for
6305 // example, it is not possible to goto into a stmt expression apparently.
6306 // More semantic analysis is needed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00006307
Chris Lattner366727f2007-07-24 16:58:17 +00006308 // If there are sub stmts in the compound stmt, take the type of the last one
6309 // as the type of the stmtexpr.
6310 QualType Ty = Context.VoidTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006311
Chris Lattner944d3062008-07-26 19:51:01 +00006312 if (!Compound->body_empty()) {
6313 Stmt *LastStmt = Compound->body_back();
6314 // If LastStmt is a label, skip down through into the body.
6315 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
6316 LastStmt = Label->getSubStmt();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006317
Chris Lattner944d3062008-07-26 19:51:01 +00006318 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattner366727f2007-07-24 16:58:17 +00006319 Ty = LastExpr->getType();
Chris Lattner944d3062008-07-26 19:51:01 +00006320 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006321
Eli Friedmanba961a92009-03-23 00:24:07 +00006322 // FIXME: Check that expression type is complete/non-abstract; statement
6323 // expressions are not lvalues.
6324
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006325 substmt.release();
6326 return Owned(new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc));
Chris Lattner366727f2007-07-24 16:58:17 +00006327}
Steve Naroff78864672007-08-01 22:05:33 +00006328
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006329Sema::OwningExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
6330 SourceLocation BuiltinLoc,
6331 SourceLocation TypeLoc,
6332 TypeTy *argty,
6333 OffsetOfComponent *CompPtr,
6334 unsigned NumComponents,
6335 SourceLocation RPLoc) {
6336 // FIXME: This function leaks all expressions in the offset components on
6337 // error.
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00006338 // FIXME: Preserve type source info.
6339 QualType ArgTy = GetTypeFromParser(argty);
Chris Lattnerf17bd422007-08-30 17:45:32 +00006340 assert(!ArgTy.isNull() && "Missing type argument!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00006341
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006342 bool Dependent = ArgTy->isDependentType();
6343
Chris Lattnerf17bd422007-08-30 17:45:32 +00006344 // We must have at least one component that refers to the type, and the first
6345 // one is known to be a field designator. Verify that the ArgTy represents
6346 // a struct/union/class.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006347 if (!Dependent && !ArgTy->isRecordType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006348 return ExprError(Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006349
Eli Friedmanba961a92009-03-23 00:24:07 +00006350 // FIXME: Type must be complete per C99 7.17p3 because a declaring a variable
6351 // with an incomplete type would be illegal.
Douglas Gregor26897462009-03-11 16:48:53 +00006352
Eli Friedman988a16b2009-02-27 06:44:11 +00006353 // Otherwise, create a null pointer as the base, and iteratively process
6354 // the offsetof designators.
6355 QualType ArgTyPtr = Context.getPointerType(ArgTy);
6356 Expr* Res = new (Context) ImplicitValueInitExpr(ArgTyPtr);
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006357 Res = new (Context) UnaryOperator(Res, UnaryOperator::Deref,
Eli Friedman988a16b2009-02-27 06:44:11 +00006358 ArgTy, SourceLocation());
Eli Friedman16c88df2009-01-26 01:33:06 +00006359
Chris Lattner78502cf2007-08-31 21:49:13 +00006360 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
6361 // GCC extension, diagnose them.
Eli Friedman988a16b2009-02-27 06:44:11 +00006362 // FIXME: This diagnostic isn't actually visible because the location is in
6363 // a system header!
Chris Lattner78502cf2007-08-31 21:49:13 +00006364 if (NumComponents != 1)
Chris Lattnerf490e152008-11-19 05:27:50 +00006365 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
6366 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006367
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006368 if (!Dependent) {
Eli Friedman8469bc72009-05-03 21:22:18 +00006369 bool DidWarnAboutNonPOD = false;
Mike Stump11289f42009-09-09 15:08:12 +00006370
John McCall9eff4e62009-11-04 03:03:43 +00006371 if (RequireCompleteType(TypeLoc, Res->getType(),
6372 diag::err_offsetof_incomplete_type))
6373 return ExprError();
6374
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006375 // FIXME: Dependent case loses a lot of information here. And probably
6376 // leaks like a sieve.
6377 for (unsigned i = 0; i != NumComponents; ++i) {
6378 const OffsetOfComponent &OC = CompPtr[i];
6379 if (OC.isBrackets) {
6380 // Offset of an array sub-field. TODO: Should we allow vector elements?
6381 const ArrayType *AT = Context.getAsArrayType(Res->getType());
6382 if (!AT) {
6383 Res->Destroy(Context);
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006384 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
6385 << Res->getType());
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006386 }
6387
6388 // FIXME: C++: Verify that operator[] isn't overloaded.
6389
Eli Friedman988a16b2009-02-27 06:44:11 +00006390 // Promote the array so it looks more like a normal array subscript
6391 // expression.
6392 DefaultFunctionArrayConversion(Res);
6393
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006394 // C99 6.5.2.1p1
6395 Expr *Idx = static_cast<Expr*>(OC.U.E);
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006396 // FIXME: Leaks Res
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006397 if (!Idx->isTypeDependent() && !Idx->getType()->isIntegerType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006398 return ExprError(Diag(Idx->getLocStart(),
Chris Lattner003af242009-04-25 22:50:55 +00006399 diag::err_typecheck_subscript_not_integer)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006400 << Idx->getSourceRange());
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006401
6402 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
6403 OC.LocEnd);
6404 continue;
Chris Lattnerf17bd422007-08-30 17:45:32 +00006405 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006406
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006407 const RecordType *RC = Res->getType()->getAs<RecordType>();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006408 if (!RC) {
6409 Res->Destroy(Context);
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006410 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
6411 << Res->getType());
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006412 }
Chris Lattner98dbf0a2007-08-30 17:59:59 +00006413
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006414 // Get the decl corresponding to this.
6415 RecordDecl *RD = RC->getDecl();
Anders Carlsson2bbb86b2009-05-01 23:20:30 +00006416 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
Anders Carlsson38ebcaa2009-05-02 18:36:10 +00006417 if (!CRD->isPOD() && !DidWarnAboutNonPOD) {
Anders Carlsson8b98d022009-05-02 17:45:47 +00006418 ExprError(Diag(BuiltinLoc, diag::warn_offsetof_non_pod_type)
6419 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
6420 << Res->getType());
Anders Carlsson38ebcaa2009-05-02 18:36:10 +00006421 DidWarnAboutNonPOD = true;
6422 }
Anders Carlsson2bbb86b2009-05-01 23:20:30 +00006423 }
Mike Stump11289f42009-09-09 15:08:12 +00006424
John McCall27b18f82009-11-17 02:14:36 +00006425 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
6426 LookupQualifiedName(R, RD);
John McCall9f3059a2009-10-09 21:13:30 +00006427
John McCall67c00872009-12-02 08:25:40 +00006428 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006429 // FIXME: Leaks Res
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006430 if (!MemberDecl)
Douglas Gregore40876a2009-10-13 21:16:44 +00006431 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
6432 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, OC.LocEnd));
Mike Stump4e1f26a2009-02-19 03:04:26 +00006433
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006434 // FIXME: C++: Verify that MemberDecl isn't a static field.
6435 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman64fc3c62009-04-26 20:50:44 +00006436 if (cast<RecordDecl>(MemberDecl->getDeclContext())->isAnonymousStructOrUnion()) {
Anders Carlsson3cbc8592009-05-01 19:30:39 +00006437 Res = BuildAnonymousStructUnionMemberReference(
John McCall7e1d6d72009-11-11 03:23:23 +00006438 OC.LocEnd, MemberDecl, Res, OC.LocEnd).takeAs<Expr>();
Eli Friedman64fc3c62009-04-26 20:50:44 +00006439 } else {
Eli Friedman78cde142009-12-04 07:18:51 +00006440 PerformObjectMemberConversion(Res, MemberDecl);
Eli Friedman64fc3c62009-04-26 20:50:44 +00006441 // MemberDecl->getType() doesn't get the right qualifiers, but it
6442 // doesn't matter here.
6443 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
6444 MemberDecl->getType().getNonReferenceType());
6445 }
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006446 }
Chris Lattnerf17bd422007-08-30 17:45:32 +00006447 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006448
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006449 return Owned(new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
6450 Context.getSizeType(), BuiltinLoc));
Chris Lattnerf17bd422007-08-30 17:45:32 +00006451}
6452
6453
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006454Sema::OwningExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
6455 TypeTy *arg1,TypeTy *arg2,
6456 SourceLocation RPLoc) {
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00006457 // FIXME: Preserve type source info.
6458 QualType argT1 = GetTypeFromParser(arg1);
6459 QualType argT2 = GetTypeFromParser(arg2);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006460
Steve Naroff78864672007-08-01 22:05:33 +00006461 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
Mike Stump4e1f26a2009-02-19 03:04:26 +00006462
Douglas Gregorf907cbf2009-05-19 22:28:02 +00006463 if (getLangOptions().CPlusPlus) {
6464 Diag(BuiltinLoc, diag::err_types_compatible_p_in_cplusplus)
6465 << SourceRange(BuiltinLoc, RPLoc);
6466 return ExprError();
6467 }
6468
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006469 return Owned(new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc,
6470 argT1, argT2, RPLoc));
Steve Naroff78864672007-08-01 22:05:33 +00006471}
6472
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006473Sema::OwningExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
6474 ExprArg cond,
6475 ExprArg expr1, ExprArg expr2,
6476 SourceLocation RPLoc) {
6477 Expr *CondExpr = static_cast<Expr*>(cond.get());
6478 Expr *LHSExpr = static_cast<Expr*>(expr1.get());
6479 Expr *RHSExpr = static_cast<Expr*>(expr2.get());
Mike Stump4e1f26a2009-02-19 03:04:26 +00006480
Steve Naroff9efdabc2007-08-03 21:21:27 +00006481 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
6482
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006483 QualType resType;
Douglas Gregor56751b52009-09-25 04:25:58 +00006484 bool ValueDependent = false;
Douglas Gregor0df91122009-05-19 22:43:30 +00006485 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006486 resType = Context.DependentTy;
Douglas Gregor56751b52009-09-25 04:25:58 +00006487 ValueDependent = true;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006488 } else {
6489 // The conditional expression is required to be a constant expression.
6490 llvm::APSInt condEval(32);
6491 SourceLocation ExpLoc;
6492 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006493 return ExprError(Diag(ExpLoc,
6494 diag::err_typecheck_choose_expr_requires_constant)
6495 << CondExpr->getSourceRange());
Steve Naroff9efdabc2007-08-03 21:21:27 +00006496
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006497 // If the condition is > zero, then the AST type is the same as the LSHExpr.
6498 resType = condEval.getZExtValue() ? LHSExpr->getType() : RHSExpr->getType();
Douglas Gregor56751b52009-09-25 04:25:58 +00006499 ValueDependent = condEval.getZExtValue() ? LHSExpr->isValueDependent()
6500 : RHSExpr->isValueDependent();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006501 }
6502
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006503 cond.release(); expr1.release(); expr2.release();
6504 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
Douglas Gregor56751b52009-09-25 04:25:58 +00006505 resType, RPLoc,
6506 resType->isDependentType(),
6507 ValueDependent));
Steve Naroff9efdabc2007-08-03 21:21:27 +00006508}
6509
Steve Naroffc540d662008-09-03 18:15:37 +00006510//===----------------------------------------------------------------------===//
6511// Clang Extensions.
6512//===----------------------------------------------------------------------===//
6513
6514/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff1d95e5a2008-10-10 01:28:17 +00006515void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroffc540d662008-09-03 18:15:37 +00006516 // Analyze block parameters.
6517 BlockSemaInfo *BSI = new BlockSemaInfo();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006518
Steve Naroffc540d662008-09-03 18:15:37 +00006519 // Add BSI to CurBlock.
6520 BSI->PrevBlockInfo = CurBlock;
6521 CurBlock = BSI;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006522
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00006523 BSI->ReturnType = QualType();
Steve Naroffc540d662008-09-03 18:15:37 +00006524 BSI->TheScope = BlockScope;
Mike Stumpa6703322009-02-19 22:01:56 +00006525 BSI->hasBlockDeclRefExprs = false;
Daniel Dunbarb9a68612009-07-29 01:59:17 +00006526 BSI->hasPrototype = false;
Chris Lattner45542ea2009-04-19 05:28:12 +00006527 BSI->SavedFunctionNeedsScopeChecking = CurFunctionNeedsScopeChecking;
6528 CurFunctionNeedsScopeChecking = false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006529
Steve Naroff1d95e5a2008-10-10 01:28:17 +00006530 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Ted Kremenek54ad1ab2009-12-07 22:01:30 +00006531 CurContext->addDecl(BSI->TheDecl);
Douglas Gregor91f84212008-12-11 16:49:14 +00006532 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff1d95e5a2008-10-10 01:28:17 +00006533}
6534
Mike Stump82f071f2009-02-04 22:31:32 +00006535void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpf70bcf72009-05-07 18:43:07 +00006536 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
Mike Stump82f071f2009-02-04 22:31:32 +00006537
6538 if (ParamInfo.getNumTypeObjects() == 0
6539 || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) {
Douglas Gregor758a8692009-06-17 21:51:59 +00006540 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
Mike Stump82f071f2009-02-04 22:31:32 +00006541 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
6542
Mike Stumpd456c482009-04-28 01:10:27 +00006543 if (T->isArrayType()) {
6544 Diag(ParamInfo.getSourceRange().getBegin(),
6545 diag::err_block_returns_array);
6546 return;
6547 }
6548
Mike Stump82f071f2009-02-04 22:31:32 +00006549 // The parameter list is optional, if there was none, assume ().
6550 if (!T->isFunctionType())
6551 T = Context.getFunctionType(T, NULL, 0, 0, 0);
6552
6553 CurBlock->hasPrototype = true;
6554 CurBlock->isVariadic = false;
Fariborz Jahanian6607b212009-05-14 20:53:39 +00006555 // Check for a valid sentinel attribute on this block.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00006556 if (CurBlock->TheDecl->getAttr<SentinelAttr>()) {
Mike Stump11289f42009-09-09 15:08:12 +00006557 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian6802ed92009-05-15 21:18:04 +00006558 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian6607b212009-05-14 20:53:39 +00006559 // FIXME: remove the attribute.
6560 }
John McCall9dd450b2009-09-21 23:43:11 +00006561 QualType RetTy = T.getTypePtr()->getAs<FunctionType>()->getResultType();
Mike Stump11289f42009-09-09 15:08:12 +00006562
Chris Lattner6de05082009-04-11 19:27:54 +00006563 // Do not allow returning a objc interface by-value.
6564 if (RetTy->isObjCInterfaceType()) {
6565 Diag(ParamInfo.getSourceRange().getBegin(),
6566 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
6567 return;
6568 }
Mike Stump82f071f2009-02-04 22:31:32 +00006569 return;
6570 }
6571
Steve Naroffc540d662008-09-03 18:15:37 +00006572 // Analyze arguments to block.
6573 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
6574 "Not a function declarator!");
6575 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006576
Steve Naroff1d95e5a2008-10-10 01:28:17 +00006577 CurBlock->hasPrototype = FTI.hasPrototype;
6578 CurBlock->isVariadic = true;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006579
Steve Naroffc540d662008-09-03 18:15:37 +00006580 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
6581 // no arguments, not a function that takes a single void argument.
6582 if (FTI.hasPrototype &&
6583 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
Chris Lattner83f095c2009-03-28 19:18:32 +00006584 (!FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType().getCVRQualifiers()&&
6585 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType())) {
Steve Naroffc540d662008-09-03 18:15:37 +00006586 // empty arg list, don't push any params.
Steve Naroff1d95e5a2008-10-10 01:28:17 +00006587 CurBlock->isVariadic = false;
Steve Naroffc540d662008-09-03 18:15:37 +00006588 } else if (FTI.hasPrototype) {
6589 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Chris Lattner83f095c2009-03-28 19:18:32 +00006590 CurBlock->Params.push_back(FTI.ArgInfo[i].Param.getAs<ParmVarDecl>());
Steve Naroff1d95e5a2008-10-10 01:28:17 +00006591 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroffc540d662008-09-03 18:15:37 +00006592 }
Jay Foad7d0479f2009-05-21 09:52:38 +00006593 CurBlock->TheDecl->setParams(Context, CurBlock->Params.data(),
Chris Lattner6de05082009-04-11 19:27:54 +00006594 CurBlock->Params.size());
Fariborz Jahanian960910a2009-05-19 17:08:59 +00006595 CurBlock->TheDecl->setIsVariadic(CurBlock->isVariadic);
Douglas Gregor758a8692009-06-17 21:51:59 +00006596 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
Steve Naroff1d95e5a2008-10-10 01:28:17 +00006597 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
6598 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
6599 // If this has an identifier, add it to the scope stack.
6600 if ((*AI)->getIdentifier())
6601 PushOnScopeChains(*AI, CurBlock->TheScope);
Chris Lattner6de05082009-04-11 19:27:54 +00006602
Fariborz Jahanian6607b212009-05-14 20:53:39 +00006603 // Check for a valid sentinel attribute on this block.
Mike Stump11289f42009-09-09 15:08:12 +00006604 if (!CurBlock->isVariadic &&
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00006605 CurBlock->TheDecl->getAttr<SentinelAttr>()) {
Mike Stump11289f42009-09-09 15:08:12 +00006606 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian6802ed92009-05-15 21:18:04 +00006607 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian6607b212009-05-14 20:53:39 +00006608 // FIXME: remove the attribute.
6609 }
Mike Stump11289f42009-09-09 15:08:12 +00006610
Chris Lattner6de05082009-04-11 19:27:54 +00006611 // Analyze the return type.
6612 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
John McCall9dd450b2009-09-21 23:43:11 +00006613 QualType RetTy = T->getAs<FunctionType>()->getResultType();
Mike Stump11289f42009-09-09 15:08:12 +00006614
Chris Lattner6de05082009-04-11 19:27:54 +00006615 // Do not allow returning a objc interface by-value.
6616 if (RetTy->isObjCInterfaceType()) {
6617 Diag(ParamInfo.getSourceRange().getBegin(),
6618 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
6619 } else if (!RetTy->isDependentType())
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00006620 CurBlock->ReturnType = RetTy;
Steve Naroffc540d662008-09-03 18:15:37 +00006621}
6622
6623/// ActOnBlockError - If there is an error parsing a block, this callback
6624/// is invoked to pop the information about the block from the action impl.
6625void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
6626 // Ensure that CurBlock is deleted.
6627 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006628
Chris Lattner45542ea2009-04-19 05:28:12 +00006629 CurFunctionNeedsScopeChecking = CurBlock->SavedFunctionNeedsScopeChecking;
6630
Steve Naroffc540d662008-09-03 18:15:37 +00006631 // Pop off CurBlock, handle nested blocks.
Chris Lattner41b86942009-04-21 22:38:46 +00006632 PopDeclContext();
Steve Naroffc540d662008-09-03 18:15:37 +00006633 CurBlock = CurBlock->PrevBlockInfo;
Steve Naroffc540d662008-09-03 18:15:37 +00006634 // FIXME: Delete the ParmVarDecl objects as well???
Steve Naroffc540d662008-09-03 18:15:37 +00006635}
6636
6637/// ActOnBlockStmtExpr - This is called when the body of a block statement
6638/// literal was successfully completed. ^(int x){...}
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006639Sema::OwningExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
6640 StmtArg body, Scope *CurScope) {
Chris Lattner9eac9312009-03-27 04:18:06 +00006641 // If blocks are disabled, emit an error.
6642 if (!LangOpts.Blocks)
6643 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump11289f42009-09-09 15:08:12 +00006644
Steve Naroffc540d662008-09-03 18:15:37 +00006645 // Ensure that CurBlock is deleted.
6646 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
Steve Naroffc540d662008-09-03 18:15:37 +00006647
Steve Naroff1d95e5a2008-10-10 01:28:17 +00006648 PopDeclContext();
6649
Steve Naroffc540d662008-09-03 18:15:37 +00006650 // Pop off CurBlock, handle nested blocks.
6651 CurBlock = CurBlock->PrevBlockInfo;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006652
Steve Naroffc540d662008-09-03 18:15:37 +00006653 QualType RetTy = Context.VoidTy;
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00006654 if (!BSI->ReturnType.isNull())
6655 RetTy = BSI->ReturnType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006656
Steve Naroffc540d662008-09-03 18:15:37 +00006657 llvm::SmallVector<QualType, 8> ArgTypes;
6658 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
6659 ArgTypes.push_back(BSI->Params[i]->getType());
Mike Stump4e1f26a2009-02-19 03:04:26 +00006660
Mike Stump3bf1ab42009-07-28 22:04:01 +00006661 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroffc540d662008-09-03 18:15:37 +00006662 QualType BlockTy;
6663 if (!BSI->hasPrototype)
Mike Stump3bf1ab42009-07-28 22:04:01 +00006664 BlockTy = Context.getFunctionType(RetTy, 0, 0, false, 0, false, false, 0, 0,
6665 NoReturn);
Steve Naroffc540d662008-09-03 18:15:37 +00006666 else
Jay Foad7d0479f2009-05-21 09:52:38 +00006667 BlockTy = Context.getFunctionType(RetTy, ArgTypes.data(), ArgTypes.size(),
Mike Stump3bf1ab42009-07-28 22:04:01 +00006668 BSI->isVariadic, 0, false, false, 0, 0,
6669 NoReturn);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006670
Eli Friedmanba961a92009-03-23 00:24:07 +00006671 // FIXME: Check that return/parameter types are complete/non-abstract
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006672 DiagnoseUnusedParameters(BSI->Params.begin(), BSI->Params.end());
Steve Naroffc540d662008-09-03 18:15:37 +00006673 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006674
Chris Lattner45542ea2009-04-19 05:28:12 +00006675 // If needed, diagnose invalid gotos and switches in the block.
6676 if (CurFunctionNeedsScopeChecking)
6677 DiagnoseInvalidJumps(static_cast<CompoundStmt*>(body.get()));
6678 CurFunctionNeedsScopeChecking = BSI->SavedFunctionNeedsScopeChecking;
Mike Stump11289f42009-09-09 15:08:12 +00006679
Anders Carlssonb781bcd2009-05-01 19:49:17 +00006680 BSI->TheDecl->setBody(body.takeAs<CompoundStmt>());
Mike Stump3bf1ab42009-07-28 22:04:01 +00006681 CheckFallThroughForBlock(BlockTy, BSI->TheDecl->getBody());
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006682 return Owned(new (Context) BlockExpr(BSI->TheDecl, BlockTy,
6683 BSI->hasBlockDeclRefExprs));
Steve Naroffc540d662008-09-03 18:15:37 +00006684}
6685
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006686Sema::OwningExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
6687 ExprArg expr, TypeTy *type,
6688 SourceLocation RPLoc) {
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00006689 QualType T = GetTypeFromParser(type);
Chris Lattner56382aa2009-04-05 15:49:53 +00006690 Expr *E = static_cast<Expr*>(expr.get());
6691 Expr *OrigExpr = E;
Mike Stump11289f42009-09-09 15:08:12 +00006692
Anders Carlsson7e13ab82007-10-15 20:28:48 +00006693 InitBuiltinVaListType();
Eli Friedman121ba0c2008-08-09 23:32:40 +00006694
6695 // Get the va_list type
6696 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedmane2cad652009-05-16 12:46:54 +00006697 if (VaListType->isArrayType()) {
6698 // Deal with implicit array decay; for example, on x86-64,
6699 // va_list is an array, but it's supposed to decay to
6700 // a pointer for va_arg.
Eli Friedman121ba0c2008-08-09 23:32:40 +00006701 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedmane2cad652009-05-16 12:46:54 +00006702 // Make sure the input expression also decays appropriately.
6703 UsualUnaryConversions(E);
6704 } else {
6705 // Otherwise, the va_list argument must be an l-value because
6706 // it is modified by va_arg.
Mike Stump11289f42009-09-09 15:08:12 +00006707 if (!E->isTypeDependent() &&
Douglas Gregorad3150c2009-05-19 23:10:31 +00006708 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedmane2cad652009-05-16 12:46:54 +00006709 return ExprError();
6710 }
Eli Friedman121ba0c2008-08-09 23:32:40 +00006711
Douglas Gregorad3150c2009-05-19 23:10:31 +00006712 if (!E->isTypeDependent() &&
6713 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006714 return ExprError(Diag(E->getLocStart(),
6715 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner56382aa2009-04-05 15:49:53 +00006716 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner3f5cd772009-04-05 00:59:53 +00006717 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006718
Eli Friedmanba961a92009-03-23 00:24:07 +00006719 // FIXME: Check that type is complete/non-abstract
Anders Carlsson7e13ab82007-10-15 20:28:48 +00006720 // FIXME: Warn if a non-POD type is passed in.
Mike Stump4e1f26a2009-02-19 03:04:26 +00006721
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006722 expr.release();
6723 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(),
6724 RPLoc));
Anders Carlsson7e13ab82007-10-15 20:28:48 +00006725}
6726
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006727Sema::OwningExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor3be4b122008-11-29 04:51:27 +00006728 // The type of __null will be int or long, depending on the size of
6729 // pointers on the target.
6730 QualType Ty;
6731 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
6732 Ty = Context.IntTy;
6733 else
6734 Ty = Context.LongTy;
6735
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006736 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor3be4b122008-11-29 04:51:27 +00006737}
6738
Anders Carlssonace5d072009-11-10 04:46:30 +00006739static void
6740MakeObjCStringLiteralCodeModificationHint(Sema& SemaRef,
6741 QualType DstType,
6742 Expr *SrcExpr,
6743 CodeModificationHint &Hint) {
6744 if (!SemaRef.getLangOptions().ObjC1)
6745 return;
6746
6747 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
6748 if (!PT)
6749 return;
6750
6751 // Check if the destination is of type 'id'.
6752 if (!PT->isObjCIdType()) {
6753 // Check if the destination is the 'NSString' interface.
6754 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
6755 if (!ID || !ID->getIdentifier()->isStr("NSString"))
6756 return;
6757 }
6758
6759 // Strip off any parens and casts.
6760 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
6761 if (!SL || SL->isWide())
6762 return;
6763
6764 Hint = CodeModificationHint::CreateInsertion(SL->getLocStart(), "@");
6765}
6766
Chris Lattner9bad62c2008-01-04 18:04:52 +00006767bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
6768 SourceLocation Loc,
6769 QualType DstType, QualType SrcType,
6770 Expr *SrcExpr, const char *Flavor) {
6771 // Decode the result (notice that AST's are still created for extensions).
6772 bool isInvalid = false;
6773 unsigned DiagKind;
Anders Carlssonace5d072009-11-10 04:46:30 +00006774 CodeModificationHint Hint;
6775
Chris Lattner9bad62c2008-01-04 18:04:52 +00006776 switch (ConvTy) {
6777 default: assert(0 && "Unknown conversion type");
6778 case Compatible: return false;
Chris Lattner940cfeb2008-01-04 18:22:42 +00006779 case PointerToInt:
Chris Lattner9bad62c2008-01-04 18:04:52 +00006780 DiagKind = diag::ext_typecheck_convert_pointer_int;
6781 break;
Chris Lattner940cfeb2008-01-04 18:22:42 +00006782 case IntToPointer:
6783 DiagKind = diag::ext_typecheck_convert_int_pointer;
6784 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00006785 case IncompatiblePointer:
Anders Carlssonace5d072009-11-10 04:46:30 +00006786 MakeObjCStringLiteralCodeModificationHint(*this, DstType, SrcExpr, Hint);
Chris Lattner9bad62c2008-01-04 18:04:52 +00006787 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
6788 break;
Eli Friedman80160bd2009-03-22 23:59:44 +00006789 case IncompatiblePointerSign:
6790 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
6791 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00006792 case FunctionVoidPointer:
6793 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
6794 break;
6795 case CompatiblePointerDiscardsQualifiers:
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00006796 // If the qualifiers lost were because we were applying the
6797 // (deprecated) C++ conversion from a string literal to a char*
6798 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
6799 // Ideally, this check would be performed in
6800 // CheckPointerTypesForAssignment. However, that would require a
6801 // bit of refactoring (so that the second argument is an
6802 // expression, rather than a type), which should be done as part
6803 // of a larger effort to fix CheckPointerTypesForAssignment for
6804 // C++ semantics.
6805 if (getLangOptions().CPlusPlus &&
6806 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
6807 return false;
Chris Lattner9bad62c2008-01-04 18:04:52 +00006808 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
6809 break;
Alexis Hunt6f3de502009-11-08 07:46:34 +00006810 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanianb98dade2009-11-09 22:16:37 +00006811 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00006812 break;
Steve Naroff081c7422008-09-04 15:10:53 +00006813 case IntToBlockPointer:
6814 DiagKind = diag::err_int_to_block_pointer;
6815 break;
6816 case IncompatibleBlockPointer:
Mike Stumpd79b5a82009-04-21 22:51:42 +00006817 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff081c7422008-09-04 15:10:53 +00006818 break;
Steve Naroff8afa9892008-10-14 22:18:38 +00006819 case IncompatibleObjCQualifiedId:
Mike Stump4e1f26a2009-02-19 03:04:26 +00006820 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff8afa9892008-10-14 22:18:38 +00006821 // it can give a more specific diagnostic.
6822 DiagKind = diag::warn_incompatible_qualified_id;
6823 break;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00006824 case IncompatibleVectors:
6825 DiagKind = diag::warn_incompatible_vectors;
6826 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00006827 case Incompatible:
6828 DiagKind = diag::err_typecheck_convert_incompatible;
6829 isInvalid = true;
6830 break;
6831 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006832
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00006833 Diag(Loc, DiagKind) << DstType << SrcType << Flavor
Anders Carlssonace5d072009-11-10 04:46:30 +00006834 << SrcExpr->getSourceRange() << Hint;
Chris Lattner9bad62c2008-01-04 18:04:52 +00006835 return isInvalid;
6836}
Anders Carlssone54e8a12008-11-30 19:50:32 +00006837
Chris Lattnerc71d08b2009-04-25 21:59:05 +00006838bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedmanbb967cc2009-04-25 22:26:58 +00006839 llvm::APSInt ICEResult;
6840 if (E->isIntegerConstantExpr(ICEResult, Context)) {
6841 if (Result)
6842 *Result = ICEResult;
6843 return false;
6844 }
6845
Anders Carlssone54e8a12008-11-30 19:50:32 +00006846 Expr::EvalResult EvalResult;
6847
Mike Stump4e1f26a2009-02-19 03:04:26 +00006848 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone54e8a12008-11-30 19:50:32 +00006849 EvalResult.HasSideEffects) {
6850 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
6851
6852 if (EvalResult.Diag) {
6853 // We only show the note if it's not the usual "invalid subexpression"
6854 // or if it's actually in a subexpression.
6855 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
6856 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
6857 Diag(EvalResult.DiagLoc, EvalResult.Diag);
6858 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006859
Anders Carlssone54e8a12008-11-30 19:50:32 +00006860 return true;
6861 }
6862
Eli Friedmanbb967cc2009-04-25 22:26:58 +00006863 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
6864 E->getSourceRange();
Anders Carlssone54e8a12008-11-30 19:50:32 +00006865
Eli Friedmanbb967cc2009-04-25 22:26:58 +00006866 if (EvalResult.Diag &&
6867 Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
6868 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006869
Anders Carlssone54e8a12008-11-30 19:50:32 +00006870 if (Result)
6871 *Result = EvalResult.Val.getInt();
6872 return false;
6873}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006874
Douglas Gregorff790f12009-11-26 00:44:06 +00006875void
Mike Stump11289f42009-09-09 15:08:12 +00006876Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregorff790f12009-11-26 00:44:06 +00006877 ExprEvalContexts.push_back(
6878 ExpressionEvaluationContextRecord(NewContext, ExprTemporaries.size()));
Douglas Gregor0b6a6242009-06-22 20:57:11 +00006879}
6880
Mike Stump11289f42009-09-09 15:08:12 +00006881void
Douglas Gregorff790f12009-11-26 00:44:06 +00006882Sema::PopExpressionEvaluationContext() {
6883 // Pop the current expression evaluation context off the stack.
6884 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
6885 ExprEvalContexts.pop_back();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00006886
Douglas Gregorff790f12009-11-26 00:44:06 +00006887 if (Rec.Context == PotentiallyPotentiallyEvaluated &&
6888 Rec.PotentiallyReferenced) {
Douglas Gregor0b6a6242009-06-22 20:57:11 +00006889 // Mark any remaining declarations in the current position of the stack
6890 // as "referenced". If they were not meant to be referenced, semantic
6891 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
Douglas Gregorff790f12009-11-26 00:44:06 +00006892 for (PotentiallyReferencedDecls::iterator
6893 I = Rec.PotentiallyReferenced->begin(),
6894 IEnd = Rec.PotentiallyReferenced->end();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00006895 I != IEnd; ++I)
6896 MarkDeclarationReferenced(I->first, I->second);
Douglas Gregorff790f12009-11-26 00:44:06 +00006897 }
6898
6899 // When are coming out of an unevaluated context, clear out any
6900 // temporaries that we may have created as part of the evaluation of
6901 // the expression in that context: they aren't relevant because they
6902 // will never be constructed.
6903 if (Rec.Context == Unevaluated &&
6904 ExprTemporaries.size() > Rec.NumTemporaries)
6905 ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
6906 ExprTemporaries.end());
6907
6908 // Destroy the popped expression evaluation record.
6909 Rec.Destroy();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00006910}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006911
6912/// \brief Note that the given declaration was referenced in the source code.
6913///
6914/// This routine should be invoke whenever a given declaration is referenced
6915/// in the source code, and where that reference occurred. If this declaration
6916/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
6917/// C99 6.9p3), then the declaration will be marked as used.
6918///
6919/// \param Loc the location where the declaration was referenced.
6920///
6921/// \param D the declaration that has been referenced by the source code.
6922void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
6923 assert(D && "No declaration?");
Mike Stump11289f42009-09-09 15:08:12 +00006924
Douglas Gregor77b50e12009-06-22 23:06:13 +00006925 if (D->isUsed())
6926 return;
Mike Stump11289f42009-09-09 15:08:12 +00006927
Douglas Gregor3beaf9b2009-10-08 21:35:42 +00006928 // Mark a parameter or variable declaration "used", regardless of whether we're in a
6929 // template or not. The reason for this is that unevaluated expressions
6930 // (e.g. (void)sizeof()) constitute a use for warning purposes (-Wunused-variables and
6931 // -Wunused-parameters)
6932 if (isa<ParmVarDecl>(D) ||
6933 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod()))
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006934 D->setUsed(true);
Mike Stump11289f42009-09-09 15:08:12 +00006935
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006936 // Do not mark anything as "used" within a dependent context; wait for
6937 // an instantiation.
6938 if (CurContext->isDependentContext())
6939 return;
Mike Stump11289f42009-09-09 15:08:12 +00006940
Douglas Gregorff790f12009-11-26 00:44:06 +00006941 switch (ExprEvalContexts.back().Context) {
Douglas Gregor0b6a6242009-06-22 20:57:11 +00006942 case Unevaluated:
6943 // We are in an expression that is not potentially evaluated; do nothing.
6944 return;
Mike Stump11289f42009-09-09 15:08:12 +00006945
Douglas Gregor0b6a6242009-06-22 20:57:11 +00006946 case PotentiallyEvaluated:
6947 // We are in a potentially-evaluated expression, so this declaration is
6948 // "used"; handle this below.
6949 break;
Mike Stump11289f42009-09-09 15:08:12 +00006950
Douglas Gregor0b6a6242009-06-22 20:57:11 +00006951 case PotentiallyPotentiallyEvaluated:
6952 // We are in an expression that may be potentially evaluated; queue this
6953 // declaration reference until we know whether the expression is
6954 // potentially evaluated.
Douglas Gregorff790f12009-11-26 00:44:06 +00006955 ExprEvalContexts.back().addReferencedDecl(Loc, D);
Douglas Gregor0b6a6242009-06-22 20:57:11 +00006956 return;
6957 }
Mike Stump11289f42009-09-09 15:08:12 +00006958
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006959 // Note that this declaration has been used.
Fariborz Jahanian3a363432009-06-22 17:30:33 +00006960 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Fariborz Jahanian477d2422009-06-22 23:34:40 +00006961 unsigned TypeQuals;
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00006962 if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) {
6963 if (!Constructor->isUsed())
6964 DefineImplicitDefaultConstructor(Loc, Constructor);
Mike Stump11289f42009-09-09 15:08:12 +00006965 } else if (Constructor->isImplicit() &&
Mike Stump12b8ce12009-08-04 21:02:39 +00006966 Constructor->isCopyConstructor(Context, TypeQuals)) {
Fariborz Jahanian477d2422009-06-22 23:34:40 +00006967 if (!Constructor->isUsed())
6968 DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals);
6969 }
Anders Carlsson82fccd02009-12-07 08:24:59 +00006970
6971 MaybeMarkVirtualMembersReferenced(Loc, Constructor);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00006972 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
6973 if (Destructor->isImplicit() && !Destructor->isUsed())
6974 DefineImplicitDestructor(Loc, Destructor);
Mike Stump11289f42009-09-09 15:08:12 +00006975
Fariborz Jahanian41f79272009-06-25 21:45:19 +00006976 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
6977 if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
6978 MethodDecl->getOverloadedOperator() == OO_Equal) {
6979 if (!MethodDecl->isUsed())
6980 DefineImplicitOverloadedAssign(Loc, MethodDecl);
6981 }
6982 }
Fariborz Jahanian49796cc72009-06-24 22:09:44 +00006983 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Mike Stump11289f42009-09-09 15:08:12 +00006984 // Implicit instantiation of function templates and member functions of
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00006985 // class templates.
Douglas Gregorafca3b42009-10-27 20:53:28 +00006986 if (!Function->getBody() && Function->isImplicitlyInstantiable()) {
Douglas Gregor06db9f52009-10-12 20:18:28 +00006987 bool AlreadyInstantiated = false;
6988 if (FunctionTemplateSpecializationInfo *SpecInfo
6989 = Function->getTemplateSpecializationInfo()) {
6990 if (SpecInfo->getPointOfInstantiation().isInvalid())
6991 SpecInfo->setPointOfInstantiation(Loc);
Douglas Gregorafca3b42009-10-27 20:53:28 +00006992 else if (SpecInfo->getTemplateSpecializationKind()
6993 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +00006994 AlreadyInstantiated = true;
6995 } else if (MemberSpecializationInfo *MSInfo
6996 = Function->getMemberSpecializationInfo()) {
6997 if (MSInfo->getPointOfInstantiation().isInvalid())
6998 MSInfo->setPointOfInstantiation(Loc);
Douglas Gregorafca3b42009-10-27 20:53:28 +00006999 else if (MSInfo->getTemplateSpecializationKind()
7000 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +00007001 AlreadyInstantiated = true;
7002 }
7003
7004 if (!AlreadyInstantiated)
7005 PendingImplicitInstantiations.push_back(std::make_pair(Function, Loc));
7006 }
7007
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007008 // FIXME: keep track of references to static functions
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007009 Function->setUsed(true);
7010 return;
Douglas Gregor77b50e12009-06-22 23:06:13 +00007011 }
Mike Stump11289f42009-09-09 15:08:12 +00007012
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007013 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00007014 // Implicit instantiation of static data members of class templates.
Mike Stump11289f42009-09-09 15:08:12 +00007015 if (Var->isStaticDataMember() &&
Douglas Gregor06db9f52009-10-12 20:18:28 +00007016 Var->getInstantiatedFromStaticDataMember()) {
7017 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
7018 assert(MSInfo && "Missing member specialization information?");
7019 if (MSInfo->getPointOfInstantiation().isInvalid() &&
7020 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
7021 MSInfo->setPointOfInstantiation(Loc);
7022 PendingImplicitInstantiations.push_back(std::make_pair(Var, Loc));
7023 }
7024 }
Mike Stump11289f42009-09-09 15:08:12 +00007025
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007026 // FIXME: keep track of references to static data?
Douglas Gregora6ef8f02009-07-24 20:34:43 +00007027
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007028 D->setUsed(true);
Douglas Gregora6ef8f02009-07-24 20:34:43 +00007029 return;
Sam Weinigbae69142009-09-11 03:29:30 +00007030 }
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007031}
Anders Carlsson7f84ed92009-10-09 23:51:55 +00007032
7033bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
7034 CallExpr *CE, FunctionDecl *FD) {
7035 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
7036 return false;
7037
7038 PartialDiagnostic Note =
7039 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
7040 << FD->getDeclName() : PDiag();
7041 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
7042
7043 if (RequireCompleteType(Loc, ReturnType,
7044 FD ?
7045 PDiag(diag::err_call_function_incomplete_return)
7046 << CE->getSourceRange() << FD->getDeclName() :
7047 PDiag(diag::err_call_incomplete_return)
7048 << CE->getSourceRange(),
7049 std::make_pair(NoteLoc, Note)))
7050 return true;
7051
7052 return false;
7053}
7054
John McCalld5707ab2009-10-12 21:59:07 +00007055// Diagnose the common s/=/==/ typo. Note that adding parentheses
7056// will prevent this condition from triggering, which is what we want.
7057void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
7058 SourceLocation Loc;
7059
John McCall0506e4a2009-11-11 02:41:58 +00007060 unsigned diagnostic = diag::warn_condition_is_assignment;
7061
John McCalld5707ab2009-10-12 21:59:07 +00007062 if (isa<BinaryOperator>(E)) {
7063 BinaryOperator *Op = cast<BinaryOperator>(E);
7064 if (Op->getOpcode() != BinaryOperator::Assign)
7065 return;
7066
John McCallb0e419e2009-11-12 00:06:05 +00007067 // Greylist some idioms by putting them into a warning subcategory.
7068 if (ObjCMessageExpr *ME
7069 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
7070 Selector Sel = ME->getSelector();
7071
John McCallb0e419e2009-11-12 00:06:05 +00007072 // self = [<foo> init...]
7073 if (isSelfExpr(Op->getLHS())
7074 && Sel.getIdentifierInfoForSlot(0)->getName().startswith("init"))
7075 diagnostic = diag::warn_condition_is_idiomatic_assignment;
7076
7077 // <foo> = [<bar> nextObject]
7078 else if (Sel.isUnarySelector() &&
7079 Sel.getIdentifierInfoForSlot(0)->getName() == "nextObject")
7080 diagnostic = diag::warn_condition_is_idiomatic_assignment;
7081 }
John McCall0506e4a2009-11-11 02:41:58 +00007082
John McCalld5707ab2009-10-12 21:59:07 +00007083 Loc = Op->getOperatorLoc();
7084 } else if (isa<CXXOperatorCallExpr>(E)) {
7085 CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(E);
7086 if (Op->getOperator() != OO_Equal)
7087 return;
7088
7089 Loc = Op->getOperatorLoc();
7090 } else {
7091 // Not an assignment.
7092 return;
7093 }
7094
John McCalld5707ab2009-10-12 21:59:07 +00007095 SourceLocation Open = E->getSourceRange().getBegin();
John McCalle724ae92009-10-12 22:25:59 +00007096 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
John McCalld5707ab2009-10-12 21:59:07 +00007097
John McCall0506e4a2009-11-11 02:41:58 +00007098 Diag(Loc, diagnostic)
John McCalld5707ab2009-10-12 21:59:07 +00007099 << E->getSourceRange()
7100 << CodeModificationHint::CreateInsertion(Open, "(")
7101 << CodeModificationHint::CreateInsertion(Close, ")");
7102}
7103
7104bool Sema::CheckBooleanCondition(Expr *&E, SourceLocation Loc) {
7105 DiagnoseAssignmentAsCondition(E);
7106
7107 if (!E->isTypeDependent()) {
7108 DefaultFunctionArrayConversion(E);
7109
7110 QualType T = E->getType();
7111
7112 if (getLangOptions().CPlusPlus) {
7113 if (CheckCXXBooleanCondition(E)) // C++ 6.4p4
7114 return true;
7115 } else if (!T->isScalarType()) { // C99 6.8.4.1p1
7116 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
7117 << T << E->getSourceRange();
7118 return true;
7119 }
7120 }
7121
7122 return false;
7123}