blob: c87a274122b6e21641f5c36aff4b40fd1aa1e5a4 [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"
Douglas Gregor85dabae2009-12-16 01:38:02 +000015#include "SemaInit.h"
John McCall5cebab12009-11-18 07:57:50 +000016#include "Lookup.h"
Chris Lattnercb6a3822006-11-10 06:20:45 +000017#include "clang/AST/ASTContext.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000018#include "clang/AST/DeclObjC.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000019#include "clang/AST/DeclTemplate.h"
Chris Lattneraa9c7ae2008-04-08 04:40:51 +000020#include "clang/AST/ExprCXX.h"
Steve Naroff021ca182008-05-29 21:12:08 +000021#include "clang/AST/ExprObjC.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000022#include "clang/Basic/PartialDiagnostic.h"
Steve Narofff2fb89e2007-03-13 20:29:44 +000023#include "clang/Basic/SourceManager.h"
Chris Lattner5b183d82006-11-10 05:03:26 +000024#include "clang/Basic/TargetInfo.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000025#include "clang/Lex/LiteralSupport.h"
26#include "clang/Lex/Preprocessor.h"
Steve Naroffc540d662008-09-03 18:15:37 +000027#include "clang/Parse/DeclSpec.h"
Chris Lattner07d754a2008-10-26 23:43:26 +000028#include "clang/Parse/Designator.h"
Steve Naroffc540d662008-09-03 18:15:37 +000029#include "clang/Parse/Scope.h"
Douglas Gregorb53edfb2009-11-10 19:49:08 +000030#include "clang/Parse/Template.h"
Chris Lattner5b183d82006-11-10 05:03:26 +000031using namespace clang;
32
David Chisnall9f57c292009-08-17 16:35:33 +000033
Douglas Gregor171c45a2009-02-18 21:56:37 +000034/// \brief Determine whether the use of this declaration is valid, and
35/// emit any corresponding diagnostics.
36///
37/// This routine diagnoses various problems with referencing
38/// declarations that can occur when using a declaration. For example,
39/// it might warn if a deprecated or unavailable declaration is being
40/// used, or produce an error (and return true) if a C++0x deleted
41/// function is being used.
42///
Chris Lattnerb7df3c62009-10-25 22:31:57 +000043/// If IgnoreDeprecated is set to true, this should not want about deprecated
44/// decls.
45///
Douglas Gregor171c45a2009-02-18 21:56:37 +000046/// \returns true if there was an error (this declaration cannot be
47/// referenced), false otherwise.
Chris Lattnerb7df3c62009-10-25 22:31:57 +000048///
John McCall28a6aea2009-11-04 02:18:39 +000049bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc) {
Chris Lattner4bf74fd2009-02-15 22:43:40 +000050 // See if the decl is deprecated.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +000051 if (D->getAttr<DeprecatedAttr>()) {
John McCall28a6aea2009-11-04 02:18:39 +000052 EmitDeprecationWarning(D, Loc);
Chris Lattner4bf74fd2009-02-15 22:43:40 +000053 }
54
Chris Lattnera27dd592009-10-25 17:21:40 +000055 // See if the decl is unavailable
56 if (D->getAttr<UnavailableAttr>()) {
57 Diag(Loc, diag::warn_unavailable) << D->getDeclName();
58 Diag(D->getLocation(), diag::note_unavailable_here) << 0;
59 }
60
Douglas Gregor171c45a2009-02-18 21:56:37 +000061 // See if this is a deleted function.
Douglas Gregorde681d42009-02-24 04:26:15 +000062 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +000063 if (FD->isDeleted()) {
64 Diag(Loc, diag::err_deleted_function_use);
65 Diag(D->getLocation(), diag::note_unavailable_here) << true;
66 return true;
67 }
Douglas Gregorde681d42009-02-24 04:26:15 +000068 }
Douglas Gregor171c45a2009-02-18 21:56:37 +000069
Douglas Gregor171c45a2009-02-18 21:56:37 +000070 return false;
Chris Lattner4bf74fd2009-02-15 22:43:40 +000071}
72
Fariborz Jahanian027b8862009-05-13 18:09:35 +000073/// DiagnoseSentinelCalls - This routine checks on method dispatch calls
Mike Stump11289f42009-09-09 15:08:12 +000074/// (and other functions in future), which have been declared with sentinel
Fariborz Jahanian027b8862009-05-13 18:09:35 +000075/// attribute. It warns if call does not have the sentinel argument.
76///
77void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +000078 Expr **Args, unsigned NumArgs) {
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +000079 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Mike Stump11289f42009-09-09 15:08:12 +000080 if (!attr)
Fariborz Jahanian9e877212009-05-13 23:20:50 +000081 return;
Fariborz Jahanian9e877212009-05-13 23:20:50 +000082 int sentinelPos = attr->getSentinel();
83 int nullPos = attr->getNullPos();
Mike Stump11289f42009-09-09 15:08:12 +000084
Mike Stump87c57ac2009-05-16 07:39:55 +000085 // FIXME. ObjCMethodDecl and FunctionDecl need be derived from the same common
86 // base class. Then we won't be needing two versions of the same code.
Fariborz Jahanian9e877212009-05-13 23:20:50 +000087 unsigned int i = 0;
Fariborz Jahanian4a528032009-05-14 18:00:00 +000088 bool warnNotEnoughArgs = false;
89 int isMethod = 0;
90 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
91 // skip over named parameters.
92 ObjCMethodDecl::param_iterator P, E = MD->param_end();
93 for (P = MD->param_begin(); (P != E && i < NumArgs); ++P) {
94 if (nullPos)
95 --nullPos;
96 else
97 ++i;
98 }
99 warnNotEnoughArgs = (P != E || i >= NumArgs);
100 isMethod = 1;
Mike Stump12b8ce12009-08-04 21:02:39 +0000101 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000102 // skip over named parameters.
103 ObjCMethodDecl::param_iterator P, E = FD->param_end();
104 for (P = FD->param_begin(); (P != E && i < NumArgs); ++P) {
105 if (nullPos)
106 --nullPos;
107 else
108 ++i;
109 }
110 warnNotEnoughArgs = (P != E || i >= NumArgs);
Mike Stump12b8ce12009-08-04 21:02:39 +0000111 } else if (VarDecl *V = dyn_cast<VarDecl>(D)) {
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000112 // block or function pointer call.
113 QualType Ty = V->getType();
114 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +0000115 const FunctionType *FT = Ty->isFunctionPointerType()
John McCall9dd450b2009-09-21 23:43:11 +0000116 ? Ty->getAs<PointerType>()->getPointeeType()->getAs<FunctionType>()
117 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000118 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT)) {
119 unsigned NumArgsInProto = Proto->getNumArgs();
120 unsigned k;
121 for (k = 0; (k != NumArgsInProto && i < NumArgs); k++) {
122 if (nullPos)
123 --nullPos;
124 else
125 ++i;
126 }
127 warnNotEnoughArgs = (k != NumArgsInProto || i >= NumArgs);
128 }
129 if (Ty->isBlockPointerType())
130 isMethod = 2;
Mike Stump12b8ce12009-08-04 21:02:39 +0000131 } else
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000132 return;
Mike Stump12b8ce12009-08-04 21:02:39 +0000133 } else
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000134 return;
135
136 if (warnNotEnoughArgs) {
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000137 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000138 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000139 return;
140 }
141 int sentinel = i;
142 while (sentinelPos > 0 && i < NumArgs-1) {
143 --sentinelPos;
144 ++i;
145 }
146 if (sentinelPos > 0) {
147 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000148 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000149 return;
150 }
151 while (i < NumArgs-1) {
152 ++i;
153 ++sentinel;
154 }
155 Expr *sentinelExpr = Args[sentinel];
Anders Carlsson0b11a3e2009-11-24 17:24:21 +0000156 if (sentinelExpr && (!isa<GNUNullExpr>(sentinelExpr) &&
157 (!sentinelExpr->getType()->isPointerType() ||
158 !sentinelExpr->isNullPointerConstant(Context,
159 Expr::NPC_ValueDependentIsNull)))) {
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000160 Diag(Loc, diag::warn_missing_sentinel) << isMethod;
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000161 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000162 }
163 return;
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000164}
165
Douglas Gregor87f95b02009-02-26 21:00:50 +0000166SourceRange Sema::getExprRange(ExprTy *E) const {
167 Expr *Ex = (Expr *)E;
168 return Ex? Ex->getSourceRange() : SourceRange();
169}
170
Chris Lattner513165e2008-07-25 21:10:04 +0000171//===----------------------------------------------------------------------===//
172// Standard Promotions and Conversions
173//===----------------------------------------------------------------------===//
174
Chris Lattner513165e2008-07-25 21:10:04 +0000175/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
176void Sema::DefaultFunctionArrayConversion(Expr *&E) {
177 QualType Ty = E->getType();
178 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
179
Chris Lattner513165e2008-07-25 21:10:04 +0000180 if (Ty->isFunctionType())
Mike Stump11289f42009-09-09 15:08:12 +0000181 ImpCastExprToType(E, Context.getPointerType(Ty),
Anders Carlsson6904f642009-09-01 20:37:18 +0000182 CastExpr::CK_FunctionToPointerDecay);
Chris Lattner61f60a02008-07-25 21:33:13 +0000183 else if (Ty->isArrayType()) {
184 // In C90 mode, arrays only promote to pointers if the array expression is
185 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
186 // type 'array of type' is converted to an expression that has type 'pointer
187 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
188 // that has type 'array of type' ...". The relevant change is "an lvalue"
189 // (C90) to "an expression" (C99).
Argyrios Kyrtzidis9321c742008-09-11 04:25:59 +0000190 //
191 // C++ 4.2p1:
192 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
193 // T" can be converted to an rvalue of type "pointer to T".
194 //
195 if (getLangOptions().C99 || getLangOptions().CPlusPlus ||
196 E->isLvalue(Context) == Expr::LV_Valid)
Anders Carlsson8fc489d2009-08-07 23:48:20 +0000197 ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
198 CastExpr::CK_ArrayToPointerDecay);
Chris Lattner61f60a02008-07-25 21:33:13 +0000199 }
Chris Lattner513165e2008-07-25 21:10:04 +0000200}
201
202/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump11289f42009-09-09 15:08:12 +0000203/// operators (C99 6.3). The conversions of array and function types are
Chris Lattner513165e2008-07-25 21:10:04 +0000204/// sometimes surpressed. For example, the array->pointer conversion doesn't
205/// apply if the array is an argument to the sizeof or address (&) operators.
206/// In these instances, this routine should *not* be called.
207Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
208 QualType Ty = Expr->getType();
209 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
Mike Stump11289f42009-09-09 15:08:12 +0000210
Douglas Gregor8d9c5092009-05-01 20:41:21 +0000211 // C99 6.3.1.1p2:
212 //
213 // The following may be used in an expression wherever an int or
214 // unsigned int may be used:
215 // - an object or expression with an integer type whose integer
216 // conversion rank is less than or equal to the rank of int
217 // and unsigned int.
218 // - A bit-field of type _Bool, int, signed int, or unsigned int.
219 //
220 // If an int can represent all values of the original type, the
221 // value is converted to an int; otherwise, it is converted to an
222 // unsigned int. These are called the integer promotions. All
223 // other types are unchanged by the integer promotions.
Eli Friedman629ffb92009-08-20 04:21:42 +0000224 QualType PTy = Context.isPromotableBitField(Expr);
225 if (!PTy.isNull()) {
Eli Friedman06ed2a52009-10-20 08:27:19 +0000226 ImpCastExprToType(Expr, PTy, CastExpr::CK_IntegralCast);
Eli Friedman629ffb92009-08-20 04:21:42 +0000227 return Expr;
228 }
Douglas Gregor8d9c5092009-05-01 20:41:21 +0000229 if (Ty->isPromotableIntegerType()) {
Eli Friedman5ae98ee2009-08-19 07:44:53 +0000230 QualType PT = Context.getPromotedIntegerType(Ty);
Eli Friedman06ed2a52009-10-20 08:27:19 +0000231 ImpCastExprToType(Expr, PT, CastExpr::CK_IntegralCast);
Douglas Gregor8d9c5092009-05-01 20:41:21 +0000232 return Expr;
Eli Friedman629ffb92009-08-20 04:21:42 +0000233 }
234
Douglas Gregor8d9c5092009-05-01 20:41:21 +0000235 DefaultFunctionArrayConversion(Expr);
Chris Lattner513165e2008-07-25 21:10:04 +0000236 return Expr;
237}
238
Chris Lattner2ce500f2008-07-25 22:25:12 +0000239/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Mike Stump11289f42009-09-09 15:08:12 +0000240/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner2ce500f2008-07-25 22:25:12 +0000241/// double. All other argument types are converted by UsualUnaryConversions().
242void Sema::DefaultArgumentPromotion(Expr *&Expr) {
243 QualType Ty = Expr->getType();
244 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump11289f42009-09-09 15:08:12 +0000245
Chris Lattner2ce500f2008-07-25 22:25:12 +0000246 // If this is a 'float' (CVR qualified or typedef) promote to double.
John McCall9dd450b2009-09-21 23:43:11 +0000247 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
Chris Lattner2ce500f2008-07-25 22:25:12 +0000248 if (BT->getKind() == BuiltinType::Float)
Eli Friedman06ed2a52009-10-20 08:27:19 +0000249 return ImpCastExprToType(Expr, Context.DoubleTy,
250 CastExpr::CK_FloatingCast);
Mike Stump11289f42009-09-09 15:08:12 +0000251
Chris Lattner2ce500f2008-07-25 22:25:12 +0000252 UsualUnaryConversions(Expr);
253}
254
Chris Lattnera8a7d0f2009-04-12 08:11:20 +0000255/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
256/// will warn if the resulting type is not a POD type, and rejects ObjC
257/// interfaces passed by value. This returns true if the argument type is
258/// completely illegal.
259bool Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT) {
Anders Carlssona7d069d2009-01-16 16:48:51 +0000260 DefaultArgumentPromotion(Expr);
Mike Stump11289f42009-09-09 15:08:12 +0000261
Douglas Gregorda8cdbc2009-12-22 01:01:55 +0000262 if (Expr->getType()->isObjCInterfaceType() &&
263 DiagRuntimeBehavior(Expr->getLocStart(),
264 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
265 << Expr->getType() << CT))
266 return true;
Douglas Gregor7ca84af2009-12-12 07:25:49 +0000267
Douglas Gregorda8cdbc2009-12-22 01:01:55 +0000268 if (!Expr->getType()->isPODType() &&
269 DiagRuntimeBehavior(Expr->getLocStart(),
270 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
271 << Expr->getType() << CT))
272 return true;
Chris Lattnera8a7d0f2009-04-12 08:11:20 +0000273
274 return false;
Anders Carlssona7d069d2009-01-16 16:48:51 +0000275}
276
277
Chris Lattner513165e2008-07-25 21:10:04 +0000278/// UsualArithmeticConversions - Performs various conversions that are common to
279/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump11289f42009-09-09 15:08:12 +0000280/// routine returns the first non-arithmetic type found. The client is
Chris Lattner513165e2008-07-25 21:10:04 +0000281/// responsible for emitting appropriate error diagnostics.
282/// FIXME: verify the conversion rules for "complex int" are consistent with
283/// GCC.
284QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
285 bool isCompAssign) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +0000286 if (!isCompAssign)
Chris Lattner513165e2008-07-25 21:10:04 +0000287 UsualUnaryConversions(lhsExpr);
Eli Friedman8b7b1b12009-03-28 01:22:36 +0000288
289 UsualUnaryConversions(rhsExpr);
Douglas Gregora11693b2008-11-12 17:17:38 +0000290
Mike Stump11289f42009-09-09 15:08:12 +0000291 // For conversion purposes, we ignore any qualifiers.
Chris Lattner513165e2008-07-25 21:10:04 +0000292 // For example, "const float" and "float" are equivalent.
Chris Lattner574dee62008-07-26 22:17:49 +0000293 QualType lhs =
294 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +0000295 QualType rhs =
Chris Lattner574dee62008-07-26 22:17:49 +0000296 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +0000297
298 // If both types are identical, no conversion is needed.
299 if (lhs == rhs)
300 return lhs;
301
302 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
303 // The caller can deal with this (e.g. pointer + int).
304 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
305 return lhs;
306
Douglas Gregord2c2d172009-05-02 00:36:19 +0000307 // Perform bitfield promotions.
Eli Friedman629ffb92009-08-20 04:21:42 +0000308 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr);
Douglas Gregord2c2d172009-05-02 00:36:19 +0000309 if (!LHSBitfieldPromoteTy.isNull())
310 lhs = LHSBitfieldPromoteTy;
Eli Friedman629ffb92009-08-20 04:21:42 +0000311 QualType RHSBitfieldPromoteTy = Context.isPromotableBitField(rhsExpr);
Douglas Gregord2c2d172009-05-02 00:36:19 +0000312 if (!RHSBitfieldPromoteTy.isNull())
313 rhs = RHSBitfieldPromoteTy;
314
Eli Friedman5ae98ee2009-08-19 07:44:53 +0000315 QualType destType = Context.UsualArithmeticConversionsType(lhs, rhs);
Eli Friedman8b7b1b12009-03-28 01:22:36 +0000316 if (!isCompAssign)
Eli Friedman06ed2a52009-10-20 08:27:19 +0000317 ImpCastExprToType(lhsExpr, destType, CastExpr::CK_Unknown);
318 ImpCastExprToType(rhsExpr, destType, CastExpr::CK_Unknown);
Douglas Gregora11693b2008-11-12 17:17:38 +0000319 return destType;
320}
321
Chris Lattner513165e2008-07-25 21:10:04 +0000322//===----------------------------------------------------------------------===//
323// Semantic Analysis for various Expression Types
324//===----------------------------------------------------------------------===//
325
326
Steve Naroff83895f72007-09-16 03:34:24 +0000327/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner5b183d82006-11-10 05:03:26 +0000328/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
329/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
330/// multiple tokens. However, the common case is that StringToks points to one
331/// string.
Sebastian Redlffbcf962009-01-18 18:53:16 +0000332///
333Action::OwningExprResult
Steve Naroff83895f72007-09-16 03:34:24 +0000334Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner5b183d82006-11-10 05:03:26 +0000335 assert(NumStringToks && "Must have at least one string!");
336
Chris Lattner8a24e582009-01-16 18:51:42 +0000337 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Steve Naroff4f88b312007-03-13 22:37:02 +0000338 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +0000339 return ExprError();
Chris Lattner5b183d82006-11-10 05:03:26 +0000340
Chris Lattner23b7eb62007-06-15 23:05:46 +0000341 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
Chris Lattner5b183d82006-11-10 05:03:26 +0000342 for (unsigned i = 0; i != NumStringToks; ++i)
343 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattner36fc8792008-02-11 00:02:17 +0000344
Chris Lattner36fc8792008-02-11 00:02:17 +0000345 QualType StrTy = Context.CharTy;
Argyrios Kyrtzidiscbad7252008-08-09 17:20:01 +0000346 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattner36fc8792008-02-11 00:02:17 +0000347 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregoraa1e21d2008-09-12 00:47:35 +0000348
349 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
350 if (getLangOptions().CPlusPlus)
351 StrTy.addConst();
Sebastian Redlffbcf962009-01-18 18:53:16 +0000352
Chris Lattner36fc8792008-02-11 00:02:17 +0000353 // Get an array type for the string, according to C99 6.4.5. This includes
354 // the nul terminator character as well as the string length for pascal
355 // strings.
356 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerd42c29f2009-02-26 23:01:51 +0000357 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattner36fc8792008-02-11 00:02:17 +0000358 ArrayType::Normal, 0);
Mike Stump11289f42009-09-09 15:08:12 +0000359
Chris Lattner5b183d82006-11-10 05:03:26 +0000360 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Mike Stump11289f42009-09-09 15:08:12 +0000361 return Owned(StringLiteral::Create(Context, Literal.GetString(),
Chris Lattnerf83b5af2009-02-18 06:40:38 +0000362 Literal.GetStringLength(),
363 Literal.AnyWide, StrTy,
364 &StringTokLocs[0],
365 StringTokLocs.size()));
Chris Lattner5b183d82006-11-10 05:03:26 +0000366}
367
Chris Lattner2a9d9892008-10-20 05:16:36 +0000368/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
369/// CurBlock to VD should cause it to be snapshotted (as we do for auto
370/// variables defined outside the block) or false if this is not needed (e.g.
371/// for values inside the block or for globals).
372///
Chris Lattner497d7b02009-04-21 22:26:47 +0000373/// This also keeps the 'hasBlockDeclRefExprs' in the BlockSemaInfo records
374/// up-to-date.
375///
Chris Lattner2a9d9892008-10-20 05:16:36 +0000376static bool ShouldSnapshotBlockValueReference(BlockSemaInfo *CurBlock,
377 ValueDecl *VD) {
378 // If the value is defined inside the block, we couldn't snapshot it even if
379 // we wanted to.
380 if (CurBlock->TheDecl == VD->getDeclContext())
381 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000382
Chris Lattner2a9d9892008-10-20 05:16:36 +0000383 // If this is an enum constant or function, it is constant, don't snapshot.
384 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
385 return false;
386
387 // If this is a reference to an extern, static, or global variable, no need to
388 // snapshot it.
389 // FIXME: What about 'const' variables in C++?
390 if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
Chris Lattner497d7b02009-04-21 22:26:47 +0000391 if (!Var->hasLocalStorage())
392 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000393
Chris Lattner497d7b02009-04-21 22:26:47 +0000394 // Blocks that have these can't be constant.
395 CurBlock->hasBlockDeclRefExprs = true;
396
397 // If we have nested blocks, the decl may be declared in an outer block (in
398 // which case that outer block doesn't get "hasBlockDeclRefExprs") or it may
399 // be defined outside all of the current blocks (in which case the blocks do
400 // all get the bit). Walk the nesting chain.
401 for (BlockSemaInfo *NextBlock = CurBlock->PrevBlockInfo; NextBlock;
402 NextBlock = NextBlock->PrevBlockInfo) {
403 // If we found the defining block for the variable, don't mark the block as
404 // having a reference outside it.
405 if (NextBlock->TheDecl == VD->getDeclContext())
406 break;
Mike Stump11289f42009-09-09 15:08:12 +0000407
Chris Lattner497d7b02009-04-21 22:26:47 +0000408 // Otherwise, the DeclRef from the inner block causes the outer one to need
409 // a snapshot as well.
410 NextBlock->hasBlockDeclRefExprs = true;
411 }
Mike Stump11289f42009-09-09 15:08:12 +0000412
Chris Lattner2a9d9892008-10-20 05:16:36 +0000413 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000414}
415
Chris Lattner2a9d9892008-10-20 05:16:36 +0000416
417
Douglas Gregor4bd90e52009-10-23 18:54:35 +0000418/// BuildDeclRefExpr - Build a DeclRefExpr.
Anders Carlsson946b86d2009-06-24 00:10:43 +0000419Sema::OwningExprResult
John McCallce546572009-12-08 09:08:17 +0000420Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, SourceLocation Loc,
Sebastian Redl3d3f75a2009-02-03 20:19:35 +0000421 const CXXScopeSpec *SS) {
Anders Carlsson364035d12009-06-26 19:16:07 +0000422 if (Context.getCanonicalType(Ty) == Context.UndeducedAutoTy) {
423 Diag(Loc,
Mike Stump11289f42009-09-09 15:08:12 +0000424 diag::err_auto_variable_cannot_appear_in_own_initializer)
Anders Carlsson364035d12009-06-26 19:16:07 +0000425 << D->getDeclName();
426 return ExprError();
427 }
Mike Stump11289f42009-09-09 15:08:12 +0000428
Anders Carlsson946b86d2009-06-24 00:10:43 +0000429 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
430 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
431 if (const FunctionDecl *FD = MD->getParent()->isLocalClass()) {
432 if (VD->hasLocalStorage() && VD->getDeclContext() != CurContext) {
Mike Stump11289f42009-09-09 15:08:12 +0000433 Diag(Loc, diag::err_reference_to_local_var_in_enclosing_function)
Anders Carlsson946b86d2009-06-24 00:10:43 +0000434 << D->getIdentifier() << FD->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +0000435 Diag(D->getLocation(), diag::note_local_variable_declared_here)
Anders Carlsson946b86d2009-06-24 00:10:43 +0000436 << D->getIdentifier();
437 return ExprError();
438 }
439 }
440 }
441 }
Mike Stump11289f42009-09-09 15:08:12 +0000442
Douglas Gregorc9c02ed2009-06-19 23:52:42 +0000443 MarkDeclarationReferenced(Loc, D);
Mike Stump11289f42009-09-09 15:08:12 +0000444
Douglas Gregor4bd90e52009-10-23 18:54:35 +0000445 return Owned(DeclRefExpr::Create(Context,
446 SS? (NestedNameSpecifier *)SS->getScopeRep() : 0,
447 SS? SS->getRange() : SourceRange(),
Douglas Gregored6c7442009-11-23 11:41:28 +0000448 D, Loc, Ty));
Douglas Gregorc7acfdf2009-01-06 05:10:23 +0000449}
450
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000451/// getObjectForAnonymousRecordDecl - Retrieve the (unnamed) field or
452/// variable corresponding to the anonymous union or struct whose type
453/// is Record.
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000454static Decl *getObjectForAnonymousRecordDecl(ASTContext &Context,
455 RecordDecl *Record) {
Mike Stump11289f42009-09-09 15:08:12 +0000456 assert(Record->isAnonymousStructOrUnion() &&
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000457 "Record must be an anonymous struct or union!");
Mike Stump11289f42009-09-09 15:08:12 +0000458
Mike Stump87c57ac2009-05-16 07:39:55 +0000459 // FIXME: Once Decls are directly linked together, this will be an O(1)
460 // operation rather than a slow walk through DeclContext's vector (which
461 // itself will be eliminated). DeclGroups might make this even better.
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000462 DeclContext *Ctx = Record->getDeclContext();
Mike Stump11289f42009-09-09 15:08:12 +0000463 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000464 DEnd = Ctx->decls_end();
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000465 D != DEnd; ++D) {
466 if (*D == Record) {
467 // The object for the anonymous struct/union directly
468 // follows its type in the list of declarations.
469 ++D;
470 assert(D != DEnd && "Missing object for anonymous record");
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000471 assert(!cast<NamedDecl>(*D)->getDeclName() && "Decl should be unnamed");
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000472 return *D;
473 }
474 }
475
476 assert(false && "Missing object for anonymous record");
477 return 0;
478}
479
Douglas Gregord5846a12009-04-15 06:41:24 +0000480/// \brief Given a field that represents a member of an anonymous
481/// struct/union, build the path from that field's context to the
482/// actual member.
483///
484/// Construct the sequence of field member references we'll have to
485/// perform to get to the field in the anonymous union/struct. The
486/// list of members is built from the field outward, so traverse it
487/// backwards to go from an object in the current context to the field
488/// we found.
489///
490/// \returns The variable from which the field access should begin,
491/// for an anonymous struct/union that is not a member of another
492/// class. Otherwise, returns NULL.
493VarDecl *Sema::BuildAnonymousStructUnionMemberPath(FieldDecl *Field,
494 llvm::SmallVectorImpl<FieldDecl *> &Path) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000495 assert(Field->getDeclContext()->isRecord() &&
496 cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion()
497 && "Field must be stored inside an anonymous struct or union");
498
Douglas Gregord5846a12009-04-15 06:41:24 +0000499 Path.push_back(Field);
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000500 VarDecl *BaseObject = 0;
501 DeclContext *Ctx = Field->getDeclContext();
502 do {
503 RecordDecl *Record = cast<RecordDecl>(Ctx);
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000504 Decl *AnonObject = getObjectForAnonymousRecordDecl(Context, Record);
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000505 if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject))
Douglas Gregord5846a12009-04-15 06:41:24 +0000506 Path.push_back(AnonField);
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000507 else {
508 BaseObject = cast<VarDecl>(AnonObject);
509 break;
510 }
511 Ctx = Ctx->getParent();
Mike Stump11289f42009-09-09 15:08:12 +0000512 } while (Ctx->isRecord() &&
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000513 cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion());
Douglas Gregord5846a12009-04-15 06:41:24 +0000514
515 return BaseObject;
516}
517
518Sema::OwningExprResult
519Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
520 FieldDecl *Field,
521 Expr *BaseObjectExpr,
522 SourceLocation OpLoc) {
523 llvm::SmallVector<FieldDecl *, 4> AnonFields;
Mike Stump11289f42009-09-09 15:08:12 +0000524 VarDecl *BaseObject = BuildAnonymousStructUnionMemberPath(Field,
Douglas Gregord5846a12009-04-15 06:41:24 +0000525 AnonFields);
526
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000527 // Build the expression that refers to the base object, from
528 // which we will build a sequence of member references to each
529 // of the anonymous union objects and, eventually, the field we
530 // found via name lookup.
531 bool BaseObjectIsPointer = false;
John McCall8ccfcb52009-09-24 19:53:00 +0000532 Qualifiers BaseQuals;
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000533 if (BaseObject) {
534 // BaseObject is an anonymous struct/union variable (and is,
535 // therefore, not part of another non-anonymous record).
Ted Kremenek5a201952009-02-07 01:47:29 +0000536 if (BaseObjectExpr) BaseObjectExpr->Destroy(Context);
Douglas Gregorc9c02ed2009-06-19 23:52:42 +0000537 MarkDeclarationReferenced(Loc, BaseObject);
Steve Narofff6009ed2009-01-21 00:14:39 +0000538 BaseObjectExpr = new (Context) DeclRefExpr(BaseObject,BaseObject->getType(),
Mike Stump4e1f26a2009-02-19 03:04:26 +0000539 SourceLocation());
John McCall8ccfcb52009-09-24 19:53:00 +0000540 BaseQuals
541 = Context.getCanonicalType(BaseObject->getType()).getQualifiers();
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000542 } else if (BaseObjectExpr) {
543 // The caller provided the base object expression. Determine
544 // whether its a pointer and whether it adds any qualifiers to the
545 // anonymous struct/union fields we're looking into.
546 QualType ObjectType = BaseObjectExpr->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000547 if (const PointerType *ObjectPtr = ObjectType->getAs<PointerType>()) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000548 BaseObjectIsPointer = true;
549 ObjectType = ObjectPtr->getPointeeType();
550 }
John McCall8ccfcb52009-09-24 19:53:00 +0000551 BaseQuals
552 = Context.getCanonicalType(ObjectType).getQualifiers();
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000553 } else {
554 // We've found a member of an anonymous struct/union that is
555 // inside a non-anonymous struct/union, so in a well-formed
556 // program our base object expression is "this".
557 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
558 if (!MD->isStatic()) {
Mike Stump11289f42009-09-09 15:08:12 +0000559 QualType AnonFieldType
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000560 = Context.getTagDeclType(
561 cast<RecordDecl>(AnonFields.back()->getDeclContext()));
562 QualType ThisType = Context.getTagDeclType(MD->getParent());
Mike Stump11289f42009-09-09 15:08:12 +0000563 if ((Context.getCanonicalType(AnonFieldType)
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000564 == Context.getCanonicalType(ThisType)) ||
565 IsDerivedFrom(ThisType, AnonFieldType)) {
566 // Our base object expression is "this".
Douglas Gregor4b654412009-12-24 20:23:34 +0000567 BaseObjectExpr = new (Context) CXXThisExpr(Loc,
Mike Stump4e1f26a2009-02-19 03:04:26 +0000568 MD->getThisType(Context));
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000569 BaseObjectIsPointer = true;
570 }
571 } else {
Sebastian Redlffbcf962009-01-18 18:53:16 +0000572 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
573 << Field->getDeclName());
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000574 }
John McCall8ccfcb52009-09-24 19:53:00 +0000575 BaseQuals = Qualifiers::fromCVRMask(MD->getTypeQualifiers());
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000576 }
577
Mike Stump11289f42009-09-09 15:08:12 +0000578 if (!BaseObjectExpr)
Sebastian Redlffbcf962009-01-18 18:53:16 +0000579 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
580 << Field->getDeclName());
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000581 }
582
583 // Build the implicit member references to the field of the
584 // anonymous struct/union.
585 Expr *Result = BaseObjectExpr;
John McCall8ccfcb52009-09-24 19:53:00 +0000586 Qualifiers ResultQuals = BaseQuals;
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000587 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
588 FI = AnonFields.rbegin(), FIEnd = AnonFields.rend();
589 FI != FIEnd; ++FI) {
590 QualType MemberType = (*FI)->getType();
John McCall8ccfcb52009-09-24 19:53:00 +0000591 Qualifiers MemberTypeQuals =
592 Context.getCanonicalType(MemberType).getQualifiers();
593
594 // CVR attributes from the base are picked up by members,
595 // except that 'mutable' members don't pick up 'const'.
596 if ((*FI)->isMutable())
597 ResultQuals.removeConst();
598
599 // GC attributes are never picked up by members.
600 ResultQuals.removeObjCGCAttr();
601
602 // TR 18037 does not allow fields to be declared with address spaces.
603 assert(!MemberTypeQuals.hasAddressSpace());
604
605 Qualifiers NewQuals = ResultQuals + MemberTypeQuals;
606 if (NewQuals != MemberTypeQuals)
607 MemberType = Context.getQualifiedType(MemberType, NewQuals);
608
Douglas Gregorc9c02ed2009-06-19 23:52:42 +0000609 MarkDeclarationReferenced(Loc, *FI);
Eli Friedman78cde142009-12-04 07:18:51 +0000610 PerformObjectMemberConversion(Result, *FI);
Douglas Gregorc1905232009-08-26 22:36:53 +0000611 // FIXME: Might this end up being a qualified name?
Steve Narofff6009ed2009-01-21 00:14:39 +0000612 Result = new (Context) MemberExpr(Result, BaseObjectIsPointer, *FI,
613 OpLoc, MemberType);
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000614 BaseObjectIsPointer = false;
John McCall8ccfcb52009-09-24 19:53:00 +0000615 ResultQuals = NewQuals;
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000616 }
617
Sebastian Redlffbcf962009-01-18 18:53:16 +0000618 return Owned(Result);
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000619}
620
John McCall10eae182009-11-30 22:42:35 +0000621/// Decomposes the given name into a DeclarationName, its location, and
622/// possibly a list of template arguments.
623///
624/// If this produces template arguments, it is permitted to call
625/// DecomposeTemplateName.
626///
627/// This actually loses a lot of source location information for
628/// non-standard name kinds; we should consider preserving that in
629/// some way.
630static void DecomposeUnqualifiedId(Sema &SemaRef,
631 const UnqualifiedId &Id,
632 TemplateArgumentListInfo &Buffer,
633 DeclarationName &Name,
634 SourceLocation &NameLoc,
635 const TemplateArgumentListInfo *&TemplateArgs) {
636 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
637 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
638 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
639
640 ASTTemplateArgsPtr TemplateArgsPtr(SemaRef,
641 Id.TemplateId->getTemplateArgs(),
642 Id.TemplateId->NumArgs);
643 SemaRef.translateTemplateArguments(TemplateArgsPtr, Buffer);
644 TemplateArgsPtr.release();
645
646 TemplateName TName =
647 Sema::TemplateTy::make(Id.TemplateId->Template).getAsVal<TemplateName>();
648
649 Name = SemaRef.Context.getNameForTemplate(TName);
650 NameLoc = Id.TemplateId->TemplateNameLoc;
651 TemplateArgs = &Buffer;
652 } else {
653 Name = SemaRef.GetNameFromUnqualifiedId(Id);
654 NameLoc = Id.StartLocation;
655 TemplateArgs = 0;
656 }
657}
658
659/// Decompose the given template name into a list of lookup results.
660///
661/// The unqualified ID must name a non-dependent template, which can
662/// be more easily tested by checking whether DecomposeUnqualifiedId
663/// found template arguments.
664static void DecomposeTemplateName(LookupResult &R, const UnqualifiedId &Id) {
665 assert(Id.getKind() == UnqualifiedId::IK_TemplateId);
666 TemplateName TName =
667 Sema::TemplateTy::make(Id.TemplateId->Template).getAsVal<TemplateName>();
668
John McCalle66edc12009-11-24 19:00:30 +0000669 if (TemplateDecl *TD = TName.getAsTemplateDecl())
670 R.addDecl(TD);
John McCalld28ae272009-12-02 08:04:21 +0000671 else if (OverloadedTemplateStorage *OT = TName.getAsOverloadedTemplate())
672 for (OverloadedTemplateStorage::iterator I = OT->begin(), E = OT->end();
673 I != E; ++I)
John McCalle66edc12009-11-24 19:00:30 +0000674 R.addDecl(*I);
John McCalla9ee3252009-11-22 02:49:43 +0000675
John McCalle66edc12009-11-24 19:00:30 +0000676 R.resolveKind();
Douglas Gregora121b752009-11-03 16:56:39 +0000677}
678
John McCall10eae182009-11-30 22:42:35 +0000679static bool IsFullyFormedScope(Sema &SemaRef, CXXRecordDecl *Record) {
680 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
681 E = Record->bases_end(); I != E; ++I) {
682 CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
683 CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
684 if (!BaseRT) return false;
685
686 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
687 if (!BaseRecord->isDefinition() ||
688 !IsFullyFormedScope(SemaRef, BaseRecord))
689 return false;
690 }
691
692 return true;
693}
694
John McCallf786fb12009-11-30 23:50:49 +0000695/// Determines whether we can lookup this id-expression now or whether
696/// we have to wait until template instantiation is complete.
697static bool IsDependentIdExpression(Sema &SemaRef, const CXXScopeSpec &SS) {
John McCall10eae182009-11-30 22:42:35 +0000698 DeclContext *DC = SemaRef.computeDeclContext(SS, false);
John McCall10eae182009-11-30 22:42:35 +0000699
John McCallf786fb12009-11-30 23:50:49 +0000700 // If the qualifier scope isn't computable, it's definitely dependent.
701 if (!DC) return true;
702
703 // If the qualifier scope doesn't name a record, we can always look into it.
704 if (!isa<CXXRecordDecl>(DC)) return false;
705
706 // We can't look into record types unless they're fully-formed.
707 if (!IsFullyFormedScope(SemaRef, cast<CXXRecordDecl>(DC))) return true;
708
John McCall2d74de92009-12-01 22:10:20 +0000709 return false;
710}
John McCallf786fb12009-11-30 23:50:49 +0000711
John McCall2d74de92009-12-01 22:10:20 +0000712/// Determines if the given class is provably not derived from all of
713/// the prospective base classes.
714static bool IsProvablyNotDerivedFrom(Sema &SemaRef,
715 CXXRecordDecl *Record,
716 const llvm::SmallPtrSet<CXXRecordDecl*, 4> &Bases) {
John McCalla6d407c2009-12-01 22:28:41 +0000717 if (Bases.count(Record->getCanonicalDecl()))
John McCall2d74de92009-12-01 22:10:20 +0000718 return false;
719
John McCalla6d407c2009-12-01 22:28:41 +0000720 RecordDecl *RD = Record->getDefinition(SemaRef.Context);
721 if (!RD) return false;
722 Record = cast<CXXRecordDecl>(RD);
723
John McCall2d74de92009-12-01 22:10:20 +0000724 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
725 E = Record->bases_end(); I != E; ++I) {
726 CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
727 CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
728 if (!BaseRT) return false;
729
730 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall2d74de92009-12-01 22:10:20 +0000731 if (!IsProvablyNotDerivedFrom(SemaRef, BaseRecord, Bases))
732 return false;
733 }
734
735 return true;
736}
737
John McCall5af04502009-12-02 20:26:00 +0000738/// Determines if this is an instance member of a class.
739static bool IsInstanceMember(NamedDecl *D) {
John McCall57500772009-12-16 12:17:52 +0000740 assert(D->isCXXClassMember() &&
John McCall2d74de92009-12-01 22:10:20 +0000741 "checking whether non-member is instance member");
742
743 if (isa<FieldDecl>(D)) return true;
744
745 if (isa<CXXMethodDecl>(D))
746 return !cast<CXXMethodDecl>(D)->isStatic();
747
748 if (isa<FunctionTemplateDecl>(D)) {
749 D = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
750 return !cast<CXXMethodDecl>(D)->isStatic();
751 }
752
753 return false;
754}
755
756enum IMAKind {
757 /// The reference is definitely not an instance member access.
758 IMA_Static,
759
760 /// The reference may be an implicit instance member access.
761 IMA_Mixed,
762
763 /// The reference may be to an instance member, but it is invalid if
764 /// so, because the context is not an instance method.
765 IMA_Mixed_StaticContext,
766
767 /// The reference may be to an instance member, but it is invalid if
768 /// so, because the context is from an unrelated class.
769 IMA_Mixed_Unrelated,
770
771 /// The reference is definitely an implicit instance member access.
772 IMA_Instance,
773
774 /// The reference may be to an unresolved using declaration.
775 IMA_Unresolved,
776
777 /// The reference may be to an unresolved using declaration and the
778 /// context is not an instance method.
779 IMA_Unresolved_StaticContext,
780
781 /// The reference is to a member of an anonymous structure in a
782 /// non-class context.
783 IMA_AnonymousMember,
784
785 /// All possible referrents are instance members and the current
786 /// context is not an instance method.
787 IMA_Error_StaticContext,
788
789 /// All possible referrents are instance members of an unrelated
790 /// class.
791 IMA_Error_Unrelated
792};
793
794/// The given lookup names class member(s) and is not being used for
795/// an address-of-member expression. Classify the type of access
796/// according to whether it's possible that this reference names an
797/// instance member. This is best-effort; it is okay to
798/// conservatively answer "yes", in which case some errors will simply
799/// not be caught until template-instantiation.
800static IMAKind ClassifyImplicitMemberAccess(Sema &SemaRef,
801 const LookupResult &R) {
John McCall57500772009-12-16 12:17:52 +0000802 assert(!R.empty() && (*R.begin())->isCXXClassMember());
John McCall2d74de92009-12-01 22:10:20 +0000803
804 bool isStaticContext =
805 (!isa<CXXMethodDecl>(SemaRef.CurContext) ||
806 cast<CXXMethodDecl>(SemaRef.CurContext)->isStatic());
807
808 if (R.isUnresolvableResult())
809 return isStaticContext ? IMA_Unresolved_StaticContext : IMA_Unresolved;
810
811 // Collect all the declaring classes of instance members we find.
812 bool hasNonInstance = false;
813 llvm::SmallPtrSet<CXXRecordDecl*, 4> Classes;
814 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
815 NamedDecl *D = (*I)->getUnderlyingDecl();
816 if (IsInstanceMember(D)) {
817 CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext());
818
819 // If this is a member of an anonymous record, move out to the
820 // innermost non-anonymous struct or union. If there isn't one,
821 // that's a special case.
822 while (R->isAnonymousStructOrUnion()) {
823 R = dyn_cast<CXXRecordDecl>(R->getParent());
824 if (!R) return IMA_AnonymousMember;
825 }
826 Classes.insert(R->getCanonicalDecl());
827 }
828 else
829 hasNonInstance = true;
830 }
831
832 // If we didn't find any instance members, it can't be an implicit
833 // member reference.
834 if (Classes.empty())
835 return IMA_Static;
836
837 // If the current context is not an instance method, it can't be
838 // an implicit member reference.
839 if (isStaticContext)
840 return (hasNonInstance ? IMA_Mixed_StaticContext : IMA_Error_StaticContext);
841
842 // If we can prove that the current context is unrelated to all the
843 // declaring classes, it can't be an implicit member reference (in
844 // which case it's an error if any of those members are selected).
845 if (IsProvablyNotDerivedFrom(SemaRef,
846 cast<CXXMethodDecl>(SemaRef.CurContext)->getParent(),
847 Classes))
848 return (hasNonInstance ? IMA_Mixed_Unrelated : IMA_Error_Unrelated);
849
850 return (hasNonInstance ? IMA_Mixed : IMA_Instance);
851}
852
853/// Diagnose a reference to a field with no object available.
854static void DiagnoseInstanceReference(Sema &SemaRef,
855 const CXXScopeSpec &SS,
856 const LookupResult &R) {
857 SourceLocation Loc = R.getNameLoc();
858 SourceRange Range(Loc);
859 if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
860
861 if (R.getAsSingle<FieldDecl>()) {
862 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(SemaRef.CurContext)) {
863 if (MD->isStatic()) {
864 // "invalid use of member 'x' in static member function"
865 SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method)
866 << Range << R.getLookupName();
867 return;
868 }
869 }
870
871 SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
872 << R.getLookupName() << Range;
873 return;
874 }
875
876 SemaRef.Diag(Loc, diag::err_member_call_without_object) << Range;
John McCall10eae182009-11-30 22:42:35 +0000877}
878
John McCalld681c392009-12-16 08:11:27 +0000879/// Diagnose an empty lookup.
880///
881/// \return false if new lookup candidates were found
Douglas Gregor598b08f2009-12-31 05:20:13 +0000882bool Sema::DiagnoseEmptyLookup(Scope *S, const CXXScopeSpec &SS,
John McCalld681c392009-12-16 08:11:27 +0000883 LookupResult &R) {
884 DeclarationName Name = R.getLookupName();
885
John McCalld681c392009-12-16 08:11:27 +0000886 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +0000887 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCalld681c392009-12-16 08:11:27 +0000888 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
889 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregor598b08f2009-12-31 05:20:13 +0000890 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCalld681c392009-12-16 08:11:27 +0000891 diagnostic = diag::err_undeclared_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +0000892 diagnostic_suggest = diag::err_undeclared_use_suggest;
893 }
John McCalld681c392009-12-16 08:11:27 +0000894
Douglas Gregor598b08f2009-12-31 05:20:13 +0000895 // If the original lookup was an unqualified lookup, fake an
896 // unqualified lookup. This is useful when (for example) the
897 // original lookup would not have found something because it was a
898 // dependent name.
899 for (DeclContext *DC = SS.isEmpty()? CurContext : 0;
900 DC; DC = DC->getParent()) {
John McCalld681c392009-12-16 08:11:27 +0000901 if (isa<CXXRecordDecl>(DC)) {
902 LookupQualifiedName(R, DC);
903
904 if (!R.empty()) {
905 // Don't give errors about ambiguities in this lookup.
906 R.suppressDiagnostics();
907
908 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
909 bool isInstance = CurMethod &&
910 CurMethod->isInstance() &&
911 DC == CurMethod->getParent();
912
913 // Give a code modification hint to insert 'this->'.
914 // TODO: fixit for inserting 'Base<T>::' in the other cases.
915 // Actually quite difficult!
916 if (isInstance)
917 Diag(R.getNameLoc(), diagnostic) << Name
918 << CodeModificationHint::CreateInsertion(R.getNameLoc(),
919 "this->");
920 else
921 Diag(R.getNameLoc(), diagnostic) << Name;
922
923 // Do we really want to note all of these?
924 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
925 Diag((*I)->getLocation(), diag::note_dependent_var_use);
926
927 // Tell the callee to try to recover.
928 return false;
929 }
930 }
931 }
932
Douglas Gregor598b08f2009-12-31 05:20:13 +0000933 // We didn't find anything, so try to correct for a typo.
934 if (S && CorrectTypo(R, S, &SS) &&
935 (isa<ValueDecl>(*R.begin()) || isa<TemplateDecl>(*R.begin()))) {
936 if (SS.isEmpty())
937 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName()
938 << CodeModificationHint::CreateReplacement(R.getNameLoc(),
939 R.getLookupName().getAsString());
940 else
941 Diag(R.getNameLoc(), diag::err_no_member_suggest)
942 << Name << computeDeclContext(SS, false) << R.getLookupName()
943 << SS.getRange()
944 << CodeModificationHint::CreateReplacement(R.getNameLoc(),
945 R.getLookupName().getAsString());
946
947 // Tell the callee to try to recover.
948 return false;
949 }
950
951 // Emit a special diagnostic for failed member lookups.
952 // FIXME: computing the declaration context might fail here (?)
953 if (!SS.isEmpty()) {
954 Diag(R.getNameLoc(), diag::err_no_member)
955 << Name << computeDeclContext(SS, false)
956 << SS.getRange();
957 return true;
958 }
959
John McCalld681c392009-12-16 08:11:27 +0000960 // Give up, we can't recover.
961 Diag(R.getNameLoc(), diagnostic) << Name;
962 return true;
963}
964
John McCalle66edc12009-11-24 19:00:30 +0000965Sema::OwningExprResult Sema::ActOnIdExpression(Scope *S,
966 const CXXScopeSpec &SS,
967 UnqualifiedId &Id,
968 bool HasTrailingLParen,
969 bool isAddressOfOperand) {
970 assert(!(isAddressOfOperand && HasTrailingLParen) &&
971 "cannot be direct & operand and have a trailing lparen");
972
973 if (SS.isInvalid())
Douglas Gregored8f2882009-01-30 01:04:22 +0000974 return ExprError();
Douglas Gregor90a1a652009-03-19 17:26:29 +0000975
John McCall10eae182009-11-30 22:42:35 +0000976 TemplateArgumentListInfo TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +0000977
978 // Decompose the UnqualifiedId into the following data.
979 DeclarationName Name;
980 SourceLocation NameLoc;
981 const TemplateArgumentListInfo *TemplateArgs;
John McCall10eae182009-11-30 22:42:35 +0000982 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer,
983 Name, NameLoc, TemplateArgs);
Douglas Gregor90a1a652009-03-19 17:26:29 +0000984
Douglas Gregor4ea80432008-11-18 15:03:34 +0000985 IdentifierInfo *II = Name.getAsIdentifierInfo();
John McCalld14a8642009-11-21 08:51:07 +0000986
John McCalle66edc12009-11-24 19:00:30 +0000987 // C++ [temp.dep.expr]p3:
988 // An id-expression is type-dependent if it contains:
989 // -- a nested-name-specifier that contains a class-name that
990 // names a dependent type.
991 // Determine whether this is a member of an unknown specialization;
992 // we need to handle these differently.
John McCallf786fb12009-11-30 23:50:49 +0000993 if (SS.isSet() && IsDependentIdExpression(*this, SS)) {
John McCalle66edc12009-11-24 19:00:30 +0000994 return ActOnDependentIdExpression(SS, Name, NameLoc,
John McCallcd4b4772009-12-02 03:53:29 +0000995 isAddressOfOperand,
John McCalle66edc12009-11-24 19:00:30 +0000996 TemplateArgs);
997 }
John McCalld14a8642009-11-21 08:51:07 +0000998
John McCalle66edc12009-11-24 19:00:30 +0000999 // Perform the required lookup.
1000 LookupResult R(*this, Name, NameLoc, LookupOrdinaryName);
1001 if (TemplateArgs) {
John McCalle66edc12009-11-24 19:00:30 +00001002 // Just re-use the lookup done by isTemplateName.
John McCall10eae182009-11-30 22:42:35 +00001003 DecomposeTemplateName(R, Id);
John McCalle66edc12009-11-24 19:00:30 +00001004 } else {
1005 LookupParsedName(R, S, &SS, true);
Mike Stump11289f42009-09-09 15:08:12 +00001006
John McCalle66edc12009-11-24 19:00:30 +00001007 // If this reference is in an Objective-C method, then we need to do
1008 // some special Objective-C lookup, too.
1009 if (!SS.isSet() && II && getCurMethodDecl()) {
1010 OwningExprResult E(LookupInObjCMethod(R, S, II));
1011 if (E.isInvalid())
1012 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001013
John McCalle66edc12009-11-24 19:00:30 +00001014 Expr *Ex = E.takeAs<Expr>();
1015 if (Ex) return Owned(Ex);
Steve Naroffebf4cb42008-06-02 23:03:37 +00001016 }
Chris Lattner59a25942008-03-31 00:36:02 +00001017 }
Douglas Gregorf15f5d32009-02-16 19:28:42 +00001018
John McCalle66edc12009-11-24 19:00:30 +00001019 if (R.isAmbiguous())
1020 return ExprError();
1021
Douglas Gregor171c45a2009-02-18 21:56:37 +00001022 // Determine whether this name might be a candidate for
1023 // argument-dependent lookup.
John McCalle66edc12009-11-24 19:00:30 +00001024 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor171c45a2009-02-18 21:56:37 +00001025
John McCalle66edc12009-11-24 19:00:30 +00001026 if (R.empty() && !ADL) {
Bill Wendling4073ed52007-02-13 01:51:42 +00001027 // Otherwise, this could be an implicitly declared function reference (legal
John McCalle66edc12009-11-24 19:00:30 +00001028 // in C90, extension in C99, forbidden in C++).
1029 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
1030 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1031 if (D) R.addDecl(D);
1032 }
1033
1034 // If this name wasn't predeclared and if this is not a function
1035 // call, diagnose the problem.
1036 if (R.empty()) {
Douglas Gregor598b08f2009-12-31 05:20:13 +00001037 if (DiagnoseEmptyLookup(S, SS, R))
John McCalld681c392009-12-16 08:11:27 +00001038 return ExprError();
1039
1040 assert(!R.empty() &&
1041 "DiagnoseEmptyLookup returned false but added no results");
Steve Naroff92e30f82007-04-02 22:35:25 +00001042 }
Chris Lattner17ed4872006-11-20 04:58:19 +00001043 }
Mike Stump11289f42009-09-09 15:08:12 +00001044
John McCalle66edc12009-11-24 19:00:30 +00001045 // This is guaranteed from this point on.
1046 assert(!R.empty() || ADL);
1047
1048 if (VarDecl *Var = R.getAsSingle<VarDecl>()) {
Douglas Gregor3256d042009-06-30 15:47:41 +00001049 // Warn about constructs like:
1050 // if (void *X = foo()) { ... } else { X }.
1051 // In the else block, the pointer is always false.
Mike Stump11289f42009-09-09 15:08:12 +00001052
Douglas Gregor3256d042009-06-30 15:47:41 +00001053 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
1054 Scope *CheckS = S;
Douglas Gregor13a2c032009-11-05 17:49:26 +00001055 while (CheckS && CheckS->getControlParent()) {
Mike Stump11289f42009-09-09 15:08:12 +00001056 if (CheckS->isWithinElse() &&
Douglas Gregor3256d042009-06-30 15:47:41 +00001057 CheckS->getControlParent()->isDeclScope(DeclPtrTy::make(Var))) {
John McCalle66edc12009-11-24 19:00:30 +00001058 ExprError(Diag(NameLoc, diag::warn_value_always_zero)
Douglas Gregor13a2c032009-11-05 17:49:26 +00001059 << Var->getDeclName()
1060 << (Var->getType()->isPointerType()? 2 :
1061 Var->getType()->isBooleanType()? 1 : 0));
Douglas Gregor3256d042009-06-30 15:47:41 +00001062 break;
1063 }
Mike Stump11289f42009-09-09 15:08:12 +00001064
Douglas Gregor13a2c032009-11-05 17:49:26 +00001065 // Move to the parent of this scope.
1066 CheckS = CheckS->getParent();
Douglas Gregor3256d042009-06-30 15:47:41 +00001067 }
1068 }
John McCalle66edc12009-11-24 19:00:30 +00001069 } else if (FunctionDecl *Func = R.getAsSingle<FunctionDecl>()) {
Douglas Gregor3256d042009-06-30 15:47:41 +00001070 if (!getLangOptions().CPlusPlus && !Func->hasPrototype()) {
1071 // C99 DR 316 says that, if a function type comes from a
1072 // function definition (without a prototype), that type is only
1073 // used for checking compatibility. Therefore, when referencing
1074 // the function, we pretend that we don't have the full function
1075 // type.
John McCalle66edc12009-11-24 19:00:30 +00001076 if (DiagnoseUseOfDecl(Func, NameLoc))
Douglas Gregor3256d042009-06-30 15:47:41 +00001077 return ExprError();
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001078
Douglas Gregor3256d042009-06-30 15:47:41 +00001079 QualType T = Func->getType();
1080 QualType NoProtoType = T;
John McCall9dd450b2009-09-21 23:43:11 +00001081 if (const FunctionProtoType *Proto = T->getAs<FunctionProtoType>())
Douglas Gregor3256d042009-06-30 15:47:41 +00001082 NoProtoType = Context.getFunctionNoProtoType(Proto->getResultType());
John McCalle66edc12009-11-24 19:00:30 +00001083 return BuildDeclRefExpr(Func, NoProtoType, NameLoc, &SS);
Douglas Gregor3256d042009-06-30 15:47:41 +00001084 }
1085 }
Mike Stump11289f42009-09-09 15:08:12 +00001086
John McCall2d74de92009-12-01 22:10:20 +00001087 // Check whether this might be a C++ implicit instance member access.
1088 // C++ [expr.prim.general]p6:
1089 // Within the definition of a non-static member function, an
1090 // identifier that names a non-static member is transformed to a
1091 // class member access expression.
1092 // But note that &SomeClass::foo is grammatically distinct, even
1093 // though we don't parse it that way.
John McCall57500772009-12-16 12:17:52 +00001094 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCalle66edc12009-11-24 19:00:30 +00001095 bool isAbstractMemberPointer = (isAddressOfOperand && !SS.isEmpty());
John McCall57500772009-12-16 12:17:52 +00001096 if (!isAbstractMemberPointer)
1097 return BuildPossibleImplicitMemberExpr(SS, R, TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001098 }
1099
John McCalle66edc12009-11-24 19:00:30 +00001100 if (TemplateArgs)
1101 return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001102
John McCalle66edc12009-11-24 19:00:30 +00001103 return BuildDeclarationNameExpr(SS, R, ADL);
1104}
1105
John McCall57500772009-12-16 12:17:52 +00001106/// Builds an expression which might be an implicit member expression.
1107Sema::OwningExprResult
1108Sema::BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
1109 LookupResult &R,
1110 const TemplateArgumentListInfo *TemplateArgs) {
1111 switch (ClassifyImplicitMemberAccess(*this, R)) {
1112 case IMA_Instance:
1113 return BuildImplicitMemberExpr(SS, R, TemplateArgs, true);
1114
1115 case IMA_AnonymousMember:
1116 assert(R.isSingleResult());
1117 return BuildAnonymousStructUnionMemberReference(R.getNameLoc(),
1118 R.getAsSingle<FieldDecl>());
1119
1120 case IMA_Mixed:
1121 case IMA_Mixed_Unrelated:
1122 case IMA_Unresolved:
1123 return BuildImplicitMemberExpr(SS, R, TemplateArgs, false);
1124
1125 case IMA_Static:
1126 case IMA_Mixed_StaticContext:
1127 case IMA_Unresolved_StaticContext:
1128 if (TemplateArgs)
1129 return BuildTemplateIdExpr(SS, R, false, *TemplateArgs);
1130 return BuildDeclarationNameExpr(SS, R, false);
1131
1132 case IMA_Error_StaticContext:
1133 case IMA_Error_Unrelated:
1134 DiagnoseInstanceReference(*this, SS, R);
1135 return ExprError();
1136 }
1137
1138 llvm_unreachable("unexpected instance member access kind");
1139 return ExprError();
1140}
1141
John McCall10eae182009-11-30 22:42:35 +00001142/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1143/// declaration name, generally during template instantiation.
1144/// There's a large number of things which don't need to be done along
1145/// this path.
John McCalle66edc12009-11-24 19:00:30 +00001146Sema::OwningExprResult
1147Sema::BuildQualifiedDeclarationNameExpr(const CXXScopeSpec &SS,
1148 DeclarationName Name,
1149 SourceLocation NameLoc) {
1150 DeclContext *DC;
1151 if (!(DC = computeDeclContext(SS, false)) ||
1152 DC->isDependentContext() ||
1153 RequireCompleteDeclContext(SS))
1154 return BuildDependentDeclRefExpr(SS, Name, NameLoc, 0);
1155
1156 LookupResult R(*this, Name, NameLoc, LookupOrdinaryName);
1157 LookupQualifiedName(R, DC);
1158
1159 if (R.isAmbiguous())
1160 return ExprError();
1161
1162 if (R.empty()) {
1163 Diag(NameLoc, diag::err_no_member) << Name << DC << SS.getRange();
1164 return ExprError();
1165 }
1166
1167 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1168}
1169
1170/// LookupInObjCMethod - The parser has read a name in, and Sema has
1171/// detected that we're currently inside an ObjC method. Perform some
1172/// additional lookup.
1173///
1174/// Ideally, most of this would be done by lookup, but there's
1175/// actually quite a lot of extra work involved.
1176///
1177/// Returns a null sentinel to indicate trivial success.
1178Sema::OwningExprResult
1179Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
1180 IdentifierInfo *II) {
1181 SourceLocation Loc = Lookup.getNameLoc();
1182
1183 // There are two cases to handle here. 1) scoped lookup could have failed,
1184 // in which case we should look for an ivar. 2) scoped lookup could have
1185 // found a decl, but that decl is outside the current instance method (i.e.
1186 // a global variable). In these two cases, we do a lookup for an ivar with
1187 // this name, if the lookup sucedes, we replace it our current decl.
1188
1189 // If we're in a class method, we don't normally want to look for
1190 // ivars. But if we don't find anything else, and there's an
1191 // ivar, that's an error.
1192 bool IsClassMethod = getCurMethodDecl()->isClassMethod();
1193
1194 bool LookForIvars;
1195 if (Lookup.empty())
1196 LookForIvars = true;
1197 else if (IsClassMethod)
1198 LookForIvars = false;
1199 else
1200 LookForIvars = (Lookup.isSingleResult() &&
1201 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
1202
1203 if (LookForIvars) {
1204 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
1205 ObjCInterfaceDecl *ClassDeclared;
1206 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1207 // Diagnose using an ivar in a class method.
1208 if (IsClassMethod)
1209 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1210 << IV->getDeclName());
1211
1212 // If we're referencing an invalid decl, just return this as a silent
1213 // error node. The error diagnostic was already emitted on the decl.
1214 if (IV->isInvalidDecl())
1215 return ExprError();
1216
1217 // Check if referencing a field with __attribute__((deprecated)).
1218 if (DiagnoseUseOfDecl(IV, Loc))
1219 return ExprError();
1220
1221 // Diagnose the use of an ivar outside of the declaring class.
1222 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
1223 ClassDeclared != IFace)
1224 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1225
1226 // FIXME: This should use a new expr for a direct reference, don't
1227 // turn this into Self->ivar, just return a BareIVarExpr or something.
1228 IdentifierInfo &II = Context.Idents.get("self");
1229 UnqualifiedId SelfName;
1230 SelfName.setIdentifier(&II, SourceLocation());
1231 CXXScopeSpec SelfScopeSpec;
1232 OwningExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
1233 SelfName, false, false);
1234 MarkDeclarationReferenced(Loc, IV);
1235 return Owned(new (Context)
1236 ObjCIvarRefExpr(IV, IV->getType(), Loc,
1237 SelfExpr.takeAs<Expr>(), true, true));
1238 }
1239 } else if (getCurMethodDecl()->isInstanceMethod()) {
1240 // We should warn if a local variable hides an ivar.
1241 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
1242 ObjCInterfaceDecl *ClassDeclared;
1243 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1244 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
1245 IFace == ClassDeclared)
1246 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
1247 }
1248 }
1249
1250 // Needed to implement property "super.method" notation.
1251 if (Lookup.empty() && II->isStr("super")) {
1252 QualType T;
1253
1254 if (getCurMethodDecl()->isInstanceMethod())
1255 T = Context.getObjCObjectPointerType(Context.getObjCInterfaceType(
1256 getCurMethodDecl()->getClassInterface()));
1257 else
1258 T = Context.getObjCClassType();
1259 return Owned(new (Context) ObjCSuperExpr(Loc, T));
1260 }
1261
1262 // Sentinel value saying that we didn't do anything special.
1263 return Owned((Expr*) 0);
Douglas Gregor3256d042009-06-30 15:47:41 +00001264}
John McCalld14a8642009-11-21 08:51:07 +00001265
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001266/// \brief Cast member's object to its own class if necessary.
Fariborz Jahanian3f150832009-07-29 19:40:11 +00001267bool
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001268Sema::PerformObjectMemberConversion(Expr *&From, NamedDecl *Member) {
1269 if (FieldDecl *FD = dyn_cast<FieldDecl>(Member))
Mike Stump11289f42009-09-09 15:08:12 +00001270 if (CXXRecordDecl *RD =
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001271 dyn_cast<CXXRecordDecl>(FD->getDeclContext())) {
Mike Stump11289f42009-09-09 15:08:12 +00001272 QualType DestType =
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001273 Context.getCanonicalType(Context.getTypeDeclType(RD));
Fariborz Jahanian4b12ed12009-07-29 20:41:46 +00001274 if (DestType->isDependentType() || From->getType()->isDependentType())
1275 return false;
1276 QualType FromRecordType = From->getType();
1277 QualType DestRecordType = DestType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001278 if (FromRecordType->getAs<PointerType>()) {
Fariborz Jahanian4b12ed12009-07-29 20:41:46 +00001279 DestType = Context.getPointerType(DestType);
1280 FromRecordType = FromRecordType->getPointeeType();
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001281 }
Fariborz Jahanian4b12ed12009-07-29 20:41:46 +00001282 if (!Context.hasSameUnqualifiedType(FromRecordType, DestRecordType) &&
1283 CheckDerivedToBaseConversion(FromRecordType,
1284 DestRecordType,
1285 From->getSourceRange().getBegin(),
1286 From->getSourceRange()))
1287 return true;
Anders Carlssona076d142009-07-31 01:23:52 +00001288 ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
1289 /*isLvalue=*/true);
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001290 }
Fariborz Jahanian3f150832009-07-29 19:40:11 +00001291 return false;
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001292}
Douglas Gregor3256d042009-06-30 15:47:41 +00001293
Douglas Gregorf405d7e2009-08-31 23:41:50 +00001294/// \brief Build a MemberExpr AST node.
Mike Stump11289f42009-09-09 15:08:12 +00001295static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow,
Eli Friedman2cfcef62009-12-04 06:40:45 +00001296 const CXXScopeSpec &SS, ValueDecl *Member,
John McCalle66edc12009-11-24 19:00:30 +00001297 SourceLocation Loc, QualType Ty,
1298 const TemplateArgumentListInfo *TemplateArgs = 0) {
1299 NestedNameSpecifier *Qualifier = 0;
1300 SourceRange QualifierRange;
John McCall10eae182009-11-30 22:42:35 +00001301 if (SS.isSet()) {
1302 Qualifier = (NestedNameSpecifier *) SS.getScopeRep();
1303 QualifierRange = SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00001304 }
Mike Stump11289f42009-09-09 15:08:12 +00001305
John McCalle66edc12009-11-24 19:00:30 +00001306 return MemberExpr::Create(C, Base, isArrow, Qualifier, QualifierRange,
1307 Member, Loc, TemplateArgs, Ty);
Douglas Gregorc1905232009-08-26 22:36:53 +00001308}
1309
John McCall2d74de92009-12-01 22:10:20 +00001310/// Builds an implicit member access expression. The current context
1311/// is known to be an instance method, and the given unqualified lookup
1312/// set is known to contain only instance members, at least one of which
1313/// is from an appropriate type.
John McCallb53bbd42009-11-22 01:44:31 +00001314Sema::OwningExprResult
John McCall2d74de92009-12-01 22:10:20 +00001315Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
1316 LookupResult &R,
1317 const TemplateArgumentListInfo *TemplateArgs,
1318 bool IsKnownInstance) {
John McCalle66edc12009-11-24 19:00:30 +00001319 assert(!R.empty() && !R.isAmbiguous());
1320
John McCalld14a8642009-11-21 08:51:07 +00001321 SourceLocation Loc = R.getNameLoc();
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00001322
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001323 // We may have found a field within an anonymous union or struct
1324 // (C++ [class.union]).
Douglas Gregor6493d9c2009-10-22 07:08:30 +00001325 // FIXME: This needs to happen post-isImplicitMemberReference?
John McCalle66edc12009-11-24 19:00:30 +00001326 // FIXME: template-ids inside anonymous structs?
John McCall10eae182009-11-30 22:42:35 +00001327 if (FieldDecl *FD = R.getAsSingle<FieldDecl>())
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001328 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
John McCallb53bbd42009-11-22 01:44:31 +00001329 return BuildAnonymousStructUnionMemberReference(Loc, FD);
Sebastian Redlffbcf962009-01-18 18:53:16 +00001330
John McCall2d74de92009-12-01 22:10:20 +00001331 // If this is known to be an instance access, go ahead and build a
1332 // 'this' expression now.
1333 QualType ThisType = cast<CXXMethodDecl>(CurContext)->getThisType(Context);
1334 Expr *This = 0; // null signifies implicit access
1335 if (IsKnownInstance) {
1336 This = new (Context) CXXThisExpr(SourceLocation(), ThisType);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00001337 }
1338
John McCall2d74de92009-12-01 22:10:20 +00001339 return BuildMemberReferenceExpr(ExprArg(*this, This), ThisType,
1340 /*OpLoc*/ SourceLocation(),
1341 /*IsArrow*/ true,
1342 SS, R, TemplateArgs);
John McCalld14a8642009-11-21 08:51:07 +00001343}
1344
John McCalle66edc12009-11-24 19:00:30 +00001345bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00001346 const LookupResult &R,
1347 bool HasTrailingLParen) {
John McCalld14a8642009-11-21 08:51:07 +00001348 // Only when used directly as the postfix-expression of a call.
1349 if (!HasTrailingLParen)
1350 return false;
1351
1352 // Never if a scope specifier was provided.
John McCalle66edc12009-11-24 19:00:30 +00001353 if (SS.isSet())
John McCalld14a8642009-11-21 08:51:07 +00001354 return false;
1355
1356 // Only in C++ or ObjC++.
John McCallb53bbd42009-11-22 01:44:31 +00001357 if (!getLangOptions().CPlusPlus)
John McCalld14a8642009-11-21 08:51:07 +00001358 return false;
1359
1360 // Turn off ADL when we find certain kinds of declarations during
1361 // normal lookup:
1362 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
1363 NamedDecl *D = *I;
1364
1365 // C++0x [basic.lookup.argdep]p3:
1366 // -- a declaration of a class member
1367 // Since using decls preserve this property, we check this on the
1368 // original decl.
John McCall57500772009-12-16 12:17:52 +00001369 if (D->isCXXClassMember())
John McCalld14a8642009-11-21 08:51:07 +00001370 return false;
1371
1372 // C++0x [basic.lookup.argdep]p3:
1373 // -- a block-scope function declaration that is not a
1374 // using-declaration
1375 // NOTE: we also trigger this for function templates (in fact, we
1376 // don't check the decl type at all, since all other decl types
1377 // turn off ADL anyway).
1378 if (isa<UsingShadowDecl>(D))
1379 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1380 else if (D->getDeclContext()->isFunctionOrMethod())
1381 return false;
1382
1383 // C++0x [basic.lookup.argdep]p3:
1384 // -- a declaration that is neither a function or a function
1385 // template
1386 // And also for builtin functions.
1387 if (isa<FunctionDecl>(D)) {
1388 FunctionDecl *FDecl = cast<FunctionDecl>(D);
1389
1390 // But also builtin functions.
1391 if (FDecl->getBuiltinID() && FDecl->isImplicit())
1392 return false;
1393 } else if (!isa<FunctionTemplateDecl>(D))
1394 return false;
1395 }
1396
1397 return true;
1398}
1399
1400
John McCalld14a8642009-11-21 08:51:07 +00001401/// Diagnoses obvious problems with the use of the given declaration
1402/// as an expression. This is only actually called for lookups that
1403/// were not overloaded, and it doesn't promise that the declaration
1404/// will in fact be used.
1405static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
1406 if (isa<TypedefDecl>(D)) {
1407 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
1408 return true;
1409 }
1410
1411 if (isa<ObjCInterfaceDecl>(D)) {
1412 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
1413 return true;
1414 }
1415
1416 if (isa<NamespaceDecl>(D)) {
1417 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
1418 return true;
1419 }
1420
1421 return false;
1422}
1423
1424Sema::OwningExprResult
John McCalle66edc12009-11-24 19:00:30 +00001425Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00001426 LookupResult &R,
1427 bool NeedsADL) {
John McCall3a60c872009-12-08 22:45:53 +00001428 // If this is a single, fully-resolved result and we don't need ADL,
1429 // just build an ordinary singleton decl ref.
1430 if (!NeedsADL && R.isSingleResult())
John McCallb53bbd42009-11-22 01:44:31 +00001431 return BuildDeclarationNameExpr(SS, R.getNameLoc(), R.getFoundDecl());
John McCalld14a8642009-11-21 08:51:07 +00001432
1433 // We only need to check the declaration if there's exactly one
1434 // result, because in the overloaded case the results can only be
1435 // functions and function templates.
John McCallb53bbd42009-11-22 01:44:31 +00001436 if (R.isSingleResult() &&
1437 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCalld14a8642009-11-21 08:51:07 +00001438 return ExprError();
1439
John McCalle66edc12009-11-24 19:00:30 +00001440 bool Dependent
1441 = UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(), 0);
John McCalld14a8642009-11-21 08:51:07 +00001442 UnresolvedLookupExpr *ULE
John McCalle66edc12009-11-24 19:00:30 +00001443 = UnresolvedLookupExpr::Create(Context, Dependent,
1444 (NestedNameSpecifier*) SS.getScopeRep(),
1445 SS.getRange(),
John McCallb53bbd42009-11-22 01:44:31 +00001446 R.getLookupName(), R.getNameLoc(),
1447 NeedsADL, R.isOverloadedResult());
1448 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1449 ULE->addDecl(*I);
John McCalld14a8642009-11-21 08:51:07 +00001450
1451 return Owned(ULE);
1452}
1453
1454
1455/// \brief Complete semantic analysis for a reference to the given declaration.
1456Sema::OwningExprResult
John McCalle66edc12009-11-24 19:00:30 +00001457Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCalld14a8642009-11-21 08:51:07 +00001458 SourceLocation Loc, NamedDecl *D) {
1459 assert(D && "Cannot refer to a NULL declaration");
John McCall283b9012009-11-22 00:44:51 +00001460 assert(!isa<FunctionTemplateDecl>(D) &&
1461 "Cannot refer unambiguously to a function template");
John McCalld14a8642009-11-21 08:51:07 +00001462
1463 if (CheckDeclInExpr(*this, Loc, D))
1464 return ExprError();
Steve Narofff1e53692007-03-23 22:27:02 +00001465
Douglas Gregore7488b92009-12-01 16:58:18 +00001466 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
1467 // Specifically diagnose references to class templates that are missing
1468 // a template argument list.
1469 Diag(Loc, diag::err_template_decl_ref)
1470 << Template << SS.getRange();
1471 Diag(Template->getLocation(), diag::note_template_decl_here);
1472 return ExprError();
1473 }
1474
1475 // Make sure that we're referring to a value.
1476 ValueDecl *VD = dyn_cast<ValueDecl>(D);
1477 if (!VD) {
1478 Diag(Loc, diag::err_ref_non_value)
1479 << D << SS.getRange();
John McCallb48971d2009-12-18 18:35:10 +00001480 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregore7488b92009-12-01 16:58:18 +00001481 return ExprError();
1482 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00001483
Douglas Gregor171c45a2009-02-18 21:56:37 +00001484 // Check whether this declaration can be used. Note that we suppress
1485 // this check when we're going to perform argument-dependent lookup
1486 // on this function name, because this might not be the function
1487 // that overload resolution actually selects.
John McCalld14a8642009-11-21 08:51:07 +00001488 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor171c45a2009-02-18 21:56:37 +00001489 return ExprError();
1490
Steve Naroff8de9c3a2008-09-05 22:11:13 +00001491 // Only create DeclRefExpr's for valid Decl's.
1492 if (VD->isInvalidDecl())
Sebastian Redlffbcf962009-01-18 18:53:16 +00001493 return ExprError();
1494
Chris Lattner2a9d9892008-10-20 05:16:36 +00001495 // If the identifier reference is inside a block, and it refers to a value
1496 // that is outside the block, create a BlockDeclRefExpr instead of a
1497 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
1498 // the block is formed.
Steve Naroff8de9c3a2008-09-05 22:11:13 +00001499 //
Chris Lattner2a9d9892008-10-20 05:16:36 +00001500 // We do not do this for things like enum constants, global variables, etc,
1501 // as they do not get snapshotted.
1502 //
1503 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00001504 MarkDeclarationReferenced(Loc, VD);
Eli Friedman7fa3faa2009-03-22 23:00:19 +00001505 QualType ExprTy = VD->getType().getNonReferenceType();
Steve Naroff1d95e5a2008-10-10 01:28:17 +00001506 // The BlocksAttr indicates the variable is bound by-reference.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001507 if (VD->getAttr<BlocksAttr>())
Eli Friedman7fa3faa2009-03-22 23:00:19 +00001508 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, true));
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00001509 // This is to record that a 'const' was actually synthesize and added.
1510 bool constAdded = !ExprTy.isConstQualified();
Steve Naroff1d95e5a2008-10-10 01:28:17 +00001511 // Variable will be bound by-copy, make it const within the closure.
Mike Stump11289f42009-09-09 15:08:12 +00001512
Eli Friedman7fa3faa2009-03-22 23:00:19 +00001513 ExprTy.addConst();
Mike Stump11289f42009-09-09 15:08:12 +00001514 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, false,
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00001515 constAdded));
Steve Naroff1d95e5a2008-10-10 01:28:17 +00001516 }
1517 // If this reference is not in a block or if the referenced variable is
1518 // within the block, create a normal DeclRefExpr.
Douglas Gregor4619e432008-12-05 23:32:09 +00001519
John McCalle66edc12009-11-24 19:00:30 +00001520 return BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc, &SS);
Chris Lattner17ed4872006-11-20 04:58:19 +00001521}
Chris Lattnere168f762006-11-10 05:29:30 +00001522
Sebastian Redlffbcf962009-01-18 18:53:16 +00001523Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
1524 tok::TokenKind Kind) {
Chris Lattner6307f192008-08-10 01:53:14 +00001525 PredefinedExpr::IdentType IT;
Sebastian Redlffbcf962009-01-18 18:53:16 +00001526
Chris Lattnere168f762006-11-10 05:29:30 +00001527 switch (Kind) {
Chris Lattner317e6ba2008-01-12 18:39:25 +00001528 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner6307f192008-08-10 01:53:14 +00001529 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
1530 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
1531 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattnere168f762006-11-10 05:29:30 +00001532 }
Chris Lattner317e6ba2008-01-12 18:39:25 +00001533
Chris Lattnera81a0272008-01-12 08:14:25 +00001534 // Pre-defined identifiers are of type char[x], where x is the length of the
1535 // string.
Mike Stump11289f42009-09-09 15:08:12 +00001536
Anders Carlsson2fb08242009-09-08 18:24:21 +00001537 Decl *currentDecl = getCurFunctionOrMethodDecl();
1538 if (!currentDecl) {
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00001539 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson2fb08242009-09-08 18:24:21 +00001540 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00001541 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00001542
Anders Carlsson0b209a82009-09-11 01:22:35 +00001543 QualType ResTy;
1544 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
1545 ResTy = Context.DependentTy;
1546 } else {
1547 unsigned Length =
1548 PredefinedExpr::ComputeName(Context, IT, currentDecl).length();
Sebastian Redlffbcf962009-01-18 18:53:16 +00001549
Anders Carlsson0b209a82009-09-11 01:22:35 +00001550 llvm::APInt LengthI(32, Length + 1);
John McCall8ccfcb52009-09-24 19:53:00 +00001551 ResTy = Context.CharTy.withConst();
Anders Carlsson0b209a82009-09-11 01:22:35 +00001552 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
1553 }
Steve Narofff6009ed2009-01-21 00:14:39 +00001554 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattnere168f762006-11-10 05:29:30 +00001555}
1556
Sebastian Redlffbcf962009-01-18 18:53:16 +00001557Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00001558 llvm::SmallString<16> CharBuffer;
Steve Naroffae4143e2007-04-26 20:39:23 +00001559 CharBuffer.resize(Tok.getLength());
1560 const char *ThisTokBegin = &CharBuffer[0];
1561 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlffbcf962009-01-18 18:53:16 +00001562
Steve Naroffae4143e2007-04-26 20:39:23 +00001563 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1564 Tok.getLocation(), PP);
1565 if (Literal.hadError())
Sebastian Redlffbcf962009-01-18 18:53:16 +00001566 return ExprError();
Chris Lattneref24b382008-03-01 08:32:21 +00001567
Chris Lattnerc3847ba2009-12-30 21:19:39 +00001568 QualType Ty;
1569 if (!getLangOptions().CPlusPlus)
1570 Ty = Context.IntTy; // 'x' and L'x' -> int in C.
1571 else if (Literal.isWide())
1572 Ty = Context.WCharTy; // L'x' -> wchar_t in C++.
1573 else
1574 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattneref24b382008-03-01 08:32:21 +00001575
Sebastian Redl20614a72009-01-20 22:23:13 +00001576 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
1577 Literal.isWide(),
Chris Lattnerc3847ba2009-12-30 21:19:39 +00001578 Ty, Tok.getLocation()));
Steve Naroffae4143e2007-04-26 20:39:23 +00001579}
1580
Sebastian Redlffbcf962009-01-18 18:53:16 +00001581Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
1582 // Fast path for a single digit (which is quite common). A single digit
Steve Narofff2fb89e2007-03-13 20:29:44 +00001583 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
1584 if (Tok.getLength() == 1) {
Chris Lattner9240b3e2009-01-26 22:36:52 +00001585 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattnerc4c18192009-01-16 07:10:29 +00001586 unsigned IntSize = Context.Target.getIntWidth();
Steve Narofff6009ed2009-01-21 00:14:39 +00001587 return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
Steve Naroff5faaef72009-01-20 19:53:53 +00001588 Context.IntTy, Tok.getLocation()));
Steve Narofff2fb89e2007-03-13 20:29:44 +00001589 }
Ted Kremeneke9814182009-01-13 23:19:12 +00001590
Chris Lattner23b7eb62007-06-15 23:05:46 +00001591 llvm::SmallString<512> IntegerBuffer;
Chris Lattnera1cf5f92008-09-30 20:53:45 +00001592 // Add padding so that NumericLiteralParser can overread by one character.
1593 IntegerBuffer.resize(Tok.getLength()+1);
Steve Naroff8160ea22007-03-06 01:09:46 +00001594 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlffbcf962009-01-18 18:53:16 +00001595
Chris Lattner67ca9252007-05-21 01:08:44 +00001596 // Get the spelling of the token, which eliminates trigraphs, etc.
Steve Naroff8160ea22007-03-06 01:09:46 +00001597 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlffbcf962009-01-18 18:53:16 +00001598
Mike Stump11289f42009-09-09 15:08:12 +00001599 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Steve Naroff451d8f162007-03-12 23:22:38 +00001600 Tok.getLocation(), PP);
Steve Narofff2fb89e2007-03-13 20:29:44 +00001601 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +00001602 return ExprError();
1603
Chris Lattner1c20a172007-08-26 03:42:43 +00001604 Expr *Res;
Sebastian Redlffbcf962009-01-18 18:53:16 +00001605
Chris Lattner1c20a172007-08-26 03:42:43 +00001606 if (Literal.isFloatingLiteral()) {
Chris Lattnerec0a6d92007-09-22 18:29:59 +00001607 QualType Ty;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001608 if (Literal.isFloat)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00001609 Ty = Context.FloatTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001610 else if (!Literal.isLong)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00001611 Ty = Context.DoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001612 else
Chris Lattner7570e9c2008-03-08 08:52:55 +00001613 Ty = Context.LongDoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001614
1615 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
1616
John McCall53b93a02009-12-24 09:08:04 +00001617 using llvm::APFloat;
1618 APFloat Val(Format);
1619
1620 APFloat::opStatus result = Literal.GetFloatValue(Val);
John McCall122c8312009-12-24 11:09:08 +00001621
1622 // Overflow is always an error, but underflow is only an error if
1623 // we underflowed to zero (APFloat reports denormals as underflow).
1624 if ((result & APFloat::opOverflow) ||
1625 ((result & APFloat::opUnderflow) && Val.isZero())) {
John McCall53b93a02009-12-24 09:08:04 +00001626 unsigned diagnostic;
1627 llvm::SmallVector<char, 20> buffer;
1628 if (result & APFloat::opOverflow) {
1629 diagnostic = diag::err_float_overflow;
1630 APFloat::getLargest(Format).toString(buffer);
1631 } else {
1632 diagnostic = diag::err_float_underflow;
1633 APFloat::getSmallest(Format).toString(buffer);
1634 }
1635
1636 Diag(Tok.getLocation(), diagnostic)
1637 << Ty
1638 << llvm::StringRef(buffer.data(), buffer.size());
1639 }
1640
1641 bool isExact = (result == APFloat::opOK);
Chris Lattnere4edb8e2009-06-29 17:34:55 +00001642 Res = new (Context) FloatingLiteral(Val, isExact, Ty, Tok.getLocation());
Sebastian Redlffbcf962009-01-18 18:53:16 +00001643
Chris Lattner1c20a172007-08-26 03:42:43 +00001644 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00001645 return ExprError();
Chris Lattner1c20a172007-08-26 03:42:43 +00001646 } else {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001647 QualType Ty;
Chris Lattner67ca9252007-05-21 01:08:44 +00001648
Neil Boothac582c52007-08-29 22:00:19 +00001649 // long long is a C99 feature.
1650 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth4a1ee052007-08-29 22:13:52 +00001651 Literal.isLongLong)
Neil Boothac582c52007-08-29 22:00:19 +00001652 Diag(Tok.getLocation(), diag::ext_longlong);
1653
Chris Lattner67ca9252007-05-21 01:08:44 +00001654 // Get the value in the widest-possible width.
Chris Lattner37e05872008-03-05 18:54:05 +00001655 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlffbcf962009-01-18 18:53:16 +00001656
Chris Lattner67ca9252007-05-21 01:08:44 +00001657 if (Literal.GetIntegerValue(ResultVal)) {
1658 // If this value didn't fit into uintmax_t, warn and force to ull.
1659 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001660 Ty = Context.UnsignedLongLongTy;
1661 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner37e05872008-03-05 18:54:05 +00001662 "long long is not intmax_t?");
Steve Naroff09ef4742007-03-09 23:16:33 +00001663 } else {
Chris Lattner67ca9252007-05-21 01:08:44 +00001664 // If this value fits into a ULL, try to figure out what else it fits into
1665 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlffbcf962009-01-18 18:53:16 +00001666
Chris Lattner67ca9252007-05-21 01:08:44 +00001667 // Octal, Hexadecimal, and integers with a U suffix are allowed to
1668 // be an unsigned int.
1669 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
1670
1671 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner55258cf2008-05-09 05:59:00 +00001672 unsigned Width = 0;
Chris Lattner7b939cf2007-08-23 21:58:08 +00001673 if (!Literal.isLong && !Literal.isLongLong) {
1674 // Are int/unsigned possibilities?
Chris Lattner55258cf2008-05-09 05:59:00 +00001675 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00001676
Chris Lattner67ca9252007-05-21 01:08:44 +00001677 // Does it fit in a unsigned int?
1678 if (ResultVal.isIntN(IntSize)) {
1679 // Does it fit in a signed int?
1680 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001681 Ty = Context.IntTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00001682 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001683 Ty = Context.UnsignedIntTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00001684 Width = IntSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00001685 }
Chris Lattner67ca9252007-05-21 01:08:44 +00001686 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00001687
Chris Lattner67ca9252007-05-21 01:08:44 +00001688 // Are long/unsigned long possibilities?
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001689 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner55258cf2008-05-09 05:59:00 +00001690 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00001691
Chris Lattner67ca9252007-05-21 01:08:44 +00001692 // Does it fit in a unsigned long?
1693 if (ResultVal.isIntN(LongSize)) {
1694 // Does it fit in a signed long?
1695 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001696 Ty = Context.LongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00001697 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001698 Ty = Context.UnsignedLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00001699 Width = LongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00001700 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00001701 }
1702
Chris Lattner67ca9252007-05-21 01:08:44 +00001703 // Finally, check long long if needed.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001704 if (Ty.isNull()) {
Chris Lattner55258cf2008-05-09 05:59:00 +00001705 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00001706
Chris Lattner67ca9252007-05-21 01:08:44 +00001707 // Does it fit in a unsigned long long?
1708 if (ResultVal.isIntN(LongLongSize)) {
1709 // Does it fit in a signed long long?
1710 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001711 Ty = Context.LongLongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00001712 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001713 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00001714 Width = LongLongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00001715 }
1716 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00001717
Chris Lattner67ca9252007-05-21 01:08:44 +00001718 // If we still couldn't decide a type, we probably have something that
1719 // does not fit in a signed long long, but has no U suffix.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001720 if (Ty.isNull()) {
Chris Lattner67ca9252007-05-21 01:08:44 +00001721 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001722 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00001723 Width = Context.Target.getLongLongWidth();
Chris Lattner67ca9252007-05-21 01:08:44 +00001724 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00001725
Chris Lattner55258cf2008-05-09 05:59:00 +00001726 if (ResultVal.getBitWidth() != Width)
1727 ResultVal.trunc(Width);
Steve Naroff09ef4742007-03-09 23:16:33 +00001728 }
Sebastian Redl20614a72009-01-20 22:23:13 +00001729 Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Steve Naroff09ef4742007-03-09 23:16:33 +00001730 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00001731
Chris Lattner1c20a172007-08-26 03:42:43 +00001732 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
1733 if (Literal.isImaginary)
Mike Stump11289f42009-09-09 15:08:12 +00001734 Res = new (Context) ImaginaryLiteral(Res,
Steve Narofff6009ed2009-01-21 00:14:39 +00001735 Context.getComplexType(Res->getType()));
Sebastian Redlffbcf962009-01-18 18:53:16 +00001736
1737 return Owned(Res);
Chris Lattnere168f762006-11-10 05:29:30 +00001738}
1739
Sebastian Redlffbcf962009-01-18 18:53:16 +00001740Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1741 SourceLocation R, ExprArg Val) {
Anders Carlssonb781bcd2009-05-01 19:49:17 +00001742 Expr *E = Val.takeAs<Expr>();
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001743 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Narofff6009ed2009-01-21 00:14:39 +00001744 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattnere168f762006-11-10 05:29:30 +00001745}
1746
Steve Naroff71b59a92007-06-04 22:22:31 +00001747/// The UsualUnaryConversions() function is *not* called by this routine.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00001748/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001749bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Sebastian Redl6f282892008-11-11 17:56:53 +00001750 SourceLocation OpLoc,
1751 const SourceRange &ExprRange,
1752 bool isSizeof) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001753 if (exprType->isDependentType())
1754 return false;
1755
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001756 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
1757 // the result is the size of the referenced type."
1758 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
1759 // result shall be the alignment of the referenced type."
1760 if (const ReferenceType *Ref = exprType->getAs<ReferenceType>())
1761 exprType = Ref->getPointeeType();
1762
Steve Naroff043d45d2007-05-15 02:32:35 +00001763 // C99 6.5.3.4p1:
John McCall4c98fd82009-11-04 07:28:41 +00001764 if (exprType->isFunctionType()) {
Chris Lattner62975a72009-04-24 00:30:45 +00001765 // alignof(function) is allowed as an extension.
Chris Lattnerb1355b12009-01-24 19:46:37 +00001766 if (isSizeof)
1767 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
1768 return false;
1769 }
Mike Stump11289f42009-09-09 15:08:12 +00001770
Chris Lattner62975a72009-04-24 00:30:45 +00001771 // Allow sizeof(void)/alignof(void) as an extension.
Chris Lattnerb1355b12009-01-24 19:46:37 +00001772 if (exprType->isVoidType()) {
Chris Lattner3b054132008-11-19 05:08:23 +00001773 Diag(OpLoc, diag::ext_sizeof_void_type)
1774 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattnerb1355b12009-01-24 19:46:37 +00001775 return false;
1776 }
Mike Stump11289f42009-09-09 15:08:12 +00001777
Chris Lattner62975a72009-04-24 00:30:45 +00001778 if (RequireCompleteType(OpLoc, exprType,
Douglas Gregor906db8a2009-12-15 16:44:32 +00001779 PDiag(diag::err_sizeof_alignof_incomplete_type)
1780 << int(!isSizeof) << ExprRange))
Chris Lattner62975a72009-04-24 00:30:45 +00001781 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001782
Chris Lattner62975a72009-04-24 00:30:45 +00001783 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
Fariborz Jahanian1dcb3222009-04-24 17:34:33 +00001784 if (LangOpts.ObjCNonFragileABI && exprType->isObjCInterfaceType()) {
Chris Lattner62975a72009-04-24 00:30:45 +00001785 Diag(OpLoc, diag::err_sizeof_nonfragile_interface)
Chris Lattnercd2a8c52009-04-24 22:30:50 +00001786 << exprType << isSizeof << ExprRange;
1787 return true;
Chris Lattner37920f52009-04-21 19:55:16 +00001788 }
Mike Stump11289f42009-09-09 15:08:12 +00001789
Chris Lattner62975a72009-04-24 00:30:45 +00001790 return false;
Steve Naroff043d45d2007-05-15 02:32:35 +00001791}
1792
Chris Lattner8dff0172009-01-24 20:17:12 +00001793bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
1794 const SourceRange &ExprRange) {
1795 E = E->IgnoreParens();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001796
Mike Stump11289f42009-09-09 15:08:12 +00001797 // alignof decl is always ok.
Chris Lattner8dff0172009-01-24 20:17:12 +00001798 if (isa<DeclRefExpr>(E))
1799 return false;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001800
1801 // Cannot know anything else if the expression is dependent.
1802 if (E->isTypeDependent())
1803 return false;
1804
Douglas Gregor71235ec2009-05-02 02:18:30 +00001805 if (E->getBitField()) {
1806 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
1807 return true;
Chris Lattner8dff0172009-01-24 20:17:12 +00001808 }
Douglas Gregor71235ec2009-05-02 02:18:30 +00001809
1810 // Alignment of a field access is always okay, so long as it isn't a
1811 // bit-field.
1812 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump212005c2009-07-22 18:58:19 +00001813 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor71235ec2009-05-02 02:18:30 +00001814 return false;
1815
Chris Lattner8dff0172009-01-24 20:17:12 +00001816 return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
1817}
1818
Douglas Gregor0950e412009-03-13 21:01:28 +00001819/// \brief Build a sizeof or alignof expression given a type operand.
Mike Stump11289f42009-09-09 15:08:12 +00001820Action::OwningExprResult
John McCallbcd03502009-12-07 02:54:59 +00001821Sema::CreateSizeOfAlignOfExpr(TypeSourceInfo *TInfo,
John McCall4c98fd82009-11-04 07:28:41 +00001822 SourceLocation OpLoc,
Douglas Gregor0950e412009-03-13 21:01:28 +00001823 bool isSizeOf, SourceRange R) {
John McCallbcd03502009-12-07 02:54:59 +00001824 if (!TInfo)
Douglas Gregor0950e412009-03-13 21:01:28 +00001825 return ExprError();
1826
John McCallbcd03502009-12-07 02:54:59 +00001827 QualType T = TInfo->getType();
John McCall4c98fd82009-11-04 07:28:41 +00001828
Douglas Gregor0950e412009-03-13 21:01:28 +00001829 if (!T->isDependentType() &&
1830 CheckSizeOfAlignOfOperand(T, OpLoc, R, isSizeOf))
1831 return ExprError();
1832
1833 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
John McCallbcd03502009-12-07 02:54:59 +00001834 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, TInfo,
Douglas Gregor0950e412009-03-13 21:01:28 +00001835 Context.getSizeType(), OpLoc,
1836 R.getEnd()));
1837}
1838
1839/// \brief Build a sizeof or alignof expression given an expression
1840/// operand.
Mike Stump11289f42009-09-09 15:08:12 +00001841Action::OwningExprResult
1842Sema::CreateSizeOfAlignOfExpr(Expr *E, SourceLocation OpLoc,
Douglas Gregor0950e412009-03-13 21:01:28 +00001843 bool isSizeOf, SourceRange R) {
1844 // Verify that the operand is valid.
1845 bool isInvalid = false;
1846 if (E->isTypeDependent()) {
1847 // Delay type-checking for type-dependent expressions.
1848 } else if (!isSizeOf) {
1849 isInvalid = CheckAlignOfExpr(E, OpLoc, R);
Douglas Gregor71235ec2009-05-02 02:18:30 +00001850 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Douglas Gregor0950e412009-03-13 21:01:28 +00001851 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
1852 isInvalid = true;
1853 } else {
1854 isInvalid = CheckSizeOfAlignOfOperand(E->getType(), OpLoc, R, true);
1855 }
1856
1857 if (isInvalid)
1858 return ExprError();
1859
1860 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1861 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, E,
1862 Context.getSizeType(), OpLoc,
1863 R.getEnd()));
1864}
1865
Sebastian Redl6f282892008-11-11 17:56:53 +00001866/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1867/// the same for @c alignof and @c __alignof
1868/// Note that the ArgRange is invalid if isType is false.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001869Action::OwningExprResult
Sebastian Redl6f282892008-11-11 17:56:53 +00001870Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1871 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner0d8b1a12006-11-20 04:34:45 +00001872 // If error parsing type, ignore.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001873 if (TyOrEx == 0) return ExprError();
Steve Naroff043d45d2007-05-15 02:32:35 +00001874
Sebastian Redl6f282892008-11-11 17:56:53 +00001875 if (isType) {
John McCallbcd03502009-12-07 02:54:59 +00001876 TypeSourceInfo *TInfo;
1877 (void) GetTypeFromParser(TyOrEx, &TInfo);
1878 return CreateSizeOfAlignOfExpr(TInfo, OpLoc, isSizeof, ArgRange);
Mike Stump11289f42009-09-09 15:08:12 +00001879 }
Sebastian Redl6f282892008-11-11 17:56:53 +00001880
Douglas Gregor0950e412009-03-13 21:01:28 +00001881 Expr *ArgEx = (Expr *)TyOrEx;
1882 Action::OwningExprResult Result
1883 = CreateSizeOfAlignOfExpr(ArgEx, OpLoc, isSizeof, ArgEx->getSourceRange());
1884
1885 if (Result.isInvalid())
1886 DeleteExpr(ArgEx);
1887
1888 return move(Result);
Chris Lattnere168f762006-11-10 05:29:30 +00001889}
1890
Chris Lattner709322b2009-02-17 08:12:06 +00001891QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc, bool isReal) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001892 if (V->isTypeDependent())
1893 return Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00001894
Chris Lattnere267f5d2007-08-26 05:39:26 +00001895 // These operators return the element type of a complex type.
John McCall9dd450b2009-09-21 23:43:11 +00001896 if (const ComplexType *CT = V->getType()->getAs<ComplexType>())
Chris Lattner30b5dd02007-08-24 21:16:53 +00001897 return CT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00001898
Chris Lattnere267f5d2007-08-26 05:39:26 +00001899 // Otherwise they pass through real integer and floating point types here.
1900 if (V->getType()->isArithmeticType())
1901 return V->getType();
Mike Stump11289f42009-09-09 15:08:12 +00001902
Chris Lattnere267f5d2007-08-26 05:39:26 +00001903 // Reject anything else.
Chris Lattner709322b2009-02-17 08:12:06 +00001904 Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
1905 << (isReal ? "__real" : "__imag");
Chris Lattnere267f5d2007-08-26 05:39:26 +00001906 return QualType();
Chris Lattner30b5dd02007-08-24 21:16:53 +00001907}
1908
1909
Chris Lattnere168f762006-11-10 05:29:30 +00001910
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001911Action::OwningExprResult
1912Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
1913 tok::TokenKind Kind, ExprArg Input) {
Chris Lattnere168f762006-11-10 05:29:30 +00001914 UnaryOperator::Opcode Opc;
1915 switch (Kind) {
1916 default: assert(0 && "Unknown unary op!");
1917 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
1918 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1919 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001920
Eli Friedmancfdd40c2009-11-18 03:38:04 +00001921 return BuildUnaryOp(S, OpLoc, Opc, move(Input));
Chris Lattnere168f762006-11-10 05:29:30 +00001922}
1923
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001924Action::OwningExprResult
1925Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
1926 ExprArg Idx, SourceLocation RLoc) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00001927 // Since this might be a postfix expression, get rid of ParenListExprs.
1928 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
1929
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001930 Expr *LHSExp = static_cast<Expr*>(Base.get()),
1931 *RHSExp = static_cast<Expr*>(Idx.get());
Mike Stump11289f42009-09-09 15:08:12 +00001932
Douglas Gregor40412ac2008-11-19 17:17:41 +00001933 if (getLangOptions().CPlusPlus &&
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00001934 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
1935 Base.release();
1936 Idx.release();
1937 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
1938 Context.DependentTy, RLoc));
1939 }
1940
Mike Stump11289f42009-09-09 15:08:12 +00001941 if (getLangOptions().CPlusPlus &&
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001942 (LHSExp->getType()->isRecordType() ||
Eli Friedman254a1a22008-12-15 22:34:21 +00001943 LHSExp->getType()->isEnumeralType() ||
1944 RHSExp->getType()->isRecordType() ||
1945 RHSExp->getType()->isEnumeralType())) {
Sebastian Redladba46e2009-10-29 20:17:01 +00001946 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, move(Base),move(Idx));
Douglas Gregor40412ac2008-11-19 17:17:41 +00001947 }
1948
Sebastian Redladba46e2009-10-29 20:17:01 +00001949 return CreateBuiltinArraySubscriptExpr(move(Base), LLoc, move(Idx), RLoc);
1950}
1951
1952
1953Action::OwningExprResult
1954Sema::CreateBuiltinArraySubscriptExpr(ExprArg Base, SourceLocation LLoc,
1955 ExprArg Idx, SourceLocation RLoc) {
1956 Expr *LHSExp = static_cast<Expr*>(Base.get());
1957 Expr *RHSExp = static_cast<Expr*>(Idx.get());
1958
Chris Lattner36d572b2007-07-16 00:14:47 +00001959 // Perform default conversions.
1960 DefaultFunctionArrayConversion(LHSExp);
1961 DefaultFunctionArrayConversion(RHSExp);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001962
Chris Lattner36d572b2007-07-16 00:14:47 +00001963 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
Steve Narofff1e53692007-03-23 22:27:02 +00001964
Steve Naroffc1aadb12007-03-28 21:49:40 +00001965 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattnerf17bd422007-08-30 17:45:32 +00001966 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stump4e1f26a2009-02-19 03:04:26 +00001967 // in the subscript position. As a result, we need to derive the array base
Steve Narofff1e53692007-03-23 22:27:02 +00001968 // and index from the expression types.
Chris Lattner36d572b2007-07-16 00:14:47 +00001969 Expr *BaseExpr, *IndexExpr;
1970 QualType ResultType;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001971 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
1972 BaseExpr = LHSExp;
1973 IndexExpr = RHSExp;
1974 ResultType = Context.DependentTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001975 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner36d572b2007-07-16 00:14:47 +00001976 BaseExpr = LHSExp;
1977 IndexExpr = RHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00001978 ResultType = PTy->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001979 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattneraee0cfd2007-07-16 00:23:25 +00001980 // Handle the uncommon case of "123[Ptr]".
Chris Lattner36d572b2007-07-16 00:14:47 +00001981 BaseExpr = RHSExp;
1982 IndexExpr = LHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00001983 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00001984 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00001985 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001986 BaseExpr = LHSExp;
1987 IndexExpr = RHSExp;
1988 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00001989 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00001990 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001991 // Handle the uncommon case of "123[Ptr]".
1992 BaseExpr = RHSExp;
1993 IndexExpr = LHSExp;
1994 ResultType = PTy->getPointeeType();
John McCall9dd450b2009-09-21 23:43:11 +00001995 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattner41977962007-07-31 19:29:30 +00001996 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner36d572b2007-07-16 00:14:47 +00001997 IndexExpr = RHSExp;
Nate Begemanc1bf0612009-01-18 00:45:31 +00001998
Chris Lattner36d572b2007-07-16 00:14:47 +00001999 // FIXME: need to deal with const...
2000 ResultType = VTy->getElementType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00002001 } else if (LHSTy->isArrayType()) {
2002 // If we see an array that wasn't promoted by
2003 // DefaultFunctionArrayConversion, it must be an array that
2004 // wasn't promoted because of the C90 rule that doesn't
2005 // allow promoting non-lvalue arrays. Warn, then
2006 // force the promotion here.
2007 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
2008 LHSExp->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00002009 ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
2010 CastExpr::CK_ArrayToPointerDecay);
Eli Friedmanab2784f2009-04-25 23:46:54 +00002011 LHSTy = LHSExp->getType();
2012
2013 BaseExpr = LHSExp;
2014 IndexExpr = RHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002015 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00002016 } else if (RHSTy->isArrayType()) {
2017 // Same as previous, except for 123[f().a] case
2018 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
2019 RHSExp->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00002020 ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
2021 CastExpr::CK_ArrayToPointerDecay);
Eli Friedmanab2784f2009-04-25 23:46:54 +00002022 RHSTy = RHSExp->getType();
2023
2024 BaseExpr = RHSExp;
2025 IndexExpr = LHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002026 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroffb3096442007-06-09 03:47:53 +00002027 } else {
Chris Lattner003af242009-04-25 22:50:55 +00002028 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
2029 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002030 }
Steve Naroffc1aadb12007-03-28 21:49:40 +00002031 // C99 6.5.2.1p1
Nate Begeman5ec4b312009-08-10 23:49:36 +00002032 if (!(IndexExpr->getType()->isIntegerType() &&
2033 IndexExpr->getType()->isScalarType()) && !IndexExpr->isTypeDependent())
Chris Lattner003af242009-04-25 22:50:55 +00002034 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
2035 << IndexExpr->getSourceRange());
Steve Naroffb29cdd52007-07-10 18:23:31 +00002036
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00002037 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinigb7608d72009-09-14 20:14:57 +00002038 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
2039 && !IndexExpr->isTypeDependent())
Sam Weinig914244e2009-09-14 01:58:58 +00002040 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
2041
Douglas Gregorac1fb652009-03-24 19:52:54 +00002042 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump11289f42009-09-09 15:08:12 +00002043 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
2044 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregorac1fb652009-03-24 19:52:54 +00002045 // incomplete types are not object types.
2046 if (ResultType->isFunctionType()) {
2047 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
2048 << ResultType << BaseExpr->getSourceRange();
2049 return ExprError();
2050 }
Mike Stump11289f42009-09-09 15:08:12 +00002051
Douglas Gregorac1fb652009-03-24 19:52:54 +00002052 if (!ResultType->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00002053 RequireCompleteType(LLoc, ResultType,
Anders Carlssond624e162009-08-26 23:45:07 +00002054 PDiag(diag::err_subscript_incomplete_type)
2055 << BaseExpr->getSourceRange()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00002056 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00002057
Chris Lattner62975a72009-04-24 00:30:45 +00002058 // Diagnose bad cases where we step over interface counts.
2059 if (ResultType->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
2060 Diag(LLoc, diag::err_subscript_nonfragile_interface)
2061 << ResultType << BaseExpr->getSourceRange();
2062 return ExprError();
2063 }
Mike Stump11289f42009-09-09 15:08:12 +00002064
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002065 Base.release();
2066 Idx.release();
Mike Stump4e1f26a2009-02-19 03:04:26 +00002067 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
Steve Narofff6009ed2009-01-21 00:14:39 +00002068 ResultType, RLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00002069}
2070
Steve Narofff8fd09e2007-07-27 22:15:19 +00002071QualType Sema::
Nate Begemance4d7fc2008-04-18 23:10:10 +00002072CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00002073 const IdentifierInfo *CompName,
Anders Carlssonf571c112009-08-26 18:25:21 +00002074 SourceLocation CompLoc) {
Daniel Dunbarc0429402009-10-18 02:09:38 +00002075 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
2076 // see FIXME there.
2077 //
2078 // FIXME: This logic can be greatly simplified by splitting it along
2079 // halving/not halving and reworking the component checking.
John McCall9dd450b2009-09-21 23:43:11 +00002080 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
Nate Begemanf322eab2008-05-09 06:41:27 +00002081
Steve Narofff8fd09e2007-07-27 22:15:19 +00002082 // The vector accessor can't exceed the number of elements.
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002083 const char *compStr = CompName->getNameStart();
Nate Begemanbb70bf62009-01-18 01:47:54 +00002084
Mike Stump4e1f26a2009-02-19 03:04:26 +00002085 // This flag determines whether or not the component is one of the four
Nate Begemanbb70bf62009-01-18 01:47:54 +00002086 // special names that indicate a subset of exactly half the elements are
2087 // to be selected.
2088 bool HalvingSwizzle = false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00002089
Nate Begemanbb70bf62009-01-18 01:47:54 +00002090 // This flag determines whether or not CompName has an 's' char prefix,
2091 // indicating that it is a string of hex values to be used as vector indices.
Nate Begeman0359e122009-06-25 21:06:09 +00002092 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
Nate Begemanf322eab2008-05-09 06:41:27 +00002093
2094 // Check that we've found one of the special components, or that the component
2095 // names must come from the same set.
Mike Stump4e1f26a2009-02-19 03:04:26 +00002096 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begemanbb70bf62009-01-18 01:47:54 +00002097 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
2098 HalvingSwizzle = true;
Nate Begemanf322eab2008-05-09 06:41:27 +00002099 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner7e152db2007-08-02 22:33:49 +00002100 do
2101 compStr++;
2102 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
Nate Begemanbb70bf62009-01-18 01:47:54 +00002103 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
Chris Lattner7e152db2007-08-02 22:33:49 +00002104 do
2105 compStr++;
Nate Begemanbb70bf62009-01-18 01:47:54 +00002106 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
Chris Lattner7e152db2007-08-02 22:33:49 +00002107 }
Nate Begemanbb70bf62009-01-18 01:47:54 +00002108
Mike Stump4e1f26a2009-02-19 03:04:26 +00002109 if (!HalvingSwizzle && *compStr) {
Steve Narofff8fd09e2007-07-27 22:15:19 +00002110 // We didn't get to the end of the string. This means the component names
2111 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattner3b054132008-11-19 05:08:23 +00002112 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
2113 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Narofff8fd09e2007-07-27 22:15:19 +00002114 return QualType();
2115 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00002116
Nate Begemanbb70bf62009-01-18 01:47:54 +00002117 // Ensure no component accessor exceeds the width of the vector type it
2118 // operates on.
2119 if (!HalvingSwizzle) {
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002120 compStr = CompName->getNameStart();
Nate Begemanbb70bf62009-01-18 01:47:54 +00002121
2122 if (HexSwizzle)
Steve Narofff8fd09e2007-07-27 22:15:19 +00002123 compStr++;
Nate Begemanbb70bf62009-01-18 01:47:54 +00002124
2125 while (*compStr) {
2126 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
2127 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
2128 << baseType << SourceRange(CompLoc);
2129 return QualType();
2130 }
2131 }
Steve Narofff8fd09e2007-07-27 22:15:19 +00002132 }
Nate Begemanf322eab2008-05-09 06:41:27 +00002133
Steve Narofff8fd09e2007-07-27 22:15:19 +00002134 // The component accessor looks fine - now we need to compute the actual type.
Mike Stump4e1f26a2009-02-19 03:04:26 +00002135 // The vector type is implied by the component accessor. For example,
Steve Narofff8fd09e2007-07-27 22:15:19 +00002136 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begemanbb70bf62009-01-18 01:47:54 +00002137 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begemanf322eab2008-05-09 06:41:27 +00002138 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begemanac8183a2009-12-15 18:13:04 +00002139 unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2
Anders Carlssonf571c112009-08-26 18:25:21 +00002140 : CompName->getLength();
Nate Begemanbb70bf62009-01-18 01:47:54 +00002141 if (HexSwizzle)
2142 CompSize--;
2143
Steve Narofff8fd09e2007-07-27 22:15:19 +00002144 if (CompSize == 1)
2145 return vecType->getElementType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00002146
Nate Begemance4d7fc2008-04-18 23:10:10 +00002147 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stump4e1f26a2009-02-19 03:04:26 +00002148 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemance4d7fc2008-04-18 23:10:10 +00002149 // diagostics look bad. We want extended vector types to appear built-in.
2150 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
2151 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
2152 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroffddf5a1d2007-07-29 16:33:31 +00002153 }
2154 return VT; // should never get here (a typedef type should always be found).
Steve Narofff8fd09e2007-07-27 22:15:19 +00002155}
2156
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002157static Decl *FindGetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
Anders Carlssonf571c112009-08-26 18:25:21 +00002158 IdentifierInfo *Member,
Douglas Gregorbcced4e2009-04-09 21:40:53 +00002159 const Selector &Sel,
2160 ASTContext &Context) {
Mike Stump11289f42009-09-09 15:08:12 +00002161
Anders Carlssonf571c112009-08-26 18:25:21 +00002162 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002163 return PD;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002164 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002165 return OMD;
Mike Stump11289f42009-09-09 15:08:12 +00002166
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002167 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
2168 E = PDecl->protocol_end(); I != E; ++I) {
Mike Stump11289f42009-09-09 15:08:12 +00002169 if (Decl *D = FindGetterNameDeclFromProtocolList(*I, Member, Sel,
Douglas Gregorbcced4e2009-04-09 21:40:53 +00002170 Context))
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002171 return D;
2172 }
2173 return 0;
2174}
2175
Steve Narofffb4330f2009-06-17 22:40:22 +00002176static Decl *FindGetterNameDecl(const ObjCObjectPointerType *QIdTy,
Anders Carlssonf571c112009-08-26 18:25:21 +00002177 IdentifierInfo *Member,
Douglas Gregorbcced4e2009-04-09 21:40:53 +00002178 const Selector &Sel,
2179 ASTContext &Context) {
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002180 // Check protocols on qualified interfaces.
2181 Decl *GDecl = 0;
Steve Narofffb4330f2009-06-17 22:40:22 +00002182 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002183 E = QIdTy->qual_end(); I != E; ++I) {
Anders Carlssonf571c112009-08-26 18:25:21 +00002184 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002185 GDecl = PD;
2186 break;
2187 }
2188 // Also must look for a getter name which uses property syntax.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002189 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002190 GDecl = OMD;
2191 break;
2192 }
2193 }
2194 if (!GDecl) {
Steve Narofffb4330f2009-06-17 22:40:22 +00002195 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002196 E = QIdTy->qual_end(); I != E; ++I) {
2197 // Search in the protocol-qualifier list of current protocol.
Douglas Gregorbcced4e2009-04-09 21:40:53 +00002198 GDecl = FindGetterNameDeclFromProtocolList(*I, Member, Sel, Context);
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002199 if (GDecl)
2200 return GDecl;
2201 }
2202 }
2203 return GDecl;
2204}
Chris Lattner4bf74fd2009-02-15 22:43:40 +00002205
John McCall10eae182009-11-30 22:42:35 +00002206Sema::OwningExprResult
John McCall2d74de92009-12-01 22:10:20 +00002207Sema::ActOnDependentMemberExpr(ExprArg Base, QualType BaseType,
2208 bool IsArrow, SourceLocation OpLoc,
John McCall10eae182009-11-30 22:42:35 +00002209 const CXXScopeSpec &SS,
2210 NamedDecl *FirstQualifierInScope,
2211 DeclarationName Name, SourceLocation NameLoc,
2212 const TemplateArgumentListInfo *TemplateArgs) {
2213 Expr *BaseExpr = Base.takeAs<Expr>();
2214
2215 // Even in dependent contexts, try to diagnose base expressions with
2216 // obviously wrong types, e.g.:
2217 //
2218 // T* t;
2219 // t.f;
2220 //
2221 // In Obj-C++, however, the above expression is valid, since it could be
2222 // accessing the 'f' property if T is an Obj-C interface. The extra check
2223 // allows this, while still reporting an error if T is a struct pointer.
2224 if (!IsArrow) {
John McCall2d74de92009-12-01 22:10:20 +00002225 const PointerType *PT = BaseType->getAs<PointerType>();
John McCall10eae182009-11-30 22:42:35 +00002226 if (PT && (!getLangOptions().ObjC1 ||
2227 PT->getPointeeType()->isRecordType())) {
John McCall2d74de92009-12-01 22:10:20 +00002228 assert(BaseExpr && "cannot happen with implicit member accesses");
John McCall10eae182009-11-30 22:42:35 +00002229 Diag(NameLoc, diag::err_typecheck_member_reference_struct_union)
John McCall2d74de92009-12-01 22:10:20 +00002230 << BaseType << BaseExpr->getSourceRange();
John McCall10eae182009-11-30 22:42:35 +00002231 return ExprError();
2232 }
2233 }
2234
John McCall2d74de92009-12-01 22:10:20 +00002235 assert(BaseType->isDependentType());
John McCall10eae182009-11-30 22:42:35 +00002236
2237 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
2238 // must have pointer type, and the accessed type is the pointee.
John McCall2d74de92009-12-01 22:10:20 +00002239 return Owned(CXXDependentScopeMemberExpr::Create(Context, BaseExpr, BaseType,
John McCall10eae182009-11-30 22:42:35 +00002240 IsArrow, OpLoc,
2241 static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
2242 SS.getRange(),
2243 FirstQualifierInScope,
2244 Name, NameLoc,
2245 TemplateArgs));
2246}
2247
2248/// We know that the given qualified member reference points only to
2249/// declarations which do not belong to the static type of the base
2250/// expression. Diagnose the problem.
2251static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
2252 Expr *BaseExpr,
2253 QualType BaseType,
John McCallcd4b4772009-12-02 03:53:29 +00002254 const CXXScopeSpec &SS,
John McCall10eae182009-11-30 22:42:35 +00002255 const LookupResult &R) {
John McCallcd4b4772009-12-02 03:53:29 +00002256 // If this is an implicit member access, use a different set of
2257 // diagnostics.
2258 if (!BaseExpr)
2259 return DiagnoseInstanceReference(SemaRef, SS, R);
John McCall10eae182009-11-30 22:42:35 +00002260
2261 // FIXME: this is an exceedingly lame diagnostic for some of the more
2262 // complicated cases here.
John McCallcd4b4772009-12-02 03:53:29 +00002263 DeclContext *DC = R.getRepresentativeDecl()->getDeclContext();
John McCall10eae182009-11-30 22:42:35 +00002264 SemaRef.Diag(R.getNameLoc(), diag::err_not_direct_base_or_virtual)
John McCallcd4b4772009-12-02 03:53:29 +00002265 << SS.getRange() << DC << BaseType;
John McCall10eae182009-11-30 22:42:35 +00002266}
2267
2268// Check whether the declarations we found through a nested-name
2269// specifier in a member expression are actually members of the base
2270// type. The restriction here is:
2271//
2272// C++ [expr.ref]p2:
2273// ... In these cases, the id-expression shall name a
2274// member of the class or of one of its base classes.
2275//
2276// So it's perfectly legitimate for the nested-name specifier to name
2277// an unrelated class, and for us to find an overload set including
2278// decls from classes which are not superclasses, as long as the decl
2279// we actually pick through overload resolution is from a superclass.
2280bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
2281 QualType BaseType,
John McCallcd4b4772009-12-02 03:53:29 +00002282 const CXXScopeSpec &SS,
John McCall10eae182009-11-30 22:42:35 +00002283 const LookupResult &R) {
John McCall2d74de92009-12-01 22:10:20 +00002284 const RecordType *BaseRT = BaseType->getAs<RecordType>();
2285 if (!BaseRT) {
2286 // We can't check this yet because the base type is still
2287 // dependent.
2288 assert(BaseType->isDependentType());
2289 return false;
2290 }
2291 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall10eae182009-11-30 22:42:35 +00002292
2293 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
John McCall2d74de92009-12-01 22:10:20 +00002294 // If this is an implicit member reference and we find a
2295 // non-instance member, it's not an error.
2296 if (!BaseExpr && !IsInstanceMember((*I)->getUnderlyingDecl()))
2297 return false;
John McCall10eae182009-11-30 22:42:35 +00002298
John McCall2d74de92009-12-01 22:10:20 +00002299 // Note that we use the DC of the decl, not the underlying decl.
2300 CXXRecordDecl *RecordD = cast<CXXRecordDecl>((*I)->getDeclContext());
2301 while (RecordD->isAnonymousStructOrUnion())
2302 RecordD = cast<CXXRecordDecl>(RecordD->getParent());
2303
2304 llvm::SmallPtrSet<CXXRecordDecl*,4> MemberRecord;
2305 MemberRecord.insert(RecordD->getCanonicalDecl());
2306
2307 if (!IsProvablyNotDerivedFrom(*this, BaseRecord, MemberRecord))
2308 return false;
2309 }
2310
John McCallcd4b4772009-12-02 03:53:29 +00002311 DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS, R);
John McCall2d74de92009-12-01 22:10:20 +00002312 return true;
2313}
2314
2315static bool
2316LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
2317 SourceRange BaseRange, const RecordType *RTy,
2318 SourceLocation OpLoc, const CXXScopeSpec &SS) {
2319 RecordDecl *RDecl = RTy->getDecl();
2320 if (SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
2321 PDiag(diag::err_typecheck_incomplete_tag)
2322 << BaseRange))
2323 return true;
2324
2325 DeclContext *DC = RDecl;
2326 if (SS.isSet()) {
2327 // If the member name was a qualified-id, look into the
2328 // nested-name-specifier.
2329 DC = SemaRef.computeDeclContext(SS, false);
2330
John McCallcd4b4772009-12-02 03:53:29 +00002331 if (SemaRef.RequireCompleteDeclContext(SS)) {
2332 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
2333 << SS.getRange() << DC;
2334 return true;
2335 }
2336
John McCall2d74de92009-12-01 22:10:20 +00002337 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
2338
2339 if (!isa<TypeDecl>(DC)) {
2340 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
2341 << DC << SS.getRange();
2342 return true;
John McCall10eae182009-11-30 22:42:35 +00002343 }
2344 }
2345
John McCall2d74de92009-12-01 22:10:20 +00002346 // The record definition is complete, now look up the member.
2347 SemaRef.LookupQualifiedName(R, DC);
John McCall10eae182009-11-30 22:42:35 +00002348
2349 return false;
2350}
2351
2352Sema::OwningExprResult
John McCall2d74de92009-12-01 22:10:20 +00002353Sema::BuildMemberReferenceExpr(ExprArg BaseArg, QualType BaseType,
John McCall10eae182009-11-30 22:42:35 +00002354 SourceLocation OpLoc, bool IsArrow,
2355 const CXXScopeSpec &SS,
2356 NamedDecl *FirstQualifierInScope,
2357 DeclarationName Name, SourceLocation NameLoc,
2358 const TemplateArgumentListInfo *TemplateArgs) {
2359 Expr *Base = BaseArg.takeAs<Expr>();
2360
John McCallcd4b4772009-12-02 03:53:29 +00002361 if (BaseType->isDependentType() ||
2362 (SS.isSet() && isDependentScopeSpecifier(SS)))
John McCall2d74de92009-12-01 22:10:20 +00002363 return ActOnDependentMemberExpr(ExprArg(*this, Base), BaseType,
John McCall10eae182009-11-30 22:42:35 +00002364 IsArrow, OpLoc,
2365 SS, FirstQualifierInScope,
2366 Name, NameLoc,
2367 TemplateArgs);
2368
2369 LookupResult R(*this, Name, NameLoc, LookupMemberName);
John McCall10eae182009-11-30 22:42:35 +00002370
John McCall2d74de92009-12-01 22:10:20 +00002371 // Implicit member accesses.
2372 if (!Base) {
2373 QualType RecordTy = BaseType;
2374 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
2375 if (LookupMemberExprInRecord(*this, R, SourceRange(),
2376 RecordTy->getAs<RecordType>(),
2377 OpLoc, SS))
2378 return ExprError();
2379
2380 // Explicit member accesses.
2381 } else {
2382 OwningExprResult Result =
2383 LookupMemberExpr(R, Base, IsArrow, OpLoc,
2384 SS, FirstQualifierInScope,
2385 /*ObjCImpDecl*/ DeclPtrTy());
2386
2387 if (Result.isInvalid()) {
2388 Owned(Base);
2389 return ExprError();
2390 }
2391
2392 if (Result.get())
2393 return move(Result);
John McCall10eae182009-11-30 22:42:35 +00002394 }
2395
John McCall2d74de92009-12-01 22:10:20 +00002396 return BuildMemberReferenceExpr(ExprArg(*this, Base), BaseType,
2397 OpLoc, IsArrow, SS, R, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00002398}
2399
2400Sema::OwningExprResult
John McCall2d74de92009-12-01 22:10:20 +00002401Sema::BuildMemberReferenceExpr(ExprArg Base, QualType BaseExprType,
2402 SourceLocation OpLoc, bool IsArrow,
2403 const CXXScopeSpec &SS,
John McCall10eae182009-11-30 22:42:35 +00002404 LookupResult &R,
2405 const TemplateArgumentListInfo *TemplateArgs) {
2406 Expr *BaseExpr = Base.takeAs<Expr>();
John McCall2d74de92009-12-01 22:10:20 +00002407 QualType BaseType = BaseExprType;
John McCall10eae182009-11-30 22:42:35 +00002408 if (IsArrow) {
2409 assert(BaseType->isPointerType());
2410 BaseType = BaseType->getAs<PointerType>()->getPointeeType();
2411 }
2412
2413 NestedNameSpecifier *Qualifier =
2414 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
2415 DeclarationName MemberName = R.getLookupName();
2416 SourceLocation MemberLoc = R.getNameLoc();
2417
2418 if (R.isAmbiguous())
Douglas Gregord8061562009-08-06 03:17:00 +00002419 return ExprError();
2420
John McCall10eae182009-11-30 22:42:35 +00002421 if (R.empty()) {
2422 // Rederive where we looked up.
2423 DeclContext *DC = (SS.isSet()
2424 ? computeDeclContext(SS, false)
2425 : BaseType->getAs<RecordType>()->getDecl());
Nate Begeman5ec4b312009-08-10 23:49:36 +00002426
John McCall10eae182009-11-30 22:42:35 +00002427 Diag(R.getNameLoc(), diag::err_no_member)
John McCall2d74de92009-12-01 22:10:20 +00002428 << MemberName << DC
2429 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
John McCall10eae182009-11-30 22:42:35 +00002430 return ExprError();
2431 }
2432
John McCallcd4b4772009-12-02 03:53:29 +00002433 // Diagnose qualified lookups that find only declarations from a
2434 // non-base type. Note that it's okay for lookup to find
2435 // declarations from a non-base type as long as those aren't the
2436 // ones picked by overload resolution.
2437 if (SS.isSet() && CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
John McCall10eae182009-11-30 22:42:35 +00002438 return ExprError();
2439
2440 // Construct an unresolved result if we in fact got an unresolved
2441 // result.
2442 if (R.isOverloadedResult() || R.isUnresolvableResult()) {
John McCall2d74de92009-12-01 22:10:20 +00002443 bool Dependent =
John McCall71739032009-12-19 02:05:44 +00002444 BaseExprType->isDependentType() ||
John McCall2d74de92009-12-01 22:10:20 +00002445 R.isUnresolvableResult() ||
2446 UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(), TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00002447
2448 UnresolvedMemberExpr *MemExpr
2449 = UnresolvedMemberExpr::Create(Context, Dependent,
2450 R.isUnresolvableResult(),
John McCall2d74de92009-12-01 22:10:20 +00002451 BaseExpr, BaseExprType,
2452 IsArrow, OpLoc,
John McCall10eae182009-11-30 22:42:35 +00002453 Qualifier, SS.getRange(),
2454 MemberName, MemberLoc,
2455 TemplateArgs);
2456 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
2457 MemExpr->addDecl(*I);
2458
2459 return Owned(MemExpr);
2460 }
2461
2462 assert(R.isSingleResult());
2463 NamedDecl *MemberDecl = R.getFoundDecl();
2464
2465 // FIXME: diagnose the presence of template arguments now.
2466
2467 // If the decl being referenced had an error, return an error for this
2468 // sub-expr without emitting another error, in order to avoid cascading
2469 // error cases.
2470 if (MemberDecl->isInvalidDecl())
2471 return ExprError();
2472
John McCall2d74de92009-12-01 22:10:20 +00002473 // Handle the implicit-member-access case.
2474 if (!BaseExpr) {
2475 // If this is not an instance member, convert to a non-member access.
2476 if (!IsInstanceMember(MemberDecl))
2477 return BuildDeclarationNameExpr(SS, R.getNameLoc(), MemberDecl);
2478
2479 BaseExpr = new (Context) CXXThisExpr(SourceLocation(), BaseExprType);
2480 }
2481
John McCall10eae182009-11-30 22:42:35 +00002482 bool ShouldCheckUse = true;
2483 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
2484 // Don't diagnose the use of a virtual member function unless it's
2485 // explicitly qualified.
2486 if (MD->isVirtual() && !SS.isSet())
2487 ShouldCheckUse = false;
2488 }
2489
2490 // Check the use of this member.
2491 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc)) {
2492 Owned(BaseExpr);
2493 return ExprError();
2494 }
2495
2496 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
2497 // We may have found a field within an anonymous union or struct
2498 // (C++ [class.union]).
Eli Friedman78cde142009-12-04 07:18:51 +00002499 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion() &&
2500 !BaseType->getAs<RecordType>()->getDecl()->isAnonymousStructOrUnion())
John McCall10eae182009-11-30 22:42:35 +00002501 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
2502 BaseExpr, OpLoc);
2503
2504 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
2505 QualType MemberType = FD->getType();
2506 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>())
2507 MemberType = Ref->getPointeeType();
2508 else {
2509 Qualifiers BaseQuals = BaseType.getQualifiers();
2510 BaseQuals.removeObjCGCAttr();
2511 if (FD->isMutable()) BaseQuals.removeConst();
2512
2513 Qualifiers MemberQuals
2514 = Context.getCanonicalType(MemberType).getQualifiers();
2515
2516 Qualifiers Combined = BaseQuals + MemberQuals;
2517 if (Combined != MemberQuals)
2518 MemberType = Context.getQualifiedType(MemberType, Combined);
2519 }
2520
2521 MarkDeclarationReferenced(MemberLoc, FD);
2522 if (PerformObjectMemberConversion(BaseExpr, FD))
2523 return ExprError();
2524 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
2525 FD, MemberLoc, MemberType));
2526 }
2527
2528 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
2529 MarkDeclarationReferenced(MemberLoc, Var);
2530 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
2531 Var, MemberLoc,
2532 Var->getType().getNonReferenceType()));
2533 }
2534
2535 if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl)) {
2536 MarkDeclarationReferenced(MemberLoc, MemberDecl);
2537 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
2538 MemberFn, MemberLoc,
2539 MemberFn->getType()));
2540 }
2541
2542 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
2543 MarkDeclarationReferenced(MemberLoc, MemberDecl);
2544 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
2545 Enum, MemberLoc, Enum->getType()));
2546 }
2547
2548 Owned(BaseExpr);
2549
2550 if (isa<TypeDecl>(MemberDecl))
2551 return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
2552 << MemberName << int(IsArrow));
2553
2554 // We found a declaration kind that we didn't expect. This is a
2555 // generic error message that tells the user that she can't refer
2556 // to this member with '.' or '->'.
2557 return ExprError(Diag(MemberLoc,
2558 diag::err_typecheck_member_reference_unknown)
2559 << MemberName << int(IsArrow));
2560}
2561
2562/// Look up the given member of the given non-type-dependent
2563/// expression. This can return in one of two ways:
2564/// * If it returns a sentinel null-but-valid result, the caller will
2565/// assume that lookup was performed and the results written into
2566/// the provided structure. It will take over from there.
2567/// * Otherwise, the returned expression will be produced in place of
2568/// an ordinary member expression.
2569///
2570/// The ObjCImpDecl bit is a gross hack that will need to be properly
2571/// fixed for ObjC++.
2572Sema::OwningExprResult
2573Sema::LookupMemberExpr(LookupResult &R, Expr *&BaseExpr,
John McCalla928c652009-12-07 22:46:59 +00002574 bool &IsArrow, SourceLocation OpLoc,
John McCall10eae182009-11-30 22:42:35 +00002575 const CXXScopeSpec &SS,
2576 NamedDecl *FirstQualifierInScope,
2577 DeclPtrTy ObjCImpDecl) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00002578 assert(BaseExpr && "no base expression");
Mike Stump11289f42009-09-09 15:08:12 +00002579
Steve Naroffeaaae462007-12-16 21:42:28 +00002580 // Perform default conversions.
2581 DefaultFunctionArrayConversion(BaseExpr);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002582
Steve Naroff185616f2007-07-26 03:11:44 +00002583 QualType BaseType = BaseExpr->getType();
John McCall10eae182009-11-30 22:42:35 +00002584 assert(!BaseType->isDependentType());
2585
2586 DeclarationName MemberName = R.getLookupName();
2587 SourceLocation MemberLoc = R.getNameLoc();
Douglas Gregord82ae382009-11-06 06:30:47 +00002588
2589 // If the user is trying to apply -> or . to a function pointer
John McCall10eae182009-11-30 22:42:35 +00002590 // type, it's probably because they forgot parentheses to call that
Douglas Gregord82ae382009-11-06 06:30:47 +00002591 // function. Suggest the addition of those parentheses, build the
2592 // call, and continue on.
2593 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
2594 if (const FunctionProtoType *Fun
2595 = Ptr->getPointeeType()->getAs<FunctionProtoType>()) {
2596 QualType ResultTy = Fun->getResultType();
2597 if (Fun->getNumArgs() == 0 &&
John McCall10eae182009-11-30 22:42:35 +00002598 ((!IsArrow && ResultTy->isRecordType()) ||
2599 (IsArrow && ResultTy->isPointerType() &&
Douglas Gregord82ae382009-11-06 06:30:47 +00002600 ResultTy->getAs<PointerType>()->getPointeeType()
2601 ->isRecordType()))) {
2602 SourceLocation Loc = PP.getLocForEndOfToken(BaseExpr->getLocEnd());
2603 Diag(Loc, diag::err_member_reference_needs_call)
2604 << QualType(Fun, 0)
2605 << CodeModificationHint::CreateInsertion(Loc, "()");
2606
2607 OwningExprResult NewBase
John McCall10eae182009-11-30 22:42:35 +00002608 = ActOnCallExpr(0, ExprArg(*this, BaseExpr), Loc,
Douglas Gregord82ae382009-11-06 06:30:47 +00002609 MultiExprArg(*this, 0, 0), 0, Loc);
2610 if (NewBase.isInvalid())
John McCall10eae182009-11-30 22:42:35 +00002611 return ExprError();
Douglas Gregord82ae382009-11-06 06:30:47 +00002612
2613 BaseExpr = NewBase.takeAs<Expr>();
2614 DefaultFunctionArrayConversion(BaseExpr);
2615 BaseType = BaseExpr->getType();
2616 }
2617 }
2618 }
2619
David Chisnall9f57c292009-08-17 16:35:33 +00002620 // If this is an Objective-C pseudo-builtin and a definition is provided then
2621 // use that.
2622 if (BaseType->isObjCIdType()) {
Fariborz Jahanianc2949f92009-12-07 20:09:25 +00002623 if (IsArrow) {
2624 // Handle the following exceptional case PObj->isa.
2625 if (const ObjCObjectPointerType *OPT =
2626 BaseType->getAs<ObjCObjectPointerType>()) {
2627 if (OPT->getPointeeType()->isSpecificBuiltinType(BuiltinType::ObjCId) &&
2628 MemberName.getAsIdentifierInfo()->isStr("isa"))
Fariborz Jahaniana5fee262009-12-09 19:05:56 +00002629 return Owned(new (Context) ObjCIsaExpr(BaseExpr, true, MemberLoc,
2630 Context.getObjCClassType()));
Fariborz Jahanianc2949f92009-12-07 20:09:25 +00002631 }
2632 }
David Chisnall9f57c292009-08-17 16:35:33 +00002633 // We have an 'id' type. Rather than fall through, we check if this
2634 // is a reference to 'isa'.
2635 if (BaseType != Context.ObjCIdRedefinitionType) {
2636 BaseType = Context.ObjCIdRedefinitionType;
Eli Friedman06ed2a52009-10-20 08:27:19 +00002637 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
David Chisnall9f57c292009-08-17 16:35:33 +00002638 }
David Chisnall9f57c292009-08-17 16:35:33 +00002639 }
John McCall10eae182009-11-30 22:42:35 +00002640
Fariborz Jahanian04b258c2009-11-25 23:07:42 +00002641 // If this is an Objective-C pseudo-builtin and a definition is provided then
2642 // use that.
2643 if (Context.isObjCSelType(BaseType)) {
2644 // We have an 'SEL' type. Rather than fall through, we check if this
2645 // is a reference to 'sel_id'.
2646 if (BaseType != Context.ObjCSelRedefinitionType) {
2647 BaseType = Context.ObjCSelRedefinitionType;
2648 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
2649 }
2650 }
John McCall10eae182009-11-30 22:42:35 +00002651
Steve Naroff185616f2007-07-26 03:11:44 +00002652 assert(!BaseType.isNull() && "no type for member expression");
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002653
Fariborz Jahaniane983d172009-09-22 16:48:37 +00002654 // Handle properties on ObjC 'Class' types.
John McCall10eae182009-11-30 22:42:35 +00002655 if (!IsArrow && BaseType->isObjCClassType()) {
Fariborz Jahaniane983d172009-09-22 16:48:37 +00002656 // Also must look for a getter name which uses property syntax.
2657 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
2658 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
2659 if (ObjCMethodDecl *MD = getCurMethodDecl()) {
2660 ObjCInterfaceDecl *IFace = MD->getClassInterface();
2661 ObjCMethodDecl *Getter;
2662 // FIXME: need to also look locally in the implementation.
2663 if ((Getter = IFace->lookupClassMethod(Sel))) {
2664 // Check the use of this method.
2665 if (DiagnoseUseOfDecl(Getter, MemberLoc))
2666 return ExprError();
2667 }
2668 // If we found a getter then this may be a valid dot-reference, we
2669 // will look for the matching setter, in case it is needed.
2670 Selector SetterSel =
2671 SelectorTable::constructSetterName(PP.getIdentifierTable(),
2672 PP.getSelectorTable(), Member);
2673 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
2674 if (!Setter) {
2675 // If this reference is in an @implementation, also check for 'private'
2676 // methods.
Steve Naroffbb69c942009-10-01 23:46:04 +00002677 Setter = IFace->lookupPrivateInstanceMethod(SetterSel);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00002678 }
2679 // Look through local category implementations associated with the class.
2680 if (!Setter)
2681 Setter = IFace->getCategoryClassMethod(SetterSel);
2682
2683 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2684 return ExprError();
2685
2686 if (Getter || Setter) {
2687 QualType PType;
2688
2689 if (Getter)
2690 PType = Getter->getResultType();
2691 else
2692 // Get the expression type from Setter's incoming parameter.
2693 PType = (*(Setter->param_end() -1))->getType();
2694 // FIXME: we must check that the setter has property type.
2695 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter,
2696 PType,
2697 Setter, MemberLoc, BaseExpr));
2698 }
2699 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
2700 << MemberName << BaseType);
2701 }
2702 }
2703
2704 if (BaseType->isObjCClassType() &&
2705 BaseType != Context.ObjCClassRedefinitionType) {
2706 BaseType = Context.ObjCClassRedefinitionType;
Eli Friedman06ed2a52009-10-20 08:27:19 +00002707 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00002708 }
Mike Stump11289f42009-09-09 15:08:12 +00002709
John McCall10eae182009-11-30 22:42:35 +00002710 if (IsArrow) {
2711 if (const PointerType *PT = BaseType->getAs<PointerType>())
Steve Naroff185616f2007-07-26 03:11:44 +00002712 BaseType = PT->getPointeeType();
Steve Naroff7cae42b2009-07-10 23:34:53 +00002713 else if (BaseType->isObjCObjectPointerType())
2714 ;
John McCalla928c652009-12-07 22:46:59 +00002715 else if (BaseType->isRecordType()) {
2716 // Recover from arrow accesses to records, e.g.:
2717 // struct MyRecord foo;
2718 // foo->bar
2719 // This is actually well-formed in C++ if MyRecord has an
2720 // overloaded operator->, but that should have been dealt with
2721 // by now.
2722 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
2723 << BaseType << int(IsArrow) << BaseExpr->getSourceRange()
2724 << CodeModificationHint::CreateReplacement(OpLoc, ".");
2725 IsArrow = false;
2726 } else {
John McCall10eae182009-11-30 22:42:35 +00002727 Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
2728 << BaseType << BaseExpr->getSourceRange();
2729 return ExprError();
Anders Carlsson524d5a42009-05-16 20:31:20 +00002730 }
John McCalla928c652009-12-07 22:46:59 +00002731 } else {
2732 // Recover from dot accesses to pointers, e.g.:
2733 // type *foo;
2734 // foo.bar
2735 // This is actually well-formed in two cases:
2736 // - 'type' is an Objective C type
2737 // - 'bar' is a pseudo-destructor name which happens to refer to
2738 // the appropriate pointer type
2739 if (MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
2740 const PointerType *PT = BaseType->getAs<PointerType>();
2741 if (PT && PT->getPointeeType()->isRecordType()) {
2742 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
2743 << BaseType << int(IsArrow) << BaseExpr->getSourceRange()
2744 << CodeModificationHint::CreateReplacement(OpLoc, "->");
2745 BaseType = PT->getPointeeType();
2746 IsArrow = true;
2747 }
2748 }
John McCall10eae182009-11-30 22:42:35 +00002749 }
John McCalla928c652009-12-07 22:46:59 +00002750
John McCall10eae182009-11-30 22:42:35 +00002751 // Handle field access to simple records. This also handles access
2752 // to fields of the ObjC 'id' struct.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002753 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
John McCall2d74de92009-12-01 22:10:20 +00002754 if (LookupMemberExprInRecord(*this, R, BaseExpr->getSourceRange(),
2755 RTy, OpLoc, SS))
Douglas Gregordd430f72009-01-19 19:26:10 +00002756 return ExprError();
John McCall10eae182009-11-30 22:42:35 +00002757 return Owned((Expr*) 0);
Chris Lattnerb63a7452008-07-21 04:28:12 +00002758 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002759
Douglas Gregorad8a3362009-09-04 17:36:40 +00002760 // Handle pseudo-destructors (C++ [expr.pseudo]). Since anything referring
2761 // into a record type was handled above, any destructor we see here is a
2762 // pseudo-destructor.
2763 if (MemberName.getNameKind() == DeclarationName::CXXDestructorName) {
2764 // C++ [expr.pseudo]p2:
Mike Stump11289f42009-09-09 15:08:12 +00002765 // The left hand side of the dot operator shall be of scalar type. The
2766 // left hand side of the arrow operator shall be of pointer to scalar
Douglas Gregorad8a3362009-09-04 17:36:40 +00002767 // type.
2768 if (!BaseType->isScalarType())
2769 return Owned(Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
2770 << BaseType << BaseExpr->getSourceRange());
Mike Stump11289f42009-09-09 15:08:12 +00002771
Douglas Gregorad8a3362009-09-04 17:36:40 +00002772 // [...] The type designated by the pseudo-destructor-name shall be the
2773 // same as the object type.
2774 if (!MemberName.getCXXNameType()->isDependentType() &&
2775 !Context.hasSameUnqualifiedType(BaseType, MemberName.getCXXNameType()))
2776 return Owned(Diag(OpLoc, diag::err_pseudo_dtor_type_mismatch)
2777 << BaseType << MemberName.getCXXNameType()
2778 << BaseExpr->getSourceRange() << SourceRange(MemberLoc));
Mike Stump11289f42009-09-09 15:08:12 +00002779
2780 // [...] Furthermore, the two type-names in a pseudo-destructor-name of
Douglas Gregorad8a3362009-09-04 17:36:40 +00002781 // the form
2782 //
Mike Stump11289f42009-09-09 15:08:12 +00002783 // ::[opt] nested-name-specifier[opt] type-name :: ̃ type-name
2784 //
Douglas Gregorad8a3362009-09-04 17:36:40 +00002785 // shall designate the same scalar type.
2786 //
2787 // FIXME: DPG can't see any way to trigger this particular clause, so it
2788 // isn't checked here.
Mike Stump11289f42009-09-09 15:08:12 +00002789
Douglas Gregorad8a3362009-09-04 17:36:40 +00002790 // FIXME: We've lost the precise spelling of the type by going through
2791 // DeclarationName. Can we do better?
2792 return Owned(new (Context) CXXPseudoDestructorExpr(Context, BaseExpr,
John McCall10eae182009-11-30 22:42:35 +00002793 IsArrow, OpLoc,
2794 (NestedNameSpecifier *) SS.getScopeRep(),
2795 SS.getRange(),
Douglas Gregorad8a3362009-09-04 17:36:40 +00002796 MemberName.getCXXNameType(),
2797 MemberLoc));
2798 }
Mike Stump11289f42009-09-09 15:08:12 +00002799
Chris Lattnerdc420f42008-07-21 04:59:05 +00002800 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
2801 // (*Obj).ivar.
John McCall10eae182009-11-30 22:42:35 +00002802 if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
2803 (!IsArrow && BaseType->isObjCInterfaceType())) {
John McCall9dd450b2009-09-21 23:43:11 +00002804 const ObjCObjectPointerType *OPT = BaseType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00002805 const ObjCInterfaceType *IFaceT =
John McCall9dd450b2009-09-21 23:43:11 +00002806 OPT ? OPT->getInterfaceType() : BaseType->getAs<ObjCInterfaceType>();
Steve Naroffa057ba92009-07-16 00:25:06 +00002807 if (IFaceT) {
Anders Carlssonf571c112009-08-26 18:25:21 +00002808 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
2809
Steve Naroffa057ba92009-07-16 00:25:06 +00002810 ObjCInterfaceDecl *IDecl = IFaceT->getDecl();
2811 ObjCInterfaceDecl *ClassDeclared;
Anders Carlssonf571c112009-08-26 18:25:21 +00002812 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
Mike Stump11289f42009-09-09 15:08:12 +00002813
Steve Naroffa057ba92009-07-16 00:25:06 +00002814 if (IV) {
2815 // If the decl being referenced had an error, return an error for this
2816 // sub-expr without emitting another error, in order to avoid cascading
2817 // error cases.
2818 if (IV->isInvalidDecl())
2819 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00002820
Steve Naroffa057ba92009-07-16 00:25:06 +00002821 // Check whether we can reference this field.
2822 if (DiagnoseUseOfDecl(IV, MemberLoc))
2823 return ExprError();
2824 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
2825 IV->getAccessControl() != ObjCIvarDecl::Package) {
2826 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
2827 if (ObjCMethodDecl *MD = getCurMethodDecl())
2828 ClassOfMethodDecl = MD->getClassInterface();
2829 else if (ObjCImpDecl && getCurFunctionDecl()) {
2830 // Case of a c-function declared inside an objc implementation.
2831 // FIXME: For a c-style function nested inside an objc implementation
2832 // class, there is no implementation context available, so we pass
2833 // down the context as argument to this routine. Ideally, this context
2834 // need be passed down in the AST node and somehow calculated from the
2835 // AST for a function decl.
2836 Decl *ImplDecl = ObjCImpDecl.getAs<Decl>();
Mike Stump11289f42009-09-09 15:08:12 +00002837 if (ObjCImplementationDecl *IMPD =
Steve Naroffa057ba92009-07-16 00:25:06 +00002838 dyn_cast<ObjCImplementationDecl>(ImplDecl))
2839 ClassOfMethodDecl = IMPD->getClassInterface();
2840 else if (ObjCCategoryImplDecl* CatImplClass =
2841 dyn_cast<ObjCCategoryImplDecl>(ImplDecl))
2842 ClassOfMethodDecl = CatImplClass->getClassInterface();
2843 }
Mike Stump11289f42009-09-09 15:08:12 +00002844
2845 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
2846 if (ClassDeclared != IDecl ||
Steve Naroffa057ba92009-07-16 00:25:06 +00002847 ClassOfMethodDecl != ClassDeclared)
Mike Stump11289f42009-09-09 15:08:12 +00002848 Diag(MemberLoc, diag::error_private_ivar_access)
Steve Naroffa057ba92009-07-16 00:25:06 +00002849 << IV->getDeclName();
Mike Stump12b8ce12009-08-04 21:02:39 +00002850 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
2851 // @protected
Mike Stump11289f42009-09-09 15:08:12 +00002852 Diag(MemberLoc, diag::error_protected_ivar_access)
Steve Naroffa057ba92009-07-16 00:25:06 +00002853 << IV->getDeclName();
Steve Naroffd1b64be2009-03-04 18:34:24 +00002854 }
Steve Naroffa057ba92009-07-16 00:25:06 +00002855
2856 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
2857 MemberLoc, BaseExpr,
John McCall10eae182009-11-30 22:42:35 +00002858 IsArrow));
Fariborz Jahaniana458c4f2009-03-03 01:21:12 +00002859 }
Steve Naroffa057ba92009-07-16 00:25:06 +00002860 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
Anders Carlssonf571c112009-08-26 18:25:21 +00002861 << IDecl->getDeclName() << MemberName
Steve Naroffa057ba92009-07-16 00:25:06 +00002862 << BaseExpr->getSourceRange());
Fariborz Jahanianb1378f92008-12-13 22:20:28 +00002863 }
Chris Lattnerb63a7452008-07-21 04:28:12 +00002864 }
Steve Naroff1329fa02009-07-15 18:40:39 +00002865 // Handle properties on 'id' and qualified "id".
John McCall10eae182009-11-30 22:42:35 +00002866 if (!IsArrow && (BaseType->isObjCIdType() ||
2867 BaseType->isObjCQualifiedIdType())) {
John McCall9dd450b2009-09-21 23:43:11 +00002868 const ObjCObjectPointerType *QIdTy = BaseType->getAs<ObjCObjectPointerType>();
Anders Carlssonf571c112009-08-26 18:25:21 +00002869 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Mike Stump11289f42009-09-09 15:08:12 +00002870
Steve Naroff7cae42b2009-07-10 23:34:53 +00002871 // Check protocols on qualified interfaces.
Anders Carlssonf571c112009-08-26 18:25:21 +00002872 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002873 if (Decl *PMDecl = FindGetterNameDecl(QIdTy, Member, Sel, Context)) {
2874 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
2875 // Check the use of this declaration
2876 if (DiagnoseUseOfDecl(PD, MemberLoc))
2877 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00002878
Steve Naroff7cae42b2009-07-10 23:34:53 +00002879 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
2880 MemberLoc, BaseExpr));
2881 }
2882 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
2883 // Check the use of this method.
2884 if (DiagnoseUseOfDecl(OMD, MemberLoc))
2885 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00002886
Steve Naroff7cae42b2009-07-10 23:34:53 +00002887 return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel,
Mike Stump11289f42009-09-09 15:08:12 +00002888 OMD->getResultType(),
2889 OMD, OpLoc, MemberLoc,
Steve Naroff7cae42b2009-07-10 23:34:53 +00002890 NULL, 0));
2891 }
2892 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002893
Steve Naroff7cae42b2009-07-10 23:34:53 +00002894 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlssonf571c112009-08-26 18:25:21 +00002895 << MemberName << BaseType);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002896 }
Chris Lattnerdc420f42008-07-21 04:59:05 +00002897 // Handle Objective-C property access, which is "Obj.property" where Obj is a
2898 // pointer to a (potentially qualified) interface type.
Steve Naroff7cae42b2009-07-10 23:34:53 +00002899 const ObjCObjectPointerType *OPT;
John McCall10eae182009-11-30 22:42:35 +00002900 if (!IsArrow && (OPT = BaseType->getAsObjCInterfacePointerType())) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002901 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
2902 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
Anders Carlssonf571c112009-08-26 18:25:21 +00002903 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Mike Stump11289f42009-09-09 15:08:12 +00002904
Daniel Dunbaref89086c2008-09-03 01:05:41 +00002905 // Search for a declared property first.
Anders Carlssonf571c112009-08-26 18:25:21 +00002906 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00002907 // Check whether we can reference this property.
2908 if (DiagnoseUseOfDecl(PD, MemberLoc))
2909 return ExprError();
Fariborz Jahanianb2ab73d2009-05-08 19:36:34 +00002910 QualType ResTy = PD->getType();
Anders Carlssonf571c112009-08-26 18:25:21 +00002911 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002912 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Fariborz Jahanianfe9e3942009-05-08 20:20:55 +00002913 if (DiagnosePropertyAccessorMismatch(PD, Getter, MemberLoc))
2914 ResTy = Getter->getResultType();
Fariborz Jahanianb2ab73d2009-05-08 19:36:34 +00002915 return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
Chris Lattner43df5562009-02-16 18:35:08 +00002916 MemberLoc, BaseExpr));
2917 }
Daniel Dunbaref89086c2008-09-03 01:05:41 +00002918 // Check protocols on qualified interfaces.
Steve Naroffaccc4882009-07-20 17:56:53 +00002919 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
2920 E = OPT->qual_end(); I != E; ++I)
Anders Carlssonf571c112009-08-26 18:25:21 +00002921 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00002922 // Check whether we can reference this property.
2923 if (DiagnoseUseOfDecl(PD, MemberLoc))
2924 return ExprError();
Chris Lattner43df5562009-02-16 18:35:08 +00002925
Steve Narofff6009ed2009-01-21 00:14:39 +00002926 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner43df5562009-02-16 18:35:08 +00002927 MemberLoc, BaseExpr));
2928 }
Daniel Dunbaref89086c2008-09-03 01:05:41 +00002929 // If that failed, look for an "implicit" property by seeing if the nullary
2930 // selector is implemented.
2931
2932 // FIXME: The logic for looking up nullary and unary selectors should be
2933 // shared with the code in ActOnInstanceMessage.
2934
Anders Carlssonf571c112009-08-26 18:25:21 +00002935 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002936 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002937
Daniel Dunbaref89086c2008-09-03 01:05:41 +00002938 // If this reference is in an @implementation, check for 'private' methods.
2939 if (!Getter)
Steve Naroffbb69c942009-10-01 23:46:04 +00002940 Getter = IFace->lookupPrivateInstanceMethod(Sel);
Daniel Dunbaref89086c2008-09-03 01:05:41 +00002941
Steve Naroff1df62692008-10-22 19:16:27 +00002942 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1559d67b2009-07-21 00:06:20 +00002943 if (!Getter)
2944 Getter = IFace->getCategoryInstanceMethod(Sel);
Daniel Dunbaref89086c2008-09-03 01:05:41 +00002945 if (Getter) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00002946 // Check if we can reference this property.
2947 if (DiagnoseUseOfDecl(Getter, MemberLoc))
2948 return ExprError();
Steve Naroff1d984fe2009-03-11 13:48:17 +00002949 }
2950 // If we found a getter then this may be a valid dot-reference, we
2951 // will look for the matching setter, in case it is needed.
Mike Stump11289f42009-09-09 15:08:12 +00002952 Selector SetterSel =
2953 SelectorTable::constructSetterName(PP.getIdentifierTable(),
Anders Carlssonf571c112009-08-26 18:25:21 +00002954 PP.getSelectorTable(), Member);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002955 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
Steve Naroff1d984fe2009-03-11 13:48:17 +00002956 if (!Setter) {
2957 // If this reference is in an @implementation, also check for 'private'
2958 // methods.
Steve Naroffbb69c942009-10-01 23:46:04 +00002959 Setter = IFace->lookupPrivateInstanceMethod(SetterSel);
Steve Naroff1d984fe2009-03-11 13:48:17 +00002960 }
2961 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1559d67b2009-07-21 00:06:20 +00002962 if (!Setter)
2963 Setter = IFace->getCategoryInstanceMethod(SetterSel);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002964
Steve Naroff1d984fe2009-03-11 13:48:17 +00002965 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2966 return ExprError();
2967
2968 if (Getter || Setter) {
2969 QualType PType;
2970
2971 if (Getter)
2972 PType = Getter->getResultType();
Fariborz Jahanian88cc2342009-08-18 20:50:23 +00002973 else
2974 // Get the expression type from Setter's incoming parameter.
2975 PType = (*(Setter->param_end() -1))->getType();
Steve Naroff1d984fe2009-03-11 13:48:17 +00002976 // FIXME: we must check that the setter has property type.
Fariborz Jahanian9a846652009-08-20 17:02:02 +00002977 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter, PType,
Steve Naroff1d984fe2009-03-11 13:48:17 +00002978 Setter, MemberLoc, BaseExpr));
2979 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002980 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlssonf571c112009-08-26 18:25:21 +00002981 << MemberName << BaseType);
Fariborz Jahanian21f54ee2007-11-12 22:29:28 +00002982 }
Mike Stump11289f42009-09-09 15:08:12 +00002983
Steve Naroffe87026a2009-07-24 17:54:45 +00002984 // Handle the following exceptional case (*Obj).isa.
John McCall10eae182009-11-30 22:42:35 +00002985 if (!IsArrow &&
Steve Naroffe87026a2009-07-24 17:54:45 +00002986 BaseType->isSpecificBuiltinType(BuiltinType::ObjCId) &&
Anders Carlssonf571c112009-08-26 18:25:21 +00002987 MemberName.getAsIdentifierInfo()->isStr("isa"))
Steve Naroffe87026a2009-07-24 17:54:45 +00002988 return Owned(new (Context) ObjCIsaExpr(BaseExpr, false, MemberLoc,
Fariborz Jahaniana5fee262009-12-09 19:05:56 +00002989 Context.getObjCClassType()));
Steve Naroffe87026a2009-07-24 17:54:45 +00002990
Chris Lattnerb63a7452008-07-21 04:28:12 +00002991 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner6c7ce102009-02-16 21:11:58 +00002992 if (BaseType->isExtVectorType()) {
Anders Carlssonf571c112009-08-26 18:25:21 +00002993 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Chris Lattnerb63a7452008-07-21 04:28:12 +00002994 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
2995 if (ret.isNull())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002996 return ExprError();
Anders Carlssonf571c112009-08-26 18:25:21 +00002997 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, *Member,
Steve Narofff6009ed2009-01-21 00:14:39 +00002998 MemberLoc));
Chris Lattnerb63a7452008-07-21 04:28:12 +00002999 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003000
Douglas Gregor0b08ba42009-03-27 06:00:30 +00003001 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
3002 << BaseType << BaseExpr->getSourceRange();
3003
Douglas Gregor0b08ba42009-03-27 06:00:30 +00003004 return ExprError();
Chris Lattnere168f762006-11-10 05:29:30 +00003005}
3006
John McCall10eae182009-11-30 22:42:35 +00003007static Sema::OwningExprResult DiagnoseDtorReference(Sema &SemaRef,
3008 SourceLocation NameLoc,
3009 Sema::ExprArg MemExpr) {
3010 Expr *E = (Expr *) MemExpr.get();
3011 SourceLocation ExpectedLParenLoc = SemaRef.PP.getLocForEndOfToken(NameLoc);
3012 SemaRef.Diag(E->getLocStart(), diag::err_dtor_expr_without_call)
Douglas Gregor30d60cb2009-11-03 19:44:04 +00003013 << isa<CXXPseudoDestructorExpr>(E)
3014 << CodeModificationHint::CreateInsertion(ExpectedLParenLoc, "()");
3015
John McCall10eae182009-11-30 22:42:35 +00003016 return SemaRef.ActOnCallExpr(/*Scope*/ 0,
3017 move(MemExpr),
3018 /*LPLoc*/ ExpectedLParenLoc,
3019 Sema::MultiExprArg(SemaRef, 0, 0),
3020 /*CommaLocs*/ 0,
3021 /*RPLoc*/ ExpectedLParenLoc);
3022}
3023
3024/// The main callback when the parser finds something like
3025/// expression . [nested-name-specifier] identifier
3026/// expression -> [nested-name-specifier] identifier
3027/// where 'identifier' encompasses a fairly broad spectrum of
3028/// possibilities, including destructor and operator references.
3029///
3030/// \param OpKind either tok::arrow or tok::period
3031/// \param HasTrailingLParen whether the next token is '(', which
3032/// is used to diagnose mis-uses of special members that can
3033/// only be called
3034/// \param ObjCImpDecl the current ObjC @implementation decl;
3035/// this is an ugly hack around the fact that ObjC @implementations
3036/// aren't properly put in the context chain
3037Sema::OwningExprResult Sema::ActOnMemberAccessExpr(Scope *S, ExprArg BaseArg,
3038 SourceLocation OpLoc,
3039 tok::TokenKind OpKind,
3040 const CXXScopeSpec &SS,
3041 UnqualifiedId &Id,
3042 DeclPtrTy ObjCImpDecl,
3043 bool HasTrailingLParen) {
3044 if (SS.isSet() && SS.isInvalid())
3045 return ExprError();
3046
3047 TemplateArgumentListInfo TemplateArgsBuffer;
3048
3049 // Decompose the name into its component parts.
3050 DeclarationName Name;
3051 SourceLocation NameLoc;
3052 const TemplateArgumentListInfo *TemplateArgs;
3053 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer,
3054 Name, NameLoc, TemplateArgs);
3055
3056 bool IsArrow = (OpKind == tok::arrow);
3057
3058 NamedDecl *FirstQualifierInScope
3059 = (!SS.isSet() ? 0 : FindFirstQualifierInScope(S,
3060 static_cast<NestedNameSpecifier*>(SS.getScopeRep())));
3061
3062 // This is a postfix expression, so get rid of ParenListExprs.
3063 BaseArg = MaybeConvertParenListExprToParenExpr(S, move(BaseArg));
3064
3065 Expr *Base = BaseArg.takeAs<Expr>();
3066 OwningExprResult Result(*this);
3067 if (Base->getType()->isDependentType()) {
John McCall2d74de92009-12-01 22:10:20 +00003068 Result = ActOnDependentMemberExpr(ExprArg(*this, Base), Base->getType(),
John McCall10eae182009-11-30 22:42:35 +00003069 IsArrow, OpLoc,
3070 SS, FirstQualifierInScope,
3071 Name, NameLoc,
3072 TemplateArgs);
3073 } else {
3074 LookupResult R(*this, Name, NameLoc, LookupMemberName);
3075 if (TemplateArgs) {
3076 // Re-use the lookup done for the template name.
3077 DecomposeTemplateName(R, Id);
3078 } else {
3079 Result = LookupMemberExpr(R, Base, IsArrow, OpLoc,
3080 SS, FirstQualifierInScope,
3081 ObjCImpDecl);
3082
3083 if (Result.isInvalid()) {
3084 Owned(Base);
3085 return ExprError();
3086 }
3087
3088 if (Result.get()) {
3089 // The only way a reference to a destructor can be used is to
3090 // immediately call it, which falls into this case. If the
3091 // next token is not a '(', produce a diagnostic and build the
3092 // call now.
3093 if (!HasTrailingLParen &&
3094 Id.getKind() == UnqualifiedId::IK_DestructorName)
3095 return DiagnoseDtorReference(*this, NameLoc, move(Result));
3096
3097 return move(Result);
3098 }
3099 }
3100
John McCall2d74de92009-12-01 22:10:20 +00003101 Result = BuildMemberReferenceExpr(ExprArg(*this, Base), Base->getType(),
3102 OpLoc, IsArrow, SS, R, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00003103 }
3104
3105 return move(Result);
Anders Carlssonf571c112009-08-26 18:25:21 +00003106}
3107
Anders Carlsson355933d2009-08-25 03:49:14 +00003108Sema::OwningExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
3109 FunctionDecl *FD,
3110 ParmVarDecl *Param) {
3111 if (Param->hasUnparsedDefaultArg()) {
3112 Diag (CallLoc,
3113 diag::err_use_of_default_argument_to_function_declared_later) <<
3114 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00003115 Diag(UnparsedDefaultArgLocs[Param],
Anders Carlsson355933d2009-08-25 03:49:14 +00003116 diag::note_default_argument_declared_here);
3117 } else {
3118 if (Param->hasUninstantiatedDefaultArg()) {
3119 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
3120
3121 // Instantiate the expression.
Douglas Gregor01afeef2009-08-28 20:31:08 +00003122 MultiLevelTemplateArgumentList ArgList = getTemplateInstantiationArgs(FD);
Anders Carlsson657bad42009-09-05 05:14:19 +00003123
Mike Stump11289f42009-09-09 15:08:12 +00003124 InstantiatingTemplate Inst(*this, CallLoc, Param,
3125 ArgList.getInnermost().getFlatArgumentList(),
Douglas Gregor01afeef2009-08-28 20:31:08 +00003126 ArgList.getInnermost().flat_size());
Anders Carlsson355933d2009-08-25 03:49:14 +00003127
John McCall76d824f2009-08-25 22:02:44 +00003128 OwningExprResult Result = SubstExpr(UninstExpr, ArgList);
Mike Stump11289f42009-09-09 15:08:12 +00003129 if (Result.isInvalid())
Anders Carlsson355933d2009-08-25 03:49:14 +00003130 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003131
Douglas Gregor25ab25f2009-12-23 18:19:08 +00003132 // Check the expression as an initializer for the parameter.
3133 InitializedEntity Entity
3134 = InitializedEntity::InitializeParameter(Param);
3135 InitializationKind Kind
3136 = InitializationKind::CreateCopy(Param->getLocation(),
3137 /*FIXME:EqualLoc*/UninstExpr->getSourceRange().getBegin());
3138 Expr *ResultE = Result.takeAs<Expr>();
3139
3140 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
3141 Result = InitSeq.Perform(*this, Entity, Kind,
3142 MultiExprArg(*this, (void**)&ResultE, 1));
3143 if (Result.isInvalid())
Anders Carlsson355933d2009-08-25 03:49:14 +00003144 return ExprError();
Douglas Gregor25ab25f2009-12-23 18:19:08 +00003145
3146 // Build the default argument expression.
Douglas Gregor033f6752009-12-23 23:03:06 +00003147 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param,
Douglas Gregor25ab25f2009-12-23 18:19:08 +00003148 Result.takeAs<Expr>()));
Anders Carlsson355933d2009-08-25 03:49:14 +00003149 }
Mike Stump11289f42009-09-09 15:08:12 +00003150
Anders Carlsson355933d2009-08-25 03:49:14 +00003151 // If the default expression creates temporaries, we need to
3152 // push them to the current stack of expression temporaries so they'll
3153 // be properly destroyed.
Douglas Gregor25ab25f2009-12-23 18:19:08 +00003154 // FIXME: We should really be rebuilding the default argument with new
3155 // bound temporaries; see the comment in PR5810.
Anders Carlsson714d0962009-12-15 19:16:31 +00003156 for (unsigned i = 0, e = Param->getNumDefaultArgTemporaries(); i != e; ++i)
3157 ExprTemporaries.push_back(Param->getDefaultArgTemporary(i));
Anders Carlsson355933d2009-08-25 03:49:14 +00003158 }
3159
3160 // We already type-checked the argument, so we know it works.
Douglas Gregor033f6752009-12-23 23:03:06 +00003161 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson355933d2009-08-25 03:49:14 +00003162}
3163
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003164/// ConvertArgumentsForCall - Converts the arguments specified in
3165/// Args/NumArgs to the parameter types of the function FDecl with
3166/// function prototype Proto. Call is the call expression itself, and
3167/// Fn is the function expression. For a C++ member function, this
3168/// routine does not attempt to convert the object argument. Returns
3169/// true if the call is ill-formed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003170bool
3171Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003172 FunctionDecl *FDecl,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003173 const FunctionProtoType *Proto,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003174 Expr **Args, unsigned NumArgs,
3175 SourceLocation RParenLoc) {
Mike Stump4e1f26a2009-02-19 03:04:26 +00003176 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003177 // assignment, to the types of the corresponding parameter, ...
3178 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregorb6b99612009-01-23 21:30:56 +00003179 bool Invalid = false;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003180
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003181 // If too few arguments are available (and we don't have default
3182 // arguments for the remaining parameters), don't make the call.
3183 if (NumArgs < NumArgsInProto) {
3184 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
3185 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
3186 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
Ted Kremenek5a201952009-02-07 01:47:29 +00003187 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003188 }
3189
3190 // If too many are passed and not variadic, error on the extras and drop
3191 // them.
3192 if (NumArgs > NumArgsInProto) {
3193 if (!Proto->isVariadic()) {
3194 Diag(Args[NumArgsInProto]->getLocStart(),
3195 diag::err_typecheck_call_too_many_args)
3196 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
3197 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3198 Args[NumArgs-1]->getLocEnd());
3199 // This deletes the extra arguments.
Ted Kremenek5a201952009-02-07 01:47:29 +00003200 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003201 return true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003202 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003203 }
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003204 llvm::SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003205 VariadicCallType CallType =
3206 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
3207 if (Fn->getType()->isBlockPointerType())
3208 CallType = VariadicBlock; // Block
3209 else if (isa<MemberExpr>(Fn))
3210 CallType = VariadicMethod;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003211 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00003212 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003213 if (Invalid)
3214 return true;
3215 unsigned TotalNumArgs = AllArgs.size();
3216 for (unsigned i = 0; i < TotalNumArgs; ++i)
3217 Call->setArg(i, AllArgs[i]);
3218
3219 return false;
3220}
Mike Stump4e1f26a2009-02-19 03:04:26 +00003221
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003222bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
3223 FunctionDecl *FDecl,
3224 const FunctionProtoType *Proto,
3225 unsigned FirstProtoArg,
3226 Expr **Args, unsigned NumArgs,
3227 llvm::SmallVector<Expr *, 8> &AllArgs,
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003228 VariadicCallType CallType) {
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003229 unsigned NumArgsInProto = Proto->getNumArgs();
3230 unsigned NumArgsToCheck = NumArgs;
3231 bool Invalid = false;
3232 if (NumArgs != NumArgsInProto)
3233 // Use default arguments for missing arguments
3234 NumArgsToCheck = NumArgsInProto;
3235 unsigned ArgIx = 0;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003236 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003237 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003238 QualType ProtoArgType = Proto->getArgType(i);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003239
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003240 Expr *Arg;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003241 if (ArgIx < NumArgs) {
3242 Arg = Args[ArgIx++];
3243
Eli Friedman3164fb12009-03-22 22:00:50 +00003244 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3245 ProtoArgType,
Anders Carlssond624e162009-08-26 23:45:07 +00003246 PDiag(diag::err_call_incomplete_argument)
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003247 << Arg->getSourceRange()))
Eli Friedman3164fb12009-03-22 22:00:50 +00003248 return true;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003249
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003250 // Pass the argument
3251 ParmVarDecl *Param = 0;
3252 if (FDecl && i < FDecl->getNumParams())
3253 Param = FDecl->getParamDecl(i);
Douglas Gregor96596c92009-12-22 07:24:36 +00003254
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003255
3256 InitializedEntity Entity =
3257 Param? InitializedEntity::InitializeParameter(Param)
3258 : InitializedEntity::InitializeParameter(ProtoArgType);
3259 OwningExprResult ArgE = PerformCopyInitialization(Entity,
3260 SourceLocation(),
3261 Owned(Arg));
3262 if (ArgE.isInvalid())
3263 return true;
3264
3265 Arg = ArgE.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00003266 } else {
Anders Carlssonc80a1272009-08-25 02:29:20 +00003267 ParmVarDecl *Param = FDecl->getParamDecl(i);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003268
Mike Stump11289f42009-09-09 15:08:12 +00003269 OwningExprResult ArgExpr =
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003270 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson355933d2009-08-25 03:49:14 +00003271 if (ArgExpr.isInvalid())
3272 return true;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003273
Anders Carlsson355933d2009-08-25 03:49:14 +00003274 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00003275 }
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003276 AllArgs.push_back(Arg);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003277 }
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003278
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003279 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003280 if (CallType != VariadicDoesNotApply) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003281 // Promote the arguments (C99 6.5.2.2p7).
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003282 for (unsigned i = ArgIx; i < NumArgs; i++) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003283 Expr *Arg = Args[i];
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00003284 Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003285 AllArgs.push_back(Arg);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003286 }
3287 }
Douglas Gregorb6b99612009-01-23 21:30:56 +00003288 return Invalid;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003289}
3290
Steve Naroff83895f72007-09-16 03:34:24 +00003291/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattnere168f762006-11-10 05:29:30 +00003292/// This provides the location of the left/right parens and a list of comma
3293/// locations.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003294Action::OwningExprResult
3295Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
3296 MultiExprArg args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003297 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003298 unsigned NumArgs = args.size();
Nate Begeman5ec4b312009-08-10 23:49:36 +00003299
3300 // Since this might be a postfix expression, get rid of ParenListExprs.
3301 fn = MaybeConvertParenListExprToParenExpr(S, move(fn));
Mike Stump11289f42009-09-09 15:08:12 +00003302
Anders Carlsson3cbc8592009-05-01 19:30:39 +00003303 Expr *Fn = fn.takeAs<Expr>();
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003304 Expr **Args = reinterpret_cast<Expr**>(args.release());
Chris Lattner38dbdb22007-07-21 03:03:59 +00003305 assert(Fn && "no function call expression");
Mike Stump11289f42009-09-09 15:08:12 +00003306
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003307 if (getLangOptions().CPlusPlus) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00003308 // If this is a pseudo-destructor expression, build the call immediately.
3309 if (isa<CXXPseudoDestructorExpr>(Fn)) {
3310 if (NumArgs > 0) {
3311 // Pseudo-destructor calls should not have any arguments.
3312 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
3313 << CodeModificationHint::CreateRemoval(
3314 SourceRange(Args[0]->getLocStart(),
3315 Args[NumArgs-1]->getLocEnd()));
Mike Stump11289f42009-09-09 15:08:12 +00003316
Douglas Gregorad8a3362009-09-04 17:36:40 +00003317 for (unsigned I = 0; I != NumArgs; ++I)
3318 Args[I]->Destroy(Context);
Mike Stump11289f42009-09-09 15:08:12 +00003319
Douglas Gregorad8a3362009-09-04 17:36:40 +00003320 NumArgs = 0;
3321 }
Mike Stump11289f42009-09-09 15:08:12 +00003322
Douglas Gregorad8a3362009-09-04 17:36:40 +00003323 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
3324 RParenLoc));
3325 }
Mike Stump11289f42009-09-09 15:08:12 +00003326
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003327 // Determine whether this is a dependent call inside a C++ template,
Mike Stump4e1f26a2009-02-19 03:04:26 +00003328 // in which case we won't do any semantic analysis now.
Mike Stump87c57ac2009-05-16 07:39:55 +00003329 // FIXME: Will need to cache the results of name lookup (including ADL) in
3330 // Fn.
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003331 bool Dependent = false;
3332 if (Fn->isTypeDependent())
3333 Dependent = true;
3334 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
3335 Dependent = true;
3336
3337 if (Dependent)
Ted Kremenekd7b4f402009-02-09 20:51:47 +00003338 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003339 Context.DependentTy, RParenLoc));
3340
3341 // Determine whether this is a call to an object (C++ [over.call.object]).
3342 if (Fn->getType()->isRecordType())
3343 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
3344 CommaLocs, RParenLoc));
3345
John McCall10eae182009-11-30 22:42:35 +00003346 Expr *NakedFn = Fn->IgnoreParens();
3347
3348 // Determine whether this is a call to an unresolved member function.
3349 if (UnresolvedMemberExpr *MemE = dyn_cast<UnresolvedMemberExpr>(NakedFn)) {
3350 // If lookup was unresolved but not dependent (i.e. didn't find
3351 // an unresolved using declaration), it has to be an overloaded
3352 // function set, which means it must contain either multiple
3353 // declarations (all methods or method templates) or a single
3354 // method template.
3355 assert((MemE->getNumDecls() > 1) ||
3356 isa<FunctionTemplateDecl>(*MemE->decls_begin()));
Douglas Gregor8f184a32009-12-01 03:34:29 +00003357 (void)MemE;
John McCall10eae182009-11-30 22:42:35 +00003358
John McCall2d74de92009-12-01 22:10:20 +00003359 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
3360 CommaLocs, RParenLoc);
John McCall10eae182009-11-30 22:42:35 +00003361 }
3362
Douglas Gregore254f902009-02-04 00:32:51 +00003363 // Determine whether this is a call to a member function.
John McCall10eae182009-11-30 22:42:35 +00003364 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(NakedFn)) {
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003365 NamedDecl *MemDecl = MemExpr->getMemberDecl();
John McCall10eae182009-11-30 22:42:35 +00003366 if (isa<CXXMethodDecl>(MemDecl))
John McCall2d74de92009-12-01 22:10:20 +00003367 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
3368 CommaLocs, RParenLoc);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003369 }
Anders Carlsson61914b52009-10-03 17:40:22 +00003370
3371 // Determine whether this is a call to a pointer-to-member function.
John McCall10eae182009-11-30 22:42:35 +00003372 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(NakedFn)) {
Anders Carlsson61914b52009-10-03 17:40:22 +00003373 if (BO->getOpcode() == BinaryOperator::PtrMemD ||
3374 BO->getOpcode() == BinaryOperator::PtrMemI) {
Fariborz Jahanian42f66632009-10-28 16:49:46 +00003375 if (const FunctionProtoType *FPT =
3376 dyn_cast<FunctionProtoType>(BO->getType())) {
3377 QualType ResultTy = FPT->getResultType().getNonReferenceType();
Anders Carlsson61914b52009-10-03 17:40:22 +00003378
Fariborz Jahanian42f66632009-10-28 16:49:46 +00003379 ExprOwningPtr<CXXMemberCallExpr>
3380 TheCall(this, new (Context) CXXMemberCallExpr(Context, BO, Args,
3381 NumArgs, ResultTy,
3382 RParenLoc));
Anders Carlsson61914b52009-10-03 17:40:22 +00003383
Fariborz Jahanian42f66632009-10-28 16:49:46 +00003384 if (CheckCallReturnType(FPT->getResultType(),
3385 BO->getRHS()->getSourceRange().getBegin(),
3386 TheCall.get(), 0))
3387 return ExprError();
Anders Carlsson63dce022009-10-15 00:41:48 +00003388
Fariborz Jahanian42f66632009-10-28 16:49:46 +00003389 if (ConvertArgumentsForCall(&*TheCall, BO, 0, FPT, Args, NumArgs,
3390 RParenLoc))
3391 return ExprError();
Anders Carlsson61914b52009-10-03 17:40:22 +00003392
Fariborz Jahanian42f66632009-10-28 16:49:46 +00003393 return Owned(MaybeBindToTemporary(TheCall.release()).release());
3394 }
3395 return ExprError(Diag(Fn->getLocStart(),
3396 diag::err_typecheck_call_not_function)
3397 << Fn->getType() << Fn->getSourceRange());
Anders Carlsson61914b52009-10-03 17:40:22 +00003398 }
3399 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003400 }
3401
Douglas Gregore254f902009-02-04 00:32:51 +00003402 // If we're directly calling a function, get the appropriate declaration.
Mike Stump11289f42009-09-09 15:08:12 +00003403 // Also, in C++, keep track of whether we should perform argument-dependent
Douglas Gregor89026b52009-06-30 23:57:56 +00003404 // lookup and whether there were any explicitly-specified template arguments.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003405
Eli Friedmane14b1992009-12-26 03:35:45 +00003406 Expr *NakedFn = Fn->IgnoreParens();
John McCall57500772009-12-16 12:17:52 +00003407 if (isa<UnresolvedLookupExpr>(NakedFn)) {
3408 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(NakedFn);
3409 return BuildOverloadedCallExpr(Fn, ULE, LParenLoc, Args, NumArgs,
3410 CommaLocs, RParenLoc);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003411 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00003412
John McCall57500772009-12-16 12:17:52 +00003413 NamedDecl *NDecl = 0;
3414 if (isa<DeclRefExpr>(NakedFn))
3415 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
3416
John McCall2d74de92009-12-01 22:10:20 +00003417 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc);
3418}
3419
John McCall57500772009-12-16 12:17:52 +00003420/// BuildResolvedCallExpr - Build a call to a resolved expression,
3421/// i.e. an expression not of \p OverloadTy. The expression should
John McCall2d74de92009-12-01 22:10:20 +00003422/// unary-convert to an expression of function-pointer or
3423/// block-pointer type.
3424///
3425/// \param NDecl the declaration being called, if available
3426Sema::OwningExprResult
3427Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
3428 SourceLocation LParenLoc,
3429 Expr **Args, unsigned NumArgs,
3430 SourceLocation RParenLoc) {
3431 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
3432
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00003433 // Promote the function operand.
3434 UsualUnaryConversions(Fn);
3435
Chris Lattner08464942007-12-28 05:29:59 +00003436 // Make the call expr early, before semantic checks. This guarantees cleanup
3437 // of arguments and function on error.
Ted Kremenekd7b4f402009-02-09 20:51:47 +00003438 ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
3439 Args, NumArgs,
3440 Context.BoolTy,
3441 RParenLoc));
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003442
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003443 const FunctionType *FuncT;
3444 if (!Fn->getType()->isBlockPointerType()) {
3445 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
3446 // have type pointer to function".
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003447 const PointerType *PT = Fn->getType()->getAs<PointerType>();
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003448 if (PT == 0)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003449 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3450 << Fn->getType() << Fn->getSourceRange());
John McCall9dd450b2009-09-21 23:43:11 +00003451 FuncT = PT->getPointeeType()->getAs<FunctionType>();
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003452 } else { // This is a block call.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003453 FuncT = Fn->getType()->getAs<BlockPointerType>()->getPointeeType()->
John McCall9dd450b2009-09-21 23:43:11 +00003454 getAs<FunctionType>();
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003455 }
Chris Lattner08464942007-12-28 05:29:59 +00003456 if (FuncT == 0)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003457 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3458 << Fn->getType() << Fn->getSourceRange());
3459
Eli Friedman3164fb12009-03-22 22:00:50 +00003460 // Check for a valid return type
Anders Carlsson7f84ed92009-10-09 23:51:55 +00003461 if (CheckCallReturnType(FuncT->getResultType(),
3462 Fn->getSourceRange().getBegin(), TheCall.get(),
3463 FDecl))
Eli Friedman3164fb12009-03-22 22:00:50 +00003464 return ExprError();
3465
Chris Lattner08464942007-12-28 05:29:59 +00003466 // We know the result type of the call, set it.
Douglas Gregor786ab212008-10-29 02:00:59 +00003467 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003468
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003469 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
Mike Stump4e1f26a2009-02-19 03:04:26 +00003470 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003471 RParenLoc))
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003472 return ExprError();
Chris Lattner08464942007-12-28 05:29:59 +00003473 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003474 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003475
Douglas Gregord8e97de2009-04-02 15:37:10 +00003476 if (FDecl) {
3477 // Check if we have too few/too many template arguments, based
3478 // on our knowledge of the function definition.
3479 const FunctionDecl *Def = 0;
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00003480 if (FDecl->getBody(Def) && NumArgs != Def->param_size()) {
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00003481 const FunctionProtoType *Proto =
John McCall9dd450b2009-09-21 23:43:11 +00003482 Def->getType()->getAs<FunctionProtoType>();
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00003483 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size())) {
3484 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
3485 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
3486 }
3487 }
Douglas Gregord8e97de2009-04-02 15:37:10 +00003488 }
3489
Steve Naroff0b661582007-08-28 23:30:39 +00003490 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner08464942007-12-28 05:29:59 +00003491 for (unsigned i = 0; i != NumArgs; i++) {
3492 Expr *Arg = Args[i];
3493 DefaultArgumentPromotion(Arg);
Eli Friedman3164fb12009-03-22 22:00:50 +00003494 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3495 Arg->getType(),
Anders Carlssond624e162009-08-26 23:45:07 +00003496 PDiag(diag::err_call_incomplete_argument)
3497 << Arg->getSourceRange()))
Eli Friedman3164fb12009-03-22 22:00:50 +00003498 return ExprError();
Chris Lattner08464942007-12-28 05:29:59 +00003499 TheCall->setArg(i, Arg);
Steve Naroff0b661582007-08-28 23:30:39 +00003500 }
Steve Naroffae4143e2007-04-26 20:39:23 +00003501 }
Chris Lattner08464942007-12-28 05:29:59 +00003502
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003503 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3504 if (!Method->isStatic())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003505 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
3506 << Fn->getSourceRange());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003507
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +00003508 // Check for sentinels
3509 if (NDecl)
3510 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump11289f42009-09-09 15:08:12 +00003511
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003512 // Do special checking on direct calls to functions.
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003513 if (FDecl) {
3514 if (CheckFunctionCall(FDecl, TheCall.get()))
3515 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003516
Douglas Gregor15fc9562009-09-12 00:22:50 +00003517 if (unsigned BuiltinID = FDecl->getBuiltinID())
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003518 return CheckBuiltinFunctionCall(BuiltinID, TheCall.take());
3519 } else if (NDecl) {
3520 if (CheckBlockCall(NDecl, TheCall.get()))
3521 return ExprError();
3522 }
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003523
Anders Carlssonf8984012009-08-16 03:06:32 +00003524 return MaybeBindToTemporary(TheCall.take());
Chris Lattnere168f762006-11-10 05:29:30 +00003525}
3526
Sebastian Redlb5d49352009-01-19 22:31:54 +00003527Action::OwningExprResult
3528Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
3529 SourceLocation RParenLoc, ExprArg InitExpr) {
Steve Naroff83895f72007-09-16 03:34:24 +00003530 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Douglas Gregor85dabae2009-12-16 01:38:02 +00003531
Douglas Gregor1b303932009-12-22 15:35:07 +00003532 QualType literalType = GetTypeFromParser(Ty);
Douglas Gregor85dabae2009-12-16 01:38:02 +00003533
Steve Naroff57eb2c52007-07-19 21:32:11 +00003534 // FIXME: put back this assert when initializers are worked out.
Steve Naroff83895f72007-09-16 03:34:24 +00003535 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Sebastian Redlb5d49352009-01-19 22:31:54 +00003536 Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
Anders Carlsson2c1ec6d2007-12-05 07:24:19 +00003537
Eli Friedman37a186d2008-05-20 05:22:08 +00003538 if (literalType->isArrayType()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00003539 if (literalType->isVariableArrayType())
Sebastian Redlb5d49352009-01-19 22:31:54 +00003540 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
3541 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor1c37d9e2009-05-21 23:48:18 +00003542 } else if (!literalType->isDependentType() &&
3543 RequireCompleteType(LParenLoc, literalType,
Anders Carlssond624e162009-08-26 23:45:07 +00003544 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump11289f42009-09-09 15:08:12 +00003545 << SourceRange(LParenLoc,
Anders Carlssond624e162009-08-26 23:45:07 +00003546 literalExpr->getSourceRange().getEnd())))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003547 return ExprError();
Eli Friedman37a186d2008-05-20 05:22:08 +00003548
Douglas Gregor85dabae2009-12-16 01:38:02 +00003549 InitializedEntity Entity
Douglas Gregor1b303932009-12-22 15:35:07 +00003550 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor85dabae2009-12-16 01:38:02 +00003551 InitializationKind Kind
3552 = InitializationKind::CreateCast(SourceRange(LParenLoc, RParenLoc),
3553 /*IsCStyleCast=*/true);
Eli Friedmana553d4a2009-12-22 02:35:53 +00003554 InitializationSequence InitSeq(*this, Entity, Kind, &literalExpr, 1);
3555 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
3556 MultiExprArg(*this, (void**)&literalExpr, 1),
3557 &literalType);
3558 if (Result.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00003559 return ExprError();
Eli Friedmana553d4a2009-12-22 02:35:53 +00003560 InitExpr.release();
3561 literalExpr = static_cast<Expr*>(Result.get());
Steve Naroffd32419d2008-01-14 18:19:28 +00003562
Chris Lattner79413952008-12-04 23:50:19 +00003563 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffd32419d2008-01-14 18:19:28 +00003564 if (isFileScope) { // 6.5.2.5p3
Steve Naroff98f72032008-01-10 22:15:12 +00003565 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003566 return ExprError();
Steve Naroff98f72032008-01-10 22:15:12 +00003567 }
Eli Friedmana553d4a2009-12-22 02:35:53 +00003568
3569 Result.release();
Douglas Gregor85dabae2009-12-16 01:38:02 +00003570
3571 // FIXME: Store the TInfo to preserve type information better.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003572 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType,
Steve Narofff6009ed2009-01-21 00:14:39 +00003573 literalExpr, isFileScope));
Steve Narofffbd09832007-07-19 01:06:55 +00003574}
3575
Sebastian Redlb5d49352009-01-19 22:31:54 +00003576Action::OwningExprResult
3577Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redlb5d49352009-01-19 22:31:54 +00003578 SourceLocation RBraceLoc) {
3579 unsigned NumInit = initlist.size();
3580 Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
Anders Carlsson4692db02007-08-31 04:56:16 +00003581
Steve Naroff30d242c2007-09-15 18:49:24 +00003582 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump4e1f26a2009-02-19 03:04:26 +00003583 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb5d49352009-01-19 22:31:54 +00003584
Mike Stump4e1f26a2009-02-19 03:04:26 +00003585 InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00003586 RBraceLoc);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003587 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb5d49352009-01-19 22:31:54 +00003588 return Owned(E);
Steve Narofffbd09832007-07-19 01:06:55 +00003589}
3590
Anders Carlsson094c4592009-10-18 18:12:03 +00003591static CastExpr::CastKind getScalarCastKind(ASTContext &Context,
3592 QualType SrcTy, QualType DestTy) {
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003593 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
Anders Carlsson094c4592009-10-18 18:12:03 +00003594 return CastExpr::CK_NoOp;
3595
3596 if (SrcTy->hasPointerRepresentation()) {
3597 if (DestTy->hasPointerRepresentation())
Fariborz Jahanian2b9fc832009-12-15 21:34:52 +00003598 return DestTy->isObjCObjectPointerType() ?
3599 CastExpr::CK_AnyPointerToObjCPointerCast :
3600 CastExpr::CK_BitCast;
Anders Carlsson094c4592009-10-18 18:12:03 +00003601 if (DestTy->isIntegerType())
3602 return CastExpr::CK_PointerToIntegral;
3603 }
3604
3605 if (SrcTy->isIntegerType()) {
3606 if (DestTy->isIntegerType())
3607 return CastExpr::CK_IntegralCast;
3608 if (DestTy->hasPointerRepresentation())
3609 return CastExpr::CK_IntegralToPointer;
3610 if (DestTy->isRealFloatingType())
3611 return CastExpr::CK_IntegralToFloating;
3612 }
3613
3614 if (SrcTy->isRealFloatingType()) {
3615 if (DestTy->isRealFloatingType())
3616 return CastExpr::CK_FloatingCast;
3617 if (DestTy->isIntegerType())
3618 return CastExpr::CK_FloatingToIntegral;
3619 }
3620
3621 // FIXME: Assert here.
3622 // assert(false && "Unhandled cast combination!");
3623 return CastExpr::CK_Unknown;
3624}
3625
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003626/// CheckCastTypes - Check type constraints for casting between types.
Sebastian Redl955a0672009-07-29 13:50:23 +00003627bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr,
Mike Stump11289f42009-09-09 15:08:12 +00003628 CastExpr::CastKind& Kind,
Fariborz Jahanian1cec0c42009-08-26 18:55:36 +00003629 CXXMethodDecl *& ConversionDecl,
3630 bool FunctionalStyle) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00003631 if (getLangOptions().CPlusPlus)
Fariborz Jahanian1cec0c42009-08-26 18:55:36 +00003632 return CXXCheckCStyleCast(TyR, castType, castExpr, Kind, FunctionalStyle,
3633 ConversionDecl);
Sebastian Redl9f831db2009-07-25 15:41:38 +00003634
Eli Friedmanda8d4de2009-08-15 19:02:19 +00003635 DefaultFunctionArrayConversion(castExpr);
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003636
3637 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
3638 // type needs to be scalar.
3639 if (castType->isVoidType()) {
3640 // Cast to void allows any expr type.
Anders Carlssonef918ac2009-10-16 02:35:04 +00003641 Kind = CastExpr::CK_ToVoid;
3642 return false;
3643 }
3644
3645 if (!castType->isScalarType() && !castType->isVectorType()) {
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003646 if (Context.hasSameUnqualifiedType(castType, castExpr->getType()) &&
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003647 (castType->isStructureType() || castType->isUnionType())) {
3648 // GCC struct/union extension: allow cast to self.
Eli Friedmanba961a92009-03-23 00:24:07 +00003649 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003650 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
3651 << castType << castExpr->getSourceRange();
Anders Carlssonec143772009-08-07 23:22:37 +00003652 Kind = CastExpr::CK_NoOp;
Anders Carlsson525b76b2009-10-16 02:48:28 +00003653 return false;
3654 }
3655
3656 if (castType->isUnionType()) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003657 // GCC cast to union extension
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003658 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003659 RecordDecl::field_iterator Field, FieldEnd;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003660 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003661 Field != FieldEnd; ++Field) {
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003662 if (Context.hasSameUnqualifiedType(Field->getType(),
3663 castExpr->getType())) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003664 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
3665 << castExpr->getSourceRange();
3666 break;
3667 }
3668 }
3669 if (Field == FieldEnd)
3670 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
3671 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlssonec143772009-08-07 23:22:37 +00003672 Kind = CastExpr::CK_ToUnion;
Anders Carlsson525b76b2009-10-16 02:48:28 +00003673 return false;
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003674 }
Anders Carlsson525b76b2009-10-16 02:48:28 +00003675
3676 // Reject any other conversions to non-scalar types.
3677 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
3678 << castType << castExpr->getSourceRange();
3679 }
3680
3681 if (!castExpr->getType()->isScalarType() &&
3682 !castExpr->getType()->isVectorType()) {
Chris Lattner3b054132008-11-19 05:08:23 +00003683 return Diag(castExpr->getLocStart(),
3684 diag::err_typecheck_expect_scalar_operand)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003685 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlsson525b76b2009-10-16 02:48:28 +00003686 }
3687
Anders Carlsson43d70f82009-10-16 05:23:41 +00003688 if (castType->isExtVectorType())
3689 return CheckExtVectorCast(TyR, castType, castExpr, Kind);
3690
Anders Carlsson525b76b2009-10-16 02:48:28 +00003691 if (castType->isVectorType())
3692 return CheckVectorCast(TyR, castType, castExpr->getType(), Kind);
3693 if (castExpr->getType()->isVectorType())
3694 return CheckVectorCast(TyR, castExpr->getType(), castType, Kind);
3695
3696 if (getLangOptions().ObjC1 && isa<ObjCSuperExpr>(castExpr))
Steve Naroffb47acdb2009-04-08 23:52:26 +00003697 return Diag(castExpr->getLocStart(), diag::err_illegal_super_cast) << TyR;
Anders Carlsson525b76b2009-10-16 02:48:28 +00003698
Anders Carlsson43d70f82009-10-16 05:23:41 +00003699 if (isa<ObjCSelectorExpr>(castExpr))
3700 return Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
3701
Anders Carlsson525b76b2009-10-16 02:48:28 +00003702 if (!castType->isArithmeticType()) {
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00003703 QualType castExprType = castExpr->getType();
3704 if (!castExprType->isIntegralType() && castExprType->isArithmeticType())
3705 return Diag(castExpr->getLocStart(),
3706 diag::err_cast_pointer_from_non_pointer_int)
3707 << castExprType << castExpr->getSourceRange();
3708 } else if (!castExpr->getType()->isArithmeticType()) {
3709 if (!castType->isIntegralType() && castType->isArithmeticType())
3710 return Diag(castExpr->getLocStart(),
3711 diag::err_cast_pointer_to_non_pointer_int)
3712 << castType << castExpr->getSourceRange();
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003713 }
Anders Carlsson094c4592009-10-18 18:12:03 +00003714
3715 Kind = getScalarCastKind(Context, castExpr->getType(), castType);
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003716 return false;
3717}
3718
Anders Carlsson525b76b2009-10-16 02:48:28 +00003719bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
3720 CastExpr::CastKind &Kind) {
Anders Carlssonde71adf2007-11-27 05:51:55 +00003721 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00003722
Anders Carlssonde71adf2007-11-27 05:51:55 +00003723 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner37e05872008-03-05 18:54:05 +00003724 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonde71adf2007-11-27 05:51:55 +00003725 return Diag(R.getBegin(),
Mike Stump4e1f26a2009-02-19 03:04:26 +00003726 Ty->isVectorType() ?
Anders Carlssonde71adf2007-11-27 05:51:55 +00003727 diag::err_invalid_conversion_between_vectors :
Chris Lattner3b054132008-11-19 05:08:23 +00003728 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003729 << VectorTy << Ty << R;
Anders Carlssonde71adf2007-11-27 05:51:55 +00003730 } else
3731 return Diag(R.getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00003732 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003733 << VectorTy << Ty << R;
Mike Stump4e1f26a2009-02-19 03:04:26 +00003734
Anders Carlsson525b76b2009-10-16 02:48:28 +00003735 Kind = CastExpr::CK_BitCast;
Anders Carlssonde71adf2007-11-27 05:51:55 +00003736 return false;
3737}
3738
Anders Carlsson43d70f82009-10-16 05:23:41 +00003739bool Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *&CastExpr,
3740 CastExpr::CastKind &Kind) {
Nate Begemanc69b7402009-06-26 00:50:28 +00003741 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Anders Carlsson43d70f82009-10-16 05:23:41 +00003742
3743 QualType SrcTy = CastExpr->getType();
3744
Nate Begemanc8961a42009-06-27 22:05:55 +00003745 // If SrcTy is a VectorType, the total size must match to explicitly cast to
3746 // an ExtVectorType.
Nate Begemanc69b7402009-06-26 00:50:28 +00003747 if (SrcTy->isVectorType()) {
3748 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
3749 return Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
3750 << DestTy << SrcTy << R;
Anders Carlsson43d70f82009-10-16 05:23:41 +00003751 Kind = CastExpr::CK_BitCast;
Nate Begemanc69b7402009-06-26 00:50:28 +00003752 return false;
3753 }
3754
Nate Begemanbd956c42009-06-28 02:36:38 +00003755 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begemanc69b7402009-06-26 00:50:28 +00003756 // conversion will take place first from scalar to elt type, and then
3757 // splat from elt type to vector.
Nate Begemanbd956c42009-06-28 02:36:38 +00003758 if (SrcTy->isPointerType())
3759 return Diag(R.getBegin(),
3760 diag::err_invalid_conversion_between_vector_and_scalar)
3761 << DestTy << SrcTy << R;
Eli Friedman06ed2a52009-10-20 08:27:19 +00003762
3763 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
3764 ImpCastExprToType(CastExpr, DestElemTy,
3765 getScalarCastKind(Context, SrcTy, DestElemTy));
Anders Carlsson43d70f82009-10-16 05:23:41 +00003766
3767 Kind = CastExpr::CK_VectorSplat;
Nate Begemanc69b7402009-06-26 00:50:28 +00003768 return false;
3769}
3770
Sebastian Redlb5d49352009-01-19 22:31:54 +00003771Action::OwningExprResult
Nate Begeman5ec4b312009-08-10 23:49:36 +00003772Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, TypeTy *Ty,
Sebastian Redlb5d49352009-01-19 22:31:54 +00003773 SourceLocation RParenLoc, ExprArg Op) {
Anders Carlssonf10e4142009-08-07 22:21:05 +00003774 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Mike Stump11289f42009-09-09 15:08:12 +00003775
Sebastian Redlb5d49352009-01-19 22:31:54 +00003776 assert((Ty != 0) && (Op.get() != 0) &&
3777 "ActOnCastExpr(): missing type or expr");
Steve Naroff1a2cf6b2007-07-16 23:25:18 +00003778
Nate Begeman5ec4b312009-08-10 23:49:36 +00003779 Expr *castExpr = (Expr *)Op.get();
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00003780 //FIXME: Preserve type source info.
3781 QualType castType = GetTypeFromParser(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00003782
Nate Begeman5ec4b312009-08-10 23:49:36 +00003783 // If the Expr being casted is a ParenListExpr, handle it specially.
3784 if (isa<ParenListExpr>(castExpr))
3785 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, move(Op),castType);
Anders Carlssone9766d52009-09-09 21:33:21 +00003786 CXXMethodDecl *Method = 0;
Mike Stump11289f42009-09-09 15:08:12 +00003787 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr,
Anders Carlssone9766d52009-09-09 21:33:21 +00003788 Kind, Method))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003789 return ExprError();
Anders Carlssone9766d52009-09-09 21:33:21 +00003790
3791 if (Method) {
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00003792 OwningExprResult CastArg = BuildCXXCastArgument(LParenLoc, castType, Kind,
Anders Carlssone9766d52009-09-09 21:33:21 +00003793 Method, move(Op));
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00003794
Anders Carlssone9766d52009-09-09 21:33:21 +00003795 if (CastArg.isInvalid())
3796 return ExprError();
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00003797
Anders Carlssone9766d52009-09-09 21:33:21 +00003798 castExpr = CastArg.takeAs<Expr>();
3799 } else {
3800 Op.release();
Fariborz Jahanian3df87672009-08-29 19:15:16 +00003801 }
Mike Stump11289f42009-09-09 15:08:12 +00003802
Sebastian Redl9f831db2009-07-25 15:41:38 +00003803 return Owned(new (Context) CStyleCastExpr(castType.getNonReferenceType(),
Mike Stump11289f42009-09-09 15:08:12 +00003804 Kind, castExpr, castType,
Anders Carlssonf10e4142009-08-07 22:21:05 +00003805 LParenLoc, RParenLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00003806}
3807
Nate Begeman5ec4b312009-08-10 23:49:36 +00003808/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
3809/// of comma binary operators.
3810Action::OwningExprResult
3811Sema::MaybeConvertParenListExprToParenExpr(Scope *S, ExprArg EA) {
3812 Expr *expr = EA.takeAs<Expr>();
3813 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
3814 if (!E)
3815 return Owned(expr);
Mike Stump11289f42009-09-09 15:08:12 +00003816
Nate Begeman5ec4b312009-08-10 23:49:36 +00003817 OwningExprResult Result(*this, E->getExpr(0));
Mike Stump11289f42009-09-09 15:08:12 +00003818
Nate Begeman5ec4b312009-08-10 23:49:36 +00003819 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
3820 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, move(Result),
3821 Owned(E->getExpr(i)));
Mike Stump11289f42009-09-09 15:08:12 +00003822
Nate Begeman5ec4b312009-08-10 23:49:36 +00003823 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), move(Result));
3824}
3825
3826Action::OwningExprResult
3827Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
3828 SourceLocation RParenLoc, ExprArg Op,
3829 QualType Ty) {
3830 ParenListExpr *PE = (ParenListExpr *)Op.get();
Mike Stump11289f42009-09-09 15:08:12 +00003831
3832 // If this is an altivec initializer, '(' type ')' '(' init, ..., init ')'
Nate Begeman5ec4b312009-08-10 23:49:36 +00003833 // then handle it as such.
3834 if (getLangOptions().AltiVec && Ty->isVectorType()) {
3835 if (PE->getNumExprs() == 0) {
3836 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
3837 return ExprError();
3838 }
3839
3840 llvm::SmallVector<Expr *, 8> initExprs;
3841 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
3842 initExprs.push_back(PE->getExpr(i));
3843
3844 // FIXME: This means that pretty-printing the final AST will produce curly
3845 // braces instead of the original commas.
3846 Op.release();
Mike Stump11289f42009-09-09 15:08:12 +00003847 InitListExpr *E = new (Context) InitListExpr(LParenLoc, &initExprs[0],
Nate Begeman5ec4b312009-08-10 23:49:36 +00003848 initExprs.size(), RParenLoc);
3849 E->setType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00003850 return ActOnCompoundLiteral(LParenLoc, Ty.getAsOpaquePtr(), RParenLoc,
Nate Begeman5ec4b312009-08-10 23:49:36 +00003851 Owned(E));
3852 } else {
Mike Stump11289f42009-09-09 15:08:12 +00003853 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
Nate Begeman5ec4b312009-08-10 23:49:36 +00003854 // sequence of BinOp comma operators.
3855 Op = MaybeConvertParenListExprToParenExpr(S, move(Op));
3856 return ActOnCastExpr(S, LParenLoc, Ty.getAsOpaquePtr(), RParenLoc,move(Op));
3857 }
3858}
3859
Fariborz Jahanian906d8712009-11-25 01:26:41 +00003860Action::OwningExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
Nate Begeman5ec4b312009-08-10 23:49:36 +00003861 SourceLocation R,
Fariborz Jahanian906d8712009-11-25 01:26:41 +00003862 MultiExprArg Val,
3863 TypeTy *TypeOfCast) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00003864 unsigned nexprs = Val.size();
3865 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanian906d8712009-11-25 01:26:41 +00003866 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
3867 Expr *expr;
3868 if (nexprs == 1 && TypeOfCast && !TypeIsVectorType(TypeOfCast))
3869 expr = new (Context) ParenExpr(L, R, exprs[0]);
3870 else
3871 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
Nate Begeman5ec4b312009-08-10 23:49:36 +00003872 return Owned(expr);
3873}
3874
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003875/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
3876/// In that case, lhs = cond.
Chris Lattner2c486602009-02-18 04:38:20 +00003877/// C99 6.5.15
3878QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
3879 SourceLocation QuestionLoc) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00003880 // C++ is sufficiently different to merit its own checker.
3881 if (getLangOptions().CPlusPlus)
3882 return CXXCheckConditionalOperands(Cond, LHS, RHS, QuestionLoc);
3883
John McCall1fa36b72009-11-05 09:23:39 +00003884 CheckSignCompare(LHS, RHS, QuestionLoc, diag::warn_mixed_sign_conditional);
3885
Chris Lattner432cff52009-02-18 04:28:32 +00003886 UsualUnaryConversions(Cond);
3887 UsualUnaryConversions(LHS);
3888 UsualUnaryConversions(RHS);
3889 QualType CondTy = Cond->getType();
3890 QualType LHSTy = LHS->getType();
3891 QualType RHSTy = RHS->getType();
Steve Naroff31090012007-07-16 21:54:35 +00003892
Steve Naroffa78fe7e2007-05-16 19:47:19 +00003893 // first, check the condition.
Sebastian Redl1a99f442009-04-16 17:51:27 +00003894 if (!CondTy->isScalarType()) { // C99 6.5.15p2
3895 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
3896 << CondTy;
3897 return QualType();
Steve Naroffa78fe7e2007-05-16 19:47:19 +00003898 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00003899
Chris Lattnere2949f42008-01-06 22:42:25 +00003900 // Now check the two expressions.
Nate Begeman5ec4b312009-08-10 23:49:36 +00003901 if (LHSTy->isVectorType() || RHSTy->isVectorType())
3902 return CheckVectorOperands(QuestionLoc, LHS, RHS);
Douglas Gregor4619e432008-12-05 23:32:09 +00003903
Chris Lattnere2949f42008-01-06 22:42:25 +00003904 // If both operands have arithmetic type, do the usual arithmetic conversions
3905 // to find a common type: C99 6.5.15p3,5.
Chris Lattner432cff52009-02-18 04:28:32 +00003906 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
3907 UsualArithmeticConversions(LHS, RHS);
3908 return LHS->getType();
Steve Naroffdbd9e892007-07-17 00:58:39 +00003909 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00003910
Chris Lattnere2949f42008-01-06 22:42:25 +00003911 // If both operands are the same structure or union type, the result is that
3912 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003913 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
3914 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattner2ab40a62007-11-26 01:40:58 +00003915 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump4e1f26a2009-02-19 03:04:26 +00003916 // "If both the operands have structure or union type, the result has
Chris Lattnere2949f42008-01-06 22:42:25 +00003917 // that type." This implies that CV qualifiers are dropped.
Chris Lattner432cff52009-02-18 04:28:32 +00003918 return LHSTy.getUnqualifiedType();
Eli Friedmanba961a92009-03-23 00:24:07 +00003919 // FIXME: Type of conditional expression must be complete in C mode.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00003920 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00003921
Chris Lattnere2949f42008-01-06 22:42:25 +00003922 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffbf1516c2008-05-12 21:44:38 +00003923 // The following || allows only one side to be void (a GCC-ism).
Chris Lattner432cff52009-02-18 04:28:32 +00003924 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
3925 if (!LHSTy->isVoidType())
3926 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
3927 << RHS->getSourceRange();
3928 if (!RHSTy->isVoidType())
3929 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
3930 << LHS->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00003931 ImpCastExprToType(LHS, Context.VoidTy, CastExpr::CK_ToVoid);
3932 ImpCastExprToType(RHS, Context.VoidTy, CastExpr::CK_ToVoid);
Eli Friedman3e1852f2008-06-04 19:47:51 +00003933 return Context.VoidTy;
Steve Naroffbf1516c2008-05-12 21:44:38 +00003934 }
Steve Naroff039ad3c2008-01-08 01:11:38 +00003935 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
3936 // the type of the other operand."
Steve Naroff6b712a72009-07-14 18:25:06 +00003937 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
Douglas Gregor56751b52009-09-25 04:25:58 +00003938 RHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00003939 // promote the null to a pointer.
3940 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_Unknown);
Chris Lattner432cff52009-02-18 04:28:32 +00003941 return LHSTy;
Steve Naroff039ad3c2008-01-08 01:11:38 +00003942 }
Steve Naroff6b712a72009-07-14 18:25:06 +00003943 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
Douglas Gregor56751b52009-09-25 04:25:58 +00003944 LHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00003945 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_Unknown);
Chris Lattner432cff52009-02-18 04:28:32 +00003946 return RHSTy;
Steve Naroff039ad3c2008-01-08 01:11:38 +00003947 }
Fariborz Jahaniana430f712009-12-10 19:47:41 +00003948
3949 // All objective-c pointer type analysis is done here.
3950 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
3951 QuestionLoc);
3952 if (!compositeType.isNull())
3953 return compositeType;
3954
3955
Steve Naroff05efa972009-07-01 14:36:47 +00003956 // Handle block pointer types.
3957 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
3958 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
3959 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
3960 QualType destType = Context.getPointerType(Context.VoidTy);
Eli Friedman06ed2a52009-10-20 08:27:19 +00003961 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
3962 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00003963 return destType;
3964 }
3965 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Fariborz Jahaniana430f712009-12-10 19:47:41 +00003966 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Steve Naroff05efa972009-07-01 14:36:47 +00003967 return QualType();
Mike Stump1b821b42009-05-07 03:14:14 +00003968 }
Steve Naroff05efa972009-07-01 14:36:47 +00003969 // We have 2 block pointer types.
3970 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3971 // Two identical block pointer types are always compatible.
Mike Stump1b821b42009-05-07 03:14:14 +00003972 return LHSTy;
3973 }
Steve Naroff05efa972009-07-01 14:36:47 +00003974 // The block pointer types aren't identical, continue checking.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003975 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
3976 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00003977
Steve Naroff05efa972009-07-01 14:36:47 +00003978 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
3979 rhptee.getUnqualifiedType())) {
Mike Stump1b821b42009-05-07 03:14:14 +00003980 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
Fariborz Jahaniana430f712009-12-10 19:47:41 +00003981 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stump1b821b42009-05-07 03:14:14 +00003982 // In this situation, we assume void* type. No especially good
3983 // reason, but this is what gcc does, and we do have to pick
3984 // to get a consistent AST.
3985 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Eli Friedman06ed2a52009-10-20 08:27:19 +00003986 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
3987 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
Mike Stump1b821b42009-05-07 03:14:14 +00003988 return incompatTy;
Steve Naroffa78fe7e2007-05-16 19:47:19 +00003989 }
Steve Naroff05efa972009-07-01 14:36:47 +00003990 // The block pointer types are compatible.
Eli Friedman06ed2a52009-10-20 08:27:19 +00003991 ImpCastExprToType(LHS, LHSTy, CastExpr::CK_BitCast);
3992 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
Steve Naroffea4c7802009-04-08 17:05:15 +00003993 return LHSTy;
3994 }
Fariborz Jahaniana430f712009-12-10 19:47:41 +00003995
Steve Naroff05efa972009-07-01 14:36:47 +00003996 // Check constraints for C object pointers types (C99 6.5.15p3,6).
3997 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
3998 // get the "pointed to" types
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003999 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4000 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff05efa972009-07-01 14:36:47 +00004001
4002 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
4003 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
4004 // Figure out necessary qualifiers (C99 6.5.15p6)
John McCall8ccfcb52009-09-24 19:53:00 +00004005 QualType destPointee
4006 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
Steve Naroff05efa972009-07-01 14:36:47 +00004007 QualType destType = Context.getPointerType(destPointee);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004008 // Add qualifiers if necessary.
4009 ImpCastExprToType(LHS, destType, CastExpr::CK_NoOp);
4010 // Promote to void*.
4011 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004012 return destType;
4013 }
4014 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00004015 QualType destPointee
4016 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
Steve Naroff05efa972009-07-01 14:36:47 +00004017 QualType destType = Context.getPointerType(destPointee);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004018 // Add qualifiers if necessary.
Eli Friedmanb0bc5592009-11-17 01:22:05 +00004019 ImpCastExprToType(RHS, destType, CastExpr::CK_NoOp);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004020 // Promote to void*.
Eli Friedmanb0bc5592009-11-17 01:22:05 +00004021 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004022 return destType;
4023 }
4024
4025 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4026 // Two identical pointer types are always compatible.
4027 return LHSTy;
4028 }
4029 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
4030 rhptee.getUnqualifiedType())) {
4031 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
4032 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
4033 // In this situation, we assume void* type. No especially good
4034 // reason, but this is what gcc does, and we do have to pick
4035 // to get a consistent AST.
4036 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004037 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
4038 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004039 return incompatTy;
4040 }
4041 // The pointer types are compatible.
4042 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
4043 // differently qualified versions of compatible types, the result type is
4044 // a pointer to an appropriately qualified version of the *composite*
4045 // type.
4046 // FIXME: Need to calculate the composite type.
4047 // FIXME: Need to add qualifiers
Eli Friedman06ed2a52009-10-20 08:27:19 +00004048 ImpCastExprToType(LHS, LHSTy, CastExpr::CK_BitCast);
4049 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004050 return LHSTy;
4051 }
Mike Stump11289f42009-09-09 15:08:12 +00004052
Steve Naroff05efa972009-07-01 14:36:47 +00004053 // GCC compatibility: soften pointer/integer mismatch.
4054 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
4055 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4056 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00004057 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_IntegralToPointer);
Steve Naroff05efa972009-07-01 14:36:47 +00004058 return RHSTy;
4059 }
4060 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
4061 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4062 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00004063 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_IntegralToPointer);
Steve Naroff05efa972009-07-01 14:36:47 +00004064 return LHSTy;
4065 }
Daniel Dunbar484603b2008-09-11 23:12:46 +00004066
Chris Lattnere2949f42008-01-06 22:42:25 +00004067 // Otherwise, the operands are not compatible.
Chris Lattner432cff52009-02-18 04:28:32 +00004068 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
4069 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004070 return QualType();
Steve Narofff8a28c52007-05-15 20:29:32 +00004071}
4072
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004073/// FindCompositeObjCPointerType - Helper method to find composite type of
4074/// two objective-c pointer types of the two input expressions.
4075QualType Sema::FindCompositeObjCPointerType(Expr *&LHS, Expr *&RHS,
4076 SourceLocation QuestionLoc) {
4077 QualType LHSTy = LHS->getType();
4078 QualType RHSTy = RHS->getType();
4079
4080 // Handle things like Class and struct objc_class*. Here we case the result
4081 // to the pseudo-builtin, because that will be implicitly cast back to the
4082 // redefinition type if an attempt is made to access its fields.
4083 if (LHSTy->isObjCClassType() &&
4084 (RHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
4085 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
4086 return LHSTy;
4087 }
4088 if (RHSTy->isObjCClassType() &&
4089 (LHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
4090 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
4091 return RHSTy;
4092 }
4093 // And the same for struct objc_object* / id
4094 if (LHSTy->isObjCIdType() &&
4095 (RHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
4096 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
4097 return LHSTy;
4098 }
4099 if (RHSTy->isObjCIdType() &&
4100 (LHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
4101 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
4102 return RHSTy;
4103 }
4104 // And the same for struct objc_selector* / SEL
4105 if (Context.isObjCSelType(LHSTy) &&
4106 (RHSTy.getDesugaredType() == Context.ObjCSelRedefinitionType)) {
4107 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
4108 return LHSTy;
4109 }
4110 if (Context.isObjCSelType(RHSTy) &&
4111 (LHSTy.getDesugaredType() == Context.ObjCSelRedefinitionType)) {
4112 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
4113 return RHSTy;
4114 }
4115 // Check constraints for Objective-C object pointers types.
4116 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
4117
4118 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4119 // Two identical object pointer types are always compatible.
4120 return LHSTy;
4121 }
4122 const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>();
4123 const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>();
4124 QualType compositeType = LHSTy;
4125
4126 // If both operands are interfaces and either operand can be
4127 // assigned to the other, use that type as the composite
4128 // type. This allows
4129 // xxx ? (A*) a : (B*) b
4130 // where B is a subclass of A.
4131 //
4132 // Additionally, as for assignment, if either type is 'id'
4133 // allow silent coercion. Finally, if the types are
4134 // incompatible then make sure to use 'id' as the composite
4135 // type so the result is acceptable for sending messages to.
4136
4137 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
4138 // It could return the composite type.
4139 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
4140 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
4141 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
4142 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
4143 } else if ((LHSTy->isObjCQualifiedIdType() ||
4144 RHSTy->isObjCQualifiedIdType()) &&
4145 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
4146 // Need to handle "id<xx>" explicitly.
4147 // GCC allows qualified id and any Objective-C type to devolve to
4148 // id. Currently localizing to here until clear this should be
4149 // part of ObjCQualifiedIdTypesAreCompatible.
4150 compositeType = Context.getObjCIdType();
4151 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
4152 compositeType = Context.getObjCIdType();
4153 } else if (!(compositeType =
4154 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
4155 ;
4156 else {
4157 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
4158 << LHSTy << RHSTy
4159 << LHS->getSourceRange() << RHS->getSourceRange();
4160 QualType incompatTy = Context.getObjCIdType();
4161 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
4162 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
4163 return incompatTy;
4164 }
4165 // The object pointer types are compatible.
4166 ImpCastExprToType(LHS, compositeType, CastExpr::CK_BitCast);
4167 ImpCastExprToType(RHS, compositeType, CastExpr::CK_BitCast);
4168 return compositeType;
4169 }
4170 // Check Objective-C object pointer types and 'void *'
4171 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
4172 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4173 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4174 QualType destPointee
4175 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4176 QualType destType = Context.getPointerType(destPointee);
4177 // Add qualifiers if necessary.
4178 ImpCastExprToType(LHS, destType, CastExpr::CK_NoOp);
4179 // Promote to void*.
4180 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
4181 return destType;
4182 }
4183 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
4184 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4185 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4186 QualType destPointee
4187 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4188 QualType destType = Context.getPointerType(destPointee);
4189 // Add qualifiers if necessary.
4190 ImpCastExprToType(RHS, destType, CastExpr::CK_NoOp);
4191 // Promote to void*.
4192 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
4193 return destType;
4194 }
4195 return QualType();
4196}
4197
Steve Naroff83895f72007-09-16 03:34:24 +00004198/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattnere168f762006-11-10 05:29:30 +00004199/// in the case of a the GNU conditional expr extension.
Sebastian Redlb5d49352009-01-19 22:31:54 +00004200Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
4201 SourceLocation ColonLoc,
4202 ExprArg Cond, ExprArg LHS,
4203 ExprArg RHS) {
4204 Expr *CondExpr = (Expr *) Cond.get();
4205 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
Chris Lattner2ab40a62007-11-26 01:40:58 +00004206
4207 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
4208 // was the condition.
4209 bool isLHSNull = LHSExpr == 0;
4210 if (isLHSNull)
4211 LHSExpr = CondExpr;
Sebastian Redlb5d49352009-01-19 22:31:54 +00004212
4213 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
Chris Lattnerdaaa9f22007-07-16 21:39:03 +00004214 RHSExpr, QuestionLoc);
Steve Narofff8a28c52007-05-15 20:29:32 +00004215 if (result.isNull())
Sebastian Redlb5d49352009-01-19 22:31:54 +00004216 return ExprError();
4217
4218 Cond.release();
4219 LHS.release();
4220 RHS.release();
Douglas Gregor7e112b02009-08-26 14:37:04 +00004221 return Owned(new (Context) ConditionalOperator(CondExpr, QuestionLoc,
Steve Narofff6009ed2009-01-21 00:14:39 +00004222 isLHSNull ? 0 : LHSExpr,
Douglas Gregor7e112b02009-08-26 14:37:04 +00004223 ColonLoc, RHSExpr, result));
Chris Lattnere168f762006-11-10 05:29:30 +00004224}
4225
Steve Naroff3f597292007-05-11 22:18:03 +00004226// CheckPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump4e1f26a2009-02-19 03:04:26 +00004227// being closely modeled after the C99 spec:-). The odd characteristic of this
Steve Naroff3f597292007-05-11 22:18:03 +00004228// routine is it effectively iqnores the qualifiers on the top level pointee.
4229// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
4230// FIXME: add a couple examples in this comment.
Mike Stump4e1f26a2009-02-19 03:04:26 +00004231Sema::AssignConvertType
Steve Naroff98cf3e92007-06-06 18:38:38 +00004232Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
Steve Naroff3f597292007-05-11 22:18:03 +00004233 QualType lhptee, rhptee;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004234
David Chisnall9f57c292009-08-17 16:35:33 +00004235 if ((lhsType->isObjCClassType() &&
4236 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
4237 (rhsType->isObjCClassType() &&
4238 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
4239 return Compatible;
4240 }
4241
Steve Naroff1f4d7272007-05-11 04:00:31 +00004242 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004243 lhptee = lhsType->getAs<PointerType>()->getPointeeType();
4244 rhptee = rhsType->getAs<PointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004245
Steve Naroff1f4d7272007-05-11 04:00:31 +00004246 // make sure we operate on the canonical type
Chris Lattner574dee62008-07-26 22:17:49 +00004247 lhptee = Context.getCanonicalType(lhptee);
4248 rhptee = Context.getCanonicalType(rhptee);
Steve Naroff1f4d7272007-05-11 04:00:31 +00004249
Chris Lattner9bad62c2008-01-04 18:04:52 +00004250 AssignConvertType ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004251
4252 // C99 6.5.16.1p1: This following citation is common to constraints
4253 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
4254 // qualifiers of the type *pointed to* by the right;
Fariborz Jahanianece85822009-02-17 18:27:45 +00004255 // FIXME: Handle ExtQualType
Douglas Gregor9a657932008-10-21 23:43:52 +00004256 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner9bad62c2008-01-04 18:04:52 +00004257 ConvTy = CompatiblePointerDiscardsQualifiers;
Steve Naroff3f597292007-05-11 22:18:03 +00004258
Mike Stump4e1f26a2009-02-19 03:04:26 +00004259 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
4260 // incomplete type and the other is a pointer to a qualified or unqualified
Steve Naroff3f597292007-05-11 22:18:03 +00004261 // version of void...
Chris Lattner0a788432008-01-03 22:56:36 +00004262 if (lhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00004263 if (rhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00004264 return ConvTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004265
Chris Lattner0a788432008-01-03 22:56:36 +00004266 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00004267 assert(rhptee->isFunctionType());
4268 return FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00004269 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004270
Chris Lattner0a788432008-01-03 22:56:36 +00004271 if (rhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00004272 if (lhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00004273 return ConvTy;
Chris Lattner0a788432008-01-03 22:56:36 +00004274
4275 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00004276 assert(lhptee->isFunctionType());
4277 return FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00004278 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004279 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Steve Naroff3f597292007-05-11 22:18:03 +00004280 // unqualified versions of compatible types, ...
Eli Friedman80160bd2009-03-22 23:59:44 +00004281 lhptee = lhptee.getUnqualifiedType();
4282 rhptee = rhptee.getUnqualifiedType();
4283 if (!Context.typesAreCompatible(lhptee, rhptee)) {
4284 // Check if the pointee types are compatible ignoring the sign.
4285 // We explicitly check for char so that we catch "char" vs
4286 // "unsigned char" on systems where "char" is unsigned.
Chris Lattnerec3a1562009-10-17 20:33:28 +00004287 if (lhptee->isCharType())
Eli Friedman80160bd2009-03-22 23:59:44 +00004288 lhptee = Context.UnsignedCharTy;
Chris Lattnerec3a1562009-10-17 20:33:28 +00004289 else if (lhptee->isSignedIntegerType())
Eli Friedman80160bd2009-03-22 23:59:44 +00004290 lhptee = Context.getCorrespondingUnsignedType(lhptee);
Chris Lattnerec3a1562009-10-17 20:33:28 +00004291
4292 if (rhptee->isCharType())
Eli Friedman80160bd2009-03-22 23:59:44 +00004293 rhptee = Context.UnsignedCharTy;
Chris Lattnerec3a1562009-10-17 20:33:28 +00004294 else if (rhptee->isSignedIntegerType())
Eli Friedman80160bd2009-03-22 23:59:44 +00004295 rhptee = Context.getCorrespondingUnsignedType(rhptee);
Chris Lattnerec3a1562009-10-17 20:33:28 +00004296
Eli Friedman80160bd2009-03-22 23:59:44 +00004297 if (lhptee == rhptee) {
4298 // Types are compatible ignoring the sign. Qualifier incompatibility
4299 // takes priority over sign incompatibility because the sign
4300 // warning can be disabled.
4301 if (ConvTy != Compatible)
4302 return ConvTy;
4303 return IncompatiblePointerSign;
4304 }
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00004305
4306 // If we are a multi-level pointer, it's possible that our issue is simply
4307 // one of qualification - e.g. char ** -> const char ** is not allowed. If
4308 // the eventual target type is the same and the pointers have the same
4309 // level of indirection, this must be the issue.
4310 if (lhptee->isPointerType() && rhptee->isPointerType()) {
4311 do {
4312 lhptee = lhptee->getAs<PointerType>()->getPointeeType();
4313 rhptee = rhptee->getAs<PointerType>()->getPointeeType();
4314
4315 lhptee = Context.getCanonicalType(lhptee);
4316 rhptee = Context.getCanonicalType(rhptee);
4317 } while (lhptee->isPointerType() && rhptee->isPointerType());
4318
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004319 if (Context.hasSameUnqualifiedType(lhptee, rhptee))
Alexis Hunt6f3de502009-11-08 07:46:34 +00004320 return IncompatibleNestedPointerQualifiers;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00004321 }
4322
Eli Friedman80160bd2009-03-22 23:59:44 +00004323 // General pointer incompatibility takes priority over qualifiers.
Mike Stump11289f42009-09-09 15:08:12 +00004324 return IncompatiblePointer;
Eli Friedman80160bd2009-03-22 23:59:44 +00004325 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00004326 return ConvTy;
Steve Naroff1f4d7272007-05-11 04:00:31 +00004327}
4328
Steve Naroff081c7422008-09-04 15:10:53 +00004329/// CheckBlockPointerTypesForAssignment - This routine determines whether two
4330/// block pointer types are compatible or whether a block and normal pointer
4331/// are compatible. It is more restrict than comparing two function pointer
4332// types.
Mike Stump4e1f26a2009-02-19 03:04:26 +00004333Sema::AssignConvertType
4334Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
Steve Naroff081c7422008-09-04 15:10:53 +00004335 QualType rhsType) {
4336 QualType lhptee, rhptee;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004337
Steve Naroff081c7422008-09-04 15:10:53 +00004338 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004339 lhptee = lhsType->getAs<BlockPointerType>()->getPointeeType();
4340 rhptee = rhsType->getAs<BlockPointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004341
Steve Naroff081c7422008-09-04 15:10:53 +00004342 // make sure we operate on the canonical type
4343 lhptee = Context.getCanonicalType(lhptee);
4344 rhptee = Context.getCanonicalType(rhptee);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004345
Steve Naroff081c7422008-09-04 15:10:53 +00004346 AssignConvertType ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004347
Steve Naroff081c7422008-09-04 15:10:53 +00004348 // For blocks we enforce that qualifiers are identical.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004349 if (lhptee.getLocalCVRQualifiers() != rhptee.getLocalCVRQualifiers())
Steve Naroff081c7422008-09-04 15:10:53 +00004350 ConvTy = CompatiblePointerDiscardsQualifiers;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004351
Eli Friedmana6638ca2009-06-08 05:08:54 +00004352 if (!Context.typesAreCompatible(lhptee, rhptee))
Mike Stump4e1f26a2009-02-19 03:04:26 +00004353 return IncompatibleBlockPointer;
Steve Naroff081c7422008-09-04 15:10:53 +00004354 return ConvTy;
4355}
4356
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00004357/// CheckObjCPointerTypesForAssignment - Compares two objective-c pointer types
4358/// for assignment compatibility.
4359Sema::AssignConvertType
4360Sema::CheckObjCPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
4361 if (lhsType->isObjCBuiltinType() || rhsType->isObjCBuiltinType())
4362 return Compatible;
4363 QualType lhptee =
4364 lhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
4365 QualType rhptee =
4366 rhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
4367 // make sure we operate on the canonical type
4368 lhptee = Context.getCanonicalType(lhptee);
4369 rhptee = Context.getCanonicalType(rhptee);
4370 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
4371 return CompatiblePointerDiscardsQualifiers;
4372
4373 if (Context.typesAreCompatible(lhsType, rhsType))
4374 return Compatible;
4375 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
4376 return IncompatibleObjCQualifiedId;
4377 return IncompatiblePointer;
4378}
4379
Mike Stump4e1f26a2009-02-19 03:04:26 +00004380/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
4381/// has code to accommodate several GCC extensions when type checking
Steve Naroff17f76e02007-05-03 21:03:48 +00004382/// pointers. Here are some objectionable examples that GCC considers warnings:
4383///
4384/// int a, *pint;
4385/// short *pshort;
4386/// struct foo *pfoo;
4387///
4388/// pint = pshort; // warning: assignment from incompatible pointer type
4389/// a = pint; // warning: assignment makes integer from pointer without a cast
4390/// pint = a; // warning: assignment makes pointer from integer without a cast
4391/// pint = pfoo; // warning: assignment from incompatible pointer type
4392///
4393/// As a result, the code for dealing with pointers is more complex than the
Mike Stump4e1f26a2009-02-19 03:04:26 +00004394/// C99 spec dictates.
Steve Naroff17f76e02007-05-03 21:03:48 +00004395///
Chris Lattner9bad62c2008-01-04 18:04:52 +00004396Sema::AssignConvertType
Steve Naroff98cf3e92007-06-06 18:38:38 +00004397Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattnera52c2f22008-01-04 23:18:45 +00004398 // Get canonical types. We're not formatting these types, just comparing
4399 // them.
Chris Lattner574dee62008-07-26 22:17:49 +00004400 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
4401 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman3360d892008-05-30 18:07:22 +00004402
4403 if (lhsType == rhsType)
Chris Lattnerf5c973d2008-01-07 17:51:46 +00004404 return Compatible; // Common case: fast path an exact match.
Steve Naroff44fd8ff2007-07-24 21:46:40 +00004405
David Chisnall9f57c292009-08-17 16:35:33 +00004406 if ((lhsType->isObjCClassType() &&
4407 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
4408 (rhsType->isObjCClassType() &&
4409 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
4410 return Compatible;
4411 }
4412
Douglas Gregor6b754842008-10-28 00:22:11 +00004413 // If the left-hand side is a reference type, then we are in a
4414 // (rare!) case where we've allowed the use of references in C,
4415 // e.g., as a parameter type in a built-in function. In this case,
4416 // just make sure that the type referenced is compatible with the
4417 // right-hand side type. The caller is responsible for adjusting
4418 // lhsType so that the resulting expression does not have reference
4419 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004420 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
Douglas Gregor6b754842008-10-28 00:22:11 +00004421 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlsson24ebce62007-10-12 23:56:29 +00004422 return Compatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00004423 return Incompatible;
Fariborz Jahaniana1e34202007-12-19 17:45:58 +00004424 }
Nate Begemanbd956c42009-06-28 02:36:38 +00004425 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
4426 // to the same ExtVector type.
4427 if (lhsType->isExtVectorType()) {
4428 if (rhsType->isExtVectorType())
4429 return lhsType == rhsType ? Compatible : Incompatible;
4430 if (!rhsType->isVectorType() && rhsType->isArithmeticType())
4431 return Compatible;
4432 }
Mike Stump11289f42009-09-09 15:08:12 +00004433
Nate Begeman191a6b12008-07-14 18:02:46 +00004434 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begeman191a6b12008-07-14 18:02:46 +00004435 // If we are allowing lax vector conversions, and LHS and RHS are both
Mike Stump4e1f26a2009-02-19 03:04:26 +00004436 // vectors, the total size only needs to be the same. This is a bitcast;
Nate Begeman191a6b12008-07-14 18:02:46 +00004437 // no bits are changed but the result type is different.
Chris Lattner881a2122008-01-04 23:32:24 +00004438 if (getLangOptions().LaxVectorConversions &&
4439 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begeman191a6b12008-07-14 18:02:46 +00004440 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
Anders Carlssondb5a9b62009-01-30 23:17:46 +00004441 return IncompatibleVectors;
Chris Lattner881a2122008-01-04 23:32:24 +00004442 }
4443 return Incompatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004444 }
Eli Friedman3360d892008-05-30 18:07:22 +00004445
Chris Lattner881a2122008-01-04 23:32:24 +00004446 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Steve Naroff98cf3e92007-06-06 18:38:38 +00004447 return Compatible;
Eli Friedman3360d892008-05-30 18:07:22 +00004448
Chris Lattnerec646832008-04-07 06:49:41 +00004449 if (isa<PointerType>(lhsType)) {
Steve Naroff98cf3e92007-06-06 18:38:38 +00004450 if (rhsType->isIntegerType())
Chris Lattner940cfeb2008-01-04 18:22:42 +00004451 return IntToPointer;
Eli Friedman3360d892008-05-30 18:07:22 +00004452
Chris Lattnerec646832008-04-07 06:49:41 +00004453 if (isa<PointerType>(rhsType))
Steve Naroff98cf3e92007-06-06 18:38:38 +00004454 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004455
Steve Naroffaccc4882009-07-20 17:56:53 +00004456 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004457 if (isa<ObjCObjectPointerType>(rhsType)) {
Steve Naroffaccc4882009-07-20 17:56:53 +00004458 if (lhsType->isVoidPointerType()) // an exception to the rule.
4459 return Compatible;
4460 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004461 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004462 if (rhsType->getAs<BlockPointerType>()) {
4463 if (lhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregore7dd1452008-11-27 00:44:28 +00004464 return Compatible;
Steve Naroff32d072c2008-09-29 18:10:17 +00004465
4466 // Treat block pointers as objects.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004467 if (getLangOptions().ObjC1 && lhsType->isObjCIdType())
Steve Naroff32d072c2008-09-29 18:10:17 +00004468 return Compatible;
4469 }
Steve Naroff081c7422008-09-04 15:10:53 +00004470 return Incompatible;
4471 }
4472
4473 if (isa<BlockPointerType>(lhsType)) {
4474 if (rhsType->isIntegerType())
Eli Friedman8163b7a2009-02-25 04:20:42 +00004475 return IntToBlockPointer;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004476
Steve Naroff32d072c2008-09-29 18:10:17 +00004477 // Treat block pointers as objects.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004478 if (getLangOptions().ObjC1 && rhsType->isObjCIdType())
Steve Naroff32d072c2008-09-29 18:10:17 +00004479 return Compatible;
4480
Steve Naroff081c7422008-09-04 15:10:53 +00004481 if (rhsType->isBlockPointerType())
4482 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004483
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004484 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff081c7422008-09-04 15:10:53 +00004485 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregore7dd1452008-11-27 00:44:28 +00004486 return Compatible;
Steve Naroff081c7422008-09-04 15:10:53 +00004487 }
Chris Lattnera52c2f22008-01-04 23:18:45 +00004488 return Incompatible;
4489 }
4490
Steve Naroff7cae42b2009-07-10 23:34:53 +00004491 if (isa<ObjCObjectPointerType>(lhsType)) {
4492 if (rhsType->isIntegerType())
4493 return IntToPointer;
Mike Stump11289f42009-09-09 15:08:12 +00004494
Steve Naroffaccc4882009-07-20 17:56:53 +00004495 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004496 if (isa<PointerType>(rhsType)) {
Steve Naroffaccc4882009-07-20 17:56:53 +00004497 if (rhsType->isVoidPointerType()) // an exception to the rule.
4498 return Compatible;
4499 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004500 }
4501 if (rhsType->isObjCObjectPointerType()) {
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00004502 return CheckObjCPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff7cae42b2009-07-10 23:34:53 +00004503 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004504 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004505 if (RHSPT->getPointeeType()->isVoidType())
4506 return Compatible;
4507 }
4508 // Treat block pointers as objects.
4509 if (rhsType->isBlockPointerType())
4510 return Compatible;
4511 return Incompatible;
4512 }
Chris Lattnerec646832008-04-07 06:49:41 +00004513 if (isa<PointerType>(rhsType)) {
Steve Naroff98cf3e92007-06-06 18:38:38 +00004514 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedman3360d892008-05-30 18:07:22 +00004515 if (lhsType == Context.BoolTy)
4516 return Compatible;
4517
4518 if (lhsType->isIntegerType())
Chris Lattner940cfeb2008-01-04 18:22:42 +00004519 return PointerToInt;
Steve Naroff98cf3e92007-06-06 18:38:38 +00004520
Mike Stump4e1f26a2009-02-19 03:04:26 +00004521 if (isa<PointerType>(lhsType))
Steve Naroff98cf3e92007-06-06 18:38:38 +00004522 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004523
4524 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004525 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregore7dd1452008-11-27 00:44:28 +00004526 return Compatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00004527 return Incompatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00004528 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00004529 if (isa<ObjCObjectPointerType>(rhsType)) {
4530 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
4531 if (lhsType == Context.BoolTy)
4532 return Compatible;
4533
4534 if (lhsType->isIntegerType())
4535 return PointerToInt;
4536
Steve Naroffaccc4882009-07-20 17:56:53 +00004537 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004538 if (isa<PointerType>(lhsType)) {
Steve Naroffaccc4882009-07-20 17:56:53 +00004539 if (lhsType->isVoidPointerType()) // an exception to the rule.
4540 return Compatible;
4541 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004542 }
4543 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004544 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00004545 return Compatible;
4546 return Incompatible;
4547 }
Eli Friedman3360d892008-05-30 18:07:22 +00004548
Chris Lattnera52c2f22008-01-04 23:18:45 +00004549 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattnerec646832008-04-07 06:49:41 +00004550 if (Context.typesAreCompatible(lhsType, rhsType))
Steve Naroff98cf3e92007-06-06 18:38:38 +00004551 return Compatible;
Bill Wendling216423b2007-05-30 06:30:29 +00004552 }
Steve Naroff98cf3e92007-06-06 18:38:38 +00004553 return Incompatible;
Steve Naroff9eb24652007-05-02 21:58:15 +00004554}
4555
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004556/// \brief Constructs a transparent union from an expression that is
4557/// used to initialize the transparent union.
Mike Stump11289f42009-09-09 15:08:12 +00004558static void ConstructTransparentUnion(ASTContext &C, Expr *&E,
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004559 QualType UnionType, FieldDecl *Field) {
4560 // Build an initializer list that designates the appropriate member
4561 // of the transparent union.
4562 InitListExpr *Initializer = new (C) InitListExpr(SourceLocation(),
4563 &E, 1,
4564 SourceLocation());
4565 Initializer->setType(UnionType);
4566 Initializer->setInitializedFieldInUnion(Field);
4567
4568 // Build a compound literal constructing a value of the transparent
4569 // union type from this initializer list.
4570 E = new (C) CompoundLiteralExpr(SourceLocation(), UnionType, Initializer,
4571 false);
4572}
4573
4574Sema::AssignConvertType
4575Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) {
4576 QualType FromType = rExpr->getType();
4577
Mike Stump11289f42009-09-09 15:08:12 +00004578 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004579 // transparent_union GCC extension.
4580 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004581 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004582 return Incompatible;
4583
4584 // The field to initialize within the transparent union.
4585 RecordDecl *UD = UT->getDecl();
4586 FieldDecl *InitField = 0;
4587 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004588 for (RecordDecl::field_iterator it = UD->field_begin(),
4589 itend = UD->field_end();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004590 it != itend; ++it) {
4591 if (it->getType()->isPointerType()) {
4592 // If the transparent union contains a pointer type, we allow:
4593 // 1) void pointer
4594 // 2) null pointer constant
4595 if (FromType->isPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004596 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004597 ImpCastExprToType(rExpr, it->getType(), CastExpr::CK_BitCast);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004598 InitField = *it;
4599 break;
4600 }
Mike Stump11289f42009-09-09 15:08:12 +00004601
Douglas Gregor56751b52009-09-25 04:25:58 +00004602 if (rExpr->isNullPointerConstant(Context,
4603 Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004604 ImpCastExprToType(rExpr, it->getType(), CastExpr::CK_IntegralToPointer);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004605 InitField = *it;
4606 break;
4607 }
4608 }
4609
4610 if (CheckAssignmentConstraints(it->getType(), rExpr->getType())
4611 == Compatible) {
4612 InitField = *it;
4613 break;
4614 }
4615 }
4616
4617 if (!InitField)
4618 return Incompatible;
4619
4620 ConstructTransparentUnion(Context, rExpr, ArgType, InitField);
4621 return Compatible;
4622}
4623
Chris Lattner9bad62c2008-01-04 18:04:52 +00004624Sema::AssignConvertType
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00004625Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor9a657932008-10-21 23:43:52 +00004626 if (getLangOptions().CPlusPlus) {
4627 if (!lhsType->isRecordType()) {
4628 // C++ 5.17p3: If the left operand is not of class type, the
4629 // expression is implicitly converted (C++ 4) to the
4630 // cv-unqualified type of the left operand.
Douglas Gregor47d3f272008-12-19 17:40:08 +00004631 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00004632 AA_Assigning))
Douglas Gregor9a657932008-10-21 23:43:52 +00004633 return Incompatible;
Chris Lattner0d5640c2009-04-12 09:02:39 +00004634 return Compatible;
Douglas Gregor9a657932008-10-21 23:43:52 +00004635 }
4636
4637 // FIXME: Currently, we fall through and treat C++ classes like C
4638 // structures.
4639 }
4640
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00004641 // C99 6.5.16.1p1: the left operand is a pointer and the right is
4642 // a null pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00004643 if ((lhsType->isPointerType() ||
4644 lhsType->isObjCObjectPointerType() ||
Mike Stump4e1f26a2009-02-19 03:04:26 +00004645 lhsType->isBlockPointerType())
Douglas Gregor56751b52009-09-25 04:25:58 +00004646 && rExpr->isNullPointerConstant(Context,
4647 Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004648 ImpCastExprToType(rExpr, lhsType, CastExpr::CK_Unknown);
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00004649 return Compatible;
4650 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004651
Chris Lattnere6dcd502007-10-16 02:55:40 +00004652 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00004653 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregora121b752009-11-03 16:56:39 +00004654 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00004655 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattnere6dcd502007-10-16 02:55:40 +00004656 //
Mike Stump4e1f26a2009-02-19 03:04:26 +00004657 // Suppress this for references: C++ 8.5.3p5.
Chris Lattnere6dcd502007-10-16 02:55:40 +00004658 if (!lhsType->isReferenceType())
4659 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00004660
Chris Lattner9bad62c2008-01-04 18:04:52 +00004661 Sema::AssignConvertType result =
4662 CheckAssignmentConstraints(lhsType, rExpr->getType());
Mike Stump4e1f26a2009-02-19 03:04:26 +00004663
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00004664 // C99 6.5.16.1p2: The value of the right operand is converted to the
4665 // type of the assignment expression.
Douglas Gregor6b754842008-10-28 00:22:11 +00004666 // CheckAssignmentConstraints allows the left-hand side to be a reference,
4667 // so that we can use references in built-in functions even in C.
4668 // The getNonReferenceType() call makes sure that the resulting expression
4669 // does not have reference type.
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004670 if (result != Incompatible && rExpr->getType() != lhsType)
Eli Friedman06ed2a52009-10-20 08:27:19 +00004671 ImpCastExprToType(rExpr, lhsType.getNonReferenceType(),
4672 CastExpr::CK_Unknown);
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00004673 return result;
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00004674}
4675
Chris Lattner326f7572008-11-18 01:30:42 +00004676QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattner377d1f82008-11-18 22:52:51 +00004677 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattner6a2ed6f2008-11-23 09:13:29 +00004678 << lex->getType() << rex->getType()
Chris Lattner377d1f82008-11-18 22:52:51 +00004679 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner5c11c412007-12-12 05:47:28 +00004680 return QualType();
Steve Naroff6f49f5d2007-05-29 14:23:36 +00004681}
4682
Mike Stump4e1f26a2009-02-19 03:04:26 +00004683inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Steve Naroff7a5af782007-07-13 16:58:59 +00004684 Expr *&rex) {
Mike Stump4e1f26a2009-02-19 03:04:26 +00004685 // For conversion purposes, we ignore any qualifiers.
Nate Begeman002e4bd2008-04-04 01:30:25 +00004686 // For example, "const float" and "float" are equivalent.
Chris Lattner574dee62008-07-26 22:17:49 +00004687 QualType lhsType =
4688 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
4689 QualType rhsType =
4690 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004691
Nate Begeman191a6b12008-07-14 18:02:46 +00004692 // If the vector types are identical, return.
Nate Begeman002e4bd2008-04-04 01:30:25 +00004693 if (lhsType == rhsType)
Steve Naroff84ff4b42007-07-09 21:31:10 +00004694 return lhsType;
Nate Begeman330aaa72007-12-30 02:59:45 +00004695
Nate Begeman191a6b12008-07-14 18:02:46 +00004696 // Handle the case of a vector & extvector type of the same size and element
4697 // type. It would be nice if we only had one vector type someday.
Anders Carlssondb5a9b62009-01-30 23:17:46 +00004698 if (getLangOptions().LaxVectorConversions) {
4699 // FIXME: Should we warn here?
John McCall9dd450b2009-09-21 23:43:11 +00004700 if (const VectorType *LV = lhsType->getAs<VectorType>()) {
4701 if (const VectorType *RV = rhsType->getAs<VectorType>())
Nate Begeman191a6b12008-07-14 18:02:46 +00004702 if (LV->getElementType() == RV->getElementType() &&
Anders Carlssondb5a9b62009-01-30 23:17:46 +00004703 LV->getNumElements() == RV->getNumElements()) {
Nate Begeman191a6b12008-07-14 18:02:46 +00004704 return lhsType->isExtVectorType() ? lhsType : rhsType;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00004705 }
4706 }
4707 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004708
Nate Begemanbd956c42009-06-28 02:36:38 +00004709 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
4710 // swap back (so that we don't reverse the inputs to a subtract, for instance.
4711 bool swapped = false;
4712 if (rhsType->isExtVectorType()) {
4713 swapped = true;
4714 std::swap(rex, lex);
4715 std::swap(rhsType, lhsType);
4716 }
Mike Stump11289f42009-09-09 15:08:12 +00004717
Nate Begeman886448d2009-06-28 19:12:57 +00004718 // Handle the case of an ext vector and scalar.
John McCall9dd450b2009-09-21 23:43:11 +00004719 if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) {
Nate Begemanbd956c42009-06-28 02:36:38 +00004720 QualType EltTy = LV->getElementType();
4721 if (EltTy->isIntegralType() && rhsType->isIntegralType()) {
4722 if (Context.getIntegerTypeOrder(EltTy, rhsType) >= 0) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004723 ImpCastExprToType(rex, lhsType, CastExpr::CK_IntegralCast);
Nate Begemanbd956c42009-06-28 02:36:38 +00004724 if (swapped) std::swap(rex, lex);
4725 return lhsType;
4726 }
4727 }
4728 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
4729 rhsType->isRealFloatingType()) {
4730 if (Context.getFloatingTypeOrder(EltTy, rhsType) >= 0) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004731 ImpCastExprToType(rex, lhsType, CastExpr::CK_FloatingCast);
Nate Begemanbd956c42009-06-28 02:36:38 +00004732 if (swapped) std::swap(rex, lex);
4733 return lhsType;
4734 }
Nate Begeman330aaa72007-12-30 02:59:45 +00004735 }
4736 }
Mike Stump11289f42009-09-09 15:08:12 +00004737
Nate Begeman886448d2009-06-28 19:12:57 +00004738 // Vectors of different size or scalar and non-ext-vector are errors.
Chris Lattner377d1f82008-11-18 22:52:51 +00004739 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004740 << lex->getType() << rex->getType()
Chris Lattner377d1f82008-11-18 22:52:51 +00004741 << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff84ff4b42007-07-09 21:31:10 +00004742 return QualType();
Sebastian Redl112a97662009-02-07 00:15:38 +00004743}
4744
Steve Naroff218bc2b2007-05-04 21:54:46 +00004745inline QualType Sema::CheckMultiplyDivideOperands(
Mike Stump11289f42009-09-09 15:08:12 +00004746 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Daniel Dunbar060d5e22009-01-05 22:42:10 +00004747 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner326f7572008-11-18 01:30:42 +00004748 return CheckVectorOperands(Loc, lex, rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004749
Steve Naroffbe4c4d12007-08-24 19:07:16 +00004750 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004751
Steve Naroffdbd9e892007-07-17 00:58:39 +00004752 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroffbe4c4d12007-08-24 19:07:16 +00004753 return compType;
Chris Lattner326f7572008-11-18 01:30:42 +00004754 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00004755}
4756
Steve Naroff218bc2b2007-05-04 21:54:46 +00004757inline QualType Sema::CheckRemainderOperands(
Mike Stump11289f42009-09-09 15:08:12 +00004758 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Daniel Dunbar0d2bfec2009-01-05 22:55:36 +00004759 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4760 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
4761 return CheckVectorOperands(Loc, lex, rex);
4762 return InvalidOperands(Loc, lex, rex);
4763 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00004764
Steve Naroffbe4c4d12007-08-24 19:07:16 +00004765 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004766
Steve Naroffdbd9e892007-07-17 00:58:39 +00004767 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroffbe4c4d12007-08-24 19:07:16 +00004768 return compType;
Chris Lattner326f7572008-11-18 01:30:42 +00004769 return InvalidOperands(Loc, lex, rex);
Steve Naroff218bc2b2007-05-04 21:54:46 +00004770}
4771
4772inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Mike Stump11289f42009-09-09 15:08:12 +00004773 Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004774 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4775 QualType compType = CheckVectorOperands(Loc, lex, rex);
4776 if (CompLHSTy) *CompLHSTy = compType;
4777 return compType;
4778 }
Steve Naroff7a5af782007-07-13 16:58:59 +00004779
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004780 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Eli Friedman8e122982008-05-18 18:08:51 +00004781
Steve Naroffe4718892007-04-27 18:30:00 +00004782 // handle the common case first (both operands are arithmetic).
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004783 if (lex->getType()->isArithmeticType() &&
4784 rex->getType()->isArithmeticType()) {
4785 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00004786 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004787 }
Steve Naroff218bc2b2007-05-04 21:54:46 +00004788
Eli Friedman8e122982008-05-18 18:08:51 +00004789 // Put any potential pointer into PExp
4790 Expr* PExp = lex, *IExp = rex;
Steve Naroff6b712a72009-07-14 18:25:06 +00004791 if (IExp->getType()->isAnyPointerType())
Eli Friedman8e122982008-05-18 18:08:51 +00004792 std::swap(PExp, IExp);
4793
Steve Naroff6b712a72009-07-14 18:25:06 +00004794 if (PExp->getType()->isAnyPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00004795
Eli Friedman8e122982008-05-18 18:08:51 +00004796 if (IExp->getType()->isIntegerType()) {
Steve Naroffaacd4cc2009-07-13 21:20:41 +00004797 QualType PointeeTy = PExp->getType()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00004798
Chris Lattner12bdebb2009-04-24 23:50:08 +00004799 // Check for arithmetic on pointers to incomplete types.
4800 if (PointeeTy->isVoidType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00004801 if (getLangOptions().CPlusPlus) {
4802 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
Chris Lattner3b054132008-11-19 05:08:23 +00004803 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregordd430f72009-01-19 19:26:10 +00004804 return QualType();
Eli Friedman8e122982008-05-18 18:08:51 +00004805 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00004806
4807 // GNU extension: arithmetic on pointer to void
4808 Diag(Loc, diag::ext_gnu_void_ptr)
4809 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner12bdebb2009-04-24 23:50:08 +00004810 } else if (PointeeTy->isFunctionType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00004811 if (getLangOptions().CPlusPlus) {
4812 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
4813 << lex->getType() << lex->getSourceRange();
4814 return QualType();
4815 }
4816
4817 // GNU extension: arithmetic on pointer to function
4818 Diag(Loc, diag::ext_gnu_ptr_func_arith)
4819 << lex->getType() << lex->getSourceRange();
Steve Naroffa63372d2009-07-13 21:32:29 +00004820 } else {
Steve Naroffaacd4cc2009-07-13 21:20:41 +00004821 // Check if we require a complete type.
Mike Stump11289f42009-09-09 15:08:12 +00004822 if (((PExp->getType()->isPointerType() &&
Steve Naroffa63372d2009-07-13 21:32:29 +00004823 !PExp->getType()->isDependentType()) ||
Steve Naroffaacd4cc2009-07-13 21:20:41 +00004824 PExp->getType()->isObjCObjectPointerType()) &&
4825 RequireCompleteType(Loc, PointeeTy,
Mike Stump11289f42009-09-09 15:08:12 +00004826 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
4827 << PExp->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00004828 << PExp->getType()))
Steve Naroffaacd4cc2009-07-13 21:20:41 +00004829 return QualType();
4830 }
Chris Lattner12bdebb2009-04-24 23:50:08 +00004831 // Diagnose bad cases where we step over interface counts.
4832 if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4833 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
4834 << PointeeTy << PExp->getSourceRange();
4835 return QualType();
4836 }
Mike Stump11289f42009-09-09 15:08:12 +00004837
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004838 if (CompLHSTy) {
Eli Friedman629ffb92009-08-20 04:21:42 +00004839 QualType LHSTy = Context.isPromotableBitField(lex);
4840 if (LHSTy.isNull()) {
4841 LHSTy = lex->getType();
4842 if (LHSTy->isPromotableIntegerType())
4843 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregord2c2d172009-05-02 00:36:19 +00004844 }
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004845 *CompLHSTy = LHSTy;
4846 }
Eli Friedman8e122982008-05-18 18:08:51 +00004847 return PExp->getType();
4848 }
4849 }
4850
Chris Lattner326f7572008-11-18 01:30:42 +00004851 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00004852}
4853
Chris Lattner2a3569b2008-04-07 05:30:13 +00004854// C99 6.5.6
4855QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004856 SourceLocation Loc, QualType* CompLHSTy) {
4857 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4858 QualType compType = CheckVectorOperands(Loc, lex, rex);
4859 if (CompLHSTy) *CompLHSTy = compType;
4860 return compType;
4861 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004862
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004863 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004864
Chris Lattner4d62f422007-12-09 21:53:25 +00004865 // Enforce type constraints: C99 6.5.6p3.
Mike Stump4e1f26a2009-02-19 03:04:26 +00004866
Chris Lattner4d62f422007-12-09 21:53:25 +00004867 // Handle the common case first (both operands are arithmetic).
Mike Stumpf70bcf72009-05-07 18:43:07 +00004868 if (lex->getType()->isArithmeticType()
4869 && rex->getType()->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004870 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00004871 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004872 }
Mike Stump11289f42009-09-09 15:08:12 +00004873
Chris Lattner4d62f422007-12-09 21:53:25 +00004874 // Either ptr - int or ptr - ptr.
Steve Naroff6b712a72009-07-14 18:25:06 +00004875 if (lex->getType()->isAnyPointerType()) {
Steve Naroff4eed7a12009-07-13 17:19:15 +00004876 QualType lpointee = lex->getType()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004877
Douglas Gregorac1fb652009-03-24 19:52:54 +00004878 // The LHS must be an completely-defined object type.
Douglas Gregorf6cd9282009-01-23 00:36:41 +00004879
Douglas Gregorac1fb652009-03-24 19:52:54 +00004880 bool ComplainAboutVoid = false;
4881 Expr *ComplainAboutFunc = 0;
4882 if (lpointee->isVoidType()) {
4883 if (getLangOptions().CPlusPlus) {
4884 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
4885 << lex->getSourceRange() << rex->getSourceRange();
4886 return QualType();
4887 }
4888
4889 // GNU C extension: arithmetic on pointer to void
4890 ComplainAboutVoid = true;
4891 } else if (lpointee->isFunctionType()) {
4892 if (getLangOptions().CPlusPlus) {
4893 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004894 << lex->getType() << lex->getSourceRange();
Chris Lattner4d62f422007-12-09 21:53:25 +00004895 return QualType();
4896 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00004897
4898 // GNU C extension: arithmetic on pointer to function
4899 ComplainAboutFunc = lex;
4900 } else if (!lpointee->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00004901 RequireCompleteType(Loc, lpointee,
Anders Carlsson029fc692009-08-26 22:59:12 +00004902 PDiag(diag::err_typecheck_sub_ptr_object)
Mike Stump11289f42009-09-09 15:08:12 +00004903 << lex->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00004904 << lex->getType()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00004905 return QualType();
Chris Lattner4d62f422007-12-09 21:53:25 +00004906
Chris Lattner12bdebb2009-04-24 23:50:08 +00004907 // Diagnose bad cases where we step over interface counts.
4908 if (lpointee->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4909 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
4910 << lpointee << lex->getSourceRange();
4911 return QualType();
4912 }
Mike Stump11289f42009-09-09 15:08:12 +00004913
Chris Lattner4d62f422007-12-09 21:53:25 +00004914 // The result type of a pointer-int computation is the pointer type.
Douglas Gregorac1fb652009-03-24 19:52:54 +00004915 if (rex->getType()->isIntegerType()) {
4916 if (ComplainAboutVoid)
4917 Diag(Loc, diag::ext_gnu_void_ptr)
4918 << lex->getSourceRange() << rex->getSourceRange();
4919 if (ComplainAboutFunc)
4920 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump11289f42009-09-09 15:08:12 +00004921 << ComplainAboutFunc->getType()
Douglas Gregorac1fb652009-03-24 19:52:54 +00004922 << ComplainAboutFunc->getSourceRange();
4923
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004924 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00004925 return lex->getType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00004926 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004927
Chris Lattner4d62f422007-12-09 21:53:25 +00004928 // Handle pointer-pointer subtractions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004929 if (const PointerType *RHSPTy = rex->getType()->getAs<PointerType>()) {
Eli Friedman1974e532008-02-08 01:19:44 +00004930 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004931
Douglas Gregorac1fb652009-03-24 19:52:54 +00004932 // RHS must be a completely-type object type.
4933 // Handle the GNU void* extension.
4934 if (rpointee->isVoidType()) {
4935 if (getLangOptions().CPlusPlus) {
4936 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
4937 << lex->getSourceRange() << rex->getSourceRange();
4938 return QualType();
4939 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004940
Douglas Gregorac1fb652009-03-24 19:52:54 +00004941 ComplainAboutVoid = true;
4942 } else if (rpointee->isFunctionType()) {
4943 if (getLangOptions().CPlusPlus) {
4944 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004945 << rex->getType() << rex->getSourceRange();
Chris Lattner4d62f422007-12-09 21:53:25 +00004946 return QualType();
4947 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00004948
4949 // GNU extension: arithmetic on pointer to function
4950 if (!ComplainAboutFunc)
4951 ComplainAboutFunc = rex;
4952 } else if (!rpointee->isDependentType() &&
4953 RequireCompleteType(Loc, rpointee,
Anders Carlsson029fc692009-08-26 22:59:12 +00004954 PDiag(diag::err_typecheck_sub_ptr_object)
4955 << rex->getSourceRange()
4956 << rex->getType()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00004957 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004958
Eli Friedman168fe152009-05-16 13:54:38 +00004959 if (getLangOptions().CPlusPlus) {
4960 // Pointee types must be the same: C++ [expr.add]
4961 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
4962 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
4963 << lex->getType() << rex->getType()
4964 << lex->getSourceRange() << rex->getSourceRange();
4965 return QualType();
4966 }
4967 } else {
4968 // Pointee types must be compatible C99 6.5.6p3
4969 if (!Context.typesAreCompatible(
4970 Context.getCanonicalType(lpointee).getUnqualifiedType(),
4971 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
4972 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
4973 << lex->getType() << rex->getType()
4974 << lex->getSourceRange() << rex->getSourceRange();
4975 return QualType();
4976 }
Chris Lattner4d62f422007-12-09 21:53:25 +00004977 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004978
Douglas Gregorac1fb652009-03-24 19:52:54 +00004979 if (ComplainAboutVoid)
4980 Diag(Loc, diag::ext_gnu_void_ptr)
4981 << lex->getSourceRange() << rex->getSourceRange();
4982 if (ComplainAboutFunc)
4983 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump11289f42009-09-09 15:08:12 +00004984 << ComplainAboutFunc->getType()
Douglas Gregorac1fb652009-03-24 19:52:54 +00004985 << ComplainAboutFunc->getSourceRange();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004986
4987 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00004988 return Context.getPointerDiffType();
4989 }
4990 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004991
Chris Lattner326f7572008-11-18 01:30:42 +00004992 return InvalidOperands(Loc, lex, rex);
Steve Naroff218bc2b2007-05-04 21:54:46 +00004993}
4994
Chris Lattner2a3569b2008-04-07 05:30:13 +00004995// C99 6.5.7
Chris Lattner326f7572008-11-18 01:30:42 +00004996QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattner2a3569b2008-04-07 05:30:13 +00004997 bool isCompAssign) {
Chris Lattner5c11c412007-12-12 05:47:28 +00004998 // C99 6.5.7p2: Each of the operands shall have integer type.
4999 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner326f7572008-11-18 01:30:42 +00005000 return InvalidOperands(Loc, lex, rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005001
Nate Begemane46ee9a2009-10-25 02:26:48 +00005002 // Vector shifts promote their scalar inputs to vector type.
5003 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
5004 return CheckVectorOperands(Loc, lex, rex);
5005
Chris Lattner5c11c412007-12-12 05:47:28 +00005006 // Shifts don't perform usual arithmetic conversions, they just do integer
5007 // promotions on each operand. C99 6.5.7p3
Eli Friedman629ffb92009-08-20 04:21:42 +00005008 QualType LHSTy = Context.isPromotableBitField(lex);
5009 if (LHSTy.isNull()) {
5010 LHSTy = lex->getType();
5011 if (LHSTy->isPromotableIntegerType())
5012 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregord2c2d172009-05-02 00:36:19 +00005013 }
Chris Lattner3c133402007-12-13 07:28:16 +00005014 if (!isCompAssign)
Eli Friedman06ed2a52009-10-20 08:27:19 +00005015 ImpCastExprToType(lex, LHSTy, CastExpr::CK_IntegralCast);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005016
Chris Lattner5c11c412007-12-12 05:47:28 +00005017 UsualUnaryConversions(rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005018
Ryan Flynnf53fab82009-08-07 16:20:20 +00005019 // Sanity-check shift operands
5020 llvm::APSInt Right;
5021 // Check right/shifter operand
Daniel Dunbar687fa862009-09-17 06:31:27 +00005022 if (!rex->isValueDependent() &&
5023 rex->isIntegerConstantExpr(Right, Context)) {
Ryan Flynn2f085712009-08-08 19:18:23 +00005024 if (Right.isNegative())
Ryan Flynnf53fab82009-08-07 16:20:20 +00005025 Diag(Loc, diag::warn_shift_negative) << rex->getSourceRange();
5026 else {
5027 llvm::APInt LeftBits(Right.getBitWidth(),
5028 Context.getTypeSize(lex->getType()));
5029 if (Right.uge(LeftBits))
5030 Diag(Loc, diag::warn_shift_gt_typewidth) << rex->getSourceRange();
5031 }
5032 }
5033
Chris Lattner5c11c412007-12-12 05:47:28 +00005034 // "The type of the result is that of the promoted left operand."
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005035 return LHSTy;
Steve Naroff26c8ea52007-03-21 21:08:52 +00005036}
5037
John McCall99ce6bf2009-11-06 08:49:08 +00005038/// \brief Implements -Wsign-compare.
5039///
5040/// \param lex the left-hand expression
5041/// \param rex the right-hand expression
5042/// \param OpLoc the location of the joining operator
John McCalle46fd852009-11-06 08:53:51 +00005043/// \param Equality whether this is an "equality-like" join, which
5044/// suppresses the warning in some cases
John McCall1fa36b72009-11-05 09:23:39 +00005045void Sema::CheckSignCompare(Expr *lex, Expr *rex, SourceLocation OpLoc,
John McCall99ce6bf2009-11-06 08:49:08 +00005046 const PartialDiagnostic &PD, bool Equality) {
John McCalle2c91e62009-11-06 18:16:06 +00005047 // Don't warn if we're in an unevaluated context.
Douglas Gregorff790f12009-11-26 00:44:06 +00005048 if (ExprEvalContexts.back().Context == Unevaluated)
John McCalle2c91e62009-11-06 18:16:06 +00005049 return;
5050
John McCall644a4182009-11-05 00:40:04 +00005051 QualType lt = lex->getType(), rt = rex->getType();
5052
5053 // Only warn if both operands are integral.
5054 if (!lt->isIntegerType() || !rt->isIntegerType())
5055 return;
5056
Sebastian Redl0b7c85f2009-11-05 21:09:23 +00005057 // If either expression is value-dependent, don't warn. We'll get another
5058 // chance at instantiation time.
5059 if (lex->isValueDependent() || rex->isValueDependent())
5060 return;
5061
John McCall644a4182009-11-05 00:40:04 +00005062 // The rule is that the signed operand becomes unsigned, so isolate the
5063 // signed operand.
John McCall99ce6bf2009-11-06 08:49:08 +00005064 Expr *signedOperand, *unsignedOperand;
John McCall644a4182009-11-05 00:40:04 +00005065 if (lt->isSignedIntegerType()) {
5066 if (rt->isSignedIntegerType()) return;
5067 signedOperand = lex;
John McCall99ce6bf2009-11-06 08:49:08 +00005068 unsignedOperand = rex;
John McCall644a4182009-11-05 00:40:04 +00005069 } else {
5070 if (!rt->isSignedIntegerType()) return;
5071 signedOperand = rex;
John McCall99ce6bf2009-11-06 08:49:08 +00005072 unsignedOperand = lex;
John McCall644a4182009-11-05 00:40:04 +00005073 }
5074
John McCall99ce6bf2009-11-06 08:49:08 +00005075 // If the unsigned type is strictly smaller than the signed type,
John McCalle46fd852009-11-06 08:53:51 +00005076 // then (1) the result type will be signed and (2) the unsigned
5077 // value will fit fully within the signed type, and thus the result
John McCall99ce6bf2009-11-06 08:49:08 +00005078 // of the comparison will be exact.
5079 if (Context.getIntWidth(signedOperand->getType()) >
5080 Context.getIntWidth(unsignedOperand->getType()))
5081 return;
5082
John McCall644a4182009-11-05 00:40:04 +00005083 // If the value is a non-negative integer constant, then the
5084 // signed->unsigned conversion won't change it.
5085 llvm::APSInt value;
John McCall1fa36b72009-11-05 09:23:39 +00005086 if (signedOperand->isIntegerConstantExpr(value, Context)) {
John McCall644a4182009-11-05 00:40:04 +00005087 assert(value.isSigned() && "result of signed expression not signed");
5088
5089 if (value.isNonNegative())
5090 return;
5091 }
5092
John McCall99ce6bf2009-11-06 08:49:08 +00005093 if (Equality) {
5094 // For (in)equality comparisons, if the unsigned operand is a
John McCalle46fd852009-11-06 08:53:51 +00005095 // constant which cannot collide with a overflowed signed operand,
5096 // then reinterpreting the signed operand as unsigned will not
5097 // change the result of the comparison.
John McCall99ce6bf2009-11-06 08:49:08 +00005098 if (unsignedOperand->isIntegerConstantExpr(value, Context)) {
5099 assert(!value.isSigned() && "result of unsigned expression is signed");
5100
5101 // 2's complement: test the top bit.
5102 if (value.isNonNegative())
5103 return;
5104 }
5105 }
5106
John McCall1fa36b72009-11-05 09:23:39 +00005107 Diag(OpLoc, PD)
John McCall644a4182009-11-05 00:40:04 +00005108 << lex->getType() << rex->getType()
5109 << lex->getSourceRange() << rex->getSourceRange();
5110}
5111
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00005112// C99 6.5.8, C++ [expr.rel]
Chris Lattner326f7572008-11-18 01:30:42 +00005113QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Douglas Gregor7a5bc762009-04-06 18:45:53 +00005114 unsigned OpaqueOpc, bool isRelational) {
5115 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)OpaqueOpc;
5116
Chris Lattner9a152e22009-12-05 05:40:13 +00005117 // Handle vector comparisons separately.
Nate Begeman191a6b12008-07-14 18:02:46 +00005118 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner326f7572008-11-18 01:30:42 +00005119 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005120
John McCall99ce6bf2009-11-06 08:49:08 +00005121 CheckSignCompare(lex, rex, Loc, diag::warn_mixed_sign_comparison,
5122 (Opc == BinaryOperator::EQ || Opc == BinaryOperator::NE));
John McCall644a4182009-11-05 00:40:04 +00005123
Chris Lattnerb620c342007-08-26 01:18:55 +00005124 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroff47fea352007-08-10 18:26:40 +00005125 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
5126 UsualArithmeticConversions(lex, rex);
5127 else {
5128 UsualUnaryConversions(lex);
5129 UsualUnaryConversions(rex);
5130 }
Steve Naroff31090012007-07-16 21:54:35 +00005131 QualType lType = lex->getType();
5132 QualType rType = rex->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005133
Mike Stumpf70bcf72009-05-07 18:43:07 +00005134 if (!lType->isFloatingType()
5135 && !(lType->isBlockPointerType() && isRelational)) {
Chris Lattner222b8bd2009-03-08 19:39:53 +00005136 // For non-floating point types, check for self-comparisons of the form
5137 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
5138 // often indicate logic errors in the program.
Mike Stump11289f42009-09-09 15:08:12 +00005139 // NOTE: Don't warn about comparisons of enum constants. These can arise
Ted Kremenekde9e9682009-03-20 19:57:37 +00005140 // from macro expansions, and are usually quite deliberate.
Chris Lattner222b8bd2009-03-08 19:39:53 +00005141 Expr *LHSStripped = lex->IgnoreParens();
5142 Expr *RHSStripped = rex->IgnoreParens();
5143 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped))
5144 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped))
Ted Kremenek9ffbe412009-03-20 18:35:45 +00005145 if (DRL->getDecl() == DRR->getDecl() &&
5146 !isa<EnumConstantDecl>(DRL->getDecl()))
Mike Stump4e1f26a2009-02-19 03:04:26 +00005147 Diag(Loc, diag::warn_selfcomparison);
Mike Stump11289f42009-09-09 15:08:12 +00005148
Chris Lattner222b8bd2009-03-08 19:39:53 +00005149 if (isa<CastExpr>(LHSStripped))
5150 LHSStripped = LHSStripped->IgnoreParenCasts();
5151 if (isa<CastExpr>(RHSStripped))
5152 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00005153
Chris Lattner222b8bd2009-03-08 19:39:53 +00005154 // Warn about comparisons against a string constant (unless the other
5155 // operand is null), the user probably wants strcmp.
Douglas Gregor7a5bc762009-04-06 18:45:53 +00005156 Expr *literalString = 0;
5157 Expr *literalStringStripped = 0;
Chris Lattner222b8bd2009-03-08 19:39:53 +00005158 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Douglas Gregor56751b52009-09-25 04:25:58 +00005159 !RHSStripped->isNullPointerConstant(Context,
5160 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregor7a5bc762009-04-06 18:45:53 +00005161 literalString = lex;
5162 literalStringStripped = LHSStripped;
Mike Stump12b8ce12009-08-04 21:02:39 +00005163 } else if ((isa<StringLiteral>(RHSStripped) ||
5164 isa<ObjCEncodeExpr>(RHSStripped)) &&
Douglas Gregor56751b52009-09-25 04:25:58 +00005165 !LHSStripped->isNullPointerConstant(Context,
5166 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregor7a5bc762009-04-06 18:45:53 +00005167 literalString = rex;
5168 literalStringStripped = RHSStripped;
5169 }
5170
5171 if (literalString) {
5172 std::string resultComparison;
5173 switch (Opc) {
5174 case BinaryOperator::LT: resultComparison = ") < 0"; break;
5175 case BinaryOperator::GT: resultComparison = ") > 0"; break;
5176 case BinaryOperator::LE: resultComparison = ") <= 0"; break;
5177 case BinaryOperator::GE: resultComparison = ") >= 0"; break;
5178 case BinaryOperator::EQ: resultComparison = ") == 0"; break;
5179 case BinaryOperator::NE: resultComparison = ") != 0"; break;
5180 default: assert(false && "Invalid comparison operator");
5181 }
5182 Diag(Loc, diag::warn_stringcompare)
5183 << isa<ObjCEncodeExpr>(literalStringStripped)
5184 << literalString->getSourceRange()
Douglas Gregor170512f2009-04-01 23:51:29 +00005185 << CodeModificationHint::CreateReplacement(SourceRange(Loc), ", ")
5186 << CodeModificationHint::CreateInsertion(lex->getLocStart(),
5187 "strcmp(")
5188 << CodeModificationHint::CreateInsertion(
5189 PP.getLocForEndOfToken(rex->getLocEnd()),
Douglas Gregor7a5bc762009-04-06 18:45:53 +00005190 resultComparison);
5191 }
Ted Kremeneke451eae2007-10-29 16:58:49 +00005192 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005193
Douglas Gregorca63811b2008-11-19 03:25:36 +00005194 // The result of comparisons is 'bool' in C++, 'int' in C.
Chris Lattner9a152e22009-12-05 05:40:13 +00005195 QualType ResultTy = getLangOptions().CPlusPlus ? Context.BoolTy:Context.IntTy;
Douglas Gregorca63811b2008-11-19 03:25:36 +00005196
Chris Lattnerb620c342007-08-26 01:18:55 +00005197 if (isRelational) {
5198 if (lType->isRealType() && rType->isRealType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00005199 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00005200 } else {
Ted Kremeneke2763b02007-10-29 17:13:39 +00005201 // Check for comparisons of floating point operands using != and ==.
Chris Lattner9a152e22009-12-05 05:40:13 +00005202 if (lType->isFloatingType() && rType->isFloatingType())
Chris Lattner326f7572008-11-18 01:30:42 +00005203 CheckFloatComparison(Loc,lex,rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005204
Chris Lattnerb620c342007-08-26 01:18:55 +00005205 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00005206 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00005207 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005208
Douglas Gregor56751b52009-09-25 04:25:58 +00005209 bool LHSIsNull = lex->isNullPointerConstant(Context,
5210 Expr::NPC_ValueDependentIsNull);
5211 bool RHSIsNull = rex->isNullPointerConstant(Context,
5212 Expr::NPC_ValueDependentIsNull);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005213
Chris Lattnerb620c342007-08-26 01:18:55 +00005214 // All of the following pointer related warnings are GCC extensions, except
5215 // when handling null pointer constants. One day, we can consider making them
5216 // errors (when -pedantic-errors is enabled).
Steve Naroff808eb8f2007-08-27 04:08:11 +00005217 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner3a0702e2008-04-03 05:07:25 +00005218 QualType LCanPointeeTy =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005219 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattner3a0702e2008-04-03 05:07:25 +00005220 QualType RCanPointeeTy =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005221 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stump4e1f26a2009-02-19 03:04:26 +00005222
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00005223 if (getLangOptions().CPlusPlus) {
Eli Friedman16c209612009-08-23 00:27:47 +00005224 if (LCanPointeeTy == RCanPointeeTy)
5225 return ResultTy;
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00005226 if (!isRelational &&
5227 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
5228 // Valid unless comparison between non-null pointer and function pointer
5229 // This is a gcc extension compatibility comparison.
5230 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
5231 && !LHSIsNull && !RHSIsNull) {
5232 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
5233 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5234 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
5235 return ResultTy;
5236 }
5237 }
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00005238 // C++ [expr.rel]p2:
5239 // [...] Pointer conversions (4.10) and qualification
5240 // conversions (4.4) are performed on pointer operands (or on
5241 // a pointer operand and a null pointer constant) to bring
5242 // them to their composite pointer type. [...]
5243 //
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005244 // C++ [expr.eq]p1 uses the same notion for (in)equality
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00005245 // comparisons of pointers.
Douglas Gregorb8420462009-05-05 04:50:50 +00005246 QualType T = FindCompositePointerType(lex, rex);
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00005247 if (T.isNull()) {
5248 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
5249 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5250 return QualType();
5251 }
5252
Eli Friedman06ed2a52009-10-20 08:27:19 +00005253 ImpCastExprToType(lex, T, CastExpr::CK_BitCast);
5254 ImpCastExprToType(rex, T, CastExpr::CK_BitCast);
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00005255 return ResultTy;
5256 }
Eli Friedman16c209612009-08-23 00:27:47 +00005257 // C99 6.5.9p2 and C99 6.5.8p2
5258 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
5259 RCanPointeeTy.getUnqualifiedType())) {
5260 // Valid unless a relational comparison of function pointers
5261 if (isRelational && LCanPointeeTy->isFunctionType()) {
5262 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
5263 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5264 }
5265 } else if (!isRelational &&
5266 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
5267 // Valid unless comparison between non-null pointer and function pointer
5268 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
5269 && !LHSIsNull && !RHSIsNull) {
5270 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
5271 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5272 }
5273 } else {
5274 // Invalid
Chris Lattner377d1f82008-11-18 22:52:51 +00005275 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005276 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff75c17232007-06-13 21:41:08 +00005277 }
Eli Friedman16c209612009-08-23 00:27:47 +00005278 if (LCanPointeeTy != RCanPointeeTy)
Eli Friedman06ed2a52009-10-20 08:27:19 +00005279 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005280 return ResultTy;
Steve Naroffcdee44c2007-08-16 21:48:38 +00005281 }
Mike Stump11289f42009-09-09 15:08:12 +00005282
Sebastian Redl576fd422009-05-10 18:38:11 +00005283 if (getLangOptions().CPlusPlus) {
Mike Stump11289f42009-09-09 15:08:12 +00005284 // Comparison of pointers with null pointer constants and equality
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005285 // comparisons of member pointers to null pointer constants.
Mike Stump11289f42009-09-09 15:08:12 +00005286 if (RHSIsNull &&
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005287 (lType->isPointerType() ||
5288 (!isRelational && lType->isMemberPointerType()))) {
Anders Carlsson83133d92009-08-24 18:03:14 +00005289 ImpCastExprToType(rex, lType, CastExpr::CK_NullToMemberPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00005290 return ResultTy;
5291 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005292 if (LHSIsNull &&
5293 (rType->isPointerType() ||
5294 (!isRelational && rType->isMemberPointerType()))) {
Anders Carlsson83133d92009-08-24 18:03:14 +00005295 ImpCastExprToType(lex, rType, CastExpr::CK_NullToMemberPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00005296 return ResultTy;
5297 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005298
5299 // Comparison of member pointers.
Mike Stump11289f42009-09-09 15:08:12 +00005300 if (!isRelational &&
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005301 lType->isMemberPointerType() && rType->isMemberPointerType()) {
5302 // C++ [expr.eq]p2:
Mike Stump11289f42009-09-09 15:08:12 +00005303 // In addition, pointers to members can be compared, or a pointer to
5304 // member and a null pointer constant. Pointer to member conversions
5305 // (4.11) and qualification conversions (4.4) are performed to bring
5306 // them to a common type. If one operand is a null pointer constant,
5307 // the common type is the type of the other operand. Otherwise, the
5308 // common type is a pointer to member type similar (4.4) to the type
5309 // of one of the operands, with a cv-qualification signature (4.4)
5310 // that is the union of the cv-qualification signatures of the operand
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005311 // types.
5312 QualType T = FindCompositePointerType(lex, rex);
5313 if (T.isNull()) {
5314 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
5315 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5316 return QualType();
5317 }
Mike Stump11289f42009-09-09 15:08:12 +00005318
Eli Friedman06ed2a52009-10-20 08:27:19 +00005319 ImpCastExprToType(lex, T, CastExpr::CK_BitCast);
5320 ImpCastExprToType(rex, T, CastExpr::CK_BitCast);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005321 return ResultTy;
5322 }
Mike Stump11289f42009-09-09 15:08:12 +00005323
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005324 // Comparison of nullptr_t with itself.
Sebastian Redl576fd422009-05-10 18:38:11 +00005325 if (lType->isNullPtrType() && rType->isNullPtrType())
5326 return ResultTy;
5327 }
Mike Stump11289f42009-09-09 15:08:12 +00005328
Steve Naroff081c7422008-09-04 15:10:53 +00005329 // Handle block pointer types.
Mike Stump1b821b42009-05-07 03:14:14 +00005330 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005331 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
5332 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005333
Steve Naroff081c7422008-09-04 15:10:53 +00005334 if (!LHSIsNull && !RHSIsNull &&
Eli Friedmana6638ca2009-06-08 05:08:54 +00005335 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00005336 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005337 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff081c7422008-09-04 15:10:53 +00005338 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00005339 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005340 return ResultTy;
Steve Naroff081c7422008-09-04 15:10:53 +00005341 }
Steve Naroffe18f94c2008-09-28 01:11:11 +00005342 // Allow block pointers to be compared with null pointer constants.
Mike Stump1b821b42009-05-07 03:14:14 +00005343 if (!isRelational
5344 && ((lType->isBlockPointerType() && rType->isPointerType())
5345 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Naroffe18f94c2008-09-28 01:11:11 +00005346 if (!LHSIsNull && !RHSIsNull) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005347 if (!((rType->isPointerType() && rType->getAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00005348 ->getPointeeType()->isVoidType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005349 || (lType->isPointerType() && lType->getAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00005350 ->getPointeeType()->isVoidType())))
5351 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
5352 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroffe18f94c2008-09-28 01:11:11 +00005353 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00005354 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005355 return ResultTy;
Steve Naroffe18f94c2008-09-28 01:11:11 +00005356 }
Steve Naroff081c7422008-09-04 15:10:53 +00005357
Steve Naroff7cae42b2009-07-10 23:34:53 +00005358 if ((lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType())) {
Steve Naroff1d4a9a32008-10-27 10:33:19 +00005359 if (lType->isPointerType() || rType->isPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005360 const PointerType *LPT = lType->getAs<PointerType>();
5361 const PointerType *RPT = rType->getAs<PointerType>();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005362 bool LPtrToVoid = LPT ?
Steve Naroff753567f2008-11-17 19:49:16 +00005363 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005364 bool RPtrToVoid = RPT ?
Steve Naroff753567f2008-11-17 19:49:16 +00005365 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005366
Steve Naroff753567f2008-11-17 19:49:16 +00005367 if (!LPtrToVoid && !RPtrToVoid &&
5368 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00005369 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005370 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff1d4a9a32008-10-27 10:33:19 +00005371 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00005372 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005373 return ResultTy;
Steve Naroffea54d9e2008-10-20 18:19:10 +00005374 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00005375 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00005376 if (!Context.areComparableObjCPointerTypes(lType, rType))
Steve Naroff7cae42b2009-07-10 23:34:53 +00005377 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
5378 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00005379 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005380 return ResultTy;
Steve Naroffb788d9b2008-06-03 14:04:54 +00005381 }
Fariborz Jahanian134cbef2007-12-20 01:06:58 +00005382 }
Steve Naroff6b712a72009-07-14 18:25:06 +00005383 if (lType->isAnyPointerType() && rType->isIntegerType()) {
Chris Lattnerd99bd522009-08-23 00:03:44 +00005384 unsigned DiagID = 0;
5385 if (RHSIsNull) {
5386 if (isRelational)
5387 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
5388 } else if (isRelational)
5389 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
5390 else
5391 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump11289f42009-09-09 15:08:12 +00005392
Chris Lattnerd99bd522009-08-23 00:03:44 +00005393 if (DiagID) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00005394 Diag(Loc, DiagID)
Chris Lattnerd466ea12009-06-30 06:24:05 +00005395 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf8344db2009-08-22 18:58:31 +00005396 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00005397 ImpCastExprToType(rex, lType, CastExpr::CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005398 return ResultTy;
Steve Naroffcdee44c2007-08-16 21:48:38 +00005399 }
Steve Naroff6b712a72009-07-14 18:25:06 +00005400 if (lType->isIntegerType() && rType->isAnyPointerType()) {
Chris Lattnerd99bd522009-08-23 00:03:44 +00005401 unsigned DiagID = 0;
5402 if (LHSIsNull) {
5403 if (isRelational)
5404 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
5405 } else if (isRelational)
5406 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
5407 else
5408 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump11289f42009-09-09 15:08:12 +00005409
Chris Lattnerd99bd522009-08-23 00:03:44 +00005410 if (DiagID) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00005411 Diag(Loc, DiagID)
Chris Lattnerd466ea12009-06-30 06:24:05 +00005412 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf8344db2009-08-22 18:58:31 +00005413 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00005414 ImpCastExprToType(lex, rType, CastExpr::CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005415 return ResultTy;
Steve Naroff043d45d2007-05-15 02:32:35 +00005416 }
Steve Naroff4b191572008-09-04 16:56:14 +00005417 // Handle block pointers.
Mike Stumpf70bcf72009-05-07 18:43:07 +00005418 if (!isRelational && RHSIsNull
5419 && lType->isBlockPointerType() && rType->isIntegerType()) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00005420 ImpCastExprToType(rex, lType, CastExpr::CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005421 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00005422 }
Mike Stumpf70bcf72009-05-07 18:43:07 +00005423 if (!isRelational && LHSIsNull
5424 && lType->isIntegerType() && rType->isBlockPointerType()) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00005425 ImpCastExprToType(lex, rType, CastExpr::CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005426 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00005427 }
Chris Lattner326f7572008-11-18 01:30:42 +00005428 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00005429}
5430
Nate Begeman191a6b12008-07-14 18:02:46 +00005431/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump4e1f26a2009-02-19 03:04:26 +00005432/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begeman191a6b12008-07-14 18:02:46 +00005433/// like a scalar comparison, a vector comparison produces a vector of integer
5434/// types.
5435QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner326f7572008-11-18 01:30:42 +00005436 SourceLocation Loc,
Nate Begeman191a6b12008-07-14 18:02:46 +00005437 bool isRelational) {
5438 // Check to make sure we're operating on vectors of the same type and width,
5439 // Allowing one side to be a scalar of element type.
Chris Lattner326f7572008-11-18 01:30:42 +00005440 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begeman191a6b12008-07-14 18:02:46 +00005441 if (vType.isNull())
5442 return vType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005443
Nate Begeman191a6b12008-07-14 18:02:46 +00005444 QualType lType = lex->getType();
5445 QualType rType = rex->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005446
Nate Begeman191a6b12008-07-14 18:02:46 +00005447 // For non-floating point types, check for self-comparisons of the form
5448 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
5449 // often indicate logic errors in the program.
5450 if (!lType->isFloatingType()) {
5451 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
5452 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
5453 if (DRL->getDecl() == DRR->getDecl())
Mike Stump4e1f26a2009-02-19 03:04:26 +00005454 Diag(Loc, diag::warn_selfcomparison);
Nate Begeman191a6b12008-07-14 18:02:46 +00005455 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005456
Nate Begeman191a6b12008-07-14 18:02:46 +00005457 // Check for comparisons of floating point operands using != and ==.
5458 if (!isRelational && lType->isFloatingType()) {
5459 assert (rType->isFloatingType());
Chris Lattner326f7572008-11-18 01:30:42 +00005460 CheckFloatComparison(Loc,lex,rex);
Nate Begeman191a6b12008-07-14 18:02:46 +00005461 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005462
Nate Begeman191a6b12008-07-14 18:02:46 +00005463 // Return the type for the comparison, which is the same as vector type for
5464 // integer vectors, or an integer type of identical size and number of
5465 // elements for floating point vectors.
5466 if (lType->isIntegerType())
5467 return lType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005468
John McCall9dd450b2009-09-21 23:43:11 +00005469 const VectorType *VTy = lType->getAs<VectorType>();
Nate Begeman191a6b12008-07-14 18:02:46 +00005470 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005471 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begeman191a6b12008-07-14 18:02:46 +00005472 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattner5d688962009-03-31 07:46:52 +00005473 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005474 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
5475
Mike Stump4e1f26a2009-02-19 03:04:26 +00005476 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005477 "Unhandled vector element size in vector compare");
Nate Begeman191a6b12008-07-14 18:02:46 +00005478 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
5479}
5480
Steve Naroff218bc2b2007-05-04 21:54:46 +00005481inline QualType Sema::CheckBitwiseOperands(
Mike Stump11289f42009-09-09 15:08:12 +00005482 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Steve Naroff94a5aca2007-07-16 22:23:01 +00005483 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner326f7572008-11-18 01:30:42 +00005484 return CheckVectorOperands(Loc, lex, rex);
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005485
Steve Naroffbe4c4d12007-08-24 19:07:16 +00005486 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005487
Steve Naroffdbd9e892007-07-17 00:58:39 +00005488 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroffbe4c4d12007-08-24 19:07:16 +00005489 return compType;
Chris Lattner326f7572008-11-18 01:30:42 +00005490 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00005491}
5492
Steve Naroff218bc2b2007-05-04 21:54:46 +00005493inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Mike Stump11289f42009-09-09 15:08:12 +00005494 Expr *&lex, Expr *&rex, SourceLocation Loc) {
Anders Carlsson2e7bc112009-11-23 21:47:44 +00005495 if (!Context.getLangOptions().CPlusPlus) {
5496 UsualUnaryConversions(lex);
5497 UsualUnaryConversions(rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005498
Anders Carlsson2e7bc112009-11-23 21:47:44 +00005499 if (!lex->getType()->isScalarType() || !rex->getType()->isScalarType())
5500 return InvalidOperands(Loc, lex, rex);
Anders Carlsson35a99d92009-10-16 01:44:21 +00005501
Anders Carlsson2e7bc112009-11-23 21:47:44 +00005502 return Context.IntTy;
Anders Carlsson35a99d92009-10-16 01:44:21 +00005503 }
Anders Carlsson2e7bc112009-11-23 21:47:44 +00005504
5505 // C++ [expr.log.and]p1
5506 // C++ [expr.log.or]p1
5507 // The operands are both implicitly converted to type bool (clause 4).
5508 StandardConversionSequence LHS;
5509 if (!IsStandardConversion(lex, Context.BoolTy,
5510 /*InOverloadResolution=*/false, LHS))
5511 return InvalidOperands(Loc, lex, rex);
Anders Carlsson35a99d92009-10-16 01:44:21 +00005512
Anders Carlsson2e7bc112009-11-23 21:47:44 +00005513 if (PerformImplicitConversion(lex, Context.BoolTy, LHS,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005514 AA_Passing, /*IgnoreBaseAccess=*/false))
Anders Carlsson2e7bc112009-11-23 21:47:44 +00005515 return InvalidOperands(Loc, lex, rex);
5516
5517 StandardConversionSequence RHS;
5518 if (!IsStandardConversion(rex, Context.BoolTy,
5519 /*InOverloadResolution=*/false, RHS))
5520 return InvalidOperands(Loc, lex, rex);
5521
5522 if (PerformImplicitConversion(rex, Context.BoolTy, RHS,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005523 AA_Passing, /*IgnoreBaseAccess=*/false))
Anders Carlsson2e7bc112009-11-23 21:47:44 +00005524 return InvalidOperands(Loc, lex, rex);
5525
5526 // C++ [expr.log.and]p2
5527 // C++ [expr.log.or]p2
5528 // The result is a bool.
5529 return Context.BoolTy;
Steve Naroffae4143e2007-04-26 20:39:23 +00005530}
5531
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00005532/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
5533/// is a read-only property; return true if so. A readonly property expression
5534/// depends on various declarations and thus must be treated specially.
5535///
Mike Stump11289f42009-09-09 15:08:12 +00005536static bool IsReadonlyProperty(Expr *E, Sema &S) {
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00005537 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
5538 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
5539 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
5540 QualType BaseType = PropExpr->getBase()->getType();
Mike Stump11289f42009-09-09 15:08:12 +00005541 if (const ObjCObjectPointerType *OPT =
Steve Naroff7cae42b2009-07-10 23:34:53 +00005542 BaseType->getAsObjCInterfacePointerType())
5543 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
5544 if (S.isPropertyReadonly(PDecl, IFace))
5545 return true;
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00005546 }
5547 }
5548 return false;
5549}
5550
Chris Lattner30bd3272008-11-18 01:22:49 +00005551/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
5552/// emit an error and return true. If so, return false.
5553static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00005554 SourceLocation OrigLoc = Loc;
Mike Stump11289f42009-09-09 15:08:12 +00005555 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00005556 &Loc);
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00005557 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
5558 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattner30bd3272008-11-18 01:22:49 +00005559 if (IsLV == Expr::MLV_Valid)
5560 return false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005561
Chris Lattner30bd3272008-11-18 01:22:49 +00005562 unsigned Diag = 0;
5563 bool NeedType = false;
5564 switch (IsLV) { // C99 6.5.16p2
5565 default: assert(0 && "Unknown result from isModifiableLvalue!");
5566 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005567 case Expr::MLV_ArrayType:
Chris Lattner30bd3272008-11-18 01:22:49 +00005568 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
5569 NeedType = true;
5570 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005571 case Expr::MLV_NotObjectType:
Chris Lattner30bd3272008-11-18 01:22:49 +00005572 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
5573 NeedType = true;
5574 break;
Chris Lattner9b3bbe92008-11-17 19:51:54 +00005575 case Expr::MLV_LValueCast:
Chris Lattner30bd3272008-11-18 01:22:49 +00005576 Diag = diag::err_typecheck_lvalue_casts_not_supported;
5577 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00005578 case Expr::MLV_InvalidExpression:
Chris Lattner30bd3272008-11-18 01:22:49 +00005579 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
5580 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00005581 case Expr::MLV_IncompleteType:
5582 case Expr::MLV_IncompleteVoidType:
Douglas Gregored0cfbd2009-03-09 16:13:40 +00005583 return S.RequireCompleteType(Loc, E->getType(),
Anders Carlssond624e162009-08-26 23:45:07 +00005584 PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
5585 << E->getSourceRange());
Chris Lattner9bad62c2008-01-04 18:04:52 +00005586 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner30bd3272008-11-18 01:22:49 +00005587 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
5588 break;
Steve Naroffba756cb2008-09-26 14:41:28 +00005589 case Expr::MLV_NotBlockQualified:
Chris Lattner30bd3272008-11-18 01:22:49 +00005590 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
5591 break;
Fariborz Jahanian8a1810f2008-11-22 18:39:36 +00005592 case Expr::MLV_ReadonlyProperty:
5593 Diag = diag::error_readonly_property_assignment;
5594 break;
Fariborz Jahanian5118c412008-11-22 20:25:50 +00005595 case Expr::MLV_NoSetterProperty:
5596 Diag = diag::error_nosetter_property_assignment;
5597 break;
Fariborz Jahaniane8d28902009-12-15 23:59:41 +00005598 case Expr::MLV_SubObjCPropertySetting:
5599 Diag = diag::error_no_subobject_property_setting;
5600 break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00005601 }
Steve Naroffad373bd2007-07-31 12:34:36 +00005602
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00005603 SourceRange Assign;
5604 if (Loc != OrigLoc)
5605 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattner30bd3272008-11-18 01:22:49 +00005606 if (NeedType)
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00005607 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00005608 else
Mike Stump11289f42009-09-09 15:08:12 +00005609 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00005610 return true;
5611}
5612
5613
5614
5615// C99 6.5.16.1
Chris Lattner326f7572008-11-18 01:30:42 +00005616QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
5617 SourceLocation Loc,
5618 QualType CompoundType) {
5619 // Verify that LHS is a modifiable lvalue, and emit error if not.
5620 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner30bd3272008-11-18 01:22:49 +00005621 return QualType();
Chris Lattner326f7572008-11-18 01:30:42 +00005622
5623 QualType LHSType = LHS->getType();
5624 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005625
Chris Lattner9bad62c2008-01-04 18:04:52 +00005626 AssignConvertType ConvTy;
Chris Lattner326f7572008-11-18 01:30:42 +00005627 if (CompoundType.isNull()) {
Chris Lattnerea714382008-08-21 18:04:13 +00005628 // Simple assignment "x = y".
Chris Lattner326f7572008-11-18 01:30:42 +00005629 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Fariborz Jahanian255c0952009-01-13 23:34:40 +00005630 // Special case of NSObject attributes on c-style pointer types.
5631 if (ConvTy == IncompatiblePointer &&
5632 ((Context.isObjCNSObjectType(LHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00005633 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanian255c0952009-01-13 23:34:40 +00005634 (Context.isObjCNSObjectType(RHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00005635 LHSType->isObjCObjectPointerType())))
Fariborz Jahanian255c0952009-01-13 23:34:40 +00005636 ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005637
Chris Lattnerea714382008-08-21 18:04:13 +00005638 // If the RHS is a unary plus or minus, check to see if they = and + are
5639 // right next to each other. If so, the user may have typo'd "x =+ 4"
5640 // instead of "x += 4".
Chris Lattner326f7572008-11-18 01:30:42 +00005641 Expr *RHSCheck = RHS;
Chris Lattnerea714382008-08-21 18:04:13 +00005642 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
5643 RHSCheck = ICE->getSubExpr();
5644 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
5645 if ((UO->getOpcode() == UnaryOperator::Plus ||
5646 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner326f7572008-11-18 01:30:42 +00005647 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattnerea714382008-08-21 18:04:13 +00005648 // Only if the two operators are exactly adjacent.
Chris Lattner36c39c92009-03-08 06:51:10 +00005649 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
5650 // And there is a space or other character before the subexpr of the
5651 // unary +/-. We don't want to warn on "x=-1".
Chris Lattnered9f14c2009-03-09 07:11:10 +00005652 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
5653 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattner29e812b2008-11-20 06:06:08 +00005654 Diag(Loc, diag::warn_not_compound_assign)
5655 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
5656 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner36c39c92009-03-08 06:51:10 +00005657 }
Chris Lattnerea714382008-08-21 18:04:13 +00005658 }
5659 } else {
5660 // Compound assignment "x += y"
Eli Friedmanb05c41e2009-05-16 05:56:02 +00005661 ConvTy = CheckAssignmentConstraints(LHSType, RHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00005662 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00005663
Chris Lattner326f7572008-11-18 01:30:42 +00005664 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005665 RHS, AA_Assigning))
Chris Lattner9bad62c2008-01-04 18:04:52 +00005666 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005667
Steve Naroff98cf3e92007-06-06 18:38:38 +00005668 // C99 6.5.16p3: The type of an assignment expression is the type of the
5669 // left operand unless the left operand has qualified type, in which case
Mike Stump4e1f26a2009-02-19 03:04:26 +00005670 // it is the unqualified version of the type of the left operand.
Steve Naroff98cf3e92007-06-06 18:38:38 +00005671 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
5672 // is converted to the type of the assignment expression (above).
Chris Lattnerf17bd422007-08-30 17:45:32 +00005673 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregord2c2d172009-05-02 00:36:19 +00005674 // operand.
Chris Lattner326f7572008-11-18 01:30:42 +00005675 return LHSType.getUnqualifiedType();
Steve Naroffae4143e2007-04-26 20:39:23 +00005676}
5677
Chris Lattner326f7572008-11-18 01:30:42 +00005678// C99 6.5.17
5679QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
Chris Lattnerf6e1e302008-07-25 20:54:07 +00005680 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner326f7572008-11-18 01:30:42 +00005681 DefaultFunctionArrayConversion(RHS);
Eli Friedmanba961a92009-03-23 00:24:07 +00005682
5683 // FIXME: Check that RHS type is complete in C mode (it's legal for it to be
5684 // incomplete in C++).
5685
Chris Lattner326f7572008-11-18 01:30:42 +00005686 return RHS->getType();
Steve Naroff95af0132007-03-30 23:47:58 +00005687}
5688
Steve Naroff7a5af782007-07-13 16:58:59 +00005689/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
5690/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redle10c2c32008-12-20 09:35:34 +00005691QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
5692 bool isInc) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005693 if (Op->isTypeDependent())
5694 return Context.DependentTy;
5695
Chris Lattner6b0cf142008-11-21 07:05:48 +00005696 QualType ResType = Op->getType();
5697 assert(!ResType.isNull() && "no type for increment/decrement expression");
Steve Naroffd50c88e2007-04-05 21:15:20 +00005698
Sebastian Redle10c2c32008-12-20 09:35:34 +00005699 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
5700 // Decrement of bool is not allowed.
5701 if (!isInc) {
5702 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
5703 return QualType();
5704 }
5705 // Increment of bool sets it to true, but is deprecated.
5706 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
5707 } else if (ResType->isRealType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00005708 // OK!
Steve Naroff6b712a72009-07-14 18:25:06 +00005709 } else if (ResType->isAnyPointerType()) {
5710 QualType PointeeTy = ResType->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00005711
Chris Lattner6b0cf142008-11-21 07:05:48 +00005712 // C99 6.5.2.4p2, 6.5.6p2
Steve Naroff7cae42b2009-07-10 23:34:53 +00005713 if (PointeeTy->isVoidType()) {
Douglas Gregorf6cd9282009-01-23 00:36:41 +00005714 if (getLangOptions().CPlusPlus) {
5715 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
5716 << Op->getSourceRange();
5717 return QualType();
5718 }
5719
5720 // Pointer to void is a GNU extension in C.
Chris Lattner6b0cf142008-11-21 07:05:48 +00005721 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005722 } else if (PointeeTy->isFunctionType()) {
Douglas Gregorf6cd9282009-01-23 00:36:41 +00005723 if (getLangOptions().CPlusPlus) {
5724 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
5725 << Op->getType() << Op->getSourceRange();
5726 return QualType();
5727 }
5728
5729 Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005730 << ResType << Op->getSourceRange();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005731 } else if (RequireCompleteType(OpLoc, PointeeTy,
Anders Carlsson029fc692009-08-26 22:59:12 +00005732 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
Mike Stump11289f42009-09-09 15:08:12 +00005733 << Op->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00005734 << ResType))
Douglas Gregordd430f72009-01-19 19:26:10 +00005735 return QualType();
Fariborz Jahanianca75db72009-07-16 17:59:14 +00005736 // Diagnose bad cases where we step over interface counts.
5737 else if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
5738 Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
5739 << PointeeTy << Op->getSourceRange();
5740 return QualType();
5741 }
Chris Lattner6b0cf142008-11-21 07:05:48 +00005742 } else if (ResType->isComplexType()) {
5743 // C99 does not support ++/-- on complex types, we allow as an extension.
5744 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005745 << ResType << Op->getSourceRange();
Chris Lattner6b0cf142008-11-21 07:05:48 +00005746 } else {
5747 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Douglas Gregor906db8a2009-12-15 16:44:32 +00005748 << ResType << int(isInc) << Op->getSourceRange();
Chris Lattner6b0cf142008-11-21 07:05:48 +00005749 return QualType();
Steve Naroff46ba1eb2007-04-03 23:13:13 +00005750 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005751 // At this point, we know we have a real, complex or pointer type.
Steve Naroff9e1e5512007-08-23 21:37:33 +00005752 // Now make sure the operand is a modifiable lvalue.
Chris Lattner6b0cf142008-11-21 07:05:48 +00005753 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Steve Naroff35d85152007-05-07 00:24:15 +00005754 return QualType();
Chris Lattner6b0cf142008-11-21 07:05:48 +00005755 return ResType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00005756}
5757
Anders Carlsson806700f2008-02-01 07:15:58 +00005758/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Steve Naroff47500512007-04-19 23:00:49 +00005759/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb692ef42008-08-04 20:02:37 +00005760/// where the declaration is needed for type checking. We only need to
5761/// handle cases when the expression references a function designator
5762/// or is an lvalue. Here are some examples:
5763/// - &(x) => x
5764/// - &*****f => f for f a function designator.
5765/// - &s.xx => s
5766/// - &s.zz[1].yy -> s, if zz is an array
5767/// - *(x + 1) -> x, if x is an array
5768/// - &"123"[2] -> 0
5769/// - & __real__ x -> x
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005770static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00005771 switch (E->getStmtClass()) {
Steve Naroff47500512007-04-19 23:00:49 +00005772 case Stmt::DeclRefExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00005773 return cast<DeclRefExpr>(E)->getDecl();
Steve Naroff47500512007-04-19 23:00:49 +00005774 case Stmt::MemberExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00005775 // If this is an arrow operator, the address is an offset from
5776 // the base's value, so the object the base refers to is
5777 // irrelevant.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00005778 if (cast<MemberExpr>(E)->isArrow())
Chris Lattner48d52842007-11-16 17:46:48 +00005779 return 0;
Eli Friedman3a1e6922009-04-20 08:23:18 +00005780 // Otherwise, the expression refers to a part of the base
Chris Lattner24d5bfe2008-04-02 04:24:33 +00005781 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson806700f2008-02-01 07:15:58 +00005782 case Stmt::ArraySubscriptExprClass: {
Mike Stump87c57ac2009-05-16 07:39:55 +00005783 // FIXME: This code shouldn't be necessary! We should catch the implicit
5784 // promotion of register arrays earlier.
Eli Friedman3a1e6922009-04-20 08:23:18 +00005785 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
5786 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
5787 if (ICE->getSubExpr()->getType()->isArrayType())
5788 return getPrimaryDecl(ICE->getSubExpr());
5789 }
5790 return 0;
Anders Carlsson806700f2008-02-01 07:15:58 +00005791 }
Daniel Dunbarb692ef42008-08-04 20:02:37 +00005792 case Stmt::UnaryOperatorClass: {
5793 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005794
Daniel Dunbarb692ef42008-08-04 20:02:37 +00005795 switch(UO->getOpcode()) {
Daniel Dunbarb692ef42008-08-04 20:02:37 +00005796 case UnaryOperator::Real:
5797 case UnaryOperator::Imag:
5798 case UnaryOperator::Extension:
5799 return getPrimaryDecl(UO->getSubExpr());
5800 default:
5801 return 0;
5802 }
5803 }
Steve Naroff47500512007-04-19 23:00:49 +00005804 case Stmt::ParenExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00005805 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattner48d52842007-11-16 17:46:48 +00005806 case Stmt::ImplicitCastExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00005807 // If the result of an implicit cast is an l-value, we care about
5808 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00005809 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Steve Naroff47500512007-04-19 23:00:49 +00005810 default:
5811 return 0;
5812 }
5813}
5814
5815/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump4e1f26a2009-02-19 03:04:26 +00005816/// designator or an lvalue designating an object. If it is an lvalue, the
Steve Naroff47500512007-04-19 23:00:49 +00005817/// object cannot be declared with storage class register or be a bit field.
Mike Stump4e1f26a2009-02-19 03:04:26 +00005818/// Note: The usual conversions are *not* applied to the operand of the &
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005819/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump4e1f26a2009-02-19 03:04:26 +00005820/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregorcd695e52008-11-10 20:40:00 +00005821/// we allow the '&' but retain the overloaded-function type.
Steve Naroff35d85152007-05-07 00:24:15 +00005822QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Eli Friedman3a1e6922009-04-20 08:23:18 +00005823 // Make sure to ignore parentheses in subsequent checks
5824 op = op->IgnoreParens();
5825
Douglas Gregor19b8c4f2008-12-17 22:52:20 +00005826 if (op->isTypeDependent())
5827 return Context.DependentTy;
5828
Steve Naroff826e91a2008-01-13 17:10:08 +00005829 if (getLangOptions().C99) {
5830 // Implement C99-only parts of addressof rules.
5831 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
5832 if (uOp->getOpcode() == UnaryOperator::Deref)
5833 // Per C99 6.5.3.2, the address of a deref always returns a valid result
5834 // (assuming the deref expression is valid).
5835 return uOp->getSubExpr()->getType();
5836 }
5837 // Technically, there should be a check for array subscript
5838 // expressions here, but the result of one is always an lvalue anyway.
5839 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005840 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner67315442008-07-26 21:30:36 +00005841 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes17f345f2008-12-16 22:59:47 +00005842
Eli Friedmance7f9002009-05-16 23:27:50 +00005843 if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
5844 // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00005845 // The operand must be either an l-value or a function designator
Eli Friedmance7f9002009-05-16 23:27:50 +00005846 if (!op->getType()->isFunctionType()) {
Chris Lattner48d52842007-11-16 17:46:48 +00005847 // FIXME: emit more specific diag...
Chris Lattnerf490e152008-11-19 05:27:50 +00005848 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
5849 << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00005850 return QualType();
5851 }
Douglas Gregor71235ec2009-05-02 02:18:30 +00005852 } else if (op->getBitField()) { // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00005853 // The operand cannot be a bit-field
5854 Diag(OpLoc, diag::err_typecheck_address_of)
5855 << "bit-field" << op->getSourceRange();
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00005856 return QualType();
Nate Begemana6b47a42009-02-15 22:45:20 +00005857 } else if (isa<ExtVectorElementExpr>(op) || (isa<ArraySubscriptExpr>(op) &&
5858 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType())){
Eli Friedman3a1e6922009-04-20 08:23:18 +00005859 // The operand cannot be an element of a vector
Chris Lattner29e812b2008-11-20 06:06:08 +00005860 Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemana6b47a42009-02-15 22:45:20 +00005861 << "vector element" << op->getSourceRange();
Steve Naroffb96e4ab62008-02-29 23:30:25 +00005862 return QualType();
Fariborz Jahanian385db802009-07-07 18:50:52 +00005863 } else if (isa<ObjCPropertyRefExpr>(op)) {
5864 // cannot take address of a property expression.
5865 Diag(OpLoc, diag::err_typecheck_address_of)
5866 << "property expression" << op->getSourceRange();
5867 return QualType();
Anders Carlsson3fa58d12009-09-14 23:15:26 +00005868 } else if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(op)) {
5869 // FIXME: Can LHS ever be null here?
Anders Carlsson01ccf992009-09-15 16:03:44 +00005870 if (!CheckAddressOfOperand(CO->getTrueExpr(), OpLoc).isNull())
5871 return CheckAddressOfOperand(CO->getFalseExpr(), OpLoc);
John McCalld14a8642009-11-21 08:51:07 +00005872 } else if (isa<UnresolvedLookupExpr>(op)) {
5873 return Context.OverloadTy;
Steve Naroffb96e4ab62008-02-29 23:30:25 +00005874 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump4e1f26a2009-02-19 03:04:26 +00005875 // We have an lvalue with a decl. Make sure the decl is not declared
Steve Naroff47500512007-04-19 23:00:49 +00005876 // with the register storage-class specifier.
5877 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Steve Naroff35d85152007-05-07 00:24:15 +00005878 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattner29e812b2008-11-20 06:06:08 +00005879 Diag(OpLoc, diag::err_typecheck_address_of)
5880 << "register variable" << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00005881 return QualType();
5882 }
John McCalld14a8642009-11-21 08:51:07 +00005883 } else if (isa<FunctionTemplateDecl>(dcl)) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00005884 return Context.OverloadTy;
Anders Carlsson0b675f52009-07-08 21:45:58 +00005885 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(dcl)) {
Douglas Gregor9aa8b552008-12-10 21:26:49 +00005886 // Okay: we can take the address of a field.
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00005887 // Could be a pointer to member, though, if there is an explicit
5888 // scope qualifier for the class.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00005889 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00005890 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlsson0b675f52009-07-08 21:45:58 +00005891 if (Ctx && Ctx->isRecord()) {
5892 if (FD->getType()->isReferenceType()) {
Mike Stump11289f42009-09-09 15:08:12 +00005893 Diag(OpLoc,
Anders Carlsson0b675f52009-07-08 21:45:58 +00005894 diag::err_cannot_form_pointer_to_member_of_reference_type)
5895 << FD->getDeclName() << FD->getType();
5896 return QualType();
5897 }
Mike Stump11289f42009-09-09 15:08:12 +00005898
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00005899 return Context.getMemberPointerType(op->getType(),
5900 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlsson0b675f52009-07-08 21:45:58 +00005901 }
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00005902 }
Anders Carlsson5b535762009-05-16 21:43:42 +00005903 } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(dcl)) {
Nuno Lopes5773a1b2008-12-16 22:58:26 +00005904 // Okay: we can take the address of a function.
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005905 // As above.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00005906 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier() &&
5907 MD->isInstance())
Anders Carlsson5b535762009-05-16 21:43:42 +00005908 return Context.getMemberPointerType(op->getType(),
5909 Context.getTypeDeclType(MD->getParent()).getTypePtr());
5910 } else if (!isa<FunctionDecl>(dcl))
Steve Narofff633d092007-04-25 19:01:39 +00005911 assert(0 && "Unknown/unexpected decl type");
Steve Naroff47500512007-04-19 23:00:49 +00005912 }
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005913
Eli Friedmance7f9002009-05-16 23:27:50 +00005914 if (lval == Expr::LV_IncompleteVoidType) {
5915 // Taking the address of a void variable is technically illegal, but we
5916 // allow it in cases which are otherwise valid.
5917 // Example: "extern void x; void* y = &x;".
5918 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
5919 }
5920
Steve Naroff47500512007-04-19 23:00:49 +00005921 // If the operand has type "type", the result has type "pointer to type".
Steve Naroff35d85152007-05-07 00:24:15 +00005922 return Context.getPointerType(op->getType());
Steve Naroff47500512007-04-19 23:00:49 +00005923}
5924
Chris Lattner6a2ed6f2008-11-23 09:13:29 +00005925QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005926 if (Op->isTypeDependent())
5927 return Context.DependentTy;
5928
Chris Lattner6a2ed6f2008-11-23 09:13:29 +00005929 UsualUnaryConversions(Op);
5930 QualType Ty = Op->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005931
Chris Lattner6a2ed6f2008-11-23 09:13:29 +00005932 // Note that per both C89 and C99, this is always legal, even if ptype is an
5933 // incomplete type or void. It would be possible to warn about dereferencing
5934 // a void pointer, but it's completely well-defined, and such a warning is
5935 // unlikely to catch any mistakes.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005936 if (const PointerType *PT = Ty->getAs<PointerType>())
Steve Naroff826e91a2008-01-13 17:10:08 +00005937 return PT->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005938
John McCall9dd450b2009-09-21 23:43:11 +00005939 if (const ObjCObjectPointerType *OPT = Ty->getAs<ObjCObjectPointerType>())
Fariborz Jahanianf15d4b62009-09-03 00:43:07 +00005940 return OPT->getPointeeType();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005941
Chris Lattner29e812b2008-11-20 06:06:08 +00005942 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner6a2ed6f2008-11-23 09:13:29 +00005943 << Ty << Op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00005944 return QualType();
Steve Naroff1926c832007-04-24 00:23:05 +00005945}
Steve Naroff218bc2b2007-05-04 21:54:46 +00005946
5947static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
5948 tok::TokenKind Kind) {
5949 BinaryOperator::Opcode Opc;
5950 switch (Kind) {
5951 default: assert(0 && "Unknown binop!");
Sebastian Redl112a97662009-02-07 00:15:38 +00005952 case tok::periodstar: Opc = BinaryOperator::PtrMemD; break;
5953 case tok::arrowstar: Opc = BinaryOperator::PtrMemI; break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00005954 case tok::star: Opc = BinaryOperator::Mul; break;
5955 case tok::slash: Opc = BinaryOperator::Div; break;
5956 case tok::percent: Opc = BinaryOperator::Rem; break;
5957 case tok::plus: Opc = BinaryOperator::Add; break;
5958 case tok::minus: Opc = BinaryOperator::Sub; break;
5959 case tok::lessless: Opc = BinaryOperator::Shl; break;
5960 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
5961 case tok::lessequal: Opc = BinaryOperator::LE; break;
5962 case tok::less: Opc = BinaryOperator::LT; break;
5963 case tok::greaterequal: Opc = BinaryOperator::GE; break;
5964 case tok::greater: Opc = BinaryOperator::GT; break;
5965 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
5966 case tok::equalequal: Opc = BinaryOperator::EQ; break;
5967 case tok::amp: Opc = BinaryOperator::And; break;
5968 case tok::caret: Opc = BinaryOperator::Xor; break;
5969 case tok::pipe: Opc = BinaryOperator::Or; break;
5970 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
5971 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
5972 case tok::equal: Opc = BinaryOperator::Assign; break;
5973 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
5974 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
5975 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
5976 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
5977 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
5978 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
5979 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
5980 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
5981 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
5982 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
5983 case tok::comma: Opc = BinaryOperator::Comma; break;
5984 }
5985 return Opc;
5986}
5987
Steve Naroff35d85152007-05-07 00:24:15 +00005988static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
5989 tok::TokenKind Kind) {
5990 UnaryOperator::Opcode Opc;
5991 switch (Kind) {
5992 default: assert(0 && "Unknown unary op!");
5993 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
5994 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
5995 case tok::amp: Opc = UnaryOperator::AddrOf; break;
5996 case tok::star: Opc = UnaryOperator::Deref; break;
5997 case tok::plus: Opc = UnaryOperator::Plus; break;
5998 case tok::minus: Opc = UnaryOperator::Minus; break;
5999 case tok::tilde: Opc = UnaryOperator::Not; break;
6000 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Steve Naroff35d85152007-05-07 00:24:15 +00006001 case tok::kw___real: Opc = UnaryOperator::Real; break;
6002 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
Chris Lattnerd0f76512007-06-08 22:16:53 +00006003 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
Steve Naroff35d85152007-05-07 00:24:15 +00006004 }
6005 return Opc;
6006}
6007
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006008/// CreateBuiltinBinOp - Creates a new built-in binary operation with
6009/// operator @p Opc at location @c TokLoc. This routine only supports
6010/// built-in operations; ActOnBinOp handles overloaded operators.
Sebastian Redlb5d49352009-01-19 22:31:54 +00006011Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
6012 unsigned Op,
6013 Expr *lhs, Expr *rhs) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006014 QualType ResultTy; // Result type of the binary operator.
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006015 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006016 // The following two variables are used for compound assignment operators
6017 QualType CompLHSTy; // Type of LHS after promotions for computation
6018 QualType CompResultTy; // Type of computation result
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006019
6020 switch (Opc) {
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006021 case BinaryOperator::Assign:
6022 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
6023 break;
Sebastian Redl112a97662009-02-07 00:15:38 +00006024 case BinaryOperator::PtrMemD:
6025 case BinaryOperator::PtrMemI:
6026 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
6027 Opc == BinaryOperator::PtrMemI);
6028 break;
6029 case BinaryOperator::Mul:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006030 case BinaryOperator::Div:
6031 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
6032 break;
6033 case BinaryOperator::Rem:
6034 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
6035 break;
6036 case BinaryOperator::Add:
6037 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
6038 break;
6039 case BinaryOperator::Sub:
6040 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
6041 break;
Sebastian Redl112a97662009-02-07 00:15:38 +00006042 case BinaryOperator::Shl:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006043 case BinaryOperator::Shr:
6044 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
6045 break;
6046 case BinaryOperator::LE:
6047 case BinaryOperator::LT:
6048 case BinaryOperator::GE:
6049 case BinaryOperator::GT:
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006050 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006051 break;
6052 case BinaryOperator::EQ:
6053 case BinaryOperator::NE:
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006054 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006055 break;
6056 case BinaryOperator::And:
6057 case BinaryOperator::Xor:
6058 case BinaryOperator::Or:
6059 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
6060 break;
6061 case BinaryOperator::LAnd:
6062 case BinaryOperator::LOr:
6063 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
6064 break;
6065 case BinaryOperator::MulAssign:
6066 case BinaryOperator::DivAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006067 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
6068 CompLHSTy = CompResultTy;
6069 if (!CompResultTy.isNull())
6070 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006071 break;
6072 case BinaryOperator::RemAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006073 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
6074 CompLHSTy = CompResultTy;
6075 if (!CompResultTy.isNull())
6076 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006077 break;
6078 case BinaryOperator::AddAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006079 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
6080 if (!CompResultTy.isNull())
6081 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006082 break;
6083 case BinaryOperator::SubAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006084 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
6085 if (!CompResultTy.isNull())
6086 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006087 break;
6088 case BinaryOperator::ShlAssign:
6089 case BinaryOperator::ShrAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006090 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
6091 CompLHSTy = CompResultTy;
6092 if (!CompResultTy.isNull())
6093 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006094 break;
6095 case BinaryOperator::AndAssign:
6096 case BinaryOperator::XorAssign:
6097 case BinaryOperator::OrAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006098 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
6099 CompLHSTy = CompResultTy;
6100 if (!CompResultTy.isNull())
6101 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006102 break;
6103 case BinaryOperator::Comma:
6104 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
6105 break;
6106 }
6107 if (ResultTy.isNull())
Sebastian Redlb5d49352009-01-19 22:31:54 +00006108 return ExprError();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006109 if (CompResultTy.isNull())
Steve Narofff6009ed2009-01-21 00:14:39 +00006110 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
6111 else
6112 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006113 CompLHSTy, CompResultTy,
6114 OpLoc));
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006115}
6116
Sebastian Redl44615072009-10-27 12:10:02 +00006117/// SuggestParentheses - Emit a diagnostic together with a fixit hint that wraps
6118/// ParenRange in parentheses.
Sebastian Redl4afb7c582009-10-26 17:01:32 +00006119static void SuggestParentheses(Sema &Self, SourceLocation Loc,
6120 const PartialDiagnostic &PD,
6121 SourceRange ParenRange)
6122{
6123 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
6124 if (!ParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
6125 // We can't display the parentheses, so just dig the
6126 // warning/error and return.
6127 Self.Diag(Loc, PD);
6128 return;
6129 }
6130
6131 Self.Diag(Loc, PD)
6132 << CodeModificationHint::CreateInsertion(ParenRange.getBegin(), "(")
6133 << CodeModificationHint::CreateInsertion(EndLoc, ")");
6134}
6135
Sebastian Redl44615072009-10-27 12:10:02 +00006136/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
6137/// operators are mixed in a way that suggests that the programmer forgot that
6138/// comparison operators have higher precedence. The most typical example of
6139/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
Sebastian Redl43028242009-10-26 15:24:15 +00006140static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperator::Opcode Opc,
6141 SourceLocation OpLoc,Expr *lhs,Expr *rhs){
Sebastian Redl44615072009-10-27 12:10:02 +00006142 typedef BinaryOperator BinOp;
6143 BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1),
6144 rhsopc = static_cast<BinOp::Opcode>(-1);
6145 if (BinOp *BO = dyn_cast<BinOp>(lhs))
Sebastian Redl43028242009-10-26 15:24:15 +00006146 lhsopc = BO->getOpcode();
Sebastian Redl44615072009-10-27 12:10:02 +00006147 if (BinOp *BO = dyn_cast<BinOp>(rhs))
Sebastian Redl43028242009-10-26 15:24:15 +00006148 rhsopc = BO->getOpcode();
6149
6150 // Subs are not binary operators.
6151 if (lhsopc == -1 && rhsopc == -1)
6152 return;
6153
6154 // Bitwise operations are sometimes used as eager logical ops.
6155 // Don't diagnose this.
Sebastian Redl44615072009-10-27 12:10:02 +00006156 if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) &&
6157 (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc)))
Sebastian Redl43028242009-10-26 15:24:15 +00006158 return;
6159
Sebastian Redl44615072009-10-27 12:10:02 +00006160 if (BinOp::isComparisonOp(lhsopc))
Sebastian Redl4afb7c582009-10-26 17:01:32 +00006161 SuggestParentheses(Self, OpLoc,
6162 PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redl44615072009-10-27 12:10:02 +00006163 << SourceRange(lhs->getLocStart(), OpLoc)
6164 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(lhsopc),
6165 SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(), rhs->getLocEnd()));
6166 else if (BinOp::isComparisonOp(rhsopc))
Sebastian Redl4afb7c582009-10-26 17:01:32 +00006167 SuggestParentheses(Self, OpLoc,
6168 PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redl44615072009-10-27 12:10:02 +00006169 << SourceRange(OpLoc, rhs->getLocEnd())
6170 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(rhsopc),
6171 SourceRange(lhs->getLocEnd(), cast<BinOp>(rhs)->getLHS()->getLocStart()));
Sebastian Redl43028242009-10-26 15:24:15 +00006172}
6173
6174/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
6175/// precedence. This currently diagnoses only "arg1 'bitwise' arg2 'eq' arg3".
6176/// But it could also warn about arg1 && arg2 || arg3, as GCC 4.3+ does.
6177static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperator::Opcode Opc,
6178 SourceLocation OpLoc, Expr *lhs, Expr *rhs){
Sebastian Redl44615072009-10-27 12:10:02 +00006179 if (BinaryOperator::isBitwiseOp(Opc))
Sebastian Redl43028242009-10-26 15:24:15 +00006180 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs);
6181}
6182
Steve Naroff218bc2b2007-05-04 21:54:46 +00006183// Binary Operators. 'Tok' is the token for the operator.
Sebastian Redlb5d49352009-01-19 22:31:54 +00006184Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
6185 tok::TokenKind Kind,
6186 ExprArg LHS, ExprArg RHS) {
Steve Naroff218bc2b2007-05-04 21:54:46 +00006187 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
Anders Carlssonb781bcd2009-05-01 19:49:17 +00006188 Expr *lhs = LHS.takeAs<Expr>(), *rhs = RHS.takeAs<Expr>();
Steve Naroff218bc2b2007-05-04 21:54:46 +00006189
Steve Naroff83895f72007-09-16 03:34:24 +00006190 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
6191 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Steve Naroff218bc2b2007-05-04 21:54:46 +00006192
Sebastian Redl43028242009-10-26 15:24:15 +00006193 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
6194 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs);
6195
Douglas Gregor5287f092009-11-05 00:51:44 +00006196 return BuildBinOp(S, TokLoc, Opc, lhs, rhs);
6197}
6198
6199Action::OwningExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
6200 BinaryOperator::Opcode Opc,
6201 Expr *lhs, Expr *rhs) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006202 if (getLangOptions().CPlusPlus &&
Mike Stump11289f42009-09-09 15:08:12 +00006203 (lhs->getType()->isOverloadableType() ||
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006204 rhs->getType()->isOverloadableType())) {
6205 // Find all of the overloaded operators visible from this
6206 // point. We perform both an operator-name lookup from the local
6207 // scope and an argument-dependent lookup based on the types of
6208 // the arguments.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00006209 FunctionSet Functions;
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006210 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
6211 if (OverOp != OO_None) {
Douglas Gregor5287f092009-11-05 00:51:44 +00006212 if (S)
6213 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
6214 Functions);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006215 Expr *Args[2] = { lhs, rhs };
Mike Stump11289f42009-09-09 15:08:12 +00006216 DeclarationName OpName
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006217 = Context.DeclarationNames.getCXXOperatorName(OverOp);
Sebastian Redlc057f422009-10-23 19:23:15 +00006218 ArgumentDependentLookup(OpName, /*Operator*/true, Args, 2, Functions);
Douglas Gregora11693b2008-11-12 17:17:38 +00006219 }
Douglas Gregor5287f092009-11-05 00:51:44 +00006220
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006221 // Build the (potentially-overloaded, potentially-dependent)
6222 // binary operation.
Douglas Gregor5287f092009-11-05 00:51:44 +00006223 return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs);
Sebastian Redlb5d49352009-01-19 22:31:54 +00006224 }
Douglas Gregor5287f092009-11-05 00:51:44 +00006225
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006226 // Build a built-in binary operation.
Douglas Gregor5287f092009-11-05 00:51:44 +00006227 return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs);
Steve Naroff218bc2b2007-05-04 21:54:46 +00006228}
6229
Douglas Gregor084d8552009-03-13 23:49:33 +00006230Action::OwningExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00006231 unsigned OpcIn,
Douglas Gregor084d8552009-03-13 23:49:33 +00006232 ExprArg InputArg) {
6233 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregord08452f2008-11-19 15:42:04 +00006234
Mike Stump87c57ac2009-05-16 07:39:55 +00006235 // FIXME: Input is modified below, but InputArg is not updated appropriately.
Douglas Gregor084d8552009-03-13 23:49:33 +00006236 Expr *Input = (Expr *)InputArg.get();
Steve Naroff35d85152007-05-07 00:24:15 +00006237 QualType resultType;
6238 switch (Opc) {
Douglas Gregor084d8552009-03-13 23:49:33 +00006239 case UnaryOperator::OffsetOf:
6240 assert(false && "Invalid unary operator");
6241 break;
6242
Steve Naroff35d85152007-05-07 00:24:15 +00006243 case UnaryOperator::PreInc:
6244 case UnaryOperator::PreDec:
Eli Friedman6aea5752009-07-22 22:25:00 +00006245 case UnaryOperator::PostInc:
6246 case UnaryOperator::PostDec:
Sebastian Redle10c2c32008-12-20 09:35:34 +00006247 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
Eli Friedman6aea5752009-07-22 22:25:00 +00006248 Opc == UnaryOperator::PreInc ||
6249 Opc == UnaryOperator::PostInc);
Steve Naroff35d85152007-05-07 00:24:15 +00006250 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006251 case UnaryOperator::AddrOf:
Chris Lattner86554282007-06-08 22:32:33 +00006252 resultType = CheckAddressOfOperand(Input, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00006253 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006254 case UnaryOperator::Deref:
Steve Naroffb7235642007-12-18 04:06:57 +00006255 DefaultFunctionArrayConversion(Input);
Chris Lattner86554282007-06-08 22:32:33 +00006256 resultType = CheckIndirectionOperand(Input, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00006257 break;
6258 case UnaryOperator::Plus:
6259 case UnaryOperator::Minus:
Steve Naroff31090012007-07-16 21:54:35 +00006260 UsualUnaryConversions(Input);
6261 resultType = Input->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006262 if (resultType->isDependentType())
6263 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00006264 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
6265 break;
6266 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
6267 resultType->isEnumeralType())
6268 break;
6269 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
6270 Opc == UnaryOperator::Plus &&
6271 resultType->isPointerType())
6272 break;
6273
Sebastian Redlc215cfc2009-01-19 00:08:26 +00006274 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
6275 << resultType << Input->getSourceRange());
Steve Naroff35d85152007-05-07 00:24:15 +00006276 case UnaryOperator::Not: // bitwise complement
Steve Naroff31090012007-07-16 21:54:35 +00006277 UsualUnaryConversions(Input);
6278 resultType = Input->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006279 if (resultType->isDependentType())
6280 break;
Chris Lattner0d707612008-07-25 23:52:49 +00006281 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
6282 if (resultType->isComplexType() || resultType->isComplexIntegerType())
6283 // C99 does not support '~' for complex conjugation.
Chris Lattner29e812b2008-11-20 06:06:08 +00006284 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006285 << resultType << Input->getSourceRange();
Chris Lattner0d707612008-07-25 23:52:49 +00006286 else if (!resultType->isIntegerType())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00006287 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
6288 << resultType << Input->getSourceRange());
Steve Naroff35d85152007-05-07 00:24:15 +00006289 break;
6290 case UnaryOperator::LNot: // logical negation
Steve Naroff71b59a92007-06-04 22:22:31 +00006291 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Steve Naroff31090012007-07-16 21:54:35 +00006292 DefaultFunctionArrayConversion(Input);
6293 resultType = Input->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006294 if (resultType->isDependentType())
6295 break;
Steve Naroff35d85152007-05-07 00:24:15 +00006296 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redlc215cfc2009-01-19 00:08:26 +00006297 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
6298 << resultType << Input->getSourceRange());
Chris Lattnerbe31ed82007-06-02 19:11:33 +00006299 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00006300 // In C++, it's bool. C++ 5.3.1p8
6301 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Steve Naroff35d85152007-05-07 00:24:15 +00006302 break;
Chris Lattner30b5dd02007-08-24 21:16:53 +00006303 case UnaryOperator::Real:
Chris Lattner30b5dd02007-08-24 21:16:53 +00006304 case UnaryOperator::Imag:
Chris Lattner709322b2009-02-17 08:12:06 +00006305 resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real);
Chris Lattner30b5dd02007-08-24 21:16:53 +00006306 break;
Chris Lattner86554282007-06-08 22:32:33 +00006307 case UnaryOperator::Extension:
Chris Lattner86554282007-06-08 22:32:33 +00006308 resultType = Input->getType();
Steve Naroff043d45d2007-05-15 02:32:35 +00006309 break;
Steve Naroff35d85152007-05-07 00:24:15 +00006310 }
6311 if (resultType.isNull())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00006312 return ExprError();
Douglas Gregor084d8552009-03-13 23:49:33 +00006313
6314 InputArg.release();
Steve Narofff6009ed2009-01-21 00:14:39 +00006315 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
Steve Naroff35d85152007-05-07 00:24:15 +00006316}
Chris Lattnereefa10e2007-05-28 06:56:27 +00006317
Douglas Gregor5287f092009-11-05 00:51:44 +00006318Action::OwningExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
6319 UnaryOperator::Opcode Opc,
6320 ExprArg input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00006321 Expr *Input = (Expr*)input.get();
Anders Carlsson461a2c02009-11-14 21:26:41 +00006322 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
6323 Opc != UnaryOperator::Extension) {
Douglas Gregor084d8552009-03-13 23:49:33 +00006324 // Find all of the overloaded operators visible from this
6325 // point. We perform both an operator-name lookup from the local
6326 // scope and an argument-dependent lookup based on the types of
6327 // the arguments.
6328 FunctionSet Functions;
6329 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
6330 if (OverOp != OO_None) {
Douglas Gregor5287f092009-11-05 00:51:44 +00006331 if (S)
6332 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
6333 Functions);
Mike Stump11289f42009-09-09 15:08:12 +00006334 DeclarationName OpName
Douglas Gregor084d8552009-03-13 23:49:33 +00006335 = Context.DeclarationNames.getCXXOperatorName(OverOp);
Sebastian Redlc057f422009-10-23 19:23:15 +00006336 ArgumentDependentLookup(OpName, /*Operator*/true, &Input, 1, Functions);
Douglas Gregor084d8552009-03-13 23:49:33 +00006337 }
Douglas Gregor5287f092009-11-05 00:51:44 +00006338
Douglas Gregor084d8552009-03-13 23:49:33 +00006339 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, move(input));
6340 }
Douglas Gregor5287f092009-11-05 00:51:44 +00006341
Douglas Gregor084d8552009-03-13 23:49:33 +00006342 return CreateBuiltinUnaryOp(OpLoc, Opc, move(input));
6343}
6344
Douglas Gregor5287f092009-11-05 00:51:44 +00006345// Unary Operators. 'Tok' is the token for the operator.
6346Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
6347 tok::TokenKind Op, ExprArg input) {
6348 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), move(input));
6349}
6350
Steve Naroff66356bd2007-09-16 14:56:35 +00006351/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006352Sema::OwningExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
6353 SourceLocation LabLoc,
6354 IdentifierInfo *LabelII) {
Chris Lattnereefa10e2007-05-28 06:56:27 +00006355 // Look up the record for this label identifier.
Chris Lattner3318e862009-04-18 20:01:55 +00006356 LabelStmt *&LabelDecl = getLabelMap()[LabelII];
Mike Stump4e1f26a2009-02-19 03:04:26 +00006357
Daniel Dunbar88402ce2008-08-04 16:51:22 +00006358 // If we haven't seen this label yet, create a forward reference. It
6359 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Steve Naroff846b1ec2009-03-13 15:38:40 +00006360 if (LabelDecl == 0)
Steve Narofff6009ed2009-01-21 00:14:39 +00006361 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006362
Chris Lattnereefa10e2007-05-28 06:56:27 +00006363 // Create the AST node. The address of a label always has type 'void*'.
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006364 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
6365 Context.getPointerType(Context.VoidTy)));
Chris Lattnereefa10e2007-05-28 06:56:27 +00006366}
6367
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006368Sema::OwningExprResult
6369Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtArg substmt,
6370 SourceLocation RPLoc) { // "({..})"
6371 Stmt *SubStmt = static_cast<Stmt*>(substmt.get());
Chris Lattner366727f2007-07-24 16:58:17 +00006372 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
6373 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
6374
Eli Friedman52cc0162009-01-24 23:09:00 +00006375 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Chris Lattnera69b0762009-04-25 19:11:05 +00006376 if (isFileScope)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006377 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedman52cc0162009-01-24 23:09:00 +00006378
Chris Lattner366727f2007-07-24 16:58:17 +00006379 // FIXME: there are a variety of strange constraints to enforce here, for
6380 // example, it is not possible to goto into a stmt expression apparently.
6381 // More semantic analysis is needed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00006382
Chris Lattner366727f2007-07-24 16:58:17 +00006383 // If there are sub stmts in the compound stmt, take the type of the last one
6384 // as the type of the stmtexpr.
6385 QualType Ty = Context.VoidTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006386
Chris Lattner944d3062008-07-26 19:51:01 +00006387 if (!Compound->body_empty()) {
6388 Stmt *LastStmt = Compound->body_back();
6389 // If LastStmt is a label, skip down through into the body.
6390 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
6391 LastStmt = Label->getSubStmt();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006392
Chris Lattner944d3062008-07-26 19:51:01 +00006393 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattner366727f2007-07-24 16:58:17 +00006394 Ty = LastExpr->getType();
Chris Lattner944d3062008-07-26 19:51:01 +00006395 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006396
Eli Friedmanba961a92009-03-23 00:24:07 +00006397 // FIXME: Check that expression type is complete/non-abstract; statement
6398 // expressions are not lvalues.
6399
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006400 substmt.release();
6401 return Owned(new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc));
Chris Lattner366727f2007-07-24 16:58:17 +00006402}
Steve Naroff78864672007-08-01 22:05:33 +00006403
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006404Sema::OwningExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
6405 SourceLocation BuiltinLoc,
6406 SourceLocation TypeLoc,
6407 TypeTy *argty,
6408 OffsetOfComponent *CompPtr,
6409 unsigned NumComponents,
6410 SourceLocation RPLoc) {
6411 // FIXME: This function leaks all expressions in the offset components on
6412 // error.
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00006413 // FIXME: Preserve type source info.
6414 QualType ArgTy = GetTypeFromParser(argty);
Chris Lattnerf17bd422007-08-30 17:45:32 +00006415 assert(!ArgTy.isNull() && "Missing type argument!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00006416
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006417 bool Dependent = ArgTy->isDependentType();
6418
Chris Lattnerf17bd422007-08-30 17:45:32 +00006419 // We must have at least one component that refers to the type, and the first
6420 // one is known to be a field designator. Verify that the ArgTy represents
6421 // a struct/union/class.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006422 if (!Dependent && !ArgTy->isRecordType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006423 return ExprError(Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006424
Eli Friedmanba961a92009-03-23 00:24:07 +00006425 // FIXME: Type must be complete per C99 7.17p3 because a declaring a variable
6426 // with an incomplete type would be illegal.
Douglas Gregor26897462009-03-11 16:48:53 +00006427
Eli Friedman988a16b2009-02-27 06:44:11 +00006428 // Otherwise, create a null pointer as the base, and iteratively process
6429 // the offsetof designators.
6430 QualType ArgTyPtr = Context.getPointerType(ArgTy);
6431 Expr* Res = new (Context) ImplicitValueInitExpr(ArgTyPtr);
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006432 Res = new (Context) UnaryOperator(Res, UnaryOperator::Deref,
Eli Friedman988a16b2009-02-27 06:44:11 +00006433 ArgTy, SourceLocation());
Eli Friedman16c88df2009-01-26 01:33:06 +00006434
Chris Lattner78502cf2007-08-31 21:49:13 +00006435 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
6436 // GCC extension, diagnose them.
Eli Friedman988a16b2009-02-27 06:44:11 +00006437 // FIXME: This diagnostic isn't actually visible because the location is in
6438 // a system header!
Chris Lattner78502cf2007-08-31 21:49:13 +00006439 if (NumComponents != 1)
Chris Lattnerf490e152008-11-19 05:27:50 +00006440 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
6441 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006442
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006443 if (!Dependent) {
Eli Friedman8469bc72009-05-03 21:22:18 +00006444 bool DidWarnAboutNonPOD = false;
Mike Stump11289f42009-09-09 15:08:12 +00006445
John McCall9eff4e62009-11-04 03:03:43 +00006446 if (RequireCompleteType(TypeLoc, Res->getType(),
6447 diag::err_offsetof_incomplete_type))
6448 return ExprError();
6449
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006450 // FIXME: Dependent case loses a lot of information here. And probably
6451 // leaks like a sieve.
6452 for (unsigned i = 0; i != NumComponents; ++i) {
6453 const OffsetOfComponent &OC = CompPtr[i];
6454 if (OC.isBrackets) {
6455 // Offset of an array sub-field. TODO: Should we allow vector elements?
6456 const ArrayType *AT = Context.getAsArrayType(Res->getType());
6457 if (!AT) {
6458 Res->Destroy(Context);
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006459 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
6460 << Res->getType());
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006461 }
6462
6463 // FIXME: C++: Verify that operator[] isn't overloaded.
6464
Eli Friedman988a16b2009-02-27 06:44:11 +00006465 // Promote the array so it looks more like a normal array subscript
6466 // expression.
6467 DefaultFunctionArrayConversion(Res);
6468
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006469 // C99 6.5.2.1p1
6470 Expr *Idx = static_cast<Expr*>(OC.U.E);
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006471 // FIXME: Leaks Res
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006472 if (!Idx->isTypeDependent() && !Idx->getType()->isIntegerType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006473 return ExprError(Diag(Idx->getLocStart(),
Chris Lattner003af242009-04-25 22:50:55 +00006474 diag::err_typecheck_subscript_not_integer)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006475 << Idx->getSourceRange());
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006476
6477 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
6478 OC.LocEnd);
6479 continue;
Chris Lattnerf17bd422007-08-30 17:45:32 +00006480 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006481
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006482 const RecordType *RC = Res->getType()->getAs<RecordType>();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006483 if (!RC) {
6484 Res->Destroy(Context);
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006485 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
6486 << Res->getType());
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006487 }
Chris Lattner98dbf0a2007-08-30 17:59:59 +00006488
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006489 // Get the decl corresponding to this.
6490 RecordDecl *RD = RC->getDecl();
Anders Carlsson2bbb86b2009-05-01 23:20:30 +00006491 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00006492 if (!CRD->isPOD() && !DidWarnAboutNonPOD &&
6493 DiagRuntimeBehavior(BuiltinLoc,
6494 PDiag(diag::warn_offsetof_non_pod_type)
6495 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
6496 << Res->getType()))
6497 DidWarnAboutNonPOD = true;
Anders Carlsson2bbb86b2009-05-01 23:20:30 +00006498 }
Mike Stump11289f42009-09-09 15:08:12 +00006499
John McCall27b18f82009-11-17 02:14:36 +00006500 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
6501 LookupQualifiedName(R, RD);
John McCall9f3059a2009-10-09 21:13:30 +00006502
John McCall67c00872009-12-02 08:25:40 +00006503 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006504 // FIXME: Leaks Res
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006505 if (!MemberDecl)
Douglas Gregore40876a2009-10-13 21:16:44 +00006506 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
6507 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, OC.LocEnd));
Mike Stump4e1f26a2009-02-19 03:04:26 +00006508
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006509 // FIXME: C++: Verify that MemberDecl isn't a static field.
6510 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman64fc3c62009-04-26 20:50:44 +00006511 if (cast<RecordDecl>(MemberDecl->getDeclContext())->isAnonymousStructOrUnion()) {
Anders Carlsson3cbc8592009-05-01 19:30:39 +00006512 Res = BuildAnonymousStructUnionMemberReference(
John McCall7e1d6d72009-11-11 03:23:23 +00006513 OC.LocEnd, MemberDecl, Res, OC.LocEnd).takeAs<Expr>();
Eli Friedman64fc3c62009-04-26 20:50:44 +00006514 } else {
Eli Friedman78cde142009-12-04 07:18:51 +00006515 PerformObjectMemberConversion(Res, MemberDecl);
Eli Friedman64fc3c62009-04-26 20:50:44 +00006516 // MemberDecl->getType() doesn't get the right qualifiers, but it
6517 // doesn't matter here.
6518 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
6519 MemberDecl->getType().getNonReferenceType());
6520 }
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006521 }
Chris Lattnerf17bd422007-08-30 17:45:32 +00006522 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006523
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006524 return Owned(new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
6525 Context.getSizeType(), BuiltinLoc));
Chris Lattnerf17bd422007-08-30 17:45:32 +00006526}
6527
6528
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006529Sema::OwningExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
6530 TypeTy *arg1,TypeTy *arg2,
6531 SourceLocation RPLoc) {
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00006532 // FIXME: Preserve type source info.
6533 QualType argT1 = GetTypeFromParser(arg1);
6534 QualType argT2 = GetTypeFromParser(arg2);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006535
Steve Naroff78864672007-08-01 22:05:33 +00006536 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
Mike Stump4e1f26a2009-02-19 03:04:26 +00006537
Douglas Gregorf907cbf2009-05-19 22:28:02 +00006538 if (getLangOptions().CPlusPlus) {
6539 Diag(BuiltinLoc, diag::err_types_compatible_p_in_cplusplus)
6540 << SourceRange(BuiltinLoc, RPLoc);
6541 return ExprError();
6542 }
6543
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006544 return Owned(new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc,
6545 argT1, argT2, RPLoc));
Steve Naroff78864672007-08-01 22:05:33 +00006546}
6547
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006548Sema::OwningExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
6549 ExprArg cond,
6550 ExprArg expr1, ExprArg expr2,
6551 SourceLocation RPLoc) {
6552 Expr *CondExpr = static_cast<Expr*>(cond.get());
6553 Expr *LHSExpr = static_cast<Expr*>(expr1.get());
6554 Expr *RHSExpr = static_cast<Expr*>(expr2.get());
Mike Stump4e1f26a2009-02-19 03:04:26 +00006555
Steve Naroff9efdabc2007-08-03 21:21:27 +00006556 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
6557
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006558 QualType resType;
Douglas Gregor56751b52009-09-25 04:25:58 +00006559 bool ValueDependent = false;
Douglas Gregor0df91122009-05-19 22:43:30 +00006560 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006561 resType = Context.DependentTy;
Douglas Gregor56751b52009-09-25 04:25:58 +00006562 ValueDependent = true;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006563 } else {
6564 // The conditional expression is required to be a constant expression.
6565 llvm::APSInt condEval(32);
6566 SourceLocation ExpLoc;
6567 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006568 return ExprError(Diag(ExpLoc,
6569 diag::err_typecheck_choose_expr_requires_constant)
6570 << CondExpr->getSourceRange());
Steve Naroff9efdabc2007-08-03 21:21:27 +00006571
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006572 // If the condition is > zero, then the AST type is the same as the LSHExpr.
6573 resType = condEval.getZExtValue() ? LHSExpr->getType() : RHSExpr->getType();
Douglas Gregor56751b52009-09-25 04:25:58 +00006574 ValueDependent = condEval.getZExtValue() ? LHSExpr->isValueDependent()
6575 : RHSExpr->isValueDependent();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006576 }
6577
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006578 cond.release(); expr1.release(); expr2.release();
6579 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
Douglas Gregor56751b52009-09-25 04:25:58 +00006580 resType, RPLoc,
6581 resType->isDependentType(),
6582 ValueDependent));
Steve Naroff9efdabc2007-08-03 21:21:27 +00006583}
6584
Steve Naroffc540d662008-09-03 18:15:37 +00006585//===----------------------------------------------------------------------===//
6586// Clang Extensions.
6587//===----------------------------------------------------------------------===//
6588
6589/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff1d95e5a2008-10-10 01:28:17 +00006590void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroffc540d662008-09-03 18:15:37 +00006591 // Analyze block parameters.
6592 BlockSemaInfo *BSI = new BlockSemaInfo();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006593
Steve Naroffc540d662008-09-03 18:15:37 +00006594 // Add BSI to CurBlock.
6595 BSI->PrevBlockInfo = CurBlock;
6596 CurBlock = BSI;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006597
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00006598 BSI->ReturnType = QualType();
Steve Naroffc540d662008-09-03 18:15:37 +00006599 BSI->TheScope = BlockScope;
Mike Stumpa6703322009-02-19 22:01:56 +00006600 BSI->hasBlockDeclRefExprs = false;
Daniel Dunbarb9a68612009-07-29 01:59:17 +00006601 BSI->hasPrototype = false;
Chris Lattner45542ea2009-04-19 05:28:12 +00006602 BSI->SavedFunctionNeedsScopeChecking = CurFunctionNeedsScopeChecking;
6603 CurFunctionNeedsScopeChecking = false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006604
Steve Naroff1d95e5a2008-10-10 01:28:17 +00006605 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Ted Kremenek54ad1ab2009-12-07 22:01:30 +00006606 CurContext->addDecl(BSI->TheDecl);
Douglas Gregor91f84212008-12-11 16:49:14 +00006607 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff1d95e5a2008-10-10 01:28:17 +00006608}
6609
Mike Stump82f071f2009-02-04 22:31:32 +00006610void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpf70bcf72009-05-07 18:43:07 +00006611 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
Mike Stump82f071f2009-02-04 22:31:32 +00006612
6613 if (ParamInfo.getNumTypeObjects() == 0
6614 || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) {
Douglas Gregor758a8692009-06-17 21:51:59 +00006615 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
Mike Stump82f071f2009-02-04 22:31:32 +00006616 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
6617
Mike Stumpd456c482009-04-28 01:10:27 +00006618 if (T->isArrayType()) {
6619 Diag(ParamInfo.getSourceRange().getBegin(),
6620 diag::err_block_returns_array);
6621 return;
6622 }
6623
Mike Stump82f071f2009-02-04 22:31:32 +00006624 // The parameter list is optional, if there was none, assume ().
6625 if (!T->isFunctionType())
6626 T = Context.getFunctionType(T, NULL, 0, 0, 0);
6627
6628 CurBlock->hasPrototype = true;
6629 CurBlock->isVariadic = false;
Fariborz Jahanian6607b212009-05-14 20:53:39 +00006630 // Check for a valid sentinel attribute on this block.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00006631 if (CurBlock->TheDecl->getAttr<SentinelAttr>()) {
Mike Stump11289f42009-09-09 15:08:12 +00006632 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian6802ed92009-05-15 21:18:04 +00006633 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian6607b212009-05-14 20:53:39 +00006634 // FIXME: remove the attribute.
6635 }
John McCall9dd450b2009-09-21 23:43:11 +00006636 QualType RetTy = T.getTypePtr()->getAs<FunctionType>()->getResultType();
Mike Stump11289f42009-09-09 15:08:12 +00006637
Chris Lattner6de05082009-04-11 19:27:54 +00006638 // Do not allow returning a objc interface by-value.
6639 if (RetTy->isObjCInterfaceType()) {
6640 Diag(ParamInfo.getSourceRange().getBegin(),
6641 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
6642 return;
6643 }
Mike Stump82f071f2009-02-04 22:31:32 +00006644 return;
6645 }
6646
Steve Naroffc540d662008-09-03 18:15:37 +00006647 // Analyze arguments to block.
6648 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
6649 "Not a function declarator!");
6650 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006651
Steve Naroff1d95e5a2008-10-10 01:28:17 +00006652 CurBlock->hasPrototype = FTI.hasPrototype;
6653 CurBlock->isVariadic = true;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006654
Steve Naroffc540d662008-09-03 18:15:37 +00006655 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
6656 // no arguments, not a function that takes a single void argument.
6657 if (FTI.hasPrototype &&
6658 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
Chris Lattner83f095c2009-03-28 19:18:32 +00006659 (!FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType().getCVRQualifiers()&&
6660 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType())) {
Steve Naroffc540d662008-09-03 18:15:37 +00006661 // empty arg list, don't push any params.
Steve Naroff1d95e5a2008-10-10 01:28:17 +00006662 CurBlock->isVariadic = false;
Steve Naroffc540d662008-09-03 18:15:37 +00006663 } else if (FTI.hasPrototype) {
6664 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Chris Lattner83f095c2009-03-28 19:18:32 +00006665 CurBlock->Params.push_back(FTI.ArgInfo[i].Param.getAs<ParmVarDecl>());
Steve Naroff1d95e5a2008-10-10 01:28:17 +00006666 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroffc540d662008-09-03 18:15:37 +00006667 }
Jay Foad7d0479f2009-05-21 09:52:38 +00006668 CurBlock->TheDecl->setParams(Context, CurBlock->Params.data(),
Chris Lattner6de05082009-04-11 19:27:54 +00006669 CurBlock->Params.size());
Fariborz Jahanian960910a2009-05-19 17:08:59 +00006670 CurBlock->TheDecl->setIsVariadic(CurBlock->isVariadic);
Douglas Gregor758a8692009-06-17 21:51:59 +00006671 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
Steve Naroff1d95e5a2008-10-10 01:28:17 +00006672 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
6673 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
6674 // If this has an identifier, add it to the scope stack.
6675 if ((*AI)->getIdentifier())
6676 PushOnScopeChains(*AI, CurBlock->TheScope);
Chris Lattner6de05082009-04-11 19:27:54 +00006677
Fariborz Jahanian6607b212009-05-14 20:53:39 +00006678 // Check for a valid sentinel attribute on this block.
Mike Stump11289f42009-09-09 15:08:12 +00006679 if (!CurBlock->isVariadic &&
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00006680 CurBlock->TheDecl->getAttr<SentinelAttr>()) {
Mike Stump11289f42009-09-09 15:08:12 +00006681 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian6802ed92009-05-15 21:18:04 +00006682 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian6607b212009-05-14 20:53:39 +00006683 // FIXME: remove the attribute.
6684 }
Mike Stump11289f42009-09-09 15:08:12 +00006685
Chris Lattner6de05082009-04-11 19:27:54 +00006686 // Analyze the return type.
6687 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
John McCall9dd450b2009-09-21 23:43:11 +00006688 QualType RetTy = T->getAs<FunctionType>()->getResultType();
Mike Stump11289f42009-09-09 15:08:12 +00006689
Chris Lattner6de05082009-04-11 19:27:54 +00006690 // Do not allow returning a objc interface by-value.
6691 if (RetTy->isObjCInterfaceType()) {
6692 Diag(ParamInfo.getSourceRange().getBegin(),
6693 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
6694 } else if (!RetTy->isDependentType())
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00006695 CurBlock->ReturnType = RetTy;
Steve Naroffc540d662008-09-03 18:15:37 +00006696}
6697
6698/// ActOnBlockError - If there is an error parsing a block, this callback
6699/// is invoked to pop the information about the block from the action impl.
6700void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
6701 // Ensure that CurBlock is deleted.
6702 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006703
Chris Lattner45542ea2009-04-19 05:28:12 +00006704 CurFunctionNeedsScopeChecking = CurBlock->SavedFunctionNeedsScopeChecking;
6705
Steve Naroffc540d662008-09-03 18:15:37 +00006706 // Pop off CurBlock, handle nested blocks.
Chris Lattner41b86942009-04-21 22:38:46 +00006707 PopDeclContext();
Steve Naroffc540d662008-09-03 18:15:37 +00006708 CurBlock = CurBlock->PrevBlockInfo;
Steve Naroffc540d662008-09-03 18:15:37 +00006709 // FIXME: Delete the ParmVarDecl objects as well???
Steve Naroffc540d662008-09-03 18:15:37 +00006710}
6711
6712/// ActOnBlockStmtExpr - This is called when the body of a block statement
6713/// literal was successfully completed. ^(int x){...}
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006714Sema::OwningExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
6715 StmtArg body, Scope *CurScope) {
Chris Lattner9eac9312009-03-27 04:18:06 +00006716 // If blocks are disabled, emit an error.
6717 if (!LangOpts.Blocks)
6718 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump11289f42009-09-09 15:08:12 +00006719
Steve Naroffc540d662008-09-03 18:15:37 +00006720 // Ensure that CurBlock is deleted.
6721 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
Steve Naroffc540d662008-09-03 18:15:37 +00006722
Steve Naroff1d95e5a2008-10-10 01:28:17 +00006723 PopDeclContext();
6724
Steve Naroffc540d662008-09-03 18:15:37 +00006725 // Pop off CurBlock, handle nested blocks.
6726 CurBlock = CurBlock->PrevBlockInfo;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006727
Steve Naroffc540d662008-09-03 18:15:37 +00006728 QualType RetTy = Context.VoidTy;
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00006729 if (!BSI->ReturnType.isNull())
6730 RetTy = BSI->ReturnType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006731
Steve Naroffc540d662008-09-03 18:15:37 +00006732 llvm::SmallVector<QualType, 8> ArgTypes;
6733 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
6734 ArgTypes.push_back(BSI->Params[i]->getType());
Mike Stump4e1f26a2009-02-19 03:04:26 +00006735
Mike Stump3bf1ab42009-07-28 22:04:01 +00006736 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroffc540d662008-09-03 18:15:37 +00006737 QualType BlockTy;
6738 if (!BSI->hasPrototype)
Mike Stump3bf1ab42009-07-28 22:04:01 +00006739 BlockTy = Context.getFunctionType(RetTy, 0, 0, false, 0, false, false, 0, 0,
6740 NoReturn);
Steve Naroffc540d662008-09-03 18:15:37 +00006741 else
Jay Foad7d0479f2009-05-21 09:52:38 +00006742 BlockTy = Context.getFunctionType(RetTy, ArgTypes.data(), ArgTypes.size(),
Mike Stump3bf1ab42009-07-28 22:04:01 +00006743 BSI->isVariadic, 0, false, false, 0, 0,
6744 NoReturn);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006745
Eli Friedmanba961a92009-03-23 00:24:07 +00006746 // FIXME: Check that return/parameter types are complete/non-abstract
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006747 DiagnoseUnusedParameters(BSI->Params.begin(), BSI->Params.end());
Steve Naroffc540d662008-09-03 18:15:37 +00006748 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006749
Chris Lattner45542ea2009-04-19 05:28:12 +00006750 // If needed, diagnose invalid gotos and switches in the block.
6751 if (CurFunctionNeedsScopeChecking)
6752 DiagnoseInvalidJumps(static_cast<CompoundStmt*>(body.get()));
6753 CurFunctionNeedsScopeChecking = BSI->SavedFunctionNeedsScopeChecking;
Mike Stump11289f42009-09-09 15:08:12 +00006754
Anders Carlssonb781bcd2009-05-01 19:49:17 +00006755 BSI->TheDecl->setBody(body.takeAs<CompoundStmt>());
Mike Stump3bf1ab42009-07-28 22:04:01 +00006756 CheckFallThroughForBlock(BlockTy, BSI->TheDecl->getBody());
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006757 return Owned(new (Context) BlockExpr(BSI->TheDecl, BlockTy,
6758 BSI->hasBlockDeclRefExprs));
Steve Naroffc540d662008-09-03 18:15:37 +00006759}
6760
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006761Sema::OwningExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
6762 ExprArg expr, TypeTy *type,
6763 SourceLocation RPLoc) {
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00006764 QualType T = GetTypeFromParser(type);
Chris Lattner56382aa2009-04-05 15:49:53 +00006765 Expr *E = static_cast<Expr*>(expr.get());
6766 Expr *OrigExpr = E;
Mike Stump11289f42009-09-09 15:08:12 +00006767
Anders Carlsson7e13ab82007-10-15 20:28:48 +00006768 InitBuiltinVaListType();
Eli Friedman121ba0c2008-08-09 23:32:40 +00006769
6770 // Get the va_list type
6771 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedmane2cad652009-05-16 12:46:54 +00006772 if (VaListType->isArrayType()) {
6773 // Deal with implicit array decay; for example, on x86-64,
6774 // va_list is an array, but it's supposed to decay to
6775 // a pointer for va_arg.
Eli Friedman121ba0c2008-08-09 23:32:40 +00006776 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedmane2cad652009-05-16 12:46:54 +00006777 // Make sure the input expression also decays appropriately.
6778 UsualUnaryConversions(E);
6779 } else {
6780 // Otherwise, the va_list argument must be an l-value because
6781 // it is modified by va_arg.
Mike Stump11289f42009-09-09 15:08:12 +00006782 if (!E->isTypeDependent() &&
Douglas Gregorad3150c2009-05-19 23:10:31 +00006783 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedmane2cad652009-05-16 12:46:54 +00006784 return ExprError();
6785 }
Eli Friedman121ba0c2008-08-09 23:32:40 +00006786
Douglas Gregorad3150c2009-05-19 23:10:31 +00006787 if (!E->isTypeDependent() &&
6788 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006789 return ExprError(Diag(E->getLocStart(),
6790 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner56382aa2009-04-05 15:49:53 +00006791 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner3f5cd772009-04-05 00:59:53 +00006792 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006793
Eli Friedmanba961a92009-03-23 00:24:07 +00006794 // FIXME: Check that type is complete/non-abstract
Anders Carlsson7e13ab82007-10-15 20:28:48 +00006795 // FIXME: Warn if a non-POD type is passed in.
Mike Stump4e1f26a2009-02-19 03:04:26 +00006796
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006797 expr.release();
6798 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(),
6799 RPLoc));
Anders Carlsson7e13ab82007-10-15 20:28:48 +00006800}
6801
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006802Sema::OwningExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor3be4b122008-11-29 04:51:27 +00006803 // The type of __null will be int or long, depending on the size of
6804 // pointers on the target.
6805 QualType Ty;
6806 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
6807 Ty = Context.IntTy;
6808 else
6809 Ty = Context.LongTy;
6810
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006811 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor3be4b122008-11-29 04:51:27 +00006812}
6813
Anders Carlssonace5d072009-11-10 04:46:30 +00006814static void
6815MakeObjCStringLiteralCodeModificationHint(Sema& SemaRef,
6816 QualType DstType,
6817 Expr *SrcExpr,
6818 CodeModificationHint &Hint) {
6819 if (!SemaRef.getLangOptions().ObjC1)
6820 return;
6821
6822 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
6823 if (!PT)
6824 return;
6825
6826 // Check if the destination is of type 'id'.
6827 if (!PT->isObjCIdType()) {
6828 // Check if the destination is the 'NSString' interface.
6829 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
6830 if (!ID || !ID->getIdentifier()->isStr("NSString"))
6831 return;
6832 }
6833
6834 // Strip off any parens and casts.
6835 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
6836 if (!SL || SL->isWide())
6837 return;
6838
6839 Hint = CodeModificationHint::CreateInsertion(SL->getLocStart(), "@");
6840}
6841
Chris Lattner9bad62c2008-01-04 18:04:52 +00006842bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
6843 SourceLocation Loc,
6844 QualType DstType, QualType SrcType,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006845 Expr *SrcExpr, AssignmentAction Action) {
Chris Lattner9bad62c2008-01-04 18:04:52 +00006846 // Decode the result (notice that AST's are still created for extensions).
6847 bool isInvalid = false;
6848 unsigned DiagKind;
Anders Carlssonace5d072009-11-10 04:46:30 +00006849 CodeModificationHint Hint;
6850
Chris Lattner9bad62c2008-01-04 18:04:52 +00006851 switch (ConvTy) {
6852 default: assert(0 && "Unknown conversion type");
6853 case Compatible: return false;
Chris Lattner940cfeb2008-01-04 18:22:42 +00006854 case PointerToInt:
Chris Lattner9bad62c2008-01-04 18:04:52 +00006855 DiagKind = diag::ext_typecheck_convert_pointer_int;
6856 break;
Chris Lattner940cfeb2008-01-04 18:22:42 +00006857 case IntToPointer:
6858 DiagKind = diag::ext_typecheck_convert_int_pointer;
6859 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00006860 case IncompatiblePointer:
Anders Carlssonace5d072009-11-10 04:46:30 +00006861 MakeObjCStringLiteralCodeModificationHint(*this, DstType, SrcExpr, Hint);
Chris Lattner9bad62c2008-01-04 18:04:52 +00006862 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
6863 break;
Eli Friedman80160bd2009-03-22 23:59:44 +00006864 case IncompatiblePointerSign:
6865 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
6866 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00006867 case FunctionVoidPointer:
6868 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
6869 break;
6870 case CompatiblePointerDiscardsQualifiers:
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00006871 // If the qualifiers lost were because we were applying the
6872 // (deprecated) C++ conversion from a string literal to a char*
6873 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
6874 // Ideally, this check would be performed in
6875 // CheckPointerTypesForAssignment. However, that would require a
6876 // bit of refactoring (so that the second argument is an
6877 // expression, rather than a type), which should be done as part
6878 // of a larger effort to fix CheckPointerTypesForAssignment for
6879 // C++ semantics.
6880 if (getLangOptions().CPlusPlus &&
6881 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
6882 return false;
Chris Lattner9bad62c2008-01-04 18:04:52 +00006883 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
6884 break;
Alexis Hunt6f3de502009-11-08 07:46:34 +00006885 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanianb98dade2009-11-09 22:16:37 +00006886 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00006887 break;
Steve Naroff081c7422008-09-04 15:10:53 +00006888 case IntToBlockPointer:
6889 DiagKind = diag::err_int_to_block_pointer;
6890 break;
6891 case IncompatibleBlockPointer:
Mike Stumpd79b5a82009-04-21 22:51:42 +00006892 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff081c7422008-09-04 15:10:53 +00006893 break;
Steve Naroff8afa9892008-10-14 22:18:38 +00006894 case IncompatibleObjCQualifiedId:
Mike Stump4e1f26a2009-02-19 03:04:26 +00006895 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff8afa9892008-10-14 22:18:38 +00006896 // it can give a more specific diagnostic.
6897 DiagKind = diag::warn_incompatible_qualified_id;
6898 break;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00006899 case IncompatibleVectors:
6900 DiagKind = diag::warn_incompatible_vectors;
6901 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00006902 case Incompatible:
6903 DiagKind = diag::err_typecheck_convert_incompatible;
6904 isInvalid = true;
6905 break;
6906 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006907
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006908 Diag(Loc, DiagKind) << DstType << SrcType << Action
Anders Carlssonace5d072009-11-10 04:46:30 +00006909 << SrcExpr->getSourceRange() << Hint;
Chris Lattner9bad62c2008-01-04 18:04:52 +00006910 return isInvalid;
6911}
Anders Carlssone54e8a12008-11-30 19:50:32 +00006912
Chris Lattnerc71d08b2009-04-25 21:59:05 +00006913bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedmanbb967cc2009-04-25 22:26:58 +00006914 llvm::APSInt ICEResult;
6915 if (E->isIntegerConstantExpr(ICEResult, Context)) {
6916 if (Result)
6917 *Result = ICEResult;
6918 return false;
6919 }
6920
Anders Carlssone54e8a12008-11-30 19:50:32 +00006921 Expr::EvalResult EvalResult;
6922
Mike Stump4e1f26a2009-02-19 03:04:26 +00006923 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone54e8a12008-11-30 19:50:32 +00006924 EvalResult.HasSideEffects) {
6925 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
6926
6927 if (EvalResult.Diag) {
6928 // We only show the note if it's not the usual "invalid subexpression"
6929 // or if it's actually in a subexpression.
6930 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
6931 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
6932 Diag(EvalResult.DiagLoc, EvalResult.Diag);
6933 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006934
Anders Carlssone54e8a12008-11-30 19:50:32 +00006935 return true;
6936 }
6937
Eli Friedmanbb967cc2009-04-25 22:26:58 +00006938 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
6939 E->getSourceRange();
Anders Carlssone54e8a12008-11-30 19:50:32 +00006940
Eli Friedmanbb967cc2009-04-25 22:26:58 +00006941 if (EvalResult.Diag &&
6942 Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
6943 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006944
Anders Carlssone54e8a12008-11-30 19:50:32 +00006945 if (Result)
6946 *Result = EvalResult.Val.getInt();
6947 return false;
6948}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006949
Douglas Gregorff790f12009-11-26 00:44:06 +00006950void
Mike Stump11289f42009-09-09 15:08:12 +00006951Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregorff790f12009-11-26 00:44:06 +00006952 ExprEvalContexts.push_back(
6953 ExpressionEvaluationContextRecord(NewContext, ExprTemporaries.size()));
Douglas Gregor0b6a6242009-06-22 20:57:11 +00006954}
6955
Mike Stump11289f42009-09-09 15:08:12 +00006956void
Douglas Gregorff790f12009-11-26 00:44:06 +00006957Sema::PopExpressionEvaluationContext() {
6958 // Pop the current expression evaluation context off the stack.
6959 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
6960 ExprEvalContexts.pop_back();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00006961
Douglas Gregorfab31f42009-12-12 07:57:52 +00006962 if (Rec.Context == PotentiallyPotentiallyEvaluated) {
6963 if (Rec.PotentiallyReferenced) {
6964 // Mark any remaining declarations in the current position of the stack
6965 // as "referenced". If they were not meant to be referenced, semantic
6966 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
6967 for (PotentiallyReferencedDecls::iterator
6968 I = Rec.PotentiallyReferenced->begin(),
6969 IEnd = Rec.PotentiallyReferenced->end();
6970 I != IEnd; ++I)
6971 MarkDeclarationReferenced(I->first, I->second);
6972 }
6973
6974 if (Rec.PotentiallyDiagnosed) {
6975 // Emit any pending diagnostics.
6976 for (PotentiallyEmittedDiagnostics::iterator
6977 I = Rec.PotentiallyDiagnosed->begin(),
6978 IEnd = Rec.PotentiallyDiagnosed->end();
6979 I != IEnd; ++I)
6980 Diag(I->first, I->second);
6981 }
Douglas Gregorff790f12009-11-26 00:44:06 +00006982 }
6983
6984 // When are coming out of an unevaluated context, clear out any
6985 // temporaries that we may have created as part of the evaluation of
6986 // the expression in that context: they aren't relevant because they
6987 // will never be constructed.
6988 if (Rec.Context == Unevaluated &&
6989 ExprTemporaries.size() > Rec.NumTemporaries)
6990 ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
6991 ExprTemporaries.end());
6992
6993 // Destroy the popped expression evaluation record.
6994 Rec.Destroy();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00006995}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006996
6997/// \brief Note that the given declaration was referenced in the source code.
6998///
6999/// This routine should be invoke whenever a given declaration is referenced
7000/// in the source code, and where that reference occurred. If this declaration
7001/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
7002/// C99 6.9p3), then the declaration will be marked as used.
7003///
7004/// \param Loc the location where the declaration was referenced.
7005///
7006/// \param D the declaration that has been referenced by the source code.
7007void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
7008 assert(D && "No declaration?");
Mike Stump11289f42009-09-09 15:08:12 +00007009
Douglas Gregor77b50e12009-06-22 23:06:13 +00007010 if (D->isUsed())
7011 return;
Mike Stump11289f42009-09-09 15:08:12 +00007012
Douglas Gregor3beaf9b2009-10-08 21:35:42 +00007013 // Mark a parameter or variable declaration "used", regardless of whether we're in a
7014 // template or not. The reason for this is that unevaluated expressions
7015 // (e.g. (void)sizeof()) constitute a use for warning purposes (-Wunused-variables and
7016 // -Wunused-parameters)
7017 if (isa<ParmVarDecl>(D) ||
7018 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod()))
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007019 D->setUsed(true);
Mike Stump11289f42009-09-09 15:08:12 +00007020
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007021 // Do not mark anything as "used" within a dependent context; wait for
7022 // an instantiation.
7023 if (CurContext->isDependentContext())
7024 return;
Mike Stump11289f42009-09-09 15:08:12 +00007025
Douglas Gregorff790f12009-11-26 00:44:06 +00007026 switch (ExprEvalContexts.back().Context) {
Douglas Gregor0b6a6242009-06-22 20:57:11 +00007027 case Unevaluated:
7028 // We are in an expression that is not potentially evaluated; do nothing.
7029 return;
Mike Stump11289f42009-09-09 15:08:12 +00007030
Douglas Gregor0b6a6242009-06-22 20:57:11 +00007031 case PotentiallyEvaluated:
7032 // We are in a potentially-evaluated expression, so this declaration is
7033 // "used"; handle this below.
7034 break;
Mike Stump11289f42009-09-09 15:08:12 +00007035
Douglas Gregor0b6a6242009-06-22 20:57:11 +00007036 case PotentiallyPotentiallyEvaluated:
7037 // We are in an expression that may be potentially evaluated; queue this
7038 // declaration reference until we know whether the expression is
7039 // potentially evaluated.
Douglas Gregorff790f12009-11-26 00:44:06 +00007040 ExprEvalContexts.back().addReferencedDecl(Loc, D);
Douglas Gregor0b6a6242009-06-22 20:57:11 +00007041 return;
7042 }
Mike Stump11289f42009-09-09 15:08:12 +00007043
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007044 // Note that this declaration has been used.
Fariborz Jahanian3a363432009-06-22 17:30:33 +00007045 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Fariborz Jahanian477d2422009-06-22 23:34:40 +00007046 unsigned TypeQuals;
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00007047 if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) {
7048 if (!Constructor->isUsed())
7049 DefineImplicitDefaultConstructor(Loc, Constructor);
Mike Stump11289f42009-09-09 15:08:12 +00007050 } else if (Constructor->isImplicit() &&
Douglas Gregor507eb872009-12-22 00:34:07 +00007051 Constructor->isCopyConstructor(TypeQuals)) {
Fariborz Jahanian477d2422009-06-22 23:34:40 +00007052 if (!Constructor->isUsed())
7053 DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals);
7054 }
Anders Carlsson82fccd02009-12-07 08:24:59 +00007055
7056 MaybeMarkVirtualMembersReferenced(Loc, Constructor);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00007057 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
7058 if (Destructor->isImplicit() && !Destructor->isUsed())
7059 DefineImplicitDestructor(Loc, Destructor);
Mike Stump11289f42009-09-09 15:08:12 +00007060
Fariborz Jahanian41f79272009-06-25 21:45:19 +00007061 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
7062 if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
7063 MethodDecl->getOverloadedOperator() == OO_Equal) {
7064 if (!MethodDecl->isUsed())
7065 DefineImplicitOverloadedAssign(Loc, MethodDecl);
7066 }
7067 }
Fariborz Jahanian49796cc72009-06-24 22:09:44 +00007068 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Mike Stump11289f42009-09-09 15:08:12 +00007069 // Implicit instantiation of function templates and member functions of
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00007070 // class templates.
Douglas Gregorafca3b42009-10-27 20:53:28 +00007071 if (!Function->getBody() && Function->isImplicitlyInstantiable()) {
Douglas Gregor06db9f52009-10-12 20:18:28 +00007072 bool AlreadyInstantiated = false;
7073 if (FunctionTemplateSpecializationInfo *SpecInfo
7074 = Function->getTemplateSpecializationInfo()) {
7075 if (SpecInfo->getPointOfInstantiation().isInvalid())
7076 SpecInfo->setPointOfInstantiation(Loc);
Douglas Gregorafca3b42009-10-27 20:53:28 +00007077 else if (SpecInfo->getTemplateSpecializationKind()
7078 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +00007079 AlreadyInstantiated = true;
7080 } else if (MemberSpecializationInfo *MSInfo
7081 = Function->getMemberSpecializationInfo()) {
7082 if (MSInfo->getPointOfInstantiation().isInvalid())
7083 MSInfo->setPointOfInstantiation(Loc);
Douglas Gregorafca3b42009-10-27 20:53:28 +00007084 else if (MSInfo->getTemplateSpecializationKind()
7085 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +00007086 AlreadyInstantiated = true;
7087 }
7088
7089 if (!AlreadyInstantiated)
7090 PendingImplicitInstantiations.push_back(std::make_pair(Function, Loc));
7091 }
7092
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007093 // FIXME: keep track of references to static functions
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007094 Function->setUsed(true);
7095 return;
Douglas Gregor77b50e12009-06-22 23:06:13 +00007096 }
Mike Stump11289f42009-09-09 15:08:12 +00007097
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007098 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00007099 // Implicit instantiation of static data members of class templates.
Mike Stump11289f42009-09-09 15:08:12 +00007100 if (Var->isStaticDataMember() &&
Douglas Gregor06db9f52009-10-12 20:18:28 +00007101 Var->getInstantiatedFromStaticDataMember()) {
7102 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
7103 assert(MSInfo && "Missing member specialization information?");
7104 if (MSInfo->getPointOfInstantiation().isInvalid() &&
7105 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
7106 MSInfo->setPointOfInstantiation(Loc);
7107 PendingImplicitInstantiations.push_back(std::make_pair(Var, Loc));
7108 }
7109 }
Mike Stump11289f42009-09-09 15:08:12 +00007110
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007111 // FIXME: keep track of references to static data?
Douglas Gregora6ef8f02009-07-24 20:34:43 +00007112
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007113 D->setUsed(true);
Douglas Gregora6ef8f02009-07-24 20:34:43 +00007114 return;
Sam Weinigbae69142009-09-11 03:29:30 +00007115 }
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007116}
Anders Carlsson7f84ed92009-10-09 23:51:55 +00007117
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00007118/// \brief Emit a diagnostic that describes an effect on the run-time behavior
7119/// of the program being compiled.
7120///
7121/// This routine emits the given diagnostic when the code currently being
7122/// type-checked is "potentially evaluated", meaning that there is a
7123/// possibility that the code will actually be executable. Code in sizeof()
7124/// expressions, code used only during overload resolution, etc., are not
7125/// potentially evaluated. This routine will suppress such diagnostics or,
7126/// in the absolutely nutty case of potentially potentially evaluated
7127/// expressions (C++ typeid), queue the diagnostic to potentially emit it
7128/// later.
7129///
7130/// This routine should be used for all diagnostics that describe the run-time
7131/// behavior of a program, such as passing a non-POD value through an ellipsis.
7132/// Failure to do so will likely result in spurious diagnostics or failures
7133/// during overload resolution or within sizeof/alignof/typeof/typeid.
7134bool Sema::DiagRuntimeBehavior(SourceLocation Loc,
7135 const PartialDiagnostic &PD) {
7136 switch (ExprEvalContexts.back().Context ) {
7137 case Unevaluated:
7138 // The argument will never be evaluated, so don't complain.
7139 break;
7140
7141 case PotentiallyEvaluated:
7142 Diag(Loc, PD);
7143 return true;
7144
7145 case PotentiallyPotentiallyEvaluated:
7146 ExprEvalContexts.back().addDiagnostic(Loc, PD);
7147 break;
7148 }
7149
7150 return false;
7151}
7152
Anders Carlsson7f84ed92009-10-09 23:51:55 +00007153bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
7154 CallExpr *CE, FunctionDecl *FD) {
7155 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
7156 return false;
7157
7158 PartialDiagnostic Note =
7159 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
7160 << FD->getDeclName() : PDiag();
7161 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
7162
7163 if (RequireCompleteType(Loc, ReturnType,
7164 FD ?
7165 PDiag(diag::err_call_function_incomplete_return)
7166 << CE->getSourceRange() << FD->getDeclName() :
7167 PDiag(diag::err_call_incomplete_return)
7168 << CE->getSourceRange(),
7169 std::make_pair(NoteLoc, Note)))
7170 return true;
7171
7172 return false;
7173}
7174
John McCalld5707ab2009-10-12 21:59:07 +00007175// Diagnose the common s/=/==/ typo. Note that adding parentheses
7176// will prevent this condition from triggering, which is what we want.
7177void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
7178 SourceLocation Loc;
7179
John McCall0506e4a2009-11-11 02:41:58 +00007180 unsigned diagnostic = diag::warn_condition_is_assignment;
7181
John McCalld5707ab2009-10-12 21:59:07 +00007182 if (isa<BinaryOperator>(E)) {
7183 BinaryOperator *Op = cast<BinaryOperator>(E);
7184 if (Op->getOpcode() != BinaryOperator::Assign)
7185 return;
7186
John McCallb0e419e2009-11-12 00:06:05 +00007187 // Greylist some idioms by putting them into a warning subcategory.
7188 if (ObjCMessageExpr *ME
7189 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
7190 Selector Sel = ME->getSelector();
7191
John McCallb0e419e2009-11-12 00:06:05 +00007192 // self = [<foo> init...]
7193 if (isSelfExpr(Op->getLHS())
7194 && Sel.getIdentifierInfoForSlot(0)->getName().startswith("init"))
7195 diagnostic = diag::warn_condition_is_idiomatic_assignment;
7196
7197 // <foo> = [<bar> nextObject]
7198 else if (Sel.isUnarySelector() &&
7199 Sel.getIdentifierInfoForSlot(0)->getName() == "nextObject")
7200 diagnostic = diag::warn_condition_is_idiomatic_assignment;
7201 }
John McCall0506e4a2009-11-11 02:41:58 +00007202
John McCalld5707ab2009-10-12 21:59:07 +00007203 Loc = Op->getOperatorLoc();
7204 } else if (isa<CXXOperatorCallExpr>(E)) {
7205 CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(E);
7206 if (Op->getOperator() != OO_Equal)
7207 return;
7208
7209 Loc = Op->getOperatorLoc();
7210 } else {
7211 // Not an assignment.
7212 return;
7213 }
7214
John McCalld5707ab2009-10-12 21:59:07 +00007215 SourceLocation Open = E->getSourceRange().getBegin();
John McCalle724ae92009-10-12 22:25:59 +00007216 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
John McCalld5707ab2009-10-12 21:59:07 +00007217
John McCall0506e4a2009-11-11 02:41:58 +00007218 Diag(Loc, diagnostic)
John McCalld5707ab2009-10-12 21:59:07 +00007219 << E->getSourceRange()
7220 << CodeModificationHint::CreateInsertion(Open, "(")
7221 << CodeModificationHint::CreateInsertion(Close, ")");
7222}
7223
7224bool Sema::CheckBooleanCondition(Expr *&E, SourceLocation Loc) {
7225 DiagnoseAssignmentAsCondition(E);
7226
7227 if (!E->isTypeDependent()) {
7228 DefaultFunctionArrayConversion(E);
7229
7230 QualType T = E->getType();
7231
7232 if (getLangOptions().CPlusPlus) {
7233 if (CheckCXXBooleanCondition(E)) // C++ 6.4p4
7234 return true;
7235 } else if (!T->isScalarType()) { // C99 6.8.4.1p1
7236 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
7237 << T << E->getSourceRange();
7238 return true;
7239 }
7240 }
7241
7242 return false;
7243}