blob: 535632e6db802a9cc8be10b6b928a45a6fa0fdff [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"
Chris Lattnercb6a3822006-11-10 06:20:45 +000015#include "clang/AST/ASTContext.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000016#include "clang/AST/DeclObjC.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000017#include "clang/AST/DeclTemplate.h"
Chris Lattneraa9c7ae2008-04-08 04:40:51 +000018#include "clang/AST/ExprCXX.h"
Steve Naroff021ca182008-05-29 21:12:08 +000019#include "clang/AST/ExprObjC.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000020#include "clang/Basic/PartialDiagnostic.h"
Steve Narofff2fb89e2007-03-13 20:29:44 +000021#include "clang/Basic/SourceManager.h"
Chris Lattner5b183d82006-11-10 05:03:26 +000022#include "clang/Basic/TargetInfo.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000023#include "clang/Lex/LiteralSupport.h"
24#include "clang/Lex/Preprocessor.h"
Steve Naroffc540d662008-09-03 18:15:37 +000025#include "clang/Parse/DeclSpec.h"
Chris Lattner07d754a2008-10-26 23:43:26 +000026#include "clang/Parse/Designator.h"
Steve Naroffc540d662008-09-03 18:15:37 +000027#include "clang/Parse/Scope.h"
Douglas Gregorb53edfb2009-11-10 19:49:08 +000028#include "clang/Parse/Template.h"
Chris Lattner5b183d82006-11-10 05:03:26 +000029using namespace clang;
30
David Chisnall9f57c292009-08-17 16:35:33 +000031
Douglas Gregor171c45a2009-02-18 21:56:37 +000032/// \brief Determine whether the use of this declaration is valid, and
33/// emit any corresponding diagnostics.
34///
35/// This routine diagnoses various problems with referencing
36/// declarations that can occur when using a declaration. For example,
37/// it might warn if a deprecated or unavailable declaration is being
38/// used, or produce an error (and return true) if a C++0x deleted
39/// function is being used.
40///
Chris Lattnerb7df3c62009-10-25 22:31:57 +000041/// If IgnoreDeprecated is set to true, this should not want about deprecated
42/// decls.
43///
Douglas Gregor171c45a2009-02-18 21:56:37 +000044/// \returns true if there was an error (this declaration cannot be
45/// referenced), false otherwise.
Chris Lattnerb7df3c62009-10-25 22:31:57 +000046///
John McCall28a6aea2009-11-04 02:18:39 +000047bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc) {
Chris Lattner4bf74fd2009-02-15 22:43:40 +000048 // See if the decl is deprecated.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +000049 if (D->getAttr<DeprecatedAttr>()) {
John McCall28a6aea2009-11-04 02:18:39 +000050 EmitDeprecationWarning(D, Loc);
Chris Lattner4bf74fd2009-02-15 22:43:40 +000051 }
52
Chris Lattnera27dd592009-10-25 17:21:40 +000053 // See if the decl is unavailable
54 if (D->getAttr<UnavailableAttr>()) {
55 Diag(Loc, diag::warn_unavailable) << D->getDeclName();
56 Diag(D->getLocation(), diag::note_unavailable_here) << 0;
57 }
58
Douglas Gregor171c45a2009-02-18 21:56:37 +000059 // See if this is a deleted function.
Douglas Gregorde681d42009-02-24 04:26:15 +000060 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +000061 if (FD->isDeleted()) {
62 Diag(Loc, diag::err_deleted_function_use);
63 Diag(D->getLocation(), diag::note_unavailable_here) << true;
64 return true;
65 }
Douglas Gregorde681d42009-02-24 04:26:15 +000066 }
Douglas Gregor171c45a2009-02-18 21:56:37 +000067
Douglas Gregor171c45a2009-02-18 21:56:37 +000068 return false;
Chris Lattner4bf74fd2009-02-15 22:43:40 +000069}
70
Fariborz Jahanian027b8862009-05-13 18:09:35 +000071/// DiagnoseSentinelCalls - This routine checks on method dispatch calls
Mike Stump11289f42009-09-09 15:08:12 +000072/// (and other functions in future), which have been declared with sentinel
Fariborz Jahanian027b8862009-05-13 18:09:35 +000073/// attribute. It warns if call does not have the sentinel argument.
74///
75void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +000076 Expr **Args, unsigned NumArgs) {
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +000077 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Mike Stump11289f42009-09-09 15:08:12 +000078 if (!attr)
Fariborz Jahanian9e877212009-05-13 23:20:50 +000079 return;
Fariborz Jahanian9e877212009-05-13 23:20:50 +000080 int sentinelPos = attr->getSentinel();
81 int nullPos = attr->getNullPos();
Mike Stump11289f42009-09-09 15:08:12 +000082
Mike Stump87c57ac2009-05-16 07:39:55 +000083 // FIXME. ObjCMethodDecl and FunctionDecl need be derived from the same common
84 // base class. Then we won't be needing two versions of the same code.
Fariborz Jahanian9e877212009-05-13 23:20:50 +000085 unsigned int i = 0;
Fariborz Jahanian4a528032009-05-14 18:00:00 +000086 bool warnNotEnoughArgs = false;
87 int isMethod = 0;
88 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
89 // skip over named parameters.
90 ObjCMethodDecl::param_iterator P, E = MD->param_end();
91 for (P = MD->param_begin(); (P != E && i < NumArgs); ++P) {
92 if (nullPos)
93 --nullPos;
94 else
95 ++i;
96 }
97 warnNotEnoughArgs = (P != E || i >= NumArgs);
98 isMethod = 1;
Mike Stump12b8ce12009-08-04 21:02:39 +000099 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000100 // skip over named parameters.
101 ObjCMethodDecl::param_iterator P, E = FD->param_end();
102 for (P = FD->param_begin(); (P != E && i < NumArgs); ++P) {
103 if (nullPos)
104 --nullPos;
105 else
106 ++i;
107 }
108 warnNotEnoughArgs = (P != E || i >= NumArgs);
Mike Stump12b8ce12009-08-04 21:02:39 +0000109 } else if (VarDecl *V = dyn_cast<VarDecl>(D)) {
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000110 // block or function pointer call.
111 QualType Ty = V->getType();
112 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +0000113 const FunctionType *FT = Ty->isFunctionPointerType()
John McCall9dd450b2009-09-21 23:43:11 +0000114 ? Ty->getAs<PointerType>()->getPointeeType()->getAs<FunctionType>()
115 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000116 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT)) {
117 unsigned NumArgsInProto = Proto->getNumArgs();
118 unsigned k;
119 for (k = 0; (k != NumArgsInProto && i < NumArgs); k++) {
120 if (nullPos)
121 --nullPos;
122 else
123 ++i;
124 }
125 warnNotEnoughArgs = (k != NumArgsInProto || i >= NumArgs);
126 }
127 if (Ty->isBlockPointerType())
128 isMethod = 2;
Mike Stump12b8ce12009-08-04 21:02:39 +0000129 } else
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000130 return;
Mike Stump12b8ce12009-08-04 21:02:39 +0000131 } else
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000132 return;
133
134 if (warnNotEnoughArgs) {
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000135 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000136 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000137 return;
138 }
139 int sentinel = i;
140 while (sentinelPos > 0 && i < NumArgs-1) {
141 --sentinelPos;
142 ++i;
143 }
144 if (sentinelPos > 0) {
145 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000146 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000147 return;
148 }
149 while (i < NumArgs-1) {
150 ++i;
151 ++sentinel;
152 }
153 Expr *sentinelExpr = Args[sentinel];
154 if (sentinelExpr && (!sentinelExpr->getType()->isPointerType() ||
Douglas Gregor56751b52009-09-25 04:25:58 +0000155 !sentinelExpr->isNullPointerConstant(Context,
156 Expr::NPC_ValueDependentIsNull))) {
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000157 Diag(Loc, diag::warn_missing_sentinel) << isMethod;
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000158 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000159 }
160 return;
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000161}
162
Douglas Gregor87f95b02009-02-26 21:00:50 +0000163SourceRange Sema::getExprRange(ExprTy *E) const {
164 Expr *Ex = (Expr *)E;
165 return Ex? Ex->getSourceRange() : SourceRange();
166}
167
Chris Lattner513165e2008-07-25 21:10:04 +0000168//===----------------------------------------------------------------------===//
169// Standard Promotions and Conversions
170//===----------------------------------------------------------------------===//
171
Chris Lattner513165e2008-07-25 21:10:04 +0000172/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
173void Sema::DefaultFunctionArrayConversion(Expr *&E) {
174 QualType Ty = E->getType();
175 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
176
Chris Lattner513165e2008-07-25 21:10:04 +0000177 if (Ty->isFunctionType())
Mike Stump11289f42009-09-09 15:08:12 +0000178 ImpCastExprToType(E, Context.getPointerType(Ty),
Anders Carlsson6904f642009-09-01 20:37:18 +0000179 CastExpr::CK_FunctionToPointerDecay);
Chris Lattner61f60a02008-07-25 21:33:13 +0000180 else if (Ty->isArrayType()) {
181 // In C90 mode, arrays only promote to pointers if the array expression is
182 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
183 // type 'array of type' is converted to an expression that has type 'pointer
184 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
185 // that has type 'array of type' ...". The relevant change is "an lvalue"
186 // (C90) to "an expression" (C99).
Argyrios Kyrtzidis9321c742008-09-11 04:25:59 +0000187 //
188 // C++ 4.2p1:
189 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
190 // T" can be converted to an rvalue of type "pointer to T".
191 //
192 if (getLangOptions().C99 || getLangOptions().CPlusPlus ||
193 E->isLvalue(Context) == Expr::LV_Valid)
Anders Carlsson8fc489d2009-08-07 23:48:20 +0000194 ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
195 CastExpr::CK_ArrayToPointerDecay);
Chris Lattner61f60a02008-07-25 21:33:13 +0000196 }
Chris Lattner513165e2008-07-25 21:10:04 +0000197}
198
199/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump11289f42009-09-09 15:08:12 +0000200/// operators (C99 6.3). The conversions of array and function types are
Chris Lattner513165e2008-07-25 21:10:04 +0000201/// sometimes surpressed. For example, the array->pointer conversion doesn't
202/// apply if the array is an argument to the sizeof or address (&) operators.
203/// In these instances, this routine should *not* be called.
204Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
205 QualType Ty = Expr->getType();
206 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
Mike Stump11289f42009-09-09 15:08:12 +0000207
Douglas Gregor8d9c5092009-05-01 20:41:21 +0000208 // C99 6.3.1.1p2:
209 //
210 // The following may be used in an expression wherever an int or
211 // unsigned int may be used:
212 // - an object or expression with an integer type whose integer
213 // conversion rank is less than or equal to the rank of int
214 // and unsigned int.
215 // - A bit-field of type _Bool, int, signed int, or unsigned int.
216 //
217 // If an int can represent all values of the original type, the
218 // value is converted to an int; otherwise, it is converted to an
219 // unsigned int. These are called the integer promotions. All
220 // other types are unchanged by the integer promotions.
Eli Friedman629ffb92009-08-20 04:21:42 +0000221 QualType PTy = Context.isPromotableBitField(Expr);
222 if (!PTy.isNull()) {
Eli Friedman06ed2a52009-10-20 08:27:19 +0000223 ImpCastExprToType(Expr, PTy, CastExpr::CK_IntegralCast);
Eli Friedman629ffb92009-08-20 04:21:42 +0000224 return Expr;
225 }
Douglas Gregor8d9c5092009-05-01 20:41:21 +0000226 if (Ty->isPromotableIntegerType()) {
Eli Friedman5ae98ee2009-08-19 07:44:53 +0000227 QualType PT = Context.getPromotedIntegerType(Ty);
Eli Friedman06ed2a52009-10-20 08:27:19 +0000228 ImpCastExprToType(Expr, PT, CastExpr::CK_IntegralCast);
Douglas Gregor8d9c5092009-05-01 20:41:21 +0000229 return Expr;
Eli Friedman629ffb92009-08-20 04:21:42 +0000230 }
231
Douglas Gregor8d9c5092009-05-01 20:41:21 +0000232 DefaultFunctionArrayConversion(Expr);
Chris Lattner513165e2008-07-25 21:10:04 +0000233 return Expr;
234}
235
Chris Lattner2ce500f2008-07-25 22:25:12 +0000236/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Mike Stump11289f42009-09-09 15:08:12 +0000237/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner2ce500f2008-07-25 22:25:12 +0000238/// double. All other argument types are converted by UsualUnaryConversions().
239void Sema::DefaultArgumentPromotion(Expr *&Expr) {
240 QualType Ty = Expr->getType();
241 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump11289f42009-09-09 15:08:12 +0000242
Chris Lattner2ce500f2008-07-25 22:25:12 +0000243 // If this is a 'float' (CVR qualified or typedef) promote to double.
John McCall9dd450b2009-09-21 23:43:11 +0000244 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
Chris Lattner2ce500f2008-07-25 22:25:12 +0000245 if (BT->getKind() == BuiltinType::Float)
Eli Friedman06ed2a52009-10-20 08:27:19 +0000246 return ImpCastExprToType(Expr, Context.DoubleTy,
247 CastExpr::CK_FloatingCast);
Mike Stump11289f42009-09-09 15:08:12 +0000248
Chris Lattner2ce500f2008-07-25 22:25:12 +0000249 UsualUnaryConversions(Expr);
250}
251
Chris Lattnera8a7d0f2009-04-12 08:11:20 +0000252/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
253/// will warn if the resulting type is not a POD type, and rejects ObjC
254/// interfaces passed by value. This returns true if the argument type is
255/// completely illegal.
256bool Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT) {
Anders Carlssona7d069d2009-01-16 16:48:51 +0000257 DefaultArgumentPromotion(Expr);
Mike Stump11289f42009-09-09 15:08:12 +0000258
Chris Lattnera8a7d0f2009-04-12 08:11:20 +0000259 if (Expr->getType()->isObjCInterfaceType()) {
260 Diag(Expr->getLocStart(),
261 diag::err_cannot_pass_objc_interface_to_vararg)
262 << Expr->getType() << CT;
263 return true;
Anders Carlssona7d069d2009-01-16 16:48:51 +0000264 }
Mike Stump11289f42009-09-09 15:08:12 +0000265
Chris Lattnera8a7d0f2009-04-12 08:11:20 +0000266 if (!Expr->getType()->isPODType())
267 Diag(Expr->getLocStart(), diag::warn_cannot_pass_non_pod_arg_to_vararg)
268 << Expr->getType() << CT;
269
270 return false;
Anders Carlssona7d069d2009-01-16 16:48:51 +0000271}
272
273
Chris Lattner513165e2008-07-25 21:10:04 +0000274/// UsualArithmeticConversions - Performs various conversions that are common to
275/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump11289f42009-09-09 15:08:12 +0000276/// routine returns the first non-arithmetic type found. The client is
Chris Lattner513165e2008-07-25 21:10:04 +0000277/// responsible for emitting appropriate error diagnostics.
278/// FIXME: verify the conversion rules for "complex int" are consistent with
279/// GCC.
280QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
281 bool isCompAssign) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +0000282 if (!isCompAssign)
Chris Lattner513165e2008-07-25 21:10:04 +0000283 UsualUnaryConversions(lhsExpr);
Eli Friedman8b7b1b12009-03-28 01:22:36 +0000284
285 UsualUnaryConversions(rhsExpr);
Douglas Gregora11693b2008-11-12 17:17:38 +0000286
Mike Stump11289f42009-09-09 15:08:12 +0000287 // For conversion purposes, we ignore any qualifiers.
Chris Lattner513165e2008-07-25 21:10:04 +0000288 // For example, "const float" and "float" are equivalent.
Chris Lattner574dee62008-07-26 22:17:49 +0000289 QualType lhs =
290 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +0000291 QualType rhs =
Chris Lattner574dee62008-07-26 22:17:49 +0000292 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +0000293
294 // If both types are identical, no conversion is needed.
295 if (lhs == rhs)
296 return lhs;
297
298 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
299 // The caller can deal with this (e.g. pointer + int).
300 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
301 return lhs;
302
Douglas Gregord2c2d172009-05-02 00:36:19 +0000303 // Perform bitfield promotions.
Eli Friedman629ffb92009-08-20 04:21:42 +0000304 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr);
Douglas Gregord2c2d172009-05-02 00:36:19 +0000305 if (!LHSBitfieldPromoteTy.isNull())
306 lhs = LHSBitfieldPromoteTy;
Eli Friedman629ffb92009-08-20 04:21:42 +0000307 QualType RHSBitfieldPromoteTy = Context.isPromotableBitField(rhsExpr);
Douglas Gregord2c2d172009-05-02 00:36:19 +0000308 if (!RHSBitfieldPromoteTy.isNull())
309 rhs = RHSBitfieldPromoteTy;
310
Eli Friedman5ae98ee2009-08-19 07:44:53 +0000311 QualType destType = Context.UsualArithmeticConversionsType(lhs, rhs);
Eli Friedman8b7b1b12009-03-28 01:22:36 +0000312 if (!isCompAssign)
Eli Friedman06ed2a52009-10-20 08:27:19 +0000313 ImpCastExprToType(lhsExpr, destType, CastExpr::CK_Unknown);
314 ImpCastExprToType(rhsExpr, destType, CastExpr::CK_Unknown);
Douglas Gregora11693b2008-11-12 17:17:38 +0000315 return destType;
316}
317
Chris Lattner513165e2008-07-25 21:10:04 +0000318//===----------------------------------------------------------------------===//
319// Semantic Analysis for various Expression Types
320//===----------------------------------------------------------------------===//
321
322
Steve Naroff83895f72007-09-16 03:34:24 +0000323/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner5b183d82006-11-10 05:03:26 +0000324/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
325/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
326/// multiple tokens. However, the common case is that StringToks points to one
327/// string.
Sebastian Redlffbcf962009-01-18 18:53:16 +0000328///
329Action::OwningExprResult
Steve Naroff83895f72007-09-16 03:34:24 +0000330Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner5b183d82006-11-10 05:03:26 +0000331 assert(NumStringToks && "Must have at least one string!");
332
Chris Lattner8a24e582009-01-16 18:51:42 +0000333 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Steve Naroff4f88b312007-03-13 22:37:02 +0000334 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +0000335 return ExprError();
Chris Lattner5b183d82006-11-10 05:03:26 +0000336
Chris Lattner23b7eb62007-06-15 23:05:46 +0000337 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
Chris Lattner5b183d82006-11-10 05:03:26 +0000338 for (unsigned i = 0; i != NumStringToks; ++i)
339 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattner36fc8792008-02-11 00:02:17 +0000340
Chris Lattner36fc8792008-02-11 00:02:17 +0000341 QualType StrTy = Context.CharTy;
Argyrios Kyrtzidiscbad7252008-08-09 17:20:01 +0000342 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattner36fc8792008-02-11 00:02:17 +0000343 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregoraa1e21d2008-09-12 00:47:35 +0000344
345 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
346 if (getLangOptions().CPlusPlus)
347 StrTy.addConst();
Sebastian Redlffbcf962009-01-18 18:53:16 +0000348
Chris Lattner36fc8792008-02-11 00:02:17 +0000349 // Get an array type for the string, according to C99 6.4.5. This includes
350 // the nul terminator character as well as the string length for pascal
351 // strings.
352 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerd42c29f2009-02-26 23:01:51 +0000353 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattner36fc8792008-02-11 00:02:17 +0000354 ArrayType::Normal, 0);
Mike Stump11289f42009-09-09 15:08:12 +0000355
Chris Lattner5b183d82006-11-10 05:03:26 +0000356 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Mike Stump11289f42009-09-09 15:08:12 +0000357 return Owned(StringLiteral::Create(Context, Literal.GetString(),
Chris Lattnerf83b5af2009-02-18 06:40:38 +0000358 Literal.GetStringLength(),
359 Literal.AnyWide, StrTy,
360 &StringTokLocs[0],
361 StringTokLocs.size()));
Chris Lattner5b183d82006-11-10 05:03:26 +0000362}
363
Chris Lattner2a9d9892008-10-20 05:16:36 +0000364/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
365/// CurBlock to VD should cause it to be snapshotted (as we do for auto
366/// variables defined outside the block) or false if this is not needed (e.g.
367/// for values inside the block or for globals).
368///
Chris Lattner497d7b02009-04-21 22:26:47 +0000369/// This also keeps the 'hasBlockDeclRefExprs' in the BlockSemaInfo records
370/// up-to-date.
371///
Chris Lattner2a9d9892008-10-20 05:16:36 +0000372static bool ShouldSnapshotBlockValueReference(BlockSemaInfo *CurBlock,
373 ValueDecl *VD) {
374 // If the value is defined inside the block, we couldn't snapshot it even if
375 // we wanted to.
376 if (CurBlock->TheDecl == VD->getDeclContext())
377 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000378
Chris Lattner2a9d9892008-10-20 05:16:36 +0000379 // If this is an enum constant or function, it is constant, don't snapshot.
380 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
381 return false;
382
383 // If this is a reference to an extern, static, or global variable, no need to
384 // snapshot it.
385 // FIXME: What about 'const' variables in C++?
386 if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
Chris Lattner497d7b02009-04-21 22:26:47 +0000387 if (!Var->hasLocalStorage())
388 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000389
Chris Lattner497d7b02009-04-21 22:26:47 +0000390 // Blocks that have these can't be constant.
391 CurBlock->hasBlockDeclRefExprs = true;
392
393 // If we have nested blocks, the decl may be declared in an outer block (in
394 // which case that outer block doesn't get "hasBlockDeclRefExprs") or it may
395 // be defined outside all of the current blocks (in which case the blocks do
396 // all get the bit). Walk the nesting chain.
397 for (BlockSemaInfo *NextBlock = CurBlock->PrevBlockInfo; NextBlock;
398 NextBlock = NextBlock->PrevBlockInfo) {
399 // If we found the defining block for the variable, don't mark the block as
400 // having a reference outside it.
401 if (NextBlock->TheDecl == VD->getDeclContext())
402 break;
Mike Stump11289f42009-09-09 15:08:12 +0000403
Chris Lattner497d7b02009-04-21 22:26:47 +0000404 // Otherwise, the DeclRef from the inner block causes the outer one to need
405 // a snapshot as well.
406 NextBlock->hasBlockDeclRefExprs = true;
407 }
Mike Stump11289f42009-09-09 15:08:12 +0000408
Chris Lattner2a9d9892008-10-20 05:16:36 +0000409 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000410}
411
Chris Lattner2a9d9892008-10-20 05:16:36 +0000412
413
Douglas Gregor4bd90e52009-10-23 18:54:35 +0000414/// BuildDeclRefExpr - Build a DeclRefExpr.
Anders Carlsson946b86d2009-06-24 00:10:43 +0000415Sema::OwningExprResult
Sebastian Redl3d3f75a2009-02-03 20:19:35 +0000416Sema::BuildDeclRefExpr(NamedDecl *D, QualType Ty, SourceLocation Loc,
417 bool TypeDependent, bool ValueDependent,
418 const CXXScopeSpec *SS) {
Anders Carlsson364035d12009-06-26 19:16:07 +0000419 if (Context.getCanonicalType(Ty) == Context.UndeducedAutoTy) {
420 Diag(Loc,
Mike Stump11289f42009-09-09 15:08:12 +0000421 diag::err_auto_variable_cannot_appear_in_own_initializer)
Anders Carlsson364035d12009-06-26 19:16:07 +0000422 << D->getDeclName();
423 return ExprError();
424 }
Mike Stump11289f42009-09-09 15:08:12 +0000425
Anders Carlsson946b86d2009-06-24 00:10:43 +0000426 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
427 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
428 if (const FunctionDecl *FD = MD->getParent()->isLocalClass()) {
429 if (VD->hasLocalStorage() && VD->getDeclContext() != CurContext) {
Mike Stump11289f42009-09-09 15:08:12 +0000430 Diag(Loc, diag::err_reference_to_local_var_in_enclosing_function)
Anders Carlsson946b86d2009-06-24 00:10:43 +0000431 << D->getIdentifier() << FD->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +0000432 Diag(D->getLocation(), diag::note_local_variable_declared_here)
Anders Carlsson946b86d2009-06-24 00:10:43 +0000433 << D->getIdentifier();
434 return ExprError();
435 }
436 }
437 }
438 }
Mike Stump11289f42009-09-09 15:08:12 +0000439
Douglas Gregorc9c02ed2009-06-19 23:52:42 +0000440 MarkDeclarationReferenced(Loc, D);
Mike Stump11289f42009-09-09 15:08:12 +0000441
Douglas Gregor4bd90e52009-10-23 18:54:35 +0000442 return Owned(DeclRefExpr::Create(Context,
443 SS? (NestedNameSpecifier *)SS->getScopeRep() : 0,
444 SS? SS->getRange() : SourceRange(),
445 D, Loc,
446 Ty, TypeDependent, ValueDependent));
Douglas Gregorc7acfdf2009-01-06 05:10:23 +0000447}
448
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000449/// getObjectForAnonymousRecordDecl - Retrieve the (unnamed) field or
450/// variable corresponding to the anonymous union or struct whose type
451/// is Record.
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000452static Decl *getObjectForAnonymousRecordDecl(ASTContext &Context,
453 RecordDecl *Record) {
Mike Stump11289f42009-09-09 15:08:12 +0000454 assert(Record->isAnonymousStructOrUnion() &&
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000455 "Record must be an anonymous struct or union!");
Mike Stump11289f42009-09-09 15:08:12 +0000456
Mike Stump87c57ac2009-05-16 07:39:55 +0000457 // FIXME: Once Decls are directly linked together, this will be an O(1)
458 // operation rather than a slow walk through DeclContext's vector (which
459 // itself will be eliminated). DeclGroups might make this even better.
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000460 DeclContext *Ctx = Record->getDeclContext();
Mike Stump11289f42009-09-09 15:08:12 +0000461 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000462 DEnd = Ctx->decls_end();
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000463 D != DEnd; ++D) {
464 if (*D == Record) {
465 // The object for the anonymous struct/union directly
466 // follows its type in the list of declarations.
467 ++D;
468 assert(D != DEnd && "Missing object for anonymous record");
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000469 assert(!cast<NamedDecl>(*D)->getDeclName() && "Decl should be unnamed");
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000470 return *D;
471 }
472 }
473
474 assert(false && "Missing object for anonymous record");
475 return 0;
476}
477
Douglas Gregord5846a12009-04-15 06:41:24 +0000478/// \brief Given a field that represents a member of an anonymous
479/// struct/union, build the path from that field's context to the
480/// actual member.
481///
482/// Construct the sequence of field member references we'll have to
483/// perform to get to the field in the anonymous union/struct. The
484/// list of members is built from the field outward, so traverse it
485/// backwards to go from an object in the current context to the field
486/// we found.
487///
488/// \returns The variable from which the field access should begin,
489/// for an anonymous struct/union that is not a member of another
490/// class. Otherwise, returns NULL.
491VarDecl *Sema::BuildAnonymousStructUnionMemberPath(FieldDecl *Field,
492 llvm::SmallVectorImpl<FieldDecl *> &Path) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000493 assert(Field->getDeclContext()->isRecord() &&
494 cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion()
495 && "Field must be stored inside an anonymous struct or union");
496
Douglas Gregord5846a12009-04-15 06:41:24 +0000497 Path.push_back(Field);
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000498 VarDecl *BaseObject = 0;
499 DeclContext *Ctx = Field->getDeclContext();
500 do {
501 RecordDecl *Record = cast<RecordDecl>(Ctx);
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000502 Decl *AnonObject = getObjectForAnonymousRecordDecl(Context, Record);
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000503 if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject))
Douglas Gregord5846a12009-04-15 06:41:24 +0000504 Path.push_back(AnonField);
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000505 else {
506 BaseObject = cast<VarDecl>(AnonObject);
507 break;
508 }
509 Ctx = Ctx->getParent();
Mike Stump11289f42009-09-09 15:08:12 +0000510 } while (Ctx->isRecord() &&
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000511 cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion());
Douglas Gregord5846a12009-04-15 06:41:24 +0000512
513 return BaseObject;
514}
515
516Sema::OwningExprResult
517Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
518 FieldDecl *Field,
519 Expr *BaseObjectExpr,
520 SourceLocation OpLoc) {
521 llvm::SmallVector<FieldDecl *, 4> AnonFields;
Mike Stump11289f42009-09-09 15:08:12 +0000522 VarDecl *BaseObject = BuildAnonymousStructUnionMemberPath(Field,
Douglas Gregord5846a12009-04-15 06:41:24 +0000523 AnonFields);
524
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000525 // Build the expression that refers to the base object, from
526 // which we will build a sequence of member references to each
527 // of the anonymous union objects and, eventually, the field we
528 // found via name lookup.
529 bool BaseObjectIsPointer = false;
John McCall8ccfcb52009-09-24 19:53:00 +0000530 Qualifiers BaseQuals;
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000531 if (BaseObject) {
532 // BaseObject is an anonymous struct/union variable (and is,
533 // therefore, not part of another non-anonymous record).
Ted Kremenek5a201952009-02-07 01:47:29 +0000534 if (BaseObjectExpr) BaseObjectExpr->Destroy(Context);
Douglas Gregorc9c02ed2009-06-19 23:52:42 +0000535 MarkDeclarationReferenced(Loc, BaseObject);
Steve Narofff6009ed2009-01-21 00:14:39 +0000536 BaseObjectExpr = new (Context) DeclRefExpr(BaseObject,BaseObject->getType(),
Mike Stump4e1f26a2009-02-19 03:04:26 +0000537 SourceLocation());
John McCall8ccfcb52009-09-24 19:53:00 +0000538 BaseQuals
539 = Context.getCanonicalType(BaseObject->getType()).getQualifiers();
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000540 } else if (BaseObjectExpr) {
541 // The caller provided the base object expression. Determine
542 // whether its a pointer and whether it adds any qualifiers to the
543 // anonymous struct/union fields we're looking into.
544 QualType ObjectType = BaseObjectExpr->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000545 if (const PointerType *ObjectPtr = ObjectType->getAs<PointerType>()) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000546 BaseObjectIsPointer = true;
547 ObjectType = ObjectPtr->getPointeeType();
548 }
John McCall8ccfcb52009-09-24 19:53:00 +0000549 BaseQuals
550 = Context.getCanonicalType(ObjectType).getQualifiers();
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000551 } else {
552 // We've found a member of an anonymous struct/union that is
553 // inside a non-anonymous struct/union, so in a well-formed
554 // program our base object expression is "this".
555 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
556 if (!MD->isStatic()) {
Mike Stump11289f42009-09-09 15:08:12 +0000557 QualType AnonFieldType
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000558 = Context.getTagDeclType(
559 cast<RecordDecl>(AnonFields.back()->getDeclContext()));
560 QualType ThisType = Context.getTagDeclType(MD->getParent());
Mike Stump11289f42009-09-09 15:08:12 +0000561 if ((Context.getCanonicalType(AnonFieldType)
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000562 == Context.getCanonicalType(ThisType)) ||
563 IsDerivedFrom(ThisType, AnonFieldType)) {
564 // Our base object expression is "this".
Steve Narofff6009ed2009-01-21 00:14:39 +0000565 BaseObjectExpr = new (Context) CXXThisExpr(SourceLocation(),
Mike Stump4e1f26a2009-02-19 03:04:26 +0000566 MD->getThisType(Context));
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000567 BaseObjectIsPointer = true;
568 }
569 } else {
Sebastian Redlffbcf962009-01-18 18:53:16 +0000570 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
571 << Field->getDeclName());
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000572 }
John McCall8ccfcb52009-09-24 19:53:00 +0000573 BaseQuals = Qualifiers::fromCVRMask(MD->getTypeQualifiers());
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000574 }
575
Mike Stump11289f42009-09-09 15:08:12 +0000576 if (!BaseObjectExpr)
Sebastian Redlffbcf962009-01-18 18:53:16 +0000577 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
578 << Field->getDeclName());
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000579 }
580
581 // Build the implicit member references to the field of the
582 // anonymous struct/union.
583 Expr *Result = BaseObjectExpr;
John McCall8ccfcb52009-09-24 19:53:00 +0000584 Qualifiers ResultQuals = BaseQuals;
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000585 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
586 FI = AnonFields.rbegin(), FIEnd = AnonFields.rend();
587 FI != FIEnd; ++FI) {
588 QualType MemberType = (*FI)->getType();
John McCall8ccfcb52009-09-24 19:53:00 +0000589 Qualifiers MemberTypeQuals =
590 Context.getCanonicalType(MemberType).getQualifiers();
591
592 // CVR attributes from the base are picked up by members,
593 // except that 'mutable' members don't pick up 'const'.
594 if ((*FI)->isMutable())
595 ResultQuals.removeConst();
596
597 // GC attributes are never picked up by members.
598 ResultQuals.removeObjCGCAttr();
599
600 // TR 18037 does not allow fields to be declared with address spaces.
601 assert(!MemberTypeQuals.hasAddressSpace());
602
603 Qualifiers NewQuals = ResultQuals + MemberTypeQuals;
604 if (NewQuals != MemberTypeQuals)
605 MemberType = Context.getQualifiedType(MemberType, NewQuals);
606
Douglas Gregorc9c02ed2009-06-19 23:52:42 +0000607 MarkDeclarationReferenced(Loc, *FI);
Douglas Gregorc1905232009-08-26 22:36:53 +0000608 // FIXME: Might this end up being a qualified name?
Steve Narofff6009ed2009-01-21 00:14:39 +0000609 Result = new (Context) MemberExpr(Result, BaseObjectIsPointer, *FI,
610 OpLoc, MemberType);
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000611 BaseObjectIsPointer = false;
John McCall8ccfcb52009-09-24 19:53:00 +0000612 ResultQuals = NewQuals;
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000613 }
614
Sebastian Redlffbcf962009-01-18 18:53:16 +0000615 return Owned(Result);
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000616}
617
Douglas Gregora121b752009-11-03 16:56:39 +0000618Sema::OwningExprResult Sema::ActOnIdExpression(Scope *S,
619 const CXXScopeSpec &SS,
620 UnqualifiedId &Name,
621 bool HasTrailingLParen,
622 bool IsAddressOfOperand) {
623 if (Name.getKind() == UnqualifiedId::IK_TemplateId) {
624 ASTTemplateArgsPtr TemplateArgsPtr(*this,
625 Name.TemplateId->getTemplateArgs(),
Douglas Gregora121b752009-11-03 16:56:39 +0000626 Name.TemplateId->NumArgs);
627 return ActOnTemplateIdExpr(SS,
628 TemplateTy::make(Name.TemplateId->Template),
629 Name.TemplateId->TemplateNameLoc,
630 Name.TemplateId->LAngleLoc,
631 TemplateArgsPtr,
Douglas Gregora121b752009-11-03 16:56:39 +0000632 Name.TemplateId->RAngleLoc);
633 }
634
635 // FIXME: We lose a bunch of source information by doing this. Later,
636 // we'll want to merge ActOnDeclarationNameExpr's logic into
637 // ActOnIdExpression.
638 return ActOnDeclarationNameExpr(S,
639 Name.StartLocation,
640 GetNameFromUnqualifiedId(Name),
641 HasTrailingLParen,
642 &SS,
643 IsAddressOfOperand);
644}
645
Douglas Gregor4ea80432008-11-18 15:03:34 +0000646/// ActOnDeclarationNameExpr - The parser has read some kind of name
647/// (e.g., a C++ id-expression (C++ [expr.prim]p1)). This routine
648/// performs lookup on that name and returns an expression that refers
649/// to that name. This routine isn't directly called from the parser,
650/// because the parser doesn't know about DeclarationName. Rather,
Douglas Gregora121b752009-11-03 16:56:39 +0000651/// this routine is called by ActOnIdExpression, which contains a
652/// parsed UnqualifiedId.
Douglas Gregor4ea80432008-11-18 15:03:34 +0000653///
654/// HasTrailingLParen indicates whether this identifier is used in a
655/// function call context. LookupCtx is only used for a C++
656/// qualified-id (foo::bar) to indicate the class or namespace that
657/// the identifier must be a member of.
Douglas Gregorb0846b02008-12-06 00:22:45 +0000658///
Sebastian Redl3d3f75a2009-02-03 20:19:35 +0000659/// isAddressOfOperand means that this expression is the direct operand
660/// of an address-of operator. This matters because this is the only
661/// situation where a qualified name referencing a non-static member may
662/// appear outside a member function of this class.
Sebastian Redlffbcf962009-01-18 18:53:16 +0000663Sema::OwningExprResult
664Sema::ActOnDeclarationNameExpr(Scope *S, SourceLocation Loc,
665 DeclarationName Name, bool HasTrailingLParen,
Mike Stump11289f42009-09-09 15:08:12 +0000666 const CXXScopeSpec *SS,
Sebastian Redl3d3f75a2009-02-03 20:19:35 +0000667 bool isAddressOfOperand) {
Chris Lattner59a25942008-03-31 00:36:02 +0000668 // Could be enum-constant, value decl, instance variable, etc.
Douglas Gregored8f2882009-01-30 01:04:22 +0000669 if (SS && SS->isInvalid())
670 return ExprError();
Douglas Gregor90a1a652009-03-19 17:26:29 +0000671
672 // C++ [temp.dep.expr]p3:
673 // An id-expression is type-dependent if it contains:
674 // -- a nested-name-specifier that contains a class-name that
675 // names a dependent type.
Douglas Gregor82dbbd72009-05-29 14:49:33 +0000676 // FIXME: Member of the current instantiation.
Douglas Gregor90a1a652009-03-19 17:26:29 +0000677 if (SS && isDependentScopeSpecifier(*SS)) {
Douglas Gregorf21eb492009-03-26 23:50:42 +0000678 return Owned(new (Context) UnresolvedDeclRefExpr(Name, Context.DependentTy,
Mike Stump11289f42009-09-09 15:08:12 +0000679 Loc, SS->getRange(),
Anders Carlsson03f89b12009-07-09 00:05:08 +0000680 static_cast<NestedNameSpecifier *>(SS->getScopeRep()),
681 isAddressOfOperand));
Douglas Gregor90a1a652009-03-19 17:26:29 +0000682 }
683
John McCall27b18f82009-11-17 02:14:36 +0000684 LookupResult Lookup(*this, Name, Loc, LookupOrdinaryName);
685 LookupParsedName(Lookup, S, SS, true);
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000686
John McCall27b18f82009-11-17 02:14:36 +0000687 if (Lookup.isAmbiguous())
Sebastian Redlffbcf962009-01-18 18:53:16 +0000688 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +0000689
John McCall9f3059a2009-10-09 21:13:30 +0000690 NamedDecl *D = Lookup.getAsSingleDecl(Context);
Douglas Gregorb0846b02008-12-06 00:22:45 +0000691
Chris Lattner59a25942008-03-31 00:36:02 +0000692 // If this reference is in an Objective-C method, then ivar lookup happens as
693 // well.
Douglas Gregor4ea80432008-11-18 15:03:34 +0000694 IdentifierInfo *II = Name.getAsIdentifierInfo();
695 if (II && getCurMethodDecl()) {
Chris Lattner59a25942008-03-31 00:36:02 +0000696 // There are two cases to handle here. 1) scoped lookup could have failed,
697 // in which case we should look for an ivar. 2) scoped lookup could have
Mike Stump11289f42009-09-09 15:08:12 +0000698 // found a decl, but that decl is outside the current instance method (i.e.
699 // a global variable). In these two cases, we do a lookup for an ivar with
Fariborz Jahanianbf8e8422009-03-02 21:55:29 +0000700 // this name, if the lookup sucedes, we replace it our current decl.
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000701 if (D == 0 || D->isDefinedOutsideFunctionOrMethod()) {
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +0000702 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Fariborz Jahaniana458c4f2009-03-03 01:21:12 +0000703 ObjCInterfaceDecl *ClassDeclared;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000704 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
Chris Lattner50afe312009-02-16 17:19:12 +0000705 // Check if referencing a field with __attribute__((deprecated)).
Douglas Gregor171c45a2009-02-18 21:56:37 +0000706 if (DiagnoseUseOfDecl(IV, Loc))
707 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +0000708
Chris Lattnercd2a8c52009-04-24 22:30:50 +0000709 // If we're referencing an invalid decl, just return this as a silent
710 // error node. The error diagnostic was already emitted on the decl.
711 if (IV->isInvalidDecl())
712 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +0000713
Fariborz Jahanianbf8e8422009-03-02 21:55:29 +0000714 bool IsClsMethod = getCurMethodDecl()->isClassMethod();
715 // If a class method attemps to use a free standing ivar, this is
716 // an error.
717 if (IsClsMethod && D && !D->isDefinedOutsideFunctionOrMethod())
718 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
719 << IV->getDeclName());
720 // If a class method uses a global variable, even if an ivar with
721 // same name exists, use the global.
722 if (!IsClsMethod) {
Fariborz Jahaniana458c4f2009-03-03 01:21:12 +0000723 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
724 ClassDeclared != IFace)
725 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
Mike Stump87c57ac2009-05-16 07:39:55 +0000726 // FIXME: This should use a new expr for a direct reference, don't
727 // turn this into Self->ivar, just return a BareIVarExpr or something.
Fariborz Jahanianbf8e8422009-03-02 21:55:29 +0000728 IdentifierInfo &II = Context.Idents.get("self");
Douglas Gregora121b752009-11-03 16:56:39 +0000729 UnqualifiedId SelfName;
730 SelfName.setIdentifier(&II, SourceLocation());
731 CXXScopeSpec SelfScopeSpec;
732 OwningExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
733 SelfName, false, false);
Douglas Gregorc9c02ed2009-06-19 23:52:42 +0000734 MarkDeclarationReferenced(Loc, IV);
Mike Stump11289f42009-09-09 15:08:12 +0000735 return Owned(new (Context)
736 ObjCIvarRefExpr(IV, IV->getType(), Loc,
Anders Carlssonb781bcd2009-05-01 19:49:17 +0000737 SelfExpr.takeAs<Expr>(), true, true));
Fariborz Jahanianbf8e8422009-03-02 21:55:29 +0000738 }
Chris Lattner59a25942008-03-31 00:36:02 +0000739 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000740 } else if (getCurMethodDecl()->isInstanceMethod()) {
Fariborz Jahanianbf8e8422009-03-02 21:55:29 +0000741 // We should warn if a local variable hides an ivar.
742 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Fariborz Jahaniana458c4f2009-03-03 01:21:12 +0000743 ObjCInterfaceDecl *ClassDeclared;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000744 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
Fariborz Jahaniana458c4f2009-03-03 01:21:12 +0000745 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
746 IFace == ClassDeclared)
Chris Lattnercd2a8c52009-04-24 22:30:50 +0000747 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
Fariborz Jahaniana458c4f2009-03-03 01:21:12 +0000748 }
Fariborz Jahanianbf8e8422009-03-02 21:55:29 +0000749 }
Steve Naroff0d7c6db2008-08-10 19:10:41 +0000750 // Needed to implement property "super.method" notation.
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000751 if (D == 0 && II->isStr("super")) {
Steve Naroffe29c4dd2009-03-05 20:12:00 +0000752 QualType T;
Mike Stump11289f42009-09-09 15:08:12 +0000753
Steve Naroffe29c4dd2009-03-05 20:12:00 +0000754 if (getCurMethodDecl()->isInstanceMethod())
Steve Naroff7cae42b2009-07-10 23:34:53 +0000755 T = Context.getObjCObjectPointerType(Context.getObjCInterfaceType(
756 getCurMethodDecl()->getClassInterface()));
Steve Naroffe29c4dd2009-03-05 20:12:00 +0000757 else
758 T = Context.getObjCClassType();
Steve Narofff6009ed2009-01-21 00:14:39 +0000759 return Owned(new (Context) ObjCSuperExpr(Loc, T));
Steve Naroffebf4cb42008-06-02 23:03:37 +0000760 }
Chris Lattner59a25942008-03-31 00:36:02 +0000761 }
Douglas Gregorf15f5d32009-02-16 19:28:42 +0000762
Douglas Gregor171c45a2009-02-18 21:56:37 +0000763 // Determine whether this name might be a candidate for
764 // argument-dependent lookup.
Mike Stump11289f42009-09-09 15:08:12 +0000765 bool ADL = getLangOptions().CPlusPlus && (!SS || !SS->isSet()) &&
Douglas Gregor171c45a2009-02-18 21:56:37 +0000766 HasTrailingLParen;
767
768 if (ADL && D == 0) {
Douglas Gregorf15f5d32009-02-16 19:28:42 +0000769 // We've seen something of the form
770 //
771 // identifier(
772 //
773 // and we did not find any entity by the name
774 // "identifier". However, this identifier is still subject to
775 // argument-dependent lookup, so keep track of the name.
776 return Owned(new (Context) UnresolvedFunctionNameExpr(Name,
777 Context.OverloadTy,
778 Loc));
779 }
780
Chris Lattner17ed4872006-11-20 04:58:19 +0000781 if (D == 0) {
Bill Wendling4073ed52007-02-13 01:51:42 +0000782 // Otherwise, this could be an implicitly declared function reference (legal
Chris Lattner9561a0b2007-01-28 08:20:04 +0000783 // in C90, extension in C99).
Douglas Gregor4ea80432008-11-18 15:03:34 +0000784 if (HasTrailingLParen && II &&
Chris Lattner59a25942008-03-31 00:36:02 +0000785 !getLangOptions().CPlusPlus) // Not in C++.
Douglas Gregor4ea80432008-11-18 15:03:34 +0000786 D = ImplicitlyDefineFunction(Loc, *II, S);
Steve Naroff92e30f82007-04-02 22:35:25 +0000787 else {
Chris Lattnerac18be92006-11-20 06:49:47 +0000788 // If this name wasn't predeclared and if this is not a function call,
789 // diagnose the problem.
Douglas Gregore40876a2009-10-13 21:16:44 +0000790 if (SS && !SS->isEmpty())
791 return ExprError(Diag(Loc, diag::err_no_member)
792 << Name << computeDeclContext(*SS, false)
793 << SS->getRange());
794 else if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
Douglas Gregor4ea80432008-11-18 15:03:34 +0000795 Name.getNameKind() == DeclarationName::CXXConversionFunctionName)
Sebastian Redlffbcf962009-01-18 18:53:16 +0000796 return ExprError(Diag(Loc, diag::err_undeclared_use)
797 << Name.getAsString());
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000798 else
Sebastian Redlffbcf962009-01-18 18:53:16 +0000799 return ExprError(Diag(Loc, diag::err_undeclared_var_use) << Name);
Steve Naroff92e30f82007-04-02 22:35:25 +0000800 }
Chris Lattner17ed4872006-11-20 04:58:19 +0000801 }
Mike Stump11289f42009-09-09 15:08:12 +0000802
Douglas Gregor3256d042009-06-30 15:47:41 +0000803 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
804 // Warn about constructs like:
805 // if (void *X = foo()) { ... } else { X }.
806 // In the else block, the pointer is always false.
Mike Stump11289f42009-09-09 15:08:12 +0000807
Douglas Gregor3256d042009-06-30 15:47:41 +0000808 // FIXME: In a template instantiation, we don't have scope
809 // information to check this property.
810 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
811 Scope *CheckS = S;
Douglas Gregor13a2c032009-11-05 17:49:26 +0000812 while (CheckS && CheckS->getControlParent()) {
Mike Stump11289f42009-09-09 15:08:12 +0000813 if (CheckS->isWithinElse() &&
Douglas Gregor3256d042009-06-30 15:47:41 +0000814 CheckS->getControlParent()->isDeclScope(DeclPtrTy::make(Var))) {
Douglas Gregor13a2c032009-11-05 17:49:26 +0000815 ExprError(Diag(Loc, diag::warn_value_always_zero)
816 << Var->getDeclName()
817 << (Var->getType()->isPointerType()? 2 :
818 Var->getType()->isBooleanType()? 1 : 0));
Douglas Gregor3256d042009-06-30 15:47:41 +0000819 break;
820 }
Mike Stump11289f42009-09-09 15:08:12 +0000821
Douglas Gregor13a2c032009-11-05 17:49:26 +0000822 // Move to the parent of this scope.
823 CheckS = CheckS->getParent();
Douglas Gregor3256d042009-06-30 15:47:41 +0000824 }
825 }
826 } else if (FunctionDecl *Func = dyn_cast<FunctionDecl>(D)) {
827 if (!getLangOptions().CPlusPlus && !Func->hasPrototype()) {
828 // C99 DR 316 says that, if a function type comes from a
829 // function definition (without a prototype), that type is only
830 // used for checking compatibility. Therefore, when referencing
831 // the function, we pretend that we don't have the full function
832 // type.
833 if (DiagnoseUseOfDecl(Func, Loc))
834 return ExprError();
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000835
Douglas Gregor3256d042009-06-30 15:47:41 +0000836 QualType T = Func->getType();
837 QualType NoProtoType = T;
John McCall9dd450b2009-09-21 23:43:11 +0000838 if (const FunctionProtoType *Proto = T->getAs<FunctionProtoType>())
Douglas Gregor3256d042009-06-30 15:47:41 +0000839 NoProtoType = Context.getFunctionNoProtoType(Proto->getResultType());
840 return BuildDeclRefExpr(Func, NoProtoType, Loc, false, false, SS);
841 }
842 }
Mike Stump11289f42009-09-09 15:08:12 +0000843
Douglas Gregor3256d042009-06-30 15:47:41 +0000844 return BuildDeclarationNameExpr(Loc, D, HasTrailingLParen, SS, isAddressOfOperand);
845}
Fariborz Jahanianbb67b822009-07-29 18:40:24 +0000846/// \brief Cast member's object to its own class if necessary.
Fariborz Jahanian3f150832009-07-29 19:40:11 +0000847bool
Fariborz Jahanianbb67b822009-07-29 18:40:24 +0000848Sema::PerformObjectMemberConversion(Expr *&From, NamedDecl *Member) {
849 if (FieldDecl *FD = dyn_cast<FieldDecl>(Member))
Mike Stump11289f42009-09-09 15:08:12 +0000850 if (CXXRecordDecl *RD =
Fariborz Jahanianbb67b822009-07-29 18:40:24 +0000851 dyn_cast<CXXRecordDecl>(FD->getDeclContext())) {
Mike Stump11289f42009-09-09 15:08:12 +0000852 QualType DestType =
Fariborz Jahanianbb67b822009-07-29 18:40:24 +0000853 Context.getCanonicalType(Context.getTypeDeclType(RD));
Fariborz Jahanian4b12ed12009-07-29 20:41:46 +0000854 if (DestType->isDependentType() || From->getType()->isDependentType())
855 return false;
856 QualType FromRecordType = From->getType();
857 QualType DestRecordType = DestType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000858 if (FromRecordType->getAs<PointerType>()) {
Fariborz Jahanian4b12ed12009-07-29 20:41:46 +0000859 DestType = Context.getPointerType(DestType);
860 FromRecordType = FromRecordType->getPointeeType();
Fariborz Jahanianbb67b822009-07-29 18:40:24 +0000861 }
Fariborz Jahanian4b12ed12009-07-29 20:41:46 +0000862 if (!Context.hasSameUnqualifiedType(FromRecordType, DestRecordType) &&
863 CheckDerivedToBaseConversion(FromRecordType,
864 DestRecordType,
865 From->getSourceRange().getBegin(),
866 From->getSourceRange()))
867 return true;
Anders Carlssona076d142009-07-31 01:23:52 +0000868 ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
869 /*isLvalue=*/true);
Fariborz Jahanianbb67b822009-07-29 18:40:24 +0000870 }
Fariborz Jahanian3f150832009-07-29 19:40:11 +0000871 return false;
Fariborz Jahanianbb67b822009-07-29 18:40:24 +0000872}
Douglas Gregor3256d042009-06-30 15:47:41 +0000873
Douglas Gregorf405d7e2009-08-31 23:41:50 +0000874/// \brief Build a MemberExpr AST node.
Mike Stump11289f42009-09-09 15:08:12 +0000875static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow,
876 const CXXScopeSpec *SS, NamedDecl *Member,
Douglas Gregorc1905232009-08-26 22:36:53 +0000877 SourceLocation Loc, QualType Ty) {
878 if (SS && SS->isSet())
Mike Stump11289f42009-09-09 15:08:12 +0000879 return MemberExpr::Create(C, Base, isArrow,
Douglas Gregorf405d7e2009-08-31 23:41:50 +0000880 (NestedNameSpecifier *)SS->getScopeRep(),
Mike Stump11289f42009-09-09 15:08:12 +0000881 SS->getRange(), Member, Loc,
Douglas Gregor84f14dd2009-09-01 00:37:14 +0000882 // FIXME: Explicit template argument lists
883 false, SourceLocation(), 0, 0, SourceLocation(),
884 Ty);
Mike Stump11289f42009-09-09 15:08:12 +0000885
Douglas Gregorc1905232009-08-26 22:36:53 +0000886 return new (C) MemberExpr(Base, isArrow, Member, Loc, Ty);
887}
888
Douglas Gregor3256d042009-06-30 15:47:41 +0000889/// \brief Complete semantic analysis for a reference to the given declaration.
890Sema::OwningExprResult
891Sema::BuildDeclarationNameExpr(SourceLocation Loc, NamedDecl *D,
892 bool HasTrailingLParen,
Mike Stump11289f42009-09-09 15:08:12 +0000893 const CXXScopeSpec *SS,
Douglas Gregor3256d042009-06-30 15:47:41 +0000894 bool isAddressOfOperand) {
895 assert(D && "Cannot refer to a NULL declaration");
896 DeclarationName Name = D->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +0000897
Sebastian Redl3d3f75a2009-02-03 20:19:35 +0000898 // If this is an expression of the form &Class::member, don't build an
899 // implicit member ref, because we want a pointer to the member in general,
900 // not any specific instance's member.
901 if (isAddressOfOperand && SS && !SS->isEmpty() && !HasTrailingLParen) {
Douglas Gregor52537682009-03-19 00:18:19 +0000902 DeclContext *DC = computeDeclContext(*SS);
Douglas Gregor2ada0482009-02-04 17:27:36 +0000903 if (D && isa<CXXRecordDecl>(DC)) {
Sebastian Redl3d3f75a2009-02-03 20:19:35 +0000904 QualType DType;
905 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
906 DType = FD->getType().getNonReferenceType();
907 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
908 DType = Method->getType();
909 } else if (isa<OverloadedFunctionDecl>(D)) {
910 DType = Context.OverloadTy;
911 }
912 // Could be an inner type. That's diagnosed below, so ignore it here.
913 if (!DType.isNull()) {
914 // The pointer is type- and value-dependent if it points into something
915 // dependent.
Douglas Gregor82dbbd72009-05-29 14:49:33 +0000916 bool Dependent = DC->isDependentContext();
Anders Carlsson946b86d2009-06-24 00:10:43 +0000917 return BuildDeclRefExpr(D, DType, Loc, Dependent, Dependent, SS);
Sebastian Redl3d3f75a2009-02-03 20:19:35 +0000918 }
919 }
920 }
921
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000922 // We may have found a field within an anonymous union or struct
923 // (C++ [class.union]).
Douglas Gregor6493d9c2009-10-22 07:08:30 +0000924 // FIXME: This needs to happen post-isImplicitMemberReference?
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000925 if (FieldDecl *FD = dyn_cast<FieldDecl>(D))
926 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
927 return BuildAnonymousStructUnionMemberReference(Loc, FD);
Sebastian Redlffbcf962009-01-18 18:53:16 +0000928
Douglas Gregor6493d9c2009-10-22 07:08:30 +0000929 // Cope with an implicit member access in a C++ non-static member function.
930 QualType ThisType, MemberType;
931 if (isImplicitMemberReference(SS, D, Loc, ThisType, MemberType)) {
932 Expr *This = new (Context) CXXThisExpr(SourceLocation(), ThisType);
933 MarkDeclarationReferenced(Loc, D);
934 if (PerformObjectMemberConversion(This, D))
935 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +0000936
Douglas Gregor6493d9c2009-10-22 07:08:30 +0000937 bool ShouldCheckUse = true;
938 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
939 // Don't diagnose the use of a virtual member function unless it's
940 // explicitly qualified.
941 if (MD->isVirtual() && (!SS || !SS->isSet()))
942 ShouldCheckUse = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +0000943 }
Douglas Gregor6493d9c2009-10-22 07:08:30 +0000944
945 if (ShouldCheckUse && DiagnoseUseOfDecl(D, Loc))
946 return ExprError();
947 return Owned(BuildMemberExpr(Context, This, true, SS, D,
948 Loc, MemberType));
Douglas Gregor97fd6e22008-12-22 05:46:06 +0000949 }
950
Douglas Gregor91f84212008-12-11 16:49:14 +0000951 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000952 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
953 if (MD->isStatic())
954 // "invalid use of member 'x' in static member function"
Sebastian Redlffbcf962009-01-18 18:53:16 +0000955 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
956 << FD->getDeclName());
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000957 }
958
Douglas Gregor97fd6e22008-12-22 05:46:06 +0000959 // Any other ways we could have found the field in a well-formed
960 // program would have been turned into implicit member expressions
961 // above.
Sebastian Redlffbcf962009-01-18 18:53:16 +0000962 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
963 << FD->getDeclName());
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000964 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +0000965
Steve Naroff46ba1eb2007-04-03 23:13:13 +0000966 if (isa<TypedefDecl>(D))
Sebastian Redlffbcf962009-01-18 18:53:16 +0000967 return ExprError(Diag(Loc, diag::err_unexpected_typedef) << Name);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000968 if (isa<ObjCInterfaceDecl>(D))
Sebastian Redlffbcf962009-01-18 18:53:16 +0000969 return ExprError(Diag(Loc, diag::err_unexpected_interface) << Name);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +0000970 if (isa<NamespaceDecl>(D))
Sebastian Redlffbcf962009-01-18 18:53:16 +0000971 return ExprError(Diag(Loc, diag::err_unexpected_namespace) << Name);
Steve Narofff1e53692007-03-23 22:27:02 +0000972
Steve Naroff8de9c3a2008-09-05 22:11:13 +0000973 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000974 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
Anders Carlsson946b86d2009-06-24 00:10:43 +0000975 return BuildDeclRefExpr(Ovl, Context.OverloadTy, Loc,
976 false, false, SS);
Douglas Gregord32e0282009-02-09 23:23:08 +0000977 else if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
Anders Carlsson946b86d2009-06-24 00:10:43 +0000978 return BuildDeclRefExpr(Template, Context.OverloadTy, Loc,
979 false, false, SS);
Anders Carlsson938b1002009-08-29 01:06:32 +0000980 else if (UnresolvedUsingDecl *UD = dyn_cast<UnresolvedUsingDecl>(D))
Mike Stump11289f42009-09-09 15:08:12 +0000981 return BuildDeclRefExpr(UD, Context.DependentTy, Loc,
982 /*TypeDependent=*/true,
Anders Carlsson938b1002009-08-29 01:06:32 +0000983 /*ValueDependent=*/true, SS);
984
Steve Naroff8de9c3a2008-09-05 22:11:13 +0000985 ValueDecl *VD = cast<ValueDecl>(D);
Sebastian Redlffbcf962009-01-18 18:53:16 +0000986
Douglas Gregor171c45a2009-02-18 21:56:37 +0000987 // Check whether this declaration can be used. Note that we suppress
988 // this check when we're going to perform argument-dependent lookup
989 // on this function name, because this might not be the function
990 // that overload resolution actually selects.
Mike Stump11289f42009-09-09 15:08:12 +0000991 bool ADL = getLangOptions().CPlusPlus && (!SS || !SS->isSet()) &&
Douglas Gregor3256d042009-06-30 15:47:41 +0000992 HasTrailingLParen;
Douglas Gregor171c45a2009-02-18 21:56:37 +0000993 if (!(ADL && isa<FunctionDecl>(VD)) && DiagnoseUseOfDecl(VD, Loc))
994 return ExprError();
995
Steve Naroff8de9c3a2008-09-05 22:11:13 +0000996 // Only create DeclRefExpr's for valid Decl's.
997 if (VD->isInvalidDecl())
Sebastian Redlffbcf962009-01-18 18:53:16 +0000998 return ExprError();
999
Chris Lattner2a9d9892008-10-20 05:16:36 +00001000 // If the identifier reference is inside a block, and it refers to a value
1001 // that is outside the block, create a BlockDeclRefExpr instead of a
1002 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
1003 // the block is formed.
Steve Naroff8de9c3a2008-09-05 22:11:13 +00001004 //
Chris Lattner2a9d9892008-10-20 05:16:36 +00001005 // We do not do this for things like enum constants, global variables, etc,
1006 // as they do not get snapshotted.
1007 //
1008 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00001009 MarkDeclarationReferenced(Loc, VD);
Eli Friedman7fa3faa2009-03-22 23:00:19 +00001010 QualType ExprTy = VD->getType().getNonReferenceType();
Steve Naroff1d95e5a2008-10-10 01:28:17 +00001011 // The BlocksAttr indicates the variable is bound by-reference.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001012 if (VD->getAttr<BlocksAttr>())
Eli Friedman7fa3faa2009-03-22 23:00:19 +00001013 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, true));
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00001014 // This is to record that a 'const' was actually synthesize and added.
1015 bool constAdded = !ExprTy.isConstQualified();
Steve Naroff1d95e5a2008-10-10 01:28:17 +00001016 // Variable will be bound by-copy, make it const within the closure.
Mike Stump11289f42009-09-09 15:08:12 +00001017
Eli Friedman7fa3faa2009-03-22 23:00:19 +00001018 ExprTy.addConst();
Mike Stump11289f42009-09-09 15:08:12 +00001019 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, false,
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00001020 constAdded));
Steve Naroff1d95e5a2008-10-10 01:28:17 +00001021 }
1022 // If this reference is not in a block or if the referenced variable is
1023 // within the block, create a normal DeclRefExpr.
Douglas Gregor4619e432008-12-05 23:32:09 +00001024
Douglas Gregor4619e432008-12-05 23:32:09 +00001025 bool TypeDependent = false;
Douglas Gregor872ffce2008-12-10 20:57:37 +00001026 bool ValueDependent = false;
1027 if (getLangOptions().CPlusPlus) {
1028 // C++ [temp.dep.expr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00001029 // An id-expression is type-dependent if it contains:
Douglas Gregor872ffce2008-12-10 20:57:37 +00001030 // - an identifier that was declared with a dependent type,
1031 if (VD->getType()->isDependentType())
1032 TypeDependent = true;
1033 // - FIXME: a template-id that is dependent,
1034 // - a conversion-function-id that specifies a dependent type,
1035 else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1036 Name.getCXXNameType()->isDependentType())
1037 TypeDependent = true;
1038 // - a nested-name-specifier that contains a class-name that
1039 // names a dependent type.
1040 else if (SS && !SS->isEmpty()) {
Douglas Gregor52537682009-03-19 00:18:19 +00001041 for (DeclContext *DC = computeDeclContext(*SS);
Douglas Gregor872ffce2008-12-10 20:57:37 +00001042 DC; DC = DC->getParent()) {
1043 // FIXME: could stop early at namespace scope.
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001044 if (DC->isRecord()) {
Douglas Gregor872ffce2008-12-10 20:57:37 +00001045 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
1046 if (Context.getTypeDeclType(Record)->isDependentType()) {
1047 TypeDependent = true;
1048 break;
1049 }
Douglas Gregor4619e432008-12-05 23:32:09 +00001050 }
1051 }
1052 }
Douglas Gregor4619e432008-12-05 23:32:09 +00001053
Douglas Gregor872ffce2008-12-10 20:57:37 +00001054 // C++ [temp.dep.constexpr]p2:
1055 //
1056 // An identifier is value-dependent if it is:
1057 // - a name declared with a dependent type,
1058 if (TypeDependent)
1059 ValueDependent = true;
1060 // - the name of a non-type template parameter,
1061 else if (isa<NonTypeTemplateParmDecl>(VD))
1062 ValueDependent = true;
1063 // - a constant with integral or enumeration type and is
1064 // initialized with an expression that is value-dependent
Eli Friedmandd49ee32009-06-11 01:11:20 +00001065 else if (const VarDecl *Dcl = dyn_cast<VarDecl>(VD)) {
Mike Stump96638af2009-11-03 22:20:01 +00001066 if (Context.getCanonicalType(Dcl->getType()).getCVRQualifiers()
1067 == Qualifiers::Const &&
Eli Friedmandd49ee32009-06-11 01:11:20 +00001068 Dcl->getInit()) {
1069 ValueDependent = Dcl->getInit()->isValueDependent();
1070 }
1071 }
Douglas Gregor872ffce2008-12-10 20:57:37 +00001072 }
Douglas Gregor4619e432008-12-05 23:32:09 +00001073
Anders Carlsson946b86d2009-06-24 00:10:43 +00001074 return BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc,
1075 TypeDependent, ValueDependent, SS);
Chris Lattner17ed4872006-11-20 04:58:19 +00001076}
Chris Lattnere168f762006-11-10 05:29:30 +00001077
Sebastian Redlffbcf962009-01-18 18:53:16 +00001078Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
1079 tok::TokenKind Kind) {
Chris Lattner6307f192008-08-10 01:53:14 +00001080 PredefinedExpr::IdentType IT;
Sebastian Redlffbcf962009-01-18 18:53:16 +00001081
Chris Lattnere168f762006-11-10 05:29:30 +00001082 switch (Kind) {
Chris Lattner317e6ba2008-01-12 18:39:25 +00001083 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner6307f192008-08-10 01:53:14 +00001084 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
1085 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
1086 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattnere168f762006-11-10 05:29:30 +00001087 }
Chris Lattner317e6ba2008-01-12 18:39:25 +00001088
Chris Lattnera81a0272008-01-12 08:14:25 +00001089 // Pre-defined identifiers are of type char[x], where x is the length of the
1090 // string.
Mike Stump11289f42009-09-09 15:08:12 +00001091
Anders Carlsson2fb08242009-09-08 18:24:21 +00001092 Decl *currentDecl = getCurFunctionOrMethodDecl();
1093 if (!currentDecl) {
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00001094 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson2fb08242009-09-08 18:24:21 +00001095 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00001096 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00001097
Anders Carlsson0b209a82009-09-11 01:22:35 +00001098 QualType ResTy;
1099 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
1100 ResTy = Context.DependentTy;
1101 } else {
1102 unsigned Length =
1103 PredefinedExpr::ComputeName(Context, IT, currentDecl).length();
Sebastian Redlffbcf962009-01-18 18:53:16 +00001104
Anders Carlsson0b209a82009-09-11 01:22:35 +00001105 llvm::APInt LengthI(32, Length + 1);
John McCall8ccfcb52009-09-24 19:53:00 +00001106 ResTy = Context.CharTy.withConst();
Anders Carlsson0b209a82009-09-11 01:22:35 +00001107 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
1108 }
Steve Narofff6009ed2009-01-21 00:14:39 +00001109 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattnere168f762006-11-10 05:29:30 +00001110}
1111
Sebastian Redlffbcf962009-01-18 18:53:16 +00001112Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00001113 llvm::SmallString<16> CharBuffer;
Steve Naroffae4143e2007-04-26 20:39:23 +00001114 CharBuffer.resize(Tok.getLength());
1115 const char *ThisTokBegin = &CharBuffer[0];
1116 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlffbcf962009-01-18 18:53:16 +00001117
Steve Naroffae4143e2007-04-26 20:39:23 +00001118 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1119 Tok.getLocation(), PP);
1120 if (Literal.hadError())
Sebastian Redlffbcf962009-01-18 18:53:16 +00001121 return ExprError();
Chris Lattneref24b382008-03-01 08:32:21 +00001122
1123 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
1124
Sebastian Redl20614a72009-01-20 22:23:13 +00001125 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
1126 Literal.isWide(),
1127 type, Tok.getLocation()));
Steve Naroffae4143e2007-04-26 20:39:23 +00001128}
1129
Sebastian Redlffbcf962009-01-18 18:53:16 +00001130Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
1131 // Fast path for a single digit (which is quite common). A single digit
Steve Narofff2fb89e2007-03-13 20:29:44 +00001132 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
1133 if (Tok.getLength() == 1) {
Chris Lattner9240b3e2009-01-26 22:36:52 +00001134 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattnerc4c18192009-01-16 07:10:29 +00001135 unsigned IntSize = Context.Target.getIntWidth();
Steve Narofff6009ed2009-01-21 00:14:39 +00001136 return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
Steve Naroff5faaef72009-01-20 19:53:53 +00001137 Context.IntTy, Tok.getLocation()));
Steve Narofff2fb89e2007-03-13 20:29:44 +00001138 }
Ted Kremeneke9814182009-01-13 23:19:12 +00001139
Chris Lattner23b7eb62007-06-15 23:05:46 +00001140 llvm::SmallString<512> IntegerBuffer;
Chris Lattnera1cf5f92008-09-30 20:53:45 +00001141 // Add padding so that NumericLiteralParser can overread by one character.
1142 IntegerBuffer.resize(Tok.getLength()+1);
Steve Naroff8160ea22007-03-06 01:09:46 +00001143 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlffbcf962009-01-18 18:53:16 +00001144
Chris Lattner67ca9252007-05-21 01:08:44 +00001145 // Get the spelling of the token, which eliminates trigraphs, etc.
Steve Naroff8160ea22007-03-06 01:09:46 +00001146 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlffbcf962009-01-18 18:53:16 +00001147
Mike Stump11289f42009-09-09 15:08:12 +00001148 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Steve Naroff451d8f162007-03-12 23:22:38 +00001149 Tok.getLocation(), PP);
Steve Narofff2fb89e2007-03-13 20:29:44 +00001150 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +00001151 return ExprError();
1152
Chris Lattner1c20a172007-08-26 03:42:43 +00001153 Expr *Res;
Sebastian Redlffbcf962009-01-18 18:53:16 +00001154
Chris Lattner1c20a172007-08-26 03:42:43 +00001155 if (Literal.isFloatingLiteral()) {
Chris Lattnerec0a6d92007-09-22 18:29:59 +00001156 QualType Ty;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001157 if (Literal.isFloat)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00001158 Ty = Context.FloatTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001159 else if (!Literal.isLong)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00001160 Ty = Context.DoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001161 else
Chris Lattner7570e9c2008-03-08 08:52:55 +00001162 Ty = Context.LongDoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001163
1164 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
1165
Ted Kremenek3a2c9502007-11-29 00:56:49 +00001166 // isExact will be set by GetFloatValue().
1167 bool isExact = false;
Chris Lattnere4edb8e2009-06-29 17:34:55 +00001168 llvm::APFloat Val = Literal.GetFloatValue(Format, &isExact);
1169 Res = new (Context) FloatingLiteral(Val, isExact, Ty, Tok.getLocation());
Sebastian Redlffbcf962009-01-18 18:53:16 +00001170
Chris Lattner1c20a172007-08-26 03:42:43 +00001171 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00001172 return ExprError();
Chris Lattner1c20a172007-08-26 03:42:43 +00001173 } else {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001174 QualType Ty;
Chris Lattner67ca9252007-05-21 01:08:44 +00001175
Neil Boothac582c52007-08-29 22:00:19 +00001176 // long long is a C99 feature.
1177 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth4a1ee052007-08-29 22:13:52 +00001178 Literal.isLongLong)
Neil Boothac582c52007-08-29 22:00:19 +00001179 Diag(Tok.getLocation(), diag::ext_longlong);
1180
Chris Lattner67ca9252007-05-21 01:08:44 +00001181 // Get the value in the widest-possible width.
Chris Lattner37e05872008-03-05 18:54:05 +00001182 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlffbcf962009-01-18 18:53:16 +00001183
Chris Lattner67ca9252007-05-21 01:08:44 +00001184 if (Literal.GetIntegerValue(ResultVal)) {
1185 // If this value didn't fit into uintmax_t, warn and force to ull.
1186 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001187 Ty = Context.UnsignedLongLongTy;
1188 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner37e05872008-03-05 18:54:05 +00001189 "long long is not intmax_t?");
Steve Naroff09ef4742007-03-09 23:16:33 +00001190 } else {
Chris Lattner67ca9252007-05-21 01:08:44 +00001191 // If this value fits into a ULL, try to figure out what else it fits into
1192 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlffbcf962009-01-18 18:53:16 +00001193
Chris Lattner67ca9252007-05-21 01:08:44 +00001194 // Octal, Hexadecimal, and integers with a U suffix are allowed to
1195 // be an unsigned int.
1196 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
1197
1198 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner55258cf2008-05-09 05:59:00 +00001199 unsigned Width = 0;
Chris Lattner7b939cf2007-08-23 21:58:08 +00001200 if (!Literal.isLong && !Literal.isLongLong) {
1201 // Are int/unsigned possibilities?
Chris Lattner55258cf2008-05-09 05:59:00 +00001202 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00001203
Chris Lattner67ca9252007-05-21 01:08:44 +00001204 // Does it fit in a unsigned int?
1205 if (ResultVal.isIntN(IntSize)) {
1206 // Does it fit in a signed int?
1207 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001208 Ty = Context.IntTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00001209 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001210 Ty = Context.UnsignedIntTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00001211 Width = IntSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00001212 }
Chris Lattner67ca9252007-05-21 01:08:44 +00001213 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00001214
Chris Lattner67ca9252007-05-21 01:08:44 +00001215 // Are long/unsigned long possibilities?
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001216 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner55258cf2008-05-09 05:59:00 +00001217 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00001218
Chris Lattner67ca9252007-05-21 01:08:44 +00001219 // Does it fit in a unsigned long?
1220 if (ResultVal.isIntN(LongSize)) {
1221 // Does it fit in a signed long?
1222 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001223 Ty = Context.LongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00001224 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001225 Ty = Context.UnsignedLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00001226 Width = LongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00001227 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00001228 }
1229
Chris Lattner67ca9252007-05-21 01:08:44 +00001230 // Finally, check long long if needed.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001231 if (Ty.isNull()) {
Chris Lattner55258cf2008-05-09 05:59:00 +00001232 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00001233
Chris Lattner67ca9252007-05-21 01:08:44 +00001234 // Does it fit in a unsigned long long?
1235 if (ResultVal.isIntN(LongLongSize)) {
1236 // Does it fit in a signed long long?
1237 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001238 Ty = Context.LongLongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00001239 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001240 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00001241 Width = LongLongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00001242 }
1243 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00001244
Chris Lattner67ca9252007-05-21 01:08:44 +00001245 // If we still couldn't decide a type, we probably have something that
1246 // does not fit in a signed long long, but has no U suffix.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001247 if (Ty.isNull()) {
Chris Lattner67ca9252007-05-21 01:08:44 +00001248 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001249 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00001250 Width = Context.Target.getLongLongWidth();
Chris Lattner67ca9252007-05-21 01:08:44 +00001251 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00001252
Chris Lattner55258cf2008-05-09 05:59:00 +00001253 if (ResultVal.getBitWidth() != Width)
1254 ResultVal.trunc(Width);
Steve Naroff09ef4742007-03-09 23:16:33 +00001255 }
Sebastian Redl20614a72009-01-20 22:23:13 +00001256 Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Steve Naroff09ef4742007-03-09 23:16:33 +00001257 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00001258
Chris Lattner1c20a172007-08-26 03:42:43 +00001259 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
1260 if (Literal.isImaginary)
Mike Stump11289f42009-09-09 15:08:12 +00001261 Res = new (Context) ImaginaryLiteral(Res,
Steve Narofff6009ed2009-01-21 00:14:39 +00001262 Context.getComplexType(Res->getType()));
Sebastian Redlffbcf962009-01-18 18:53:16 +00001263
1264 return Owned(Res);
Chris Lattnere168f762006-11-10 05:29:30 +00001265}
1266
Sebastian Redlffbcf962009-01-18 18:53:16 +00001267Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1268 SourceLocation R, ExprArg Val) {
Anders Carlssonb781bcd2009-05-01 19:49:17 +00001269 Expr *E = Val.takeAs<Expr>();
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001270 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Narofff6009ed2009-01-21 00:14:39 +00001271 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattnere168f762006-11-10 05:29:30 +00001272}
1273
Steve Naroff71b59a92007-06-04 22:22:31 +00001274/// The UsualUnaryConversions() function is *not* called by this routine.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00001275/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001276bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Sebastian Redl6f282892008-11-11 17:56:53 +00001277 SourceLocation OpLoc,
1278 const SourceRange &ExprRange,
1279 bool isSizeof) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001280 if (exprType->isDependentType())
1281 return false;
1282
Steve Naroff043d45d2007-05-15 02:32:35 +00001283 // C99 6.5.3.4p1:
John McCall4c98fd82009-11-04 07:28:41 +00001284 if (exprType->isFunctionType()) {
Chris Lattner62975a72009-04-24 00:30:45 +00001285 // alignof(function) is allowed as an extension.
Chris Lattnerb1355b12009-01-24 19:46:37 +00001286 if (isSizeof)
1287 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
1288 return false;
1289 }
Mike Stump11289f42009-09-09 15:08:12 +00001290
Chris Lattner62975a72009-04-24 00:30:45 +00001291 // Allow sizeof(void)/alignof(void) as an extension.
Chris Lattnerb1355b12009-01-24 19:46:37 +00001292 if (exprType->isVoidType()) {
Chris Lattner3b054132008-11-19 05:08:23 +00001293 Diag(OpLoc, diag::ext_sizeof_void_type)
1294 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattnerb1355b12009-01-24 19:46:37 +00001295 return false;
1296 }
Mike Stump11289f42009-09-09 15:08:12 +00001297
Chris Lattner62975a72009-04-24 00:30:45 +00001298 if (RequireCompleteType(OpLoc, exprType,
Mike Stump11289f42009-09-09 15:08:12 +00001299 isSizeof ? diag::err_sizeof_incomplete_type :
Anders Carlssond624e162009-08-26 23:45:07 +00001300 PDiag(diag::err_alignof_incomplete_type)
1301 << ExprRange))
Chris Lattner62975a72009-04-24 00:30:45 +00001302 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001303
Chris Lattner62975a72009-04-24 00:30:45 +00001304 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
Fariborz Jahanian1dcb3222009-04-24 17:34:33 +00001305 if (LangOpts.ObjCNonFragileABI && exprType->isObjCInterfaceType()) {
Chris Lattner62975a72009-04-24 00:30:45 +00001306 Diag(OpLoc, diag::err_sizeof_nonfragile_interface)
Chris Lattnercd2a8c52009-04-24 22:30:50 +00001307 << exprType << isSizeof << ExprRange;
1308 return true;
Chris Lattner37920f52009-04-21 19:55:16 +00001309 }
Mike Stump11289f42009-09-09 15:08:12 +00001310
Chris Lattner62975a72009-04-24 00:30:45 +00001311 return false;
Steve Naroff043d45d2007-05-15 02:32:35 +00001312}
1313
Chris Lattner8dff0172009-01-24 20:17:12 +00001314bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
1315 const SourceRange &ExprRange) {
1316 E = E->IgnoreParens();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001317
Mike Stump11289f42009-09-09 15:08:12 +00001318 // alignof decl is always ok.
Chris Lattner8dff0172009-01-24 20:17:12 +00001319 if (isa<DeclRefExpr>(E))
1320 return false;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001321
1322 // Cannot know anything else if the expression is dependent.
1323 if (E->isTypeDependent())
1324 return false;
1325
Douglas Gregor71235ec2009-05-02 02:18:30 +00001326 if (E->getBitField()) {
1327 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
1328 return true;
Chris Lattner8dff0172009-01-24 20:17:12 +00001329 }
Douglas Gregor71235ec2009-05-02 02:18:30 +00001330
1331 // Alignment of a field access is always okay, so long as it isn't a
1332 // bit-field.
1333 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump212005c2009-07-22 18:58:19 +00001334 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor71235ec2009-05-02 02:18:30 +00001335 return false;
1336
Chris Lattner8dff0172009-01-24 20:17:12 +00001337 return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
1338}
1339
Douglas Gregor0950e412009-03-13 21:01:28 +00001340/// \brief Build a sizeof or alignof expression given a type operand.
Mike Stump11289f42009-09-09 15:08:12 +00001341Action::OwningExprResult
John McCall4c98fd82009-11-04 07:28:41 +00001342Sema::CreateSizeOfAlignOfExpr(DeclaratorInfo *DInfo,
1343 SourceLocation OpLoc,
Douglas Gregor0950e412009-03-13 21:01:28 +00001344 bool isSizeOf, SourceRange R) {
John McCall4c98fd82009-11-04 07:28:41 +00001345 if (!DInfo)
Douglas Gregor0950e412009-03-13 21:01:28 +00001346 return ExprError();
1347
John McCall4c98fd82009-11-04 07:28:41 +00001348 QualType T = DInfo->getType();
1349
Douglas Gregor0950e412009-03-13 21:01:28 +00001350 if (!T->isDependentType() &&
1351 CheckSizeOfAlignOfOperand(T, OpLoc, R, isSizeOf))
1352 return ExprError();
1353
1354 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
John McCall4c98fd82009-11-04 07:28:41 +00001355 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, DInfo,
Douglas Gregor0950e412009-03-13 21:01:28 +00001356 Context.getSizeType(), OpLoc,
1357 R.getEnd()));
1358}
1359
1360/// \brief Build a sizeof or alignof expression given an expression
1361/// operand.
Mike Stump11289f42009-09-09 15:08:12 +00001362Action::OwningExprResult
1363Sema::CreateSizeOfAlignOfExpr(Expr *E, SourceLocation OpLoc,
Douglas Gregor0950e412009-03-13 21:01:28 +00001364 bool isSizeOf, SourceRange R) {
1365 // Verify that the operand is valid.
1366 bool isInvalid = false;
1367 if (E->isTypeDependent()) {
1368 // Delay type-checking for type-dependent expressions.
1369 } else if (!isSizeOf) {
1370 isInvalid = CheckAlignOfExpr(E, OpLoc, R);
Douglas Gregor71235ec2009-05-02 02:18:30 +00001371 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Douglas Gregor0950e412009-03-13 21:01:28 +00001372 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
1373 isInvalid = true;
1374 } else {
1375 isInvalid = CheckSizeOfAlignOfOperand(E->getType(), OpLoc, R, true);
1376 }
1377
1378 if (isInvalid)
1379 return ExprError();
1380
1381 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1382 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, E,
1383 Context.getSizeType(), OpLoc,
1384 R.getEnd()));
1385}
1386
Sebastian Redl6f282892008-11-11 17:56:53 +00001387/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1388/// the same for @c alignof and @c __alignof
1389/// Note that the ArgRange is invalid if isType is false.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001390Action::OwningExprResult
Sebastian Redl6f282892008-11-11 17:56:53 +00001391Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1392 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner0d8b1a12006-11-20 04:34:45 +00001393 // If error parsing type, ignore.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001394 if (TyOrEx == 0) return ExprError();
Steve Naroff043d45d2007-05-15 02:32:35 +00001395
Sebastian Redl6f282892008-11-11 17:56:53 +00001396 if (isType) {
John McCall4c98fd82009-11-04 07:28:41 +00001397 DeclaratorInfo *DInfo;
1398 (void) GetTypeFromParser(TyOrEx, &DInfo);
1399 return CreateSizeOfAlignOfExpr(DInfo, OpLoc, isSizeof, ArgRange);
Mike Stump11289f42009-09-09 15:08:12 +00001400 }
Sebastian Redl6f282892008-11-11 17:56:53 +00001401
Douglas Gregor0950e412009-03-13 21:01:28 +00001402 Expr *ArgEx = (Expr *)TyOrEx;
1403 Action::OwningExprResult Result
1404 = CreateSizeOfAlignOfExpr(ArgEx, OpLoc, isSizeof, ArgEx->getSourceRange());
1405
1406 if (Result.isInvalid())
1407 DeleteExpr(ArgEx);
1408
1409 return move(Result);
Chris Lattnere168f762006-11-10 05:29:30 +00001410}
1411
Chris Lattner709322b2009-02-17 08:12:06 +00001412QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc, bool isReal) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001413 if (V->isTypeDependent())
1414 return Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00001415
Chris Lattnere267f5d2007-08-26 05:39:26 +00001416 // These operators return the element type of a complex type.
John McCall9dd450b2009-09-21 23:43:11 +00001417 if (const ComplexType *CT = V->getType()->getAs<ComplexType>())
Chris Lattner30b5dd02007-08-24 21:16:53 +00001418 return CT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00001419
Chris Lattnere267f5d2007-08-26 05:39:26 +00001420 // Otherwise they pass through real integer and floating point types here.
1421 if (V->getType()->isArithmeticType())
1422 return V->getType();
Mike Stump11289f42009-09-09 15:08:12 +00001423
Chris Lattnere267f5d2007-08-26 05:39:26 +00001424 // Reject anything else.
Chris Lattner709322b2009-02-17 08:12:06 +00001425 Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
1426 << (isReal ? "__real" : "__imag");
Chris Lattnere267f5d2007-08-26 05:39:26 +00001427 return QualType();
Chris Lattner30b5dd02007-08-24 21:16:53 +00001428}
1429
1430
Chris Lattnere168f762006-11-10 05:29:30 +00001431
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001432Action::OwningExprResult
1433Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
1434 tok::TokenKind Kind, ExprArg Input) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00001435 // Since this might be a postfix expression, get rid of ParenListExprs.
1436 Input = MaybeConvertParenListExprToParenExpr(S, move(Input));
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001437 Expr *Arg = (Expr *)Input.get();
Douglas Gregord08452f2008-11-19 15:42:04 +00001438
Chris Lattnere168f762006-11-10 05:29:30 +00001439 UnaryOperator::Opcode Opc;
1440 switch (Kind) {
1441 default: assert(0 && "Unknown unary op!");
1442 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
1443 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1444 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001445
Douglas Gregord08452f2008-11-19 15:42:04 +00001446 if (getLangOptions().CPlusPlus &&
1447 (Arg->getType()->isRecordType() || Arg->getType()->isEnumeralType())) {
1448 // Which overloaded operator?
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001449 OverloadedOperatorKind OverOp =
Douglas Gregord08452f2008-11-19 15:42:04 +00001450 (Opc == UnaryOperator::PostInc)? OO_PlusPlus : OO_MinusMinus;
1451
1452 // C++ [over.inc]p1:
1453 //
1454 // [...] If the function is a member function with one
1455 // parameter (which shall be of type int) or a non-member
1456 // function with two parameters (the second of which shall be
1457 // of type int), it defines the postfix increment operator ++
1458 // for objects of that type. When the postfix increment is
1459 // called as a result of using the ++ operator, the int
1460 // argument will have value zero.
Mike Stump11289f42009-09-09 15:08:12 +00001461 Expr *Args[2] = {
1462 Arg,
1463 new (Context) IntegerLiteral(llvm::APInt(Context.Target.getIntWidth(), 0,
Steve Narofff6009ed2009-01-21 00:14:39 +00001464 /*isSigned=*/true), Context.IntTy, SourceLocation())
Douglas Gregord08452f2008-11-19 15:42:04 +00001465 };
1466
1467 // Build the candidate set for overloading
1468 OverloadCandidateSet CandidateSet;
Douglas Gregor1baf54e2009-03-13 18:40:31 +00001469 AddOperatorCandidates(OverOp, S, OpLoc, Args, 2, CandidateSet);
Douglas Gregord08452f2008-11-19 15:42:04 +00001470
1471 // Perform overload resolution.
1472 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00001473 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregord08452f2008-11-19 15:42:04 +00001474 case OR_Success: {
1475 // We found a built-in operator or an overloaded operator.
1476 FunctionDecl *FnDecl = Best->Function;
1477
1478 if (FnDecl) {
1479 // We matched an overloaded operator. Build a call to that
1480 // operator.
1481
1482 // Convert the arguments.
1483 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1484 if (PerformObjectArgumentInitialization(Arg, Method))
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001485 return ExprError();
Douglas Gregord08452f2008-11-19 15:42:04 +00001486 } else {
1487 // Convert the arguments.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001488 if (PerformCopyInitialization(Arg,
Douglas Gregord08452f2008-11-19 15:42:04 +00001489 FnDecl->getParamDecl(0)->getType(),
1490 "passing"))
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001491 return ExprError();
Douglas Gregord08452f2008-11-19 15:42:04 +00001492 }
1493
1494 // Determine the result type
Anders Carlsson3d5829c2009-10-13 21:49:31 +00001495 QualType ResultTy = FnDecl->getResultType().getNonReferenceType();
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001496
Douglas Gregord08452f2008-11-19 15:42:04 +00001497 // Build the actual expression node.
Steve Narofff6009ed2009-01-21 00:14:39 +00001498 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Mike Stump82191d02009-02-19 02:54:59 +00001499 SourceLocation());
Douglas Gregord08452f2008-11-19 15:42:04 +00001500 UsualUnaryConversions(FnExpr);
1501
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001502 Input.release();
Douglas Gregor2517f332009-05-27 05:00:47 +00001503 Args[0] = Arg;
Anders Carlsson3d5829c2009-10-13 21:49:31 +00001504
1505 ExprOwningPtr<CXXOperatorCallExpr>
1506 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OverOp,
1507 FnExpr, Args, 2,
1508 ResultTy, OpLoc));
1509
1510 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
1511 FnDecl))
1512 return ExprError();
Anders Carlsson834facc2009-10-13 22:22:09 +00001513 return Owned(TheCall.release());
1514
Douglas Gregord08452f2008-11-19 15:42:04 +00001515 } else {
1516 // We matched a built-in operator. Convert the arguments, then
1517 // break out so that we will build the appropriate built-in
1518 // operator node.
1519 if (PerformCopyInitialization(Arg, Best->BuiltinTypes.ParamTypes[0],
1520 "passing"))
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001521 return ExprError();
Douglas Gregord08452f2008-11-19 15:42:04 +00001522
1523 break;
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001524 }
Douglas Gregord08452f2008-11-19 15:42:04 +00001525 }
1526
Douglas Gregor66950a32009-09-30 21:46:01 +00001527 case OR_No_Viable_Function: {
1528 // No viable function; try checking this as a built-in operator, which
1529 // will fail and provide a diagnostic. Then, print the overload
1530 // candidates.
1531 OwningExprResult Result = CreateBuiltinUnaryOp(OpLoc, Opc, move(Input));
1532 assert(Result.isInvalid() &&
1533 "C++ postfix-unary operator overloading is missing candidates!");
1534 if (Result.isInvalid())
1535 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
1536
1537 return move(Result);
1538 }
1539
Douglas Gregord08452f2008-11-19 15:42:04 +00001540 case OR_Ambiguous:
1541 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
1542 << UnaryOperator::getOpcodeStr(Opc)
1543 << Arg->getSourceRange();
1544 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001545 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00001546
1547 case OR_Deleted:
1548 Diag(OpLoc, diag::err_ovl_deleted_oper)
1549 << Best->Function->isDeleted()
1550 << UnaryOperator::getOpcodeStr(Opc)
1551 << Arg->getSourceRange();
1552 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1553 return ExprError();
Douglas Gregord08452f2008-11-19 15:42:04 +00001554 }
1555
1556 // Either we found no viable overloaded operator or we matched a
1557 // built-in operator. In either case, fall through to trying to
1558 // build a built-in operation.
1559 }
1560
Eli Friedmanf32f0a72009-07-22 23:24:42 +00001561 Input.release();
1562 Input = Arg;
Eli Friedman6aea5752009-07-22 22:25:00 +00001563 return CreateBuiltinUnaryOp(OpLoc, Opc, move(Input));
Chris Lattnere168f762006-11-10 05:29:30 +00001564}
1565
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001566Action::OwningExprResult
1567Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
1568 ExprArg Idx, SourceLocation RLoc) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00001569 // Since this might be a postfix expression, get rid of ParenListExprs.
1570 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
1571
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001572 Expr *LHSExp = static_cast<Expr*>(Base.get()),
1573 *RHSExp = static_cast<Expr*>(Idx.get());
Mike Stump11289f42009-09-09 15:08:12 +00001574
Douglas Gregor40412ac2008-11-19 17:17:41 +00001575 if (getLangOptions().CPlusPlus &&
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00001576 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
1577 Base.release();
1578 Idx.release();
1579 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
1580 Context.DependentTy, RLoc));
1581 }
1582
Mike Stump11289f42009-09-09 15:08:12 +00001583 if (getLangOptions().CPlusPlus &&
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001584 (LHSExp->getType()->isRecordType() ||
Eli Friedman254a1a22008-12-15 22:34:21 +00001585 LHSExp->getType()->isEnumeralType() ||
1586 RHSExp->getType()->isRecordType() ||
1587 RHSExp->getType()->isEnumeralType())) {
Sebastian Redladba46e2009-10-29 20:17:01 +00001588 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, move(Base),move(Idx));
Douglas Gregor40412ac2008-11-19 17:17:41 +00001589 }
1590
Sebastian Redladba46e2009-10-29 20:17:01 +00001591 return CreateBuiltinArraySubscriptExpr(move(Base), LLoc, move(Idx), RLoc);
1592}
1593
1594
1595Action::OwningExprResult
1596Sema::CreateBuiltinArraySubscriptExpr(ExprArg Base, SourceLocation LLoc,
1597 ExprArg Idx, SourceLocation RLoc) {
1598 Expr *LHSExp = static_cast<Expr*>(Base.get());
1599 Expr *RHSExp = static_cast<Expr*>(Idx.get());
1600
Chris Lattner36d572b2007-07-16 00:14:47 +00001601 // Perform default conversions.
1602 DefaultFunctionArrayConversion(LHSExp);
1603 DefaultFunctionArrayConversion(RHSExp);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001604
Chris Lattner36d572b2007-07-16 00:14:47 +00001605 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
Steve Narofff1e53692007-03-23 22:27:02 +00001606
Steve Naroffc1aadb12007-03-28 21:49:40 +00001607 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattnerf17bd422007-08-30 17:45:32 +00001608 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stump4e1f26a2009-02-19 03:04:26 +00001609 // in the subscript position. As a result, we need to derive the array base
Steve Narofff1e53692007-03-23 22:27:02 +00001610 // and index from the expression types.
Chris Lattner36d572b2007-07-16 00:14:47 +00001611 Expr *BaseExpr, *IndexExpr;
1612 QualType ResultType;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001613 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
1614 BaseExpr = LHSExp;
1615 IndexExpr = RHSExp;
1616 ResultType = Context.DependentTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001617 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner36d572b2007-07-16 00:14:47 +00001618 BaseExpr = LHSExp;
1619 IndexExpr = RHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00001620 ResultType = PTy->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001621 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattneraee0cfd2007-07-16 00:23:25 +00001622 // Handle the uncommon case of "123[Ptr]".
Chris Lattner36d572b2007-07-16 00:14:47 +00001623 BaseExpr = RHSExp;
1624 IndexExpr = LHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00001625 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00001626 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00001627 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001628 BaseExpr = LHSExp;
1629 IndexExpr = RHSExp;
1630 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00001631 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00001632 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001633 // Handle the uncommon case of "123[Ptr]".
1634 BaseExpr = RHSExp;
1635 IndexExpr = LHSExp;
1636 ResultType = PTy->getPointeeType();
John McCall9dd450b2009-09-21 23:43:11 +00001637 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattner41977962007-07-31 19:29:30 +00001638 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner36d572b2007-07-16 00:14:47 +00001639 IndexExpr = RHSExp;
Nate Begemanc1bf0612009-01-18 00:45:31 +00001640
Chris Lattner36d572b2007-07-16 00:14:47 +00001641 // FIXME: need to deal with const...
1642 ResultType = VTy->getElementType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00001643 } else if (LHSTy->isArrayType()) {
1644 // If we see an array that wasn't promoted by
1645 // DefaultFunctionArrayConversion, it must be an array that
1646 // wasn't promoted because of the C90 rule that doesn't
1647 // allow promoting non-lvalue arrays. Warn, then
1648 // force the promotion here.
1649 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
1650 LHSExp->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00001651 ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
1652 CastExpr::CK_ArrayToPointerDecay);
Eli Friedmanab2784f2009-04-25 23:46:54 +00001653 LHSTy = LHSExp->getType();
1654
1655 BaseExpr = LHSExp;
1656 IndexExpr = RHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001657 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00001658 } else if (RHSTy->isArrayType()) {
1659 // Same as previous, except for 123[f().a] case
1660 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
1661 RHSExp->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00001662 ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
1663 CastExpr::CK_ArrayToPointerDecay);
Eli Friedmanab2784f2009-04-25 23:46:54 +00001664 RHSTy = RHSExp->getType();
1665
1666 BaseExpr = RHSExp;
1667 IndexExpr = LHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001668 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroffb3096442007-06-09 03:47:53 +00001669 } else {
Chris Lattner003af242009-04-25 22:50:55 +00001670 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
1671 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001672 }
Steve Naroffc1aadb12007-03-28 21:49:40 +00001673 // C99 6.5.2.1p1
Nate Begeman5ec4b312009-08-10 23:49:36 +00001674 if (!(IndexExpr->getType()->isIntegerType() &&
1675 IndexExpr->getType()->isScalarType()) && !IndexExpr->isTypeDependent())
Chris Lattner003af242009-04-25 22:50:55 +00001676 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
1677 << IndexExpr->getSourceRange());
Steve Naroffb29cdd52007-07-10 18:23:31 +00001678
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00001679 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinigb7608d72009-09-14 20:14:57 +00001680 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
1681 && !IndexExpr->isTypeDependent())
Sam Weinig914244e2009-09-14 01:58:58 +00001682 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
1683
Douglas Gregorac1fb652009-03-24 19:52:54 +00001684 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump11289f42009-09-09 15:08:12 +00001685 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
1686 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregorac1fb652009-03-24 19:52:54 +00001687 // incomplete types are not object types.
1688 if (ResultType->isFunctionType()) {
1689 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
1690 << ResultType << BaseExpr->getSourceRange();
1691 return ExprError();
1692 }
Mike Stump11289f42009-09-09 15:08:12 +00001693
Douglas Gregorac1fb652009-03-24 19:52:54 +00001694 if (!ResultType->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00001695 RequireCompleteType(LLoc, ResultType,
Anders Carlssond624e162009-08-26 23:45:07 +00001696 PDiag(diag::err_subscript_incomplete_type)
1697 << BaseExpr->getSourceRange()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00001698 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001699
Chris Lattner62975a72009-04-24 00:30:45 +00001700 // Diagnose bad cases where we step over interface counts.
1701 if (ResultType->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
1702 Diag(LLoc, diag::err_subscript_nonfragile_interface)
1703 << ResultType << BaseExpr->getSourceRange();
1704 return ExprError();
1705 }
Mike Stump11289f42009-09-09 15:08:12 +00001706
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001707 Base.release();
1708 Idx.release();
Mike Stump4e1f26a2009-02-19 03:04:26 +00001709 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
Steve Narofff6009ed2009-01-21 00:14:39 +00001710 ResultType, RLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00001711}
1712
Steve Narofff8fd09e2007-07-27 22:15:19 +00001713QualType Sema::
Nate Begemance4d7fc2008-04-18 23:10:10 +00001714CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001715 const IdentifierInfo *CompName,
Anders Carlssonf571c112009-08-26 18:25:21 +00001716 SourceLocation CompLoc) {
Daniel Dunbarc0429402009-10-18 02:09:38 +00001717 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
1718 // see FIXME there.
1719 //
1720 // FIXME: This logic can be greatly simplified by splitting it along
1721 // halving/not halving and reworking the component checking.
John McCall9dd450b2009-09-21 23:43:11 +00001722 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
Nate Begemanf322eab2008-05-09 06:41:27 +00001723
Steve Narofff8fd09e2007-07-27 22:15:19 +00001724 // The vector accessor can't exceed the number of elements.
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00001725 const char *compStr = CompName->getNameStart();
Nate Begemanbb70bf62009-01-18 01:47:54 +00001726
Mike Stump4e1f26a2009-02-19 03:04:26 +00001727 // This flag determines whether or not the component is one of the four
Nate Begemanbb70bf62009-01-18 01:47:54 +00001728 // special names that indicate a subset of exactly half the elements are
1729 // to be selected.
1730 bool HalvingSwizzle = false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00001731
Nate Begemanbb70bf62009-01-18 01:47:54 +00001732 // This flag determines whether or not CompName has an 's' char prefix,
1733 // indicating that it is a string of hex values to be used as vector indices.
Nate Begeman0359e122009-06-25 21:06:09 +00001734 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
Nate Begemanf322eab2008-05-09 06:41:27 +00001735
1736 // Check that we've found one of the special components, or that the component
1737 // names must come from the same set.
Mike Stump4e1f26a2009-02-19 03:04:26 +00001738 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begemanbb70bf62009-01-18 01:47:54 +00001739 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
1740 HalvingSwizzle = true;
Nate Begemanf322eab2008-05-09 06:41:27 +00001741 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner7e152db2007-08-02 22:33:49 +00001742 do
1743 compStr++;
1744 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
Nate Begemanbb70bf62009-01-18 01:47:54 +00001745 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
Chris Lattner7e152db2007-08-02 22:33:49 +00001746 do
1747 compStr++;
Nate Begemanbb70bf62009-01-18 01:47:54 +00001748 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
Chris Lattner7e152db2007-08-02 22:33:49 +00001749 }
Nate Begemanbb70bf62009-01-18 01:47:54 +00001750
Mike Stump4e1f26a2009-02-19 03:04:26 +00001751 if (!HalvingSwizzle && *compStr) {
Steve Narofff8fd09e2007-07-27 22:15:19 +00001752 // We didn't get to the end of the string. This means the component names
1753 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattner3b054132008-11-19 05:08:23 +00001754 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
1755 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Narofff8fd09e2007-07-27 22:15:19 +00001756 return QualType();
1757 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00001758
Nate Begemanbb70bf62009-01-18 01:47:54 +00001759 // Ensure no component accessor exceeds the width of the vector type it
1760 // operates on.
1761 if (!HalvingSwizzle) {
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00001762 compStr = CompName->getNameStart();
Nate Begemanbb70bf62009-01-18 01:47:54 +00001763
1764 if (HexSwizzle)
Steve Narofff8fd09e2007-07-27 22:15:19 +00001765 compStr++;
Nate Begemanbb70bf62009-01-18 01:47:54 +00001766
1767 while (*compStr) {
1768 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
1769 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
1770 << baseType << SourceRange(CompLoc);
1771 return QualType();
1772 }
1773 }
Steve Narofff8fd09e2007-07-27 22:15:19 +00001774 }
Nate Begemanf322eab2008-05-09 06:41:27 +00001775
Nate Begemanbb70bf62009-01-18 01:47:54 +00001776 // If this is a halving swizzle, verify that the base type has an even
1777 // number of elements.
1778 if (HalvingSwizzle && (vecType->getNumElements() & 1U)) {
Chris Lattner3b054132008-11-19 05:08:23 +00001779 Diag(OpLoc, diag::err_ext_vector_component_requires_even)
Chris Lattner1e5665e2008-11-24 06:25:27 +00001780 << baseType << SourceRange(CompLoc);
Nate Begemanf322eab2008-05-09 06:41:27 +00001781 return QualType();
1782 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00001783
Steve Narofff8fd09e2007-07-27 22:15:19 +00001784 // The component accessor looks fine - now we need to compute the actual type.
Mike Stump4e1f26a2009-02-19 03:04:26 +00001785 // The vector type is implied by the component accessor. For example,
Steve Narofff8fd09e2007-07-27 22:15:19 +00001786 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begemanbb70bf62009-01-18 01:47:54 +00001787 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begemanf322eab2008-05-09 06:41:27 +00001788 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begemanbb70bf62009-01-18 01:47:54 +00001789 unsigned CompSize = HalvingSwizzle ? vecType->getNumElements() / 2
Anders Carlssonf571c112009-08-26 18:25:21 +00001790 : CompName->getLength();
Nate Begemanbb70bf62009-01-18 01:47:54 +00001791 if (HexSwizzle)
1792 CompSize--;
1793
Steve Narofff8fd09e2007-07-27 22:15:19 +00001794 if (CompSize == 1)
1795 return vecType->getElementType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00001796
Nate Begemance4d7fc2008-04-18 23:10:10 +00001797 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stump4e1f26a2009-02-19 03:04:26 +00001798 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemance4d7fc2008-04-18 23:10:10 +00001799 // diagostics look bad. We want extended vector types to appear built-in.
1800 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
1801 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
1802 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroffddf5a1d2007-07-29 16:33:31 +00001803 }
1804 return VT; // should never get here (a typedef type should always be found).
Steve Narofff8fd09e2007-07-27 22:15:19 +00001805}
1806
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00001807static Decl *FindGetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
Anders Carlssonf571c112009-08-26 18:25:21 +00001808 IdentifierInfo *Member,
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001809 const Selector &Sel,
1810 ASTContext &Context) {
Mike Stump11289f42009-09-09 15:08:12 +00001811
Anders Carlssonf571c112009-08-26 18:25:21 +00001812 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00001813 return PD;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001814 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00001815 return OMD;
Mike Stump11289f42009-09-09 15:08:12 +00001816
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00001817 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
1818 E = PDecl->protocol_end(); I != E; ++I) {
Mike Stump11289f42009-09-09 15:08:12 +00001819 if (Decl *D = FindGetterNameDeclFromProtocolList(*I, Member, Sel,
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001820 Context))
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00001821 return D;
1822 }
1823 return 0;
1824}
1825
Steve Narofffb4330f2009-06-17 22:40:22 +00001826static Decl *FindGetterNameDecl(const ObjCObjectPointerType *QIdTy,
Anders Carlssonf571c112009-08-26 18:25:21 +00001827 IdentifierInfo *Member,
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001828 const Selector &Sel,
1829 ASTContext &Context) {
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00001830 // Check protocols on qualified interfaces.
1831 Decl *GDecl = 0;
Steve Narofffb4330f2009-06-17 22:40:22 +00001832 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00001833 E = QIdTy->qual_end(); I != E; ++I) {
Anders Carlssonf571c112009-08-26 18:25:21 +00001834 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00001835 GDecl = PD;
1836 break;
1837 }
1838 // Also must look for a getter name which uses property syntax.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001839 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00001840 GDecl = OMD;
1841 break;
1842 }
1843 }
1844 if (!GDecl) {
Steve Narofffb4330f2009-06-17 22:40:22 +00001845 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00001846 E = QIdTy->qual_end(); I != E; ++I) {
1847 // Search in the protocol-qualifier list of current protocol.
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001848 GDecl = FindGetterNameDeclFromProtocolList(*I, Member, Sel, Context);
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00001849 if (GDecl)
1850 return GDecl;
1851 }
1852 }
1853 return GDecl;
1854}
Chris Lattner4bf74fd2009-02-15 22:43:40 +00001855
Mike Stump11289f42009-09-09 15:08:12 +00001856Action::OwningExprResult
Anders Carlssonf571c112009-08-26 18:25:21 +00001857Sema::BuildMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc,
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001858 tok::TokenKind OpKind, SourceLocation MemberLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001859 DeclarationName MemberName,
Douglas Gregor84f14dd2009-09-01 00:37:14 +00001860 bool HasExplicitTemplateArgs,
1861 SourceLocation LAngleLoc,
John McCall0ad16662009-10-29 08:12:44 +00001862 const TemplateArgumentLoc *ExplicitTemplateArgs,
Douglas Gregor84f14dd2009-09-01 00:37:14 +00001863 unsigned NumExplicitTemplateArgs,
1864 SourceLocation RAngleLoc,
Douglas Gregor2b6ca462009-09-03 21:38:09 +00001865 DeclPtrTy ObjCImpDecl, const CXXScopeSpec *SS,
1866 NamedDecl *FirstQualifierInScope) {
Douglas Gregord8061562009-08-06 03:17:00 +00001867 if (SS && SS->isInvalid())
1868 return ExprError();
1869
Nate Begeman5ec4b312009-08-10 23:49:36 +00001870 // Since this might be a postfix expression, get rid of ParenListExprs.
1871 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
1872
Anders Carlsson3cbc8592009-05-01 19:30:39 +00001873 Expr *BaseExpr = Base.takeAs<Expr>();
Douglas Gregorad8a3362009-09-04 17:36:40 +00001874 assert(BaseExpr && "no base expression");
Mike Stump11289f42009-09-09 15:08:12 +00001875
Steve Naroffeaaae462007-12-16 21:42:28 +00001876 // Perform default conversions.
1877 DefaultFunctionArrayConversion(BaseExpr);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001878
Steve Naroff185616f2007-07-26 03:11:44 +00001879 QualType BaseType = BaseExpr->getType();
Douglas Gregord82ae382009-11-06 06:30:47 +00001880
1881 // If the user is trying to apply -> or . to a function pointer
1882 // type, it's probably because the forgot parentheses to call that
1883 // function. Suggest the addition of those parentheses, build the
1884 // call, and continue on.
1885 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
1886 if (const FunctionProtoType *Fun
1887 = Ptr->getPointeeType()->getAs<FunctionProtoType>()) {
1888 QualType ResultTy = Fun->getResultType();
1889 if (Fun->getNumArgs() == 0 &&
1890 ((OpKind == tok::period && ResultTy->isRecordType()) ||
1891 (OpKind == tok::arrow && ResultTy->isPointerType() &&
1892 ResultTy->getAs<PointerType>()->getPointeeType()
1893 ->isRecordType()))) {
1894 SourceLocation Loc = PP.getLocForEndOfToken(BaseExpr->getLocEnd());
1895 Diag(Loc, diag::err_member_reference_needs_call)
1896 << QualType(Fun, 0)
1897 << CodeModificationHint::CreateInsertion(Loc, "()");
1898
1899 OwningExprResult NewBase
1900 = ActOnCallExpr(S, ExprArg(*this, BaseExpr), Loc,
1901 MultiExprArg(*this, 0, 0), 0, Loc);
1902 if (NewBase.isInvalid())
1903 return move(NewBase);
1904
1905 BaseExpr = NewBase.takeAs<Expr>();
1906 DefaultFunctionArrayConversion(BaseExpr);
1907 BaseType = BaseExpr->getType();
1908 }
1909 }
1910 }
1911
David Chisnall9f57c292009-08-17 16:35:33 +00001912 // If this is an Objective-C pseudo-builtin and a definition is provided then
1913 // use that.
1914 if (BaseType->isObjCIdType()) {
1915 // We have an 'id' type. Rather than fall through, we check if this
1916 // is a reference to 'isa'.
1917 if (BaseType != Context.ObjCIdRedefinitionType) {
1918 BaseType = Context.ObjCIdRedefinitionType;
Eli Friedman06ed2a52009-10-20 08:27:19 +00001919 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
David Chisnall9f57c292009-08-17 16:35:33 +00001920 }
David Chisnall9f57c292009-08-17 16:35:33 +00001921 }
Steve Naroff185616f2007-07-26 03:11:44 +00001922 assert(!BaseType.isNull() && "no type for member expression");
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001923
Fariborz Jahaniane983d172009-09-22 16:48:37 +00001924 // Handle properties on ObjC 'Class' types.
1925 if (OpKind == tok::period && BaseType->isObjCClassType()) {
1926 // Also must look for a getter name which uses property syntax.
1927 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1928 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
1929 if (ObjCMethodDecl *MD = getCurMethodDecl()) {
1930 ObjCInterfaceDecl *IFace = MD->getClassInterface();
1931 ObjCMethodDecl *Getter;
1932 // FIXME: need to also look locally in the implementation.
1933 if ((Getter = IFace->lookupClassMethod(Sel))) {
1934 // Check the use of this method.
1935 if (DiagnoseUseOfDecl(Getter, MemberLoc))
1936 return ExprError();
1937 }
1938 // If we found a getter then this may be a valid dot-reference, we
1939 // will look for the matching setter, in case it is needed.
1940 Selector SetterSel =
1941 SelectorTable::constructSetterName(PP.getIdentifierTable(),
1942 PP.getSelectorTable(), Member);
1943 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
1944 if (!Setter) {
1945 // If this reference is in an @implementation, also check for 'private'
1946 // methods.
Steve Naroffbb69c942009-10-01 23:46:04 +00001947 Setter = IFace->lookupPrivateInstanceMethod(SetterSel);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00001948 }
1949 // Look through local category implementations associated with the class.
1950 if (!Setter)
1951 Setter = IFace->getCategoryClassMethod(SetterSel);
1952
1953 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
1954 return ExprError();
1955
1956 if (Getter || Setter) {
1957 QualType PType;
1958
1959 if (Getter)
1960 PType = Getter->getResultType();
1961 else
1962 // Get the expression type from Setter's incoming parameter.
1963 PType = (*(Setter->param_end() -1))->getType();
1964 // FIXME: we must check that the setter has property type.
1965 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter,
1966 PType,
1967 Setter, MemberLoc, BaseExpr));
1968 }
1969 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1970 << MemberName << BaseType);
1971 }
1972 }
1973
1974 if (BaseType->isObjCClassType() &&
1975 BaseType != Context.ObjCClassRedefinitionType) {
1976 BaseType = Context.ObjCClassRedefinitionType;
Eli Friedman06ed2a52009-10-20 08:27:19 +00001977 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00001978 }
1979
Chris Lattner4befd732008-07-21 04:36:39 +00001980 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
1981 // must have pointer type, and the accessed type is the pointee.
Steve Narofff1e53692007-03-23 22:27:02 +00001982 if (OpKind == tok::arrow) {
Douglas Gregor2b6ca462009-09-03 21:38:09 +00001983 if (BaseType->isDependentType()) {
1984 NestedNameSpecifier *Qualifier = 0;
1985 if (SS) {
1986 Qualifier = static_cast<NestedNameSpecifier *>(SS->getScopeRep());
1987 if (!FirstQualifierInScope)
1988 FirstQualifierInScope = FindFirstQualifierInScope(S, Qualifier);
1989 }
Mike Stump11289f42009-09-09 15:08:12 +00001990
1991 return Owned(CXXUnresolvedMemberExpr::Create(Context, BaseExpr, true,
Douglas Gregor308047d2009-09-09 00:23:06 +00001992 OpLoc, Qualifier,
Douglas Gregorc26e0f62009-09-03 16:14:30 +00001993 SS? SS->getRange() : SourceRange(),
Douglas Gregor308047d2009-09-09 00:23:06 +00001994 FirstQualifierInScope,
1995 MemberName,
1996 MemberLoc,
1997 HasExplicitTemplateArgs,
1998 LAngleLoc,
1999 ExplicitTemplateArgs,
2000 NumExplicitTemplateArgs,
2001 RAngleLoc));
Douglas Gregor2b6ca462009-09-03 21:38:09 +00002002 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002003 else if (const PointerType *PT = BaseType->getAs<PointerType>())
Steve Naroff185616f2007-07-26 03:11:44 +00002004 BaseType = PT->getPointeeType();
Steve Naroff7cae42b2009-07-10 23:34:53 +00002005 else if (BaseType->isObjCObjectPointerType())
2006 ;
Steve Naroff185616f2007-07-26 03:11:44 +00002007 else
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002008 return ExprError(Diag(MemberLoc,
2009 diag::err_typecheck_member_reference_arrow)
2010 << BaseType << BaseExpr->getSourceRange());
Fariborz Jahaniane983d172009-09-22 16:48:37 +00002011 } else if (BaseType->isDependentType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002012 // Require that the base type isn't a pointer type
Anders Carlsson524d5a42009-05-16 20:31:20 +00002013 // (so we'll report an error for)
2014 // T* t;
2015 // t.f;
Mike Stump11289f42009-09-09 15:08:12 +00002016 //
Anders Carlsson524d5a42009-05-16 20:31:20 +00002017 // In Obj-C++, however, the above expression is valid, since it could be
2018 // accessing the 'f' property if T is an Obj-C interface. The extra check
2019 // allows this, while still reporting an error if T is a struct pointer.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002020 const PointerType *PT = BaseType->getAs<PointerType>();
Anders Carlsson524d5a42009-05-16 20:31:20 +00002021
Mike Stump11289f42009-09-09 15:08:12 +00002022 if (!PT || (getLangOptions().ObjC1 &&
Douglas Gregor2b6ca462009-09-03 21:38:09 +00002023 !PT->getPointeeType()->isRecordType())) {
2024 NestedNameSpecifier *Qualifier = 0;
2025 if (SS) {
2026 Qualifier = static_cast<NestedNameSpecifier *>(SS->getScopeRep());
2027 if (!FirstQualifierInScope)
2028 FirstQualifierInScope = FindFirstQualifierInScope(S, Qualifier);
2029 }
Mike Stump11289f42009-09-09 15:08:12 +00002030
Douglas Gregor308047d2009-09-09 00:23:06 +00002031 return Owned(CXXUnresolvedMemberExpr::Create(Context,
Mike Stump11289f42009-09-09 15:08:12 +00002032 BaseExpr, false,
2033 OpLoc,
Douglas Gregor308047d2009-09-09 00:23:06 +00002034 Qualifier,
Douglas Gregorc26e0f62009-09-03 16:14:30 +00002035 SS? SS->getRange() : SourceRange(),
Douglas Gregor308047d2009-09-09 00:23:06 +00002036 FirstQualifierInScope,
2037 MemberName,
2038 MemberLoc,
2039 HasExplicitTemplateArgs,
2040 LAngleLoc,
2041 ExplicitTemplateArgs,
2042 NumExplicitTemplateArgs,
2043 RAngleLoc));
Douglas Gregor2b6ca462009-09-03 21:38:09 +00002044 }
Anders Carlsson524d5a42009-05-16 20:31:20 +00002045 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002046
Chris Lattner4befd732008-07-21 04:36:39 +00002047 // Handle field access to simple records. This also handles access to fields
2048 // of the ObjC 'id' struct.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002049 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
Steve Naroff185616f2007-07-26 03:11:44 +00002050 RecordDecl *RDecl = RTy->getDecl();
Douglas Gregored0cfbd2009-03-09 16:13:40 +00002051 if (RequireCompleteType(OpLoc, BaseType,
Anders Carlssond624e162009-08-26 23:45:07 +00002052 PDiag(diag::err_typecheck_incomplete_tag)
2053 << BaseExpr->getSourceRange()))
Douglas Gregordd430f72009-01-19 19:26:10 +00002054 return ExprError();
2055
Douglas Gregord8061562009-08-06 03:17:00 +00002056 DeclContext *DC = RDecl;
2057 if (SS && SS->isSet()) {
2058 // If the member name was a qualified-id, look into the
2059 // nested-name-specifier.
2060 DC = computeDeclContext(*SS, false);
Douglas Gregor0b3d95a2009-10-17 22:37:54 +00002061
2062 if (!isa<TypeDecl>(DC)) {
2063 Diag(MemberLoc, diag::err_qualified_member_nonclass)
2064 << DC << SS->getRange();
2065 return ExprError();
2066 }
Mike Stump11289f42009-09-09 15:08:12 +00002067
2068 // FIXME: If DC is not computable, we should build a
Douglas Gregord8061562009-08-06 03:17:00 +00002069 // CXXUnresolvedMemberExpr.
2070 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
2071 }
2072
Steve Naroff185616f2007-07-26 03:11:44 +00002073 // The record definition is complete, now make sure the member is valid.
John McCall27b18f82009-11-17 02:14:36 +00002074 LookupResult Result(*this, MemberName, MemberLoc, LookupMemberName);
2075 LookupQualifiedName(Result, DC);
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002076
John McCall9f3059a2009-10-09 21:13:30 +00002077 if (Result.empty())
Douglas Gregore40876a2009-10-13 21:16:44 +00002078 return ExprError(Diag(MemberLoc, diag::err_no_member)
2079 << MemberName << DC << BaseExpr->getSourceRange());
John McCall27b18f82009-11-17 02:14:36 +00002080 if (Result.isAmbiguous())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002081 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00002082
John McCall9f3059a2009-10-09 21:13:30 +00002083 NamedDecl *MemberDecl = Result.getAsSingleDecl(Context);
2084
Douglas Gregorc26e0f62009-09-03 16:14:30 +00002085 if (SS && SS->isSet()) {
John McCall9f3059a2009-10-09 21:13:30 +00002086 TypeDecl* TyD = cast<TypeDecl>(MemberDecl->getDeclContext());
Mike Stump11289f42009-09-09 15:08:12 +00002087 QualType BaseTypeCanon
Douglas Gregorc26e0f62009-09-03 16:14:30 +00002088 = Context.getCanonicalType(BaseType).getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00002089 QualType MemberTypeCanon
John McCall9f3059a2009-10-09 21:13:30 +00002090 = Context.getCanonicalType(Context.getTypeDeclType(TyD));
Mike Stump11289f42009-09-09 15:08:12 +00002091
Douglas Gregorc26e0f62009-09-03 16:14:30 +00002092 if (BaseTypeCanon != MemberTypeCanon &&
2093 !IsDerivedFrom(BaseTypeCanon, MemberTypeCanon))
2094 return ExprError(Diag(SS->getBeginLoc(),
2095 diag::err_not_direct_base_or_virtual)
2096 << MemberTypeCanon << BaseTypeCanon);
2097 }
Mike Stump11289f42009-09-09 15:08:12 +00002098
Chris Lattner303284a2009-02-13 22:08:30 +00002099 // If the decl being referenced had an error, return an error for this
2100 // sub-expr without emitting another error, in order to avoid cascading
2101 // error cases.
2102 if (MemberDecl->isInvalidDecl())
2103 return ExprError();
Mike Stump4e1f26a2009-02-19 03:04:26 +00002104
Anders Carlsson04e1e222009-09-10 20:48:14 +00002105 bool ShouldCheckUse = true;
2106 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
2107 // Don't diagnose the use of a virtual member function unless it's
2108 // explicitly qualified.
2109 if (MD->isVirtual() && (!SS || !SS->isSet()))
2110 ShouldCheckUse = false;
2111 }
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00002112
Douglas Gregor171c45a2009-02-18 21:56:37 +00002113 // Check the use of this field
Anders Carlsson04e1e222009-09-10 20:48:14 +00002114 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc))
Douglas Gregor171c45a2009-02-18 21:56:37 +00002115 return ExprError();
Chris Lattner303284a2009-02-13 22:08:30 +00002116
Douglas Gregor55297ac2008-12-23 00:26:44 +00002117 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002118 // We may have found a field within an anonymous union or struct
2119 // (C++ [class.union]).
2120 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002121 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002122 BaseExpr, OpLoc);
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002123
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00002124 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
Douglas Gregor55297ac2008-12-23 00:26:44 +00002125 QualType MemberType = FD->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002126 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>())
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00002127 MemberType = Ref->getPointeeType();
2128 else {
John McCall8ccfcb52009-09-24 19:53:00 +00002129 Qualifiers BaseQuals = BaseType.getQualifiers();
2130 BaseQuals.removeObjCGCAttr();
2131 if (FD->isMutable()) BaseQuals.removeConst();
2132
2133 Qualifiers MemberQuals
2134 = Context.getCanonicalType(MemberType).getQualifiers();
2135
2136 Qualifiers Combined = BaseQuals + MemberQuals;
2137 if (Combined != MemberQuals)
2138 MemberType = Context.getQualifiedType(MemberType, Combined);
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00002139 }
Eli Friedman1242fff2008-02-06 22:48:16 +00002140
Douglas Gregor77b50e12009-06-22 23:06:13 +00002141 MarkDeclarationReferenced(MemberLoc, FD);
Fariborz Jahanian3f150832009-07-29 19:40:11 +00002142 if (PerformObjectMemberConversion(BaseExpr, FD))
2143 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00002144 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
Douglas Gregorc1905232009-08-26 22:36:53 +00002145 FD, MemberLoc, MemberType));
Chris Lattnerfe4847e2009-03-31 08:18:48 +00002146 }
Mike Stump11289f42009-09-09 15:08:12 +00002147
Douglas Gregor77b50e12009-06-22 23:06:13 +00002148 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
2149 MarkDeclarationReferenced(MemberLoc, MemberDecl);
Douglas Gregorc1905232009-08-26 22:36:53 +00002150 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2151 Var, MemberLoc,
2152 Var->getType().getNonReferenceType()));
Douglas Gregor77b50e12009-06-22 23:06:13 +00002153 }
2154 if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl)) {
2155 MarkDeclarationReferenced(MemberLoc, MemberDecl);
Douglas Gregorc1905232009-08-26 22:36:53 +00002156 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2157 MemberFn, MemberLoc,
2158 MemberFn->getType()));
Douglas Gregor77b50e12009-06-22 23:06:13 +00002159 }
Mike Stump11289f42009-09-09 15:08:12 +00002160 if (FunctionTemplateDecl *FunTmpl
Douglas Gregor97628d62009-08-21 00:16:32 +00002161 = dyn_cast<FunctionTemplateDecl>(MemberDecl)) {
2162 MarkDeclarationReferenced(MemberLoc, MemberDecl);
Mike Stump11289f42009-09-09 15:08:12 +00002163
Douglas Gregor84f14dd2009-09-01 00:37:14 +00002164 if (HasExplicitTemplateArgs)
Mike Stump11289f42009-09-09 15:08:12 +00002165 return Owned(MemberExpr::Create(Context, BaseExpr, OpKind == tok::arrow,
2166 (NestedNameSpecifier *)(SS? SS->getScopeRep() : 0),
Douglas Gregor84f14dd2009-09-01 00:37:14 +00002167 SS? SS->getRange() : SourceRange(),
Mike Stump11289f42009-09-09 15:08:12 +00002168 FunTmpl, MemberLoc, true,
2169 LAngleLoc, ExplicitTemplateArgs,
2170 NumExplicitTemplateArgs, RAngleLoc,
Douglas Gregor84f14dd2009-09-01 00:37:14 +00002171 Context.OverloadTy));
Mike Stump11289f42009-09-09 15:08:12 +00002172
Douglas Gregorc1905232009-08-26 22:36:53 +00002173 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2174 FunTmpl, MemberLoc,
2175 Context.OverloadTy));
Douglas Gregor97628d62009-08-21 00:16:32 +00002176 }
Chris Lattnerfe4847e2009-03-31 08:18:48 +00002177 if (OverloadedFunctionDecl *Ovl
Douglas Gregor84f14dd2009-09-01 00:37:14 +00002178 = dyn_cast<OverloadedFunctionDecl>(MemberDecl)) {
2179 if (HasExplicitTemplateArgs)
Mike Stump11289f42009-09-09 15:08:12 +00002180 return Owned(MemberExpr::Create(Context, BaseExpr, OpKind == tok::arrow,
2181 (NestedNameSpecifier *)(SS? SS->getScopeRep() : 0),
Douglas Gregor84f14dd2009-09-01 00:37:14 +00002182 SS? SS->getRange() : SourceRange(),
Mike Stump11289f42009-09-09 15:08:12 +00002183 Ovl, MemberLoc, true,
2184 LAngleLoc, ExplicitTemplateArgs,
2185 NumExplicitTemplateArgs, RAngleLoc,
Douglas Gregor84f14dd2009-09-01 00:37:14 +00002186 Context.OverloadTy));
2187
Douglas Gregorc1905232009-08-26 22:36:53 +00002188 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2189 Ovl, MemberLoc, Context.OverloadTy));
Douglas Gregor84f14dd2009-09-01 00:37:14 +00002190 }
Douglas Gregor77b50e12009-06-22 23:06:13 +00002191 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
2192 MarkDeclarationReferenced(MemberLoc, MemberDecl);
Douglas Gregorc1905232009-08-26 22:36:53 +00002193 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2194 Enum, MemberLoc, Enum->getType()));
Douglas Gregor77b50e12009-06-22 23:06:13 +00002195 }
Chris Lattnerfe4847e2009-03-31 08:18:48 +00002196 if (isa<TypeDecl>(MemberDecl))
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002197 return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
Anders Carlssonf571c112009-08-26 18:25:21 +00002198 << MemberName << int(OpKind == tok::arrow));
Eli Friedman1242fff2008-02-06 22:48:16 +00002199
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00002200 // We found a declaration kind that we didn't expect. This is a
2201 // generic error message that tells the user that she can't refer
2202 // to this member with '.' or '->'.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002203 return ExprError(Diag(MemberLoc,
2204 diag::err_typecheck_member_reference_unknown)
Anders Carlssonf571c112009-08-26 18:25:21 +00002205 << MemberName << int(OpKind == tok::arrow));
Chris Lattnerb63a7452008-07-21 04:28:12 +00002206 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002207
Douglas Gregorad8a3362009-09-04 17:36:40 +00002208 // Handle pseudo-destructors (C++ [expr.pseudo]). Since anything referring
2209 // into a record type was handled above, any destructor we see here is a
2210 // pseudo-destructor.
2211 if (MemberName.getNameKind() == DeclarationName::CXXDestructorName) {
2212 // C++ [expr.pseudo]p2:
Mike Stump11289f42009-09-09 15:08:12 +00002213 // The left hand side of the dot operator shall be of scalar type. The
2214 // left hand side of the arrow operator shall be of pointer to scalar
Douglas Gregorad8a3362009-09-04 17:36:40 +00002215 // type.
2216 if (!BaseType->isScalarType())
2217 return Owned(Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
2218 << BaseType << BaseExpr->getSourceRange());
Mike Stump11289f42009-09-09 15:08:12 +00002219
Douglas Gregorad8a3362009-09-04 17:36:40 +00002220 // [...] The type designated by the pseudo-destructor-name shall be the
2221 // same as the object type.
2222 if (!MemberName.getCXXNameType()->isDependentType() &&
2223 !Context.hasSameUnqualifiedType(BaseType, MemberName.getCXXNameType()))
2224 return Owned(Diag(OpLoc, diag::err_pseudo_dtor_type_mismatch)
2225 << BaseType << MemberName.getCXXNameType()
2226 << BaseExpr->getSourceRange() << SourceRange(MemberLoc));
Mike Stump11289f42009-09-09 15:08:12 +00002227
2228 // [...] Furthermore, the two type-names in a pseudo-destructor-name of
Douglas Gregorad8a3362009-09-04 17:36:40 +00002229 // the form
2230 //
Mike Stump11289f42009-09-09 15:08:12 +00002231 // ::[opt] nested-name-specifier[opt] type-name :: ̃ type-name
2232 //
Douglas Gregorad8a3362009-09-04 17:36:40 +00002233 // shall designate the same scalar type.
2234 //
2235 // FIXME: DPG can't see any way to trigger this particular clause, so it
2236 // isn't checked here.
Mike Stump11289f42009-09-09 15:08:12 +00002237
Douglas Gregorad8a3362009-09-04 17:36:40 +00002238 // FIXME: We've lost the precise spelling of the type by going through
2239 // DeclarationName. Can we do better?
2240 return Owned(new (Context) CXXPseudoDestructorExpr(Context, BaseExpr,
Mike Stump11289f42009-09-09 15:08:12 +00002241 OpKind == tok::arrow,
Douglas Gregorad8a3362009-09-04 17:36:40 +00002242 OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00002243 (NestedNameSpecifier *)(SS? SS->getScopeRep() : 0),
Douglas Gregorad8a3362009-09-04 17:36:40 +00002244 SS? SS->getRange() : SourceRange(),
2245 MemberName.getCXXNameType(),
2246 MemberLoc));
2247 }
Mike Stump11289f42009-09-09 15:08:12 +00002248
Chris Lattnerdc420f42008-07-21 04:59:05 +00002249 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
2250 // (*Obj).ivar.
Steve Naroff7cae42b2009-07-10 23:34:53 +00002251 if ((OpKind == tok::arrow && BaseType->isObjCObjectPointerType()) ||
2252 (OpKind == tok::period && BaseType->isObjCInterfaceType())) {
John McCall9dd450b2009-09-21 23:43:11 +00002253 const ObjCObjectPointerType *OPT = BaseType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00002254 const ObjCInterfaceType *IFaceT =
John McCall9dd450b2009-09-21 23:43:11 +00002255 OPT ? OPT->getInterfaceType() : BaseType->getAs<ObjCInterfaceType>();
Steve Naroffa057ba92009-07-16 00:25:06 +00002256 if (IFaceT) {
Anders Carlssonf571c112009-08-26 18:25:21 +00002257 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
2258
Steve Naroffa057ba92009-07-16 00:25:06 +00002259 ObjCInterfaceDecl *IDecl = IFaceT->getDecl();
2260 ObjCInterfaceDecl *ClassDeclared;
Anders Carlssonf571c112009-08-26 18:25:21 +00002261 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
Mike Stump11289f42009-09-09 15:08:12 +00002262
Steve Naroffa057ba92009-07-16 00:25:06 +00002263 if (IV) {
2264 // If the decl being referenced had an error, return an error for this
2265 // sub-expr without emitting another error, in order to avoid cascading
2266 // error cases.
2267 if (IV->isInvalidDecl())
2268 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00002269
Steve Naroffa057ba92009-07-16 00:25:06 +00002270 // Check whether we can reference this field.
2271 if (DiagnoseUseOfDecl(IV, MemberLoc))
2272 return ExprError();
2273 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
2274 IV->getAccessControl() != ObjCIvarDecl::Package) {
2275 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
2276 if (ObjCMethodDecl *MD = getCurMethodDecl())
2277 ClassOfMethodDecl = MD->getClassInterface();
2278 else if (ObjCImpDecl && getCurFunctionDecl()) {
2279 // Case of a c-function declared inside an objc implementation.
2280 // FIXME: For a c-style function nested inside an objc implementation
2281 // class, there is no implementation context available, so we pass
2282 // down the context as argument to this routine. Ideally, this context
2283 // need be passed down in the AST node and somehow calculated from the
2284 // AST for a function decl.
2285 Decl *ImplDecl = ObjCImpDecl.getAs<Decl>();
Mike Stump11289f42009-09-09 15:08:12 +00002286 if (ObjCImplementationDecl *IMPD =
Steve Naroffa057ba92009-07-16 00:25:06 +00002287 dyn_cast<ObjCImplementationDecl>(ImplDecl))
2288 ClassOfMethodDecl = IMPD->getClassInterface();
2289 else if (ObjCCategoryImplDecl* CatImplClass =
2290 dyn_cast<ObjCCategoryImplDecl>(ImplDecl))
2291 ClassOfMethodDecl = CatImplClass->getClassInterface();
2292 }
Mike Stump11289f42009-09-09 15:08:12 +00002293
2294 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
2295 if (ClassDeclared != IDecl ||
Steve Naroffa057ba92009-07-16 00:25:06 +00002296 ClassOfMethodDecl != ClassDeclared)
Mike Stump11289f42009-09-09 15:08:12 +00002297 Diag(MemberLoc, diag::error_private_ivar_access)
Steve Naroffa057ba92009-07-16 00:25:06 +00002298 << IV->getDeclName();
Mike Stump12b8ce12009-08-04 21:02:39 +00002299 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
2300 // @protected
Mike Stump11289f42009-09-09 15:08:12 +00002301 Diag(MemberLoc, diag::error_protected_ivar_access)
Steve Naroffa057ba92009-07-16 00:25:06 +00002302 << IV->getDeclName();
Steve Naroffd1b64be2009-03-04 18:34:24 +00002303 }
Steve Naroffa057ba92009-07-16 00:25:06 +00002304
2305 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
2306 MemberLoc, BaseExpr,
2307 OpKind == tok::arrow));
Fariborz Jahaniana458c4f2009-03-03 01:21:12 +00002308 }
Steve Naroffa057ba92009-07-16 00:25:06 +00002309 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
Anders Carlssonf571c112009-08-26 18:25:21 +00002310 << IDecl->getDeclName() << MemberName
Steve Naroffa057ba92009-07-16 00:25:06 +00002311 << BaseExpr->getSourceRange());
Fariborz Jahanianb1378f92008-12-13 22:20:28 +00002312 }
Chris Lattnerb63a7452008-07-21 04:28:12 +00002313 }
Steve Naroff1329fa02009-07-15 18:40:39 +00002314 // Handle properties on 'id' and qualified "id".
Mike Stump11289f42009-09-09 15:08:12 +00002315 if (OpKind == tok::period && (BaseType->isObjCIdType() ||
Steve Naroff1329fa02009-07-15 18:40:39 +00002316 BaseType->isObjCQualifiedIdType())) {
John McCall9dd450b2009-09-21 23:43:11 +00002317 const ObjCObjectPointerType *QIdTy = BaseType->getAs<ObjCObjectPointerType>();
Anders Carlssonf571c112009-08-26 18:25:21 +00002318 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Mike Stump11289f42009-09-09 15:08:12 +00002319
Steve Naroff7cae42b2009-07-10 23:34:53 +00002320 // Check protocols on qualified interfaces.
Anders Carlssonf571c112009-08-26 18:25:21 +00002321 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002322 if (Decl *PMDecl = FindGetterNameDecl(QIdTy, Member, Sel, Context)) {
2323 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
2324 // Check the use of this declaration
2325 if (DiagnoseUseOfDecl(PD, MemberLoc))
2326 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00002327
Steve Naroff7cae42b2009-07-10 23:34:53 +00002328 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
2329 MemberLoc, BaseExpr));
2330 }
2331 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
2332 // Check the use of this method.
2333 if (DiagnoseUseOfDecl(OMD, MemberLoc))
2334 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00002335
Steve Naroff7cae42b2009-07-10 23:34:53 +00002336 return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel,
Mike Stump11289f42009-09-09 15:08:12 +00002337 OMD->getResultType(),
2338 OMD, OpLoc, MemberLoc,
Steve Naroff7cae42b2009-07-10 23:34:53 +00002339 NULL, 0));
2340 }
2341 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002342
Steve Naroff7cae42b2009-07-10 23:34:53 +00002343 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlssonf571c112009-08-26 18:25:21 +00002344 << MemberName << BaseType);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002345 }
Chris Lattnerdc420f42008-07-21 04:59:05 +00002346 // Handle Objective-C property access, which is "Obj.property" where Obj is a
2347 // pointer to a (potentially qualified) interface type.
Steve Naroff7cae42b2009-07-10 23:34:53 +00002348 const ObjCObjectPointerType *OPT;
Mike Stump11289f42009-09-09 15:08:12 +00002349 if (OpKind == tok::period &&
Steve Naroff7cae42b2009-07-10 23:34:53 +00002350 (OPT = BaseType->getAsObjCInterfacePointerType())) {
2351 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
2352 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
Anders Carlssonf571c112009-08-26 18:25:21 +00002353 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Mike Stump11289f42009-09-09 15:08:12 +00002354
Daniel Dunbaref89086c2008-09-03 01:05:41 +00002355 // Search for a declared property first.
Anders Carlssonf571c112009-08-26 18:25:21 +00002356 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00002357 // Check whether we can reference this property.
2358 if (DiagnoseUseOfDecl(PD, MemberLoc))
2359 return ExprError();
Fariborz Jahanianb2ab73d2009-05-08 19:36:34 +00002360 QualType ResTy = PD->getType();
Anders Carlssonf571c112009-08-26 18:25:21 +00002361 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002362 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Fariborz Jahanianfe9e3942009-05-08 20:20:55 +00002363 if (DiagnosePropertyAccessorMismatch(PD, Getter, MemberLoc))
2364 ResTy = Getter->getResultType();
Fariborz Jahanianb2ab73d2009-05-08 19:36:34 +00002365 return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
Chris Lattner43df5562009-02-16 18:35:08 +00002366 MemberLoc, BaseExpr));
2367 }
Daniel Dunbaref89086c2008-09-03 01:05:41 +00002368 // Check protocols on qualified interfaces.
Steve Naroffaccc4882009-07-20 17:56:53 +00002369 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
2370 E = OPT->qual_end(); I != E; ++I)
Anders Carlssonf571c112009-08-26 18:25:21 +00002371 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00002372 // Check whether we can reference this property.
2373 if (DiagnoseUseOfDecl(PD, MemberLoc))
2374 return ExprError();
Chris Lattner43df5562009-02-16 18:35:08 +00002375
Steve Narofff6009ed2009-01-21 00:14:39 +00002376 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner43df5562009-02-16 18:35:08 +00002377 MemberLoc, BaseExpr));
2378 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00002379 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
2380 E = OPT->qual_end(); I != E; ++I)
Anders Carlssonf571c112009-08-26 18:25:21 +00002381 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002382 // Check whether we can reference this property.
2383 if (DiagnoseUseOfDecl(PD, MemberLoc))
2384 return ExprError();
Daniel Dunbaref89086c2008-09-03 01:05:41 +00002385
Steve Naroff7cae42b2009-07-10 23:34:53 +00002386 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
2387 MemberLoc, BaseExpr));
2388 }
Daniel Dunbaref89086c2008-09-03 01:05:41 +00002389 // If that failed, look for an "implicit" property by seeing if the nullary
2390 // selector is implemented.
2391
2392 // FIXME: The logic for looking up nullary and unary selectors should be
2393 // shared with the code in ActOnInstanceMessage.
2394
Anders Carlssonf571c112009-08-26 18:25:21 +00002395 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002396 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002397
Daniel Dunbaref89086c2008-09-03 01:05:41 +00002398 // If this reference is in an @implementation, check for 'private' methods.
2399 if (!Getter)
Steve Naroffbb69c942009-10-01 23:46:04 +00002400 Getter = IFace->lookupPrivateInstanceMethod(Sel);
Daniel Dunbaref89086c2008-09-03 01:05:41 +00002401
Steve Naroff1df62692008-10-22 19:16:27 +00002402 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1559d67b2009-07-21 00:06:20 +00002403 if (!Getter)
2404 Getter = IFace->getCategoryInstanceMethod(Sel);
Daniel Dunbaref89086c2008-09-03 01:05:41 +00002405 if (Getter) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00002406 // Check if we can reference this property.
2407 if (DiagnoseUseOfDecl(Getter, MemberLoc))
2408 return ExprError();
Steve Naroff1d984fe2009-03-11 13:48:17 +00002409 }
2410 // If we found a getter then this may be a valid dot-reference, we
2411 // will look for the matching setter, in case it is needed.
Mike Stump11289f42009-09-09 15:08:12 +00002412 Selector SetterSel =
2413 SelectorTable::constructSetterName(PP.getIdentifierTable(),
Anders Carlssonf571c112009-08-26 18:25:21 +00002414 PP.getSelectorTable(), Member);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002415 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
Steve Naroff1d984fe2009-03-11 13:48:17 +00002416 if (!Setter) {
2417 // If this reference is in an @implementation, also check for 'private'
2418 // methods.
Steve Naroffbb69c942009-10-01 23:46:04 +00002419 Setter = IFace->lookupPrivateInstanceMethod(SetterSel);
Steve Naroff1d984fe2009-03-11 13:48:17 +00002420 }
2421 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1559d67b2009-07-21 00:06:20 +00002422 if (!Setter)
2423 Setter = IFace->getCategoryInstanceMethod(SetterSel);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002424
Steve Naroff1d984fe2009-03-11 13:48:17 +00002425 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2426 return ExprError();
2427
2428 if (Getter || Setter) {
2429 QualType PType;
2430
2431 if (Getter)
2432 PType = Getter->getResultType();
Fariborz Jahanian88cc2342009-08-18 20:50:23 +00002433 else
2434 // Get the expression type from Setter's incoming parameter.
2435 PType = (*(Setter->param_end() -1))->getType();
Steve Naroff1d984fe2009-03-11 13:48:17 +00002436 // FIXME: we must check that the setter has property type.
Fariborz Jahanian9a846652009-08-20 17:02:02 +00002437 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter, PType,
Steve Naroff1d984fe2009-03-11 13:48:17 +00002438 Setter, MemberLoc, BaseExpr));
2439 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002440 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlssonf571c112009-08-26 18:25:21 +00002441 << MemberName << BaseType);
Fariborz Jahanian21f54ee2007-11-12 22:29:28 +00002442 }
Mike Stump11289f42009-09-09 15:08:12 +00002443
Steve Naroffe87026a2009-07-24 17:54:45 +00002444 // Handle the following exceptional case (*Obj).isa.
Mike Stump11289f42009-09-09 15:08:12 +00002445 if (OpKind == tok::period &&
Steve Naroffe87026a2009-07-24 17:54:45 +00002446 BaseType->isSpecificBuiltinType(BuiltinType::ObjCId) &&
Anders Carlssonf571c112009-08-26 18:25:21 +00002447 MemberName.getAsIdentifierInfo()->isStr("isa"))
Steve Naroffe87026a2009-07-24 17:54:45 +00002448 return Owned(new (Context) ObjCIsaExpr(BaseExpr, false, MemberLoc,
2449 Context.getObjCIdType()));
2450
Chris Lattnerb63a7452008-07-21 04:28:12 +00002451 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner6c7ce102009-02-16 21:11:58 +00002452 if (BaseType->isExtVectorType()) {
Anders Carlssonf571c112009-08-26 18:25:21 +00002453 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Chris Lattnerb63a7452008-07-21 04:28:12 +00002454 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
2455 if (ret.isNull())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002456 return ExprError();
Anders Carlssonf571c112009-08-26 18:25:21 +00002457 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, *Member,
Steve Narofff6009ed2009-01-21 00:14:39 +00002458 MemberLoc));
Chris Lattnerb63a7452008-07-21 04:28:12 +00002459 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002460
Douglas Gregor0b08ba42009-03-27 06:00:30 +00002461 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
2462 << BaseType << BaseExpr->getSourceRange();
2463
Douglas Gregor0b08ba42009-03-27 06:00:30 +00002464 return ExprError();
Chris Lattnere168f762006-11-10 05:29:30 +00002465}
2466
Douglas Gregor30d60cb2009-11-03 19:44:04 +00002467Sema::OwningExprResult Sema::ActOnMemberAccessExpr(Scope *S, ExprArg Base,
2468 SourceLocation OpLoc,
2469 tok::TokenKind OpKind,
2470 const CXXScopeSpec &SS,
2471 UnqualifiedId &Member,
2472 DeclPtrTy ObjCImpDecl,
2473 bool HasTrailingLParen) {
2474 if (Member.getKind() == UnqualifiedId::IK_TemplateId) {
2475 TemplateName Template
2476 = TemplateName::getFromVoidPointer(Member.TemplateId->Template);
2477
2478 // FIXME: We're going to end up looking up the template based on its name,
2479 // twice!
2480 DeclarationName Name;
2481 if (TemplateDecl *ActualTemplate = Template.getAsTemplateDecl())
2482 Name = ActualTemplate->getDeclName();
2483 else if (OverloadedFunctionDecl *Ovl = Template.getAsOverloadedFunctionDecl())
2484 Name = Ovl->getDeclName();
Douglas Gregor71395fa2009-11-04 00:56:37 +00002485 else {
2486 DependentTemplateName *DTN = Template.getAsDependentTemplateName();
2487 if (DTN->isIdentifier())
2488 Name = DTN->getIdentifier();
2489 else
2490 Name = Context.DeclarationNames.getCXXOperatorName(DTN->getOperator());
2491 }
Douglas Gregor30d60cb2009-11-03 19:44:04 +00002492
2493 // Translate the parser's template argument list in our AST format.
2494 ASTTemplateArgsPtr TemplateArgsPtr(*this,
2495 Member.TemplateId->getTemplateArgs(),
Douglas Gregor30d60cb2009-11-03 19:44:04 +00002496 Member.TemplateId->NumArgs);
2497
2498 llvm::SmallVector<TemplateArgumentLoc, 16> TemplateArgs;
2499 translateTemplateArguments(TemplateArgsPtr,
Douglas Gregor30d60cb2009-11-03 19:44:04 +00002500 TemplateArgs);
2501 TemplateArgsPtr.release();
2502
2503 // Do we have the save the actual template name? We might need it...
2504 return BuildMemberReferenceExpr(S, move(Base), OpLoc, OpKind,
2505 Member.TemplateId->TemplateNameLoc,
2506 Name, true, Member.TemplateId->LAngleLoc,
2507 TemplateArgs.data(), TemplateArgs.size(),
2508 Member.TemplateId->RAngleLoc, DeclPtrTy(),
2509 &SS);
2510 }
2511
2512 // FIXME: We lose a lot of source information by mapping directly to the
2513 // DeclarationName.
2514 OwningExprResult Result
2515 = BuildMemberReferenceExpr(S, move(Base), OpLoc, OpKind,
2516 Member.getSourceRange().getBegin(),
2517 GetNameFromUnqualifiedId(Member),
2518 ObjCImpDecl, &SS);
2519
2520 if (Result.isInvalid() || HasTrailingLParen ||
2521 Member.getKind() != UnqualifiedId::IK_DestructorName)
2522 return move(Result);
2523
2524 // The only way a reference to a destructor can be used is to
2525 // immediately call them. Since the next token is not a '(', produce a
2526 // diagnostic and build the call now.
2527 Expr *E = (Expr *)Result.get();
2528 SourceLocation ExpectedLParenLoc
2529 = PP.getLocForEndOfToken(Member.getSourceRange().getEnd());
2530 Diag(E->getLocStart(), diag::err_dtor_expr_without_call)
2531 << isa<CXXPseudoDestructorExpr>(E)
2532 << CodeModificationHint::CreateInsertion(ExpectedLParenLoc, "()");
2533
2534 return ActOnCallExpr(0, move(Result), ExpectedLParenLoc,
2535 MultiExprArg(*this, 0, 0), 0, ExpectedLParenLoc);
Anders Carlssonf571c112009-08-26 18:25:21 +00002536}
2537
Anders Carlsson355933d2009-08-25 03:49:14 +00002538Sema::OwningExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
2539 FunctionDecl *FD,
2540 ParmVarDecl *Param) {
2541 if (Param->hasUnparsedDefaultArg()) {
2542 Diag (CallLoc,
2543 diag::err_use_of_default_argument_to_function_declared_later) <<
2544 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00002545 Diag(UnparsedDefaultArgLocs[Param],
Anders Carlsson355933d2009-08-25 03:49:14 +00002546 diag::note_default_argument_declared_here);
2547 } else {
2548 if (Param->hasUninstantiatedDefaultArg()) {
2549 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
2550
2551 // Instantiate the expression.
Douglas Gregor01afeef2009-08-28 20:31:08 +00002552 MultiLevelTemplateArgumentList ArgList = getTemplateInstantiationArgs(FD);
Anders Carlsson657bad42009-09-05 05:14:19 +00002553
Mike Stump11289f42009-09-09 15:08:12 +00002554 InstantiatingTemplate Inst(*this, CallLoc, Param,
2555 ArgList.getInnermost().getFlatArgumentList(),
Douglas Gregor01afeef2009-08-28 20:31:08 +00002556 ArgList.getInnermost().flat_size());
Anders Carlsson355933d2009-08-25 03:49:14 +00002557
John McCall76d824f2009-08-25 22:02:44 +00002558 OwningExprResult Result = SubstExpr(UninstExpr, ArgList);
Mike Stump11289f42009-09-09 15:08:12 +00002559 if (Result.isInvalid())
Anders Carlsson355933d2009-08-25 03:49:14 +00002560 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00002561
2562 if (SetParamDefaultArgument(Param, move(Result),
Anders Carlsson355933d2009-08-25 03:49:14 +00002563 /*FIXME:EqualLoc*/
2564 UninstExpr->getSourceRange().getBegin()))
2565 return ExprError();
2566 }
Mike Stump11289f42009-09-09 15:08:12 +00002567
Anders Carlsson355933d2009-08-25 03:49:14 +00002568 Expr *DefaultExpr = Param->getDefaultArg();
Mike Stump11289f42009-09-09 15:08:12 +00002569
Anders Carlsson355933d2009-08-25 03:49:14 +00002570 // If the default expression creates temporaries, we need to
2571 // push them to the current stack of expression temporaries so they'll
2572 // be properly destroyed.
Mike Stump11289f42009-09-09 15:08:12 +00002573 if (CXXExprWithTemporaries *E
Anders Carlsson355933d2009-08-25 03:49:14 +00002574 = dyn_cast_or_null<CXXExprWithTemporaries>(DefaultExpr)) {
Mike Stump11289f42009-09-09 15:08:12 +00002575 assert(!E->shouldDestroyTemporaries() &&
Anders Carlsson355933d2009-08-25 03:49:14 +00002576 "Can't destroy temporaries in a default argument expr!");
2577 for (unsigned I = 0, N = E->getNumTemporaries(); I != N; ++I)
2578 ExprTemporaries.push_back(E->getTemporary(I));
2579 }
2580 }
2581
2582 // We already type-checked the argument, so we know it works.
2583 return Owned(CXXDefaultArgExpr::Create(Context, Param));
2584}
2585
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002586/// ConvertArgumentsForCall - Converts the arguments specified in
2587/// Args/NumArgs to the parameter types of the function FDecl with
2588/// function prototype Proto. Call is the call expression itself, and
2589/// Fn is the function expression. For a C++ member function, this
2590/// routine does not attempt to convert the object argument. Returns
2591/// true if the call is ill-formed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00002592bool
2593Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002594 FunctionDecl *FDecl,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002595 const FunctionProtoType *Proto,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002596 Expr **Args, unsigned NumArgs,
2597 SourceLocation RParenLoc) {
Mike Stump4e1f26a2009-02-19 03:04:26 +00002598 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002599 // assignment, to the types of the corresponding parameter, ...
2600 unsigned NumArgsInProto = Proto->getNumArgs();
2601 unsigned NumArgsToCheck = NumArgs;
Douglas Gregorb6b99612009-01-23 21:30:56 +00002602 bool Invalid = false;
2603
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002604 // If too few arguments are available (and we don't have default
2605 // arguments for the remaining parameters), don't make the call.
2606 if (NumArgs < NumArgsInProto) {
2607 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
2608 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
2609 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
2610 // Use default arguments for missing arguments
2611 NumArgsToCheck = NumArgsInProto;
Ted Kremenek5a201952009-02-07 01:47:29 +00002612 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002613 }
2614
2615 // If too many are passed and not variadic, error on the extras and drop
2616 // them.
2617 if (NumArgs > NumArgsInProto) {
2618 if (!Proto->isVariadic()) {
2619 Diag(Args[NumArgsInProto]->getLocStart(),
2620 diag::err_typecheck_call_too_many_args)
2621 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
2622 << SourceRange(Args[NumArgsInProto]->getLocStart(),
2623 Args[NumArgs-1]->getLocEnd());
2624 // This deletes the extra arguments.
Ted Kremenek5a201952009-02-07 01:47:29 +00002625 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregorb6b99612009-01-23 21:30:56 +00002626 Invalid = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002627 }
2628 NumArgsToCheck = NumArgsInProto;
2629 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00002630
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002631 // Continue to check argument types (even if we have too few/many args).
2632 for (unsigned i = 0; i != NumArgsToCheck; i++) {
2633 QualType ProtoArgType = Proto->getArgType(i);
Mike Stump4e1f26a2009-02-19 03:04:26 +00002634
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002635 Expr *Arg;
Douglas Gregor58354032008-12-24 00:01:03 +00002636 if (i < NumArgs) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002637 Arg = Args[i];
Douglas Gregor58354032008-12-24 00:01:03 +00002638
Eli Friedman3164fb12009-03-22 22:00:50 +00002639 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
2640 ProtoArgType,
Anders Carlssond624e162009-08-26 23:45:07 +00002641 PDiag(diag::err_call_incomplete_argument)
2642 << Arg->getSourceRange()))
Eli Friedman3164fb12009-03-22 22:00:50 +00002643 return true;
2644
Douglas Gregor58354032008-12-24 00:01:03 +00002645 // Pass the argument.
2646 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
2647 return true;
Anders Carlsson78cfaa92009-11-13 04:34:45 +00002648
Anders Carlsson97df0b42009-11-13 17:04:35 +00002649 if (!ProtoArgType->isReferenceType())
2650 Arg = MaybeBindToTemporary(Arg).takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00002651 } else {
Anders Carlssonc80a1272009-08-25 02:29:20 +00002652 ParmVarDecl *Param = FDecl->getParamDecl(i);
Mike Stump11289f42009-09-09 15:08:12 +00002653
2654 OwningExprResult ArgExpr =
Anders Carlsson355933d2009-08-25 03:49:14 +00002655 BuildCXXDefaultArgExpr(Call->getSourceRange().getBegin(),
2656 FDecl, Param);
2657 if (ArgExpr.isInvalid())
2658 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002659
Anders Carlsson355933d2009-08-25 03:49:14 +00002660 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00002661 }
Mike Stump11289f42009-09-09 15:08:12 +00002662
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002663 Call->setArg(i, Arg);
2664 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00002665
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002666 // If this is a variadic call, handle args passed through "...".
2667 if (Proto->isVariadic()) {
Anders Carlssona7d069d2009-01-16 16:48:51 +00002668 VariadicCallType CallType = VariadicFunction;
2669 if (Fn->getType()->isBlockPointerType())
2670 CallType = VariadicBlock; // Block
2671 else if (isa<MemberExpr>(Fn))
2672 CallType = VariadicMethod;
2673
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002674 // Promote the arguments (C99 6.5.2.2p7).
Eli Friedmana9ea9592009-11-14 04:43:10 +00002675 for (unsigned i = NumArgsInProto; i < NumArgs; i++) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002676 Expr *Arg = Args[i];
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00002677 Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002678 Call->setArg(i, Arg);
2679 }
2680 }
2681
Douglas Gregorb6b99612009-01-23 21:30:56 +00002682 return Invalid;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002683}
2684
Douglas Gregorcabea402009-09-22 15:41:20 +00002685/// \brief "Deconstruct" the function argument of a call expression to find
2686/// the underlying declaration (if any), the name of the called function,
2687/// whether argument-dependent lookup is available, whether it has explicit
2688/// template arguments, etc.
2689void Sema::DeconstructCallFunction(Expr *FnExpr,
2690 NamedDecl *&Function,
2691 DeclarationName &Name,
2692 NestedNameSpecifier *&Qualifier,
2693 SourceRange &QualifierRange,
2694 bool &ArgumentDependentLookup,
2695 bool &HasExplicitTemplateArguments,
John McCall0ad16662009-10-29 08:12:44 +00002696 const TemplateArgumentLoc *&ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00002697 unsigned &NumExplicitTemplateArgs) {
2698 // Set defaults for all of the output parameters.
2699 Function = 0;
2700 Name = DeclarationName();
2701 Qualifier = 0;
2702 QualifierRange = SourceRange();
2703 ArgumentDependentLookup = getLangOptions().CPlusPlus;
2704 HasExplicitTemplateArguments = false;
2705
2706 // If we're directly calling a function, get the appropriate declaration.
2707 // Also, in C++, keep track of whether we should perform argument-dependent
2708 // lookup and whether there were any explicitly-specified template arguments.
2709 while (true) {
2710 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(FnExpr))
2711 FnExpr = IcExpr->getSubExpr();
2712 else if (ParenExpr *PExpr = dyn_cast<ParenExpr>(FnExpr)) {
2713 // Parentheses around a function disable ADL
2714 // (C++0x [basic.lookup.argdep]p1).
2715 ArgumentDependentLookup = false;
2716 FnExpr = PExpr->getSubExpr();
2717 } else if (isa<UnaryOperator>(FnExpr) &&
2718 cast<UnaryOperator>(FnExpr)->getOpcode()
2719 == UnaryOperator::AddrOf) {
2720 FnExpr = cast<UnaryOperator>(FnExpr)->getSubExpr();
Douglas Gregorcabea402009-09-22 15:41:20 +00002721 } else if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(FnExpr)) {
2722 Function = dyn_cast<NamedDecl>(DRExpr->getDecl());
Douglas Gregor4bd90e52009-10-23 18:54:35 +00002723 if ((Qualifier = DRExpr->getQualifier())) {
2724 ArgumentDependentLookup = false;
2725 QualifierRange = DRExpr->getQualifierRange();
2726 }
Douglas Gregorcabea402009-09-22 15:41:20 +00002727 break;
2728 } else if (UnresolvedFunctionNameExpr *DepName
2729 = dyn_cast<UnresolvedFunctionNameExpr>(FnExpr)) {
2730 Name = DepName->getName();
2731 break;
2732 } else if (TemplateIdRefExpr *TemplateIdRef
2733 = dyn_cast<TemplateIdRefExpr>(FnExpr)) {
2734 Function = TemplateIdRef->getTemplateName().getAsTemplateDecl();
2735 if (!Function)
2736 Function = TemplateIdRef->getTemplateName().getAsOverloadedFunctionDecl();
2737 HasExplicitTemplateArguments = true;
2738 ExplicitTemplateArgs = TemplateIdRef->getTemplateArgs();
2739 NumExplicitTemplateArgs = TemplateIdRef->getNumTemplateArgs();
2740
2741 // C++ [temp.arg.explicit]p6:
2742 // [Note: For simple function names, argument dependent lookup (3.4.2)
2743 // applies even when the function name is not visible within the
2744 // scope of the call. This is because the call still has the syntactic
2745 // form of a function call (3.4.1). But when a function template with
2746 // explicit template arguments is used, the call does not have the
2747 // correct syntactic form unless there is a function template with
2748 // that name visible at the point of the call. If no such name is
2749 // visible, the call is not syntactically well-formed and
2750 // argument-dependent lookup does not apply. If some such name is
2751 // visible, argument dependent lookup applies and additional function
2752 // templates may be found in other namespaces.
2753 //
2754 // The summary of this paragraph is that, if we get to this point and the
2755 // template-id was not a qualified name, then argument-dependent lookup
2756 // is still possible.
2757 if ((Qualifier = TemplateIdRef->getQualifier())) {
2758 ArgumentDependentLookup = false;
2759 QualifierRange = TemplateIdRef->getQualifierRange();
2760 }
2761 break;
2762 } else {
2763 // Any kind of name that does not refer to a declaration (or
2764 // set of declarations) disables ADL (C++0x [basic.lookup.argdep]p3).
2765 ArgumentDependentLookup = false;
2766 break;
2767 }
2768 }
2769}
2770
Steve Naroff83895f72007-09-16 03:34:24 +00002771/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattnere168f762006-11-10 05:29:30 +00002772/// This provides the location of the left/right parens and a list of comma
2773/// locations.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002774Action::OwningExprResult
2775Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
2776 MultiExprArg args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002777 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002778 unsigned NumArgs = args.size();
Nate Begeman5ec4b312009-08-10 23:49:36 +00002779
2780 // Since this might be a postfix expression, get rid of ParenListExprs.
2781 fn = MaybeConvertParenListExprToParenExpr(S, move(fn));
Mike Stump11289f42009-09-09 15:08:12 +00002782
Anders Carlsson3cbc8592009-05-01 19:30:39 +00002783 Expr *Fn = fn.takeAs<Expr>();
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002784 Expr **Args = reinterpret_cast<Expr**>(args.release());
Chris Lattner38dbdb22007-07-21 03:03:59 +00002785 assert(Fn && "no function call expression");
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00002786 FunctionDecl *FDecl = NULL;
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +00002787 NamedDecl *NDecl = NULL;
Douglas Gregorb8a9a412009-02-04 15:01:18 +00002788 DeclarationName UnqualifiedName;
Mike Stump11289f42009-09-09 15:08:12 +00002789
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002790 if (getLangOptions().CPlusPlus) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00002791 // If this is a pseudo-destructor expression, build the call immediately.
2792 if (isa<CXXPseudoDestructorExpr>(Fn)) {
2793 if (NumArgs > 0) {
2794 // Pseudo-destructor calls should not have any arguments.
2795 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
2796 << CodeModificationHint::CreateRemoval(
2797 SourceRange(Args[0]->getLocStart(),
2798 Args[NumArgs-1]->getLocEnd()));
Mike Stump11289f42009-09-09 15:08:12 +00002799
Douglas Gregorad8a3362009-09-04 17:36:40 +00002800 for (unsigned I = 0; I != NumArgs; ++I)
2801 Args[I]->Destroy(Context);
Mike Stump11289f42009-09-09 15:08:12 +00002802
Douglas Gregorad8a3362009-09-04 17:36:40 +00002803 NumArgs = 0;
2804 }
Mike Stump11289f42009-09-09 15:08:12 +00002805
Douglas Gregorad8a3362009-09-04 17:36:40 +00002806 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
2807 RParenLoc));
2808 }
Mike Stump11289f42009-09-09 15:08:12 +00002809
Douglas Gregorb8a9a412009-02-04 15:01:18 +00002810 // Determine whether this is a dependent call inside a C++ template,
Mike Stump4e1f26a2009-02-19 03:04:26 +00002811 // in which case we won't do any semantic analysis now.
Mike Stump87c57ac2009-05-16 07:39:55 +00002812 // FIXME: Will need to cache the results of name lookup (including ADL) in
2813 // Fn.
Douglas Gregorb8a9a412009-02-04 15:01:18 +00002814 bool Dependent = false;
2815 if (Fn->isTypeDependent())
2816 Dependent = true;
2817 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
2818 Dependent = true;
2819
2820 if (Dependent)
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002821 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
Douglas Gregorb8a9a412009-02-04 15:01:18 +00002822 Context.DependentTy, RParenLoc));
2823
2824 // Determine whether this is a call to an object (C++ [over.call.object]).
2825 if (Fn->getType()->isRecordType())
2826 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
2827 CommaLocs, RParenLoc));
2828
Douglas Gregore254f902009-02-04 00:32:51 +00002829 // Determine whether this is a call to a member function.
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002830 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(Fn->IgnoreParens())) {
2831 NamedDecl *MemDecl = MemExpr->getMemberDecl();
2832 if (isa<OverloadedFunctionDecl>(MemDecl) ||
2833 isa<CXXMethodDecl>(MemDecl) ||
2834 (isa<FunctionTemplateDecl>(MemDecl) &&
2835 isa<CXXMethodDecl>(
2836 cast<FunctionTemplateDecl>(MemDecl)->getTemplatedDecl())))
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002837 return Owned(BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
2838 CommaLocs, RParenLoc));
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002839 }
Anders Carlsson61914b52009-10-03 17:40:22 +00002840
2841 // Determine whether this is a call to a pointer-to-member function.
2842 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Fn->IgnoreParens())) {
2843 if (BO->getOpcode() == BinaryOperator::PtrMemD ||
2844 BO->getOpcode() == BinaryOperator::PtrMemI) {
Fariborz Jahanian42f66632009-10-28 16:49:46 +00002845 if (const FunctionProtoType *FPT =
2846 dyn_cast<FunctionProtoType>(BO->getType())) {
2847 QualType ResultTy = FPT->getResultType().getNonReferenceType();
Anders Carlsson61914b52009-10-03 17:40:22 +00002848
Fariborz Jahanian42f66632009-10-28 16:49:46 +00002849 ExprOwningPtr<CXXMemberCallExpr>
2850 TheCall(this, new (Context) CXXMemberCallExpr(Context, BO, Args,
2851 NumArgs, ResultTy,
2852 RParenLoc));
Anders Carlsson61914b52009-10-03 17:40:22 +00002853
Fariborz Jahanian42f66632009-10-28 16:49:46 +00002854 if (CheckCallReturnType(FPT->getResultType(),
2855 BO->getRHS()->getSourceRange().getBegin(),
2856 TheCall.get(), 0))
2857 return ExprError();
Anders Carlsson63dce022009-10-15 00:41:48 +00002858
Fariborz Jahanian42f66632009-10-28 16:49:46 +00002859 if (ConvertArgumentsForCall(&*TheCall, BO, 0, FPT, Args, NumArgs,
2860 RParenLoc))
2861 return ExprError();
Anders Carlsson61914b52009-10-03 17:40:22 +00002862
Fariborz Jahanian42f66632009-10-28 16:49:46 +00002863 return Owned(MaybeBindToTemporary(TheCall.release()).release());
2864 }
2865 return ExprError(Diag(Fn->getLocStart(),
2866 diag::err_typecheck_call_not_function)
2867 << Fn->getType() << Fn->getSourceRange());
Anders Carlsson61914b52009-10-03 17:40:22 +00002868 }
2869 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002870 }
2871
Douglas Gregore254f902009-02-04 00:32:51 +00002872 // If we're directly calling a function, get the appropriate declaration.
Mike Stump11289f42009-09-09 15:08:12 +00002873 // Also, in C++, keep track of whether we should perform argument-dependent
Douglas Gregor89026b52009-06-30 23:57:56 +00002874 // lookup and whether there were any explicitly-specified template arguments.
Douglas Gregore254f902009-02-04 00:32:51 +00002875 bool ADL = true;
Douglas Gregor89026b52009-06-30 23:57:56 +00002876 bool HasExplicitTemplateArgs = 0;
John McCall0ad16662009-10-29 08:12:44 +00002877 const TemplateArgumentLoc *ExplicitTemplateArgs = 0;
Douglas Gregor89026b52009-06-30 23:57:56 +00002878 unsigned NumExplicitTemplateArgs = 0;
Douglas Gregorcabea402009-09-22 15:41:20 +00002879 NestedNameSpecifier *Qualifier = 0;
2880 SourceRange QualifierRange;
2881 DeconstructCallFunction(Fn, NDecl, UnqualifiedName, Qualifier, QualifierRange,
2882 ADL,HasExplicitTemplateArgs, ExplicitTemplateArgs,
2883 NumExplicitTemplateArgs);
Mike Stump4e1f26a2009-02-19 03:04:26 +00002884
Douglas Gregorb8a9a412009-02-04 15:01:18 +00002885 OverloadedFunctionDecl *Ovl = 0;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002886 FunctionTemplateDecl *FunctionTemplate = 0;
Douglas Gregora727cb92009-06-30 22:34:41 +00002887 if (NDecl) {
2888 FDecl = dyn_cast<FunctionDecl>(NDecl);
2889 if ((FunctionTemplate = dyn_cast<FunctionTemplateDecl>(NDecl)))
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002890 FDecl = FunctionTemplate->getTemplatedDecl();
2891 else
Douglas Gregora727cb92009-06-30 22:34:41 +00002892 FDecl = dyn_cast<FunctionDecl>(NDecl);
2893 Ovl = dyn_cast<OverloadedFunctionDecl>(NDecl);
Douglas Gregorb8a9a412009-02-04 15:01:18 +00002894 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002895
Mike Stump11289f42009-09-09 15:08:12 +00002896 if (Ovl || FunctionTemplate ||
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002897 (getLangOptions().CPlusPlus && (FDecl || UnqualifiedName))) {
Douglas Gregorb9063fc2009-02-13 23:20:09 +00002898 // We don't perform ADL for implicit declarations of builtins.
Douglas Gregor15fc9562009-09-12 00:22:50 +00002899 if (FDecl && FDecl->getBuiltinID() && FDecl->isImplicit())
Douglas Gregore254f902009-02-04 00:32:51 +00002900 ADL = false;
2901
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002902 // We don't perform ADL in C.
2903 if (!getLangOptions().CPlusPlus)
2904 ADL = false;
2905
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002906 if (Ovl || FunctionTemplate || ADL) {
Mike Stump11289f42009-09-09 15:08:12 +00002907 FDecl = ResolveOverloadedCallFn(Fn, NDecl, UnqualifiedName,
Douglas Gregor89026b52009-06-30 23:57:56 +00002908 HasExplicitTemplateArgs,
2909 ExplicitTemplateArgs,
2910 NumExplicitTemplateArgs,
Mike Stump11289f42009-09-09 15:08:12 +00002911 LParenLoc, Args, NumArgs, CommaLocs,
Douglas Gregor89026b52009-06-30 23:57:56 +00002912 RParenLoc, ADL);
Douglas Gregore254f902009-02-04 00:32:51 +00002913 if (!FDecl)
2914 return ExprError();
2915
Douglas Gregor091f0422009-10-23 22:18:25 +00002916 Fn = FixOverloadedFunctionReference(Fn, FDecl);
Douglas Gregore254f902009-02-04 00:32:51 +00002917 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002918 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00002919
2920 // Promote the function operand.
2921 UsualUnaryConversions(Fn);
2922
Chris Lattner08464942007-12-28 05:29:59 +00002923 // Make the call expr early, before semantic checks. This guarantees cleanup
2924 // of arguments and function on error.
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002925 ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
2926 Args, NumArgs,
2927 Context.BoolTy,
2928 RParenLoc));
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002929
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002930 const FunctionType *FuncT;
2931 if (!Fn->getType()->isBlockPointerType()) {
2932 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
2933 // have type pointer to function".
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002934 const PointerType *PT = Fn->getType()->getAs<PointerType>();
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002935 if (PT == 0)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002936 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2937 << Fn->getType() << Fn->getSourceRange());
John McCall9dd450b2009-09-21 23:43:11 +00002938 FuncT = PT->getPointeeType()->getAs<FunctionType>();
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002939 } else { // This is a block call.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002940 FuncT = Fn->getType()->getAs<BlockPointerType>()->getPointeeType()->
John McCall9dd450b2009-09-21 23:43:11 +00002941 getAs<FunctionType>();
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002942 }
Chris Lattner08464942007-12-28 05:29:59 +00002943 if (FuncT == 0)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002944 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2945 << Fn->getType() << Fn->getSourceRange());
2946
Eli Friedman3164fb12009-03-22 22:00:50 +00002947 // Check for a valid return type
Anders Carlsson7f84ed92009-10-09 23:51:55 +00002948 if (CheckCallReturnType(FuncT->getResultType(),
2949 Fn->getSourceRange().getBegin(), TheCall.get(),
2950 FDecl))
Eli Friedman3164fb12009-03-22 22:00:50 +00002951 return ExprError();
2952
Chris Lattner08464942007-12-28 05:29:59 +00002953 // We know the result type of the call, set it.
Douglas Gregor786ab212008-10-29 02:00:59 +00002954 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002955
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002956 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
Mike Stump4e1f26a2009-02-19 03:04:26 +00002957 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002958 RParenLoc))
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002959 return ExprError();
Chris Lattner08464942007-12-28 05:29:59 +00002960 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002961 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002962
Douglas Gregord8e97de2009-04-02 15:37:10 +00002963 if (FDecl) {
2964 // Check if we have too few/too many template arguments, based
2965 // on our knowledge of the function definition.
2966 const FunctionDecl *Def = 0;
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00002967 if (FDecl->getBody(Def) && NumArgs != Def->param_size()) {
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00002968 const FunctionProtoType *Proto =
John McCall9dd450b2009-09-21 23:43:11 +00002969 Def->getType()->getAs<FunctionProtoType>();
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00002970 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size())) {
2971 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
2972 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
2973 }
2974 }
Douglas Gregord8e97de2009-04-02 15:37:10 +00002975 }
2976
Steve Naroff0b661582007-08-28 23:30:39 +00002977 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner08464942007-12-28 05:29:59 +00002978 for (unsigned i = 0; i != NumArgs; i++) {
2979 Expr *Arg = Args[i];
2980 DefaultArgumentPromotion(Arg);
Eli Friedman3164fb12009-03-22 22:00:50 +00002981 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
2982 Arg->getType(),
Anders Carlssond624e162009-08-26 23:45:07 +00002983 PDiag(diag::err_call_incomplete_argument)
2984 << Arg->getSourceRange()))
Eli Friedman3164fb12009-03-22 22:00:50 +00002985 return ExprError();
Chris Lattner08464942007-12-28 05:29:59 +00002986 TheCall->setArg(i, Arg);
Steve Naroff0b661582007-08-28 23:30:39 +00002987 }
Steve Naroffae4143e2007-04-26 20:39:23 +00002988 }
Chris Lattner08464942007-12-28 05:29:59 +00002989
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002990 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
2991 if (!Method->isStatic())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002992 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
2993 << Fn->getSourceRange());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002994
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +00002995 // Check for sentinels
2996 if (NDecl)
2997 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump11289f42009-09-09 15:08:12 +00002998
Chris Lattnerb87b1b32007-08-10 20:18:51 +00002999 // Do special checking on direct calls to functions.
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003000 if (FDecl) {
3001 if (CheckFunctionCall(FDecl, TheCall.get()))
3002 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003003
Douglas Gregor15fc9562009-09-12 00:22:50 +00003004 if (unsigned BuiltinID = FDecl->getBuiltinID())
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003005 return CheckBuiltinFunctionCall(BuiltinID, TheCall.take());
3006 } else if (NDecl) {
3007 if (CheckBlockCall(NDecl, TheCall.get()))
3008 return ExprError();
3009 }
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003010
Anders Carlssonf8984012009-08-16 03:06:32 +00003011 return MaybeBindToTemporary(TheCall.take());
Chris Lattnere168f762006-11-10 05:29:30 +00003012}
3013
Sebastian Redlb5d49352009-01-19 22:31:54 +00003014Action::OwningExprResult
3015Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
3016 SourceLocation RParenLoc, ExprArg InitExpr) {
Steve Naroff83895f72007-09-16 03:34:24 +00003017 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00003018 //FIXME: Preserve type source info.
3019 QualType literalType = GetTypeFromParser(Ty);
Steve Naroff57eb2c52007-07-19 21:32:11 +00003020 // FIXME: put back this assert when initializers are worked out.
Steve Naroff83895f72007-09-16 03:34:24 +00003021 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Sebastian Redlb5d49352009-01-19 22:31:54 +00003022 Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
Anders Carlsson2c1ec6d2007-12-05 07:24:19 +00003023
Eli Friedman37a186d2008-05-20 05:22:08 +00003024 if (literalType->isArrayType()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00003025 if (literalType->isVariableArrayType())
Sebastian Redlb5d49352009-01-19 22:31:54 +00003026 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
3027 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor1c37d9e2009-05-21 23:48:18 +00003028 } else if (!literalType->isDependentType() &&
3029 RequireCompleteType(LParenLoc, literalType,
Anders Carlssond624e162009-08-26 23:45:07 +00003030 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump11289f42009-09-09 15:08:12 +00003031 << SourceRange(LParenLoc,
Anders Carlssond624e162009-08-26 23:45:07 +00003032 literalExpr->getSourceRange().getEnd())))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003033 return ExprError();
Eli Friedman37a186d2008-05-20 05:22:08 +00003034
Sebastian Redlb5d49352009-01-19 22:31:54 +00003035 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003036 DeclarationName(), /*FIXME:DirectInit=*/false))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003037 return ExprError();
Steve Naroffd32419d2008-01-14 18:19:28 +00003038
Chris Lattner79413952008-12-04 23:50:19 +00003039 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffd32419d2008-01-14 18:19:28 +00003040 if (isFileScope) { // 6.5.2.5p3
Steve Naroff98f72032008-01-10 22:15:12 +00003041 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003042 return ExprError();
Steve Naroff98f72032008-01-10 22:15:12 +00003043 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00003044 InitExpr.release();
Mike Stump4e1f26a2009-02-19 03:04:26 +00003045 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType,
Steve Narofff6009ed2009-01-21 00:14:39 +00003046 literalExpr, isFileScope));
Steve Narofffbd09832007-07-19 01:06:55 +00003047}
3048
Sebastian Redlb5d49352009-01-19 22:31:54 +00003049Action::OwningExprResult
3050Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redlb5d49352009-01-19 22:31:54 +00003051 SourceLocation RBraceLoc) {
3052 unsigned NumInit = initlist.size();
3053 Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
Anders Carlsson4692db02007-08-31 04:56:16 +00003054
Steve Naroff30d242c2007-09-15 18:49:24 +00003055 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump4e1f26a2009-02-19 03:04:26 +00003056 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb5d49352009-01-19 22:31:54 +00003057
Mike Stump4e1f26a2009-02-19 03:04:26 +00003058 InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00003059 RBraceLoc);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003060 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb5d49352009-01-19 22:31:54 +00003061 return Owned(E);
Steve Narofffbd09832007-07-19 01:06:55 +00003062}
3063
Anders Carlsson094c4592009-10-18 18:12:03 +00003064static CastExpr::CastKind getScalarCastKind(ASTContext &Context,
3065 QualType SrcTy, QualType DestTy) {
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003066 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
Anders Carlsson094c4592009-10-18 18:12:03 +00003067 return CastExpr::CK_NoOp;
3068
3069 if (SrcTy->hasPointerRepresentation()) {
3070 if (DestTy->hasPointerRepresentation())
3071 return CastExpr::CK_BitCast;
3072 if (DestTy->isIntegerType())
3073 return CastExpr::CK_PointerToIntegral;
3074 }
3075
3076 if (SrcTy->isIntegerType()) {
3077 if (DestTy->isIntegerType())
3078 return CastExpr::CK_IntegralCast;
3079 if (DestTy->hasPointerRepresentation())
3080 return CastExpr::CK_IntegralToPointer;
3081 if (DestTy->isRealFloatingType())
3082 return CastExpr::CK_IntegralToFloating;
3083 }
3084
3085 if (SrcTy->isRealFloatingType()) {
3086 if (DestTy->isRealFloatingType())
3087 return CastExpr::CK_FloatingCast;
3088 if (DestTy->isIntegerType())
3089 return CastExpr::CK_FloatingToIntegral;
3090 }
3091
3092 // FIXME: Assert here.
3093 // assert(false && "Unhandled cast combination!");
3094 return CastExpr::CK_Unknown;
3095}
3096
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003097/// CheckCastTypes - Check type constraints for casting between types.
Sebastian Redl955a0672009-07-29 13:50:23 +00003098bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr,
Mike Stump11289f42009-09-09 15:08:12 +00003099 CastExpr::CastKind& Kind,
Fariborz Jahanian1cec0c42009-08-26 18:55:36 +00003100 CXXMethodDecl *& ConversionDecl,
3101 bool FunctionalStyle) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00003102 if (getLangOptions().CPlusPlus)
Fariborz Jahanian1cec0c42009-08-26 18:55:36 +00003103 return CXXCheckCStyleCast(TyR, castType, castExpr, Kind, FunctionalStyle,
3104 ConversionDecl);
Sebastian Redl9f831db2009-07-25 15:41:38 +00003105
Eli Friedmanda8d4de2009-08-15 19:02:19 +00003106 DefaultFunctionArrayConversion(castExpr);
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003107
3108 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
3109 // type needs to be scalar.
3110 if (castType->isVoidType()) {
3111 // Cast to void allows any expr type.
Anders Carlssonef918ac2009-10-16 02:35:04 +00003112 Kind = CastExpr::CK_ToVoid;
3113 return false;
3114 }
3115
3116 if (!castType->isScalarType() && !castType->isVectorType()) {
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003117 if (Context.hasSameUnqualifiedType(castType, castExpr->getType()) &&
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003118 (castType->isStructureType() || castType->isUnionType())) {
3119 // GCC struct/union extension: allow cast to self.
Eli Friedmanba961a92009-03-23 00:24:07 +00003120 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003121 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
3122 << castType << castExpr->getSourceRange();
Anders Carlssonec143772009-08-07 23:22:37 +00003123 Kind = CastExpr::CK_NoOp;
Anders Carlsson525b76b2009-10-16 02:48:28 +00003124 return false;
3125 }
3126
3127 if (castType->isUnionType()) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003128 // GCC cast to union extension
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003129 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003130 RecordDecl::field_iterator Field, FieldEnd;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003131 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003132 Field != FieldEnd; ++Field) {
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003133 if (Context.hasSameUnqualifiedType(Field->getType(),
3134 castExpr->getType())) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003135 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
3136 << castExpr->getSourceRange();
3137 break;
3138 }
3139 }
3140 if (Field == FieldEnd)
3141 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
3142 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlssonec143772009-08-07 23:22:37 +00003143 Kind = CastExpr::CK_ToUnion;
Anders Carlsson525b76b2009-10-16 02:48:28 +00003144 return false;
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003145 }
Anders Carlsson525b76b2009-10-16 02:48:28 +00003146
3147 // Reject any other conversions to non-scalar types.
3148 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
3149 << castType << castExpr->getSourceRange();
3150 }
3151
3152 if (!castExpr->getType()->isScalarType() &&
3153 !castExpr->getType()->isVectorType()) {
Chris Lattner3b054132008-11-19 05:08:23 +00003154 return Diag(castExpr->getLocStart(),
3155 diag::err_typecheck_expect_scalar_operand)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003156 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlsson525b76b2009-10-16 02:48:28 +00003157 }
3158
Anders Carlsson43d70f82009-10-16 05:23:41 +00003159 if (castType->isExtVectorType())
3160 return CheckExtVectorCast(TyR, castType, castExpr, Kind);
3161
Anders Carlsson525b76b2009-10-16 02:48:28 +00003162 if (castType->isVectorType())
3163 return CheckVectorCast(TyR, castType, castExpr->getType(), Kind);
3164 if (castExpr->getType()->isVectorType())
3165 return CheckVectorCast(TyR, castExpr->getType(), castType, Kind);
3166
3167 if (getLangOptions().ObjC1 && isa<ObjCSuperExpr>(castExpr))
Steve Naroffb47acdb2009-04-08 23:52:26 +00003168 return Diag(castExpr->getLocStart(), diag::err_illegal_super_cast) << TyR;
Anders Carlsson525b76b2009-10-16 02:48:28 +00003169
Anders Carlsson43d70f82009-10-16 05:23:41 +00003170 if (isa<ObjCSelectorExpr>(castExpr))
3171 return Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
3172
Anders Carlsson525b76b2009-10-16 02:48:28 +00003173 if (!castType->isArithmeticType()) {
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00003174 QualType castExprType = castExpr->getType();
3175 if (!castExprType->isIntegralType() && castExprType->isArithmeticType())
3176 return Diag(castExpr->getLocStart(),
3177 diag::err_cast_pointer_from_non_pointer_int)
3178 << castExprType << castExpr->getSourceRange();
3179 } else if (!castExpr->getType()->isArithmeticType()) {
3180 if (!castType->isIntegralType() && castType->isArithmeticType())
3181 return Diag(castExpr->getLocStart(),
3182 diag::err_cast_pointer_to_non_pointer_int)
3183 << castType << castExpr->getSourceRange();
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003184 }
Anders Carlsson094c4592009-10-18 18:12:03 +00003185
3186 Kind = getScalarCastKind(Context, castExpr->getType(), castType);
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003187 return false;
3188}
3189
Anders Carlsson525b76b2009-10-16 02:48:28 +00003190bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
3191 CastExpr::CastKind &Kind) {
Anders Carlssonde71adf2007-11-27 05:51:55 +00003192 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00003193
Anders Carlssonde71adf2007-11-27 05:51:55 +00003194 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner37e05872008-03-05 18:54:05 +00003195 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonde71adf2007-11-27 05:51:55 +00003196 return Diag(R.getBegin(),
Mike Stump4e1f26a2009-02-19 03:04:26 +00003197 Ty->isVectorType() ?
Anders Carlssonde71adf2007-11-27 05:51:55 +00003198 diag::err_invalid_conversion_between_vectors :
Chris Lattner3b054132008-11-19 05:08:23 +00003199 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003200 << VectorTy << Ty << R;
Anders Carlssonde71adf2007-11-27 05:51:55 +00003201 } else
3202 return Diag(R.getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00003203 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003204 << VectorTy << Ty << R;
Mike Stump4e1f26a2009-02-19 03:04:26 +00003205
Anders Carlsson525b76b2009-10-16 02:48:28 +00003206 Kind = CastExpr::CK_BitCast;
Anders Carlssonde71adf2007-11-27 05:51:55 +00003207 return false;
3208}
3209
Anders Carlsson43d70f82009-10-16 05:23:41 +00003210bool Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *&CastExpr,
3211 CastExpr::CastKind &Kind) {
Nate Begemanc69b7402009-06-26 00:50:28 +00003212 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Anders Carlsson43d70f82009-10-16 05:23:41 +00003213
3214 QualType SrcTy = CastExpr->getType();
3215
Nate Begemanc8961a42009-06-27 22:05:55 +00003216 // If SrcTy is a VectorType, the total size must match to explicitly cast to
3217 // an ExtVectorType.
Nate Begemanc69b7402009-06-26 00:50:28 +00003218 if (SrcTy->isVectorType()) {
3219 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
3220 return Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
3221 << DestTy << SrcTy << R;
Anders Carlsson43d70f82009-10-16 05:23:41 +00003222 Kind = CastExpr::CK_BitCast;
Nate Begemanc69b7402009-06-26 00:50:28 +00003223 return false;
3224 }
3225
Nate Begemanbd956c42009-06-28 02:36:38 +00003226 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begemanc69b7402009-06-26 00:50:28 +00003227 // conversion will take place first from scalar to elt type, and then
3228 // splat from elt type to vector.
Nate Begemanbd956c42009-06-28 02:36:38 +00003229 if (SrcTy->isPointerType())
3230 return Diag(R.getBegin(),
3231 diag::err_invalid_conversion_between_vector_and_scalar)
3232 << DestTy << SrcTy << R;
Eli Friedman06ed2a52009-10-20 08:27:19 +00003233
3234 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
3235 ImpCastExprToType(CastExpr, DestElemTy,
3236 getScalarCastKind(Context, SrcTy, DestElemTy));
Anders Carlsson43d70f82009-10-16 05:23:41 +00003237
3238 Kind = CastExpr::CK_VectorSplat;
Nate Begemanc69b7402009-06-26 00:50:28 +00003239 return false;
3240}
3241
Sebastian Redlb5d49352009-01-19 22:31:54 +00003242Action::OwningExprResult
Nate Begeman5ec4b312009-08-10 23:49:36 +00003243Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, TypeTy *Ty,
Sebastian Redlb5d49352009-01-19 22:31:54 +00003244 SourceLocation RParenLoc, ExprArg Op) {
Anders Carlssonf10e4142009-08-07 22:21:05 +00003245 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Mike Stump11289f42009-09-09 15:08:12 +00003246
Sebastian Redlb5d49352009-01-19 22:31:54 +00003247 assert((Ty != 0) && (Op.get() != 0) &&
3248 "ActOnCastExpr(): missing type or expr");
Steve Naroff1a2cf6b2007-07-16 23:25:18 +00003249
Nate Begeman5ec4b312009-08-10 23:49:36 +00003250 Expr *castExpr = (Expr *)Op.get();
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00003251 //FIXME: Preserve type source info.
3252 QualType castType = GetTypeFromParser(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00003253
Nate Begeman5ec4b312009-08-10 23:49:36 +00003254 // If the Expr being casted is a ParenListExpr, handle it specially.
3255 if (isa<ParenListExpr>(castExpr))
3256 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, move(Op),castType);
Anders Carlssone9766d52009-09-09 21:33:21 +00003257 CXXMethodDecl *Method = 0;
Mike Stump11289f42009-09-09 15:08:12 +00003258 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr,
Anders Carlssone9766d52009-09-09 21:33:21 +00003259 Kind, Method))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003260 return ExprError();
Anders Carlssone9766d52009-09-09 21:33:21 +00003261
3262 if (Method) {
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00003263 OwningExprResult CastArg = BuildCXXCastArgument(LParenLoc, castType, Kind,
Anders Carlssone9766d52009-09-09 21:33:21 +00003264 Method, move(Op));
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00003265
Anders Carlssone9766d52009-09-09 21:33:21 +00003266 if (CastArg.isInvalid())
3267 return ExprError();
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00003268
Anders Carlssone9766d52009-09-09 21:33:21 +00003269 castExpr = CastArg.takeAs<Expr>();
3270 } else {
3271 Op.release();
Fariborz Jahanian3df87672009-08-29 19:15:16 +00003272 }
Mike Stump11289f42009-09-09 15:08:12 +00003273
Sebastian Redl9f831db2009-07-25 15:41:38 +00003274 return Owned(new (Context) CStyleCastExpr(castType.getNonReferenceType(),
Mike Stump11289f42009-09-09 15:08:12 +00003275 Kind, castExpr, castType,
Anders Carlssonf10e4142009-08-07 22:21:05 +00003276 LParenLoc, RParenLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00003277}
3278
Nate Begeman5ec4b312009-08-10 23:49:36 +00003279/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
3280/// of comma binary operators.
3281Action::OwningExprResult
3282Sema::MaybeConvertParenListExprToParenExpr(Scope *S, ExprArg EA) {
3283 Expr *expr = EA.takeAs<Expr>();
3284 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
3285 if (!E)
3286 return Owned(expr);
Mike Stump11289f42009-09-09 15:08:12 +00003287
Nate Begeman5ec4b312009-08-10 23:49:36 +00003288 OwningExprResult Result(*this, E->getExpr(0));
Mike Stump11289f42009-09-09 15:08:12 +00003289
Nate Begeman5ec4b312009-08-10 23:49:36 +00003290 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
3291 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, move(Result),
3292 Owned(E->getExpr(i)));
Mike Stump11289f42009-09-09 15:08:12 +00003293
Nate Begeman5ec4b312009-08-10 23:49:36 +00003294 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), move(Result));
3295}
3296
3297Action::OwningExprResult
3298Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
3299 SourceLocation RParenLoc, ExprArg Op,
3300 QualType Ty) {
3301 ParenListExpr *PE = (ParenListExpr *)Op.get();
Mike Stump11289f42009-09-09 15:08:12 +00003302
3303 // If this is an altivec initializer, '(' type ')' '(' init, ..., init ')'
Nate Begeman5ec4b312009-08-10 23:49:36 +00003304 // then handle it as such.
3305 if (getLangOptions().AltiVec && Ty->isVectorType()) {
3306 if (PE->getNumExprs() == 0) {
3307 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
3308 return ExprError();
3309 }
3310
3311 llvm::SmallVector<Expr *, 8> initExprs;
3312 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
3313 initExprs.push_back(PE->getExpr(i));
3314
3315 // FIXME: This means that pretty-printing the final AST will produce curly
3316 // braces instead of the original commas.
3317 Op.release();
Mike Stump11289f42009-09-09 15:08:12 +00003318 InitListExpr *E = new (Context) InitListExpr(LParenLoc, &initExprs[0],
Nate Begeman5ec4b312009-08-10 23:49:36 +00003319 initExprs.size(), RParenLoc);
3320 E->setType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00003321 return ActOnCompoundLiteral(LParenLoc, Ty.getAsOpaquePtr(), RParenLoc,
Nate Begeman5ec4b312009-08-10 23:49:36 +00003322 Owned(E));
3323 } else {
Mike Stump11289f42009-09-09 15:08:12 +00003324 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
Nate Begeman5ec4b312009-08-10 23:49:36 +00003325 // sequence of BinOp comma operators.
3326 Op = MaybeConvertParenListExprToParenExpr(S, move(Op));
3327 return ActOnCastExpr(S, LParenLoc, Ty.getAsOpaquePtr(), RParenLoc,move(Op));
3328 }
3329}
3330
3331Action::OwningExprResult Sema::ActOnParenListExpr(SourceLocation L,
3332 SourceLocation R,
3333 MultiExprArg Val) {
3334 unsigned nexprs = Val.size();
3335 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
3336 assert((exprs != 0) && "ActOnParenListExpr() missing expr list");
3337 Expr *expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
3338 return Owned(expr);
3339}
3340
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003341/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
3342/// In that case, lhs = cond.
Chris Lattner2c486602009-02-18 04:38:20 +00003343/// C99 6.5.15
3344QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
3345 SourceLocation QuestionLoc) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00003346 // C++ is sufficiently different to merit its own checker.
3347 if (getLangOptions().CPlusPlus)
3348 return CXXCheckConditionalOperands(Cond, LHS, RHS, QuestionLoc);
3349
John McCall1fa36b72009-11-05 09:23:39 +00003350 CheckSignCompare(LHS, RHS, QuestionLoc, diag::warn_mixed_sign_conditional);
3351
Chris Lattner432cff52009-02-18 04:28:32 +00003352 UsualUnaryConversions(Cond);
3353 UsualUnaryConversions(LHS);
3354 UsualUnaryConversions(RHS);
3355 QualType CondTy = Cond->getType();
3356 QualType LHSTy = LHS->getType();
3357 QualType RHSTy = RHS->getType();
Steve Naroff31090012007-07-16 21:54:35 +00003358
Steve Naroffa78fe7e2007-05-16 19:47:19 +00003359 // first, check the condition.
Sebastian Redl1a99f442009-04-16 17:51:27 +00003360 if (!CondTy->isScalarType()) { // C99 6.5.15p2
3361 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
3362 << CondTy;
3363 return QualType();
Steve Naroffa78fe7e2007-05-16 19:47:19 +00003364 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00003365
Chris Lattnere2949f42008-01-06 22:42:25 +00003366 // Now check the two expressions.
Nate Begeman5ec4b312009-08-10 23:49:36 +00003367 if (LHSTy->isVectorType() || RHSTy->isVectorType())
3368 return CheckVectorOperands(QuestionLoc, LHS, RHS);
Douglas Gregor4619e432008-12-05 23:32:09 +00003369
Chris Lattnere2949f42008-01-06 22:42:25 +00003370 // If both operands have arithmetic type, do the usual arithmetic conversions
3371 // to find a common type: C99 6.5.15p3,5.
Chris Lattner432cff52009-02-18 04:28:32 +00003372 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
3373 UsualArithmeticConversions(LHS, RHS);
3374 return LHS->getType();
Steve Naroffdbd9e892007-07-17 00:58:39 +00003375 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00003376
Chris Lattnere2949f42008-01-06 22:42:25 +00003377 // If both operands are the same structure or union type, the result is that
3378 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003379 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
3380 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattner2ab40a62007-11-26 01:40:58 +00003381 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump4e1f26a2009-02-19 03:04:26 +00003382 // "If both the operands have structure or union type, the result has
Chris Lattnere2949f42008-01-06 22:42:25 +00003383 // that type." This implies that CV qualifiers are dropped.
Chris Lattner432cff52009-02-18 04:28:32 +00003384 return LHSTy.getUnqualifiedType();
Eli Friedmanba961a92009-03-23 00:24:07 +00003385 // FIXME: Type of conditional expression must be complete in C mode.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00003386 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00003387
Chris Lattnere2949f42008-01-06 22:42:25 +00003388 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffbf1516c2008-05-12 21:44:38 +00003389 // The following || allows only one side to be void (a GCC-ism).
Chris Lattner432cff52009-02-18 04:28:32 +00003390 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
3391 if (!LHSTy->isVoidType())
3392 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
3393 << RHS->getSourceRange();
3394 if (!RHSTy->isVoidType())
3395 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
3396 << LHS->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00003397 ImpCastExprToType(LHS, Context.VoidTy, CastExpr::CK_ToVoid);
3398 ImpCastExprToType(RHS, Context.VoidTy, CastExpr::CK_ToVoid);
Eli Friedman3e1852f2008-06-04 19:47:51 +00003399 return Context.VoidTy;
Steve Naroffbf1516c2008-05-12 21:44:38 +00003400 }
Steve Naroff039ad3c2008-01-08 01:11:38 +00003401 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
3402 // the type of the other operand."
Steve Naroff6b712a72009-07-14 18:25:06 +00003403 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
Douglas Gregor56751b52009-09-25 04:25:58 +00003404 RHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00003405 // promote the null to a pointer.
3406 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_Unknown);
Chris Lattner432cff52009-02-18 04:28:32 +00003407 return LHSTy;
Steve Naroff039ad3c2008-01-08 01:11:38 +00003408 }
Steve Naroff6b712a72009-07-14 18:25:06 +00003409 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
Douglas Gregor56751b52009-09-25 04:25:58 +00003410 LHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00003411 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_Unknown);
Chris Lattner432cff52009-02-18 04:28:32 +00003412 return RHSTy;
Steve Naroff039ad3c2008-01-08 01:11:38 +00003413 }
David Chisnall9f57c292009-08-17 16:35:33 +00003414 // Handle things like Class and struct objc_class*. Here we case the result
3415 // to the pseudo-builtin, because that will be implicitly cast back to the
3416 // redefinition type if an attempt is made to access its fields.
3417 if (LHSTy->isObjCClassType() &&
3418 (RHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00003419 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
David Chisnall9f57c292009-08-17 16:35:33 +00003420 return LHSTy;
3421 }
3422 if (RHSTy->isObjCClassType() &&
3423 (LHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00003424 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
David Chisnall9f57c292009-08-17 16:35:33 +00003425 return RHSTy;
3426 }
3427 // And the same for struct objc_object* / id
3428 if (LHSTy->isObjCIdType() &&
3429 (RHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00003430 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
David Chisnall9f57c292009-08-17 16:35:33 +00003431 return LHSTy;
3432 }
3433 if (RHSTy->isObjCIdType() &&
3434 (LHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00003435 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
David Chisnall9f57c292009-08-17 16:35:33 +00003436 return RHSTy;
3437 }
Steve Naroff05efa972009-07-01 14:36:47 +00003438 // Handle block pointer types.
3439 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
3440 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
3441 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
3442 QualType destType = Context.getPointerType(Context.VoidTy);
Eli Friedman06ed2a52009-10-20 08:27:19 +00003443 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
3444 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00003445 return destType;
3446 }
3447 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3448 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3449 return QualType();
Mike Stump1b821b42009-05-07 03:14:14 +00003450 }
Steve Naroff05efa972009-07-01 14:36:47 +00003451 // We have 2 block pointer types.
3452 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3453 // Two identical block pointer types are always compatible.
Mike Stump1b821b42009-05-07 03:14:14 +00003454 return LHSTy;
3455 }
Steve Naroff05efa972009-07-01 14:36:47 +00003456 // The block pointer types aren't identical, continue checking.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003457 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
3458 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00003459
Steve Naroff05efa972009-07-01 14:36:47 +00003460 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
3461 rhptee.getUnqualifiedType())) {
Mike Stump1b821b42009-05-07 03:14:14 +00003462 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
3463 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3464 // In this situation, we assume void* type. No especially good
3465 // reason, but this is what gcc does, and we do have to pick
3466 // to get a consistent AST.
3467 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Eli Friedman06ed2a52009-10-20 08:27:19 +00003468 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
3469 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
Mike Stump1b821b42009-05-07 03:14:14 +00003470 return incompatTy;
Steve Naroffa78fe7e2007-05-16 19:47:19 +00003471 }
Steve Naroff05efa972009-07-01 14:36:47 +00003472 // The block pointer types are compatible.
Eli Friedman06ed2a52009-10-20 08:27:19 +00003473 ImpCastExprToType(LHS, LHSTy, CastExpr::CK_BitCast);
3474 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
Steve Naroffea4c7802009-04-08 17:05:15 +00003475 return LHSTy;
3476 }
Steve Naroff05efa972009-07-01 14:36:47 +00003477 // Check constraints for Objective-C object pointers types.
Steve Naroff7cae42b2009-07-10 23:34:53 +00003478 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003479
Steve Naroff05efa972009-07-01 14:36:47 +00003480 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3481 // Two identical object pointer types are always compatible.
3482 return LHSTy;
3483 }
John McCall9dd450b2009-09-21 23:43:11 +00003484 const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>();
3485 const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>();
Steve Naroff05efa972009-07-01 14:36:47 +00003486 QualType compositeType = LHSTy;
Mike Stump11289f42009-09-09 15:08:12 +00003487
Steve Naroff05efa972009-07-01 14:36:47 +00003488 // If both operands are interfaces and either operand can be
3489 // assigned to the other, use that type as the composite
3490 // type. This allows
3491 // xxx ? (A*) a : (B*) b
3492 // where B is a subclass of A.
3493 //
3494 // Additionally, as for assignment, if either type is 'id'
3495 // allow silent coercion. Finally, if the types are
3496 // incompatible then make sure to use 'id' as the composite
3497 // type so the result is acceptable for sending messages to.
3498
3499 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
3500 // It could return the composite type.
Steve Naroff7cae42b2009-07-10 23:34:53 +00003501 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
Fariborz Jahaniana83c0162009-08-22 22:27:17 +00003502 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
Steve Naroff7cae42b2009-07-10 23:34:53 +00003503 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
Fariborz Jahaniana83c0162009-08-22 22:27:17 +00003504 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
Mike Stump11289f42009-09-09 15:08:12 +00003505 } else if ((LHSTy->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00003506 RHSTy->isObjCQualifiedIdType()) &&
Steve Naroff8e6aee52009-07-23 01:01:38 +00003507 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
Mike Stump11289f42009-09-09 15:08:12 +00003508 // Need to handle "id<xx>" explicitly.
Steve Naroff7cae42b2009-07-10 23:34:53 +00003509 // GCC allows qualified id and any Objective-C type to devolve to
3510 // id. Currently localizing to here until clear this should be
3511 // part of ObjCQualifiedIdTypesAreCompatible.
3512 compositeType = Context.getObjCIdType();
3513 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
Steve Naroff05efa972009-07-01 14:36:47 +00003514 compositeType = Context.getObjCIdType();
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00003515 } else if (!(compositeType =
3516 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
3517 ;
3518 else {
Steve Naroff05efa972009-07-01 14:36:47 +00003519 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
3520 << LHSTy << RHSTy
3521 << LHS->getSourceRange() << RHS->getSourceRange();
3522 QualType incompatTy = Context.getObjCIdType();
Eli Friedman06ed2a52009-10-20 08:27:19 +00003523 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
3524 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00003525 return incompatTy;
3526 }
3527 // The object pointer types are compatible.
Eli Friedman06ed2a52009-10-20 08:27:19 +00003528 ImpCastExprToType(LHS, compositeType, CastExpr::CK_BitCast);
3529 ImpCastExprToType(RHS, compositeType, CastExpr::CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00003530 return compositeType;
3531 }
Steve Naroff85d97152009-07-29 15:09:39 +00003532 // Check Objective-C object pointer types and 'void *'
3533 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003534 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
John McCall9dd450b2009-09-21 23:43:11 +00003535 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
John McCall8ccfcb52009-09-24 19:53:00 +00003536 QualType destPointee
3537 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
Steve Naroff85d97152009-07-29 15:09:39 +00003538 QualType destType = Context.getPointerType(destPointee);
Eli Friedman06ed2a52009-10-20 08:27:19 +00003539 // Add qualifiers if necessary.
3540 ImpCastExprToType(LHS, destType, CastExpr::CK_NoOp);
3541 // Promote to void*.
3542 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
Steve Naroff85d97152009-07-29 15:09:39 +00003543 return destType;
3544 }
3545 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
John McCall9dd450b2009-09-21 23:43:11 +00003546 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003547 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
John McCall8ccfcb52009-09-24 19:53:00 +00003548 QualType destPointee
3549 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
Steve Naroff85d97152009-07-29 15:09:39 +00003550 QualType destType = Context.getPointerType(destPointee);
Eli Friedman06ed2a52009-10-20 08:27:19 +00003551 // Add qualifiers if necessary.
3552 ImpCastExprToType(RHS, destType, CastExpr::CK_NoOp);
3553 // Promote to void*.
3554 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
Steve Naroff85d97152009-07-29 15:09:39 +00003555 return destType;
3556 }
Steve Naroff05efa972009-07-01 14:36:47 +00003557 // Check constraints for C object pointers types (C99 6.5.15p3,6).
3558 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
3559 // get the "pointed to" types
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003560 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
3561 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff05efa972009-07-01 14:36:47 +00003562
3563 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
3564 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
3565 // Figure out necessary qualifiers (C99 6.5.15p6)
John McCall8ccfcb52009-09-24 19:53:00 +00003566 QualType destPointee
3567 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
Steve Naroff05efa972009-07-01 14:36:47 +00003568 QualType destType = Context.getPointerType(destPointee);
Eli Friedman06ed2a52009-10-20 08:27:19 +00003569 // Add qualifiers if necessary.
3570 ImpCastExprToType(LHS, destType, CastExpr::CK_NoOp);
3571 // Promote to void*.
3572 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00003573 return destType;
3574 }
3575 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00003576 QualType destPointee
3577 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
Steve Naroff05efa972009-07-01 14:36:47 +00003578 QualType destType = Context.getPointerType(destPointee);
Eli Friedman06ed2a52009-10-20 08:27:19 +00003579 // Add qualifiers if necessary.
Eli Friedmanb0bc5592009-11-17 01:22:05 +00003580 ImpCastExprToType(RHS, destType, CastExpr::CK_NoOp);
Eli Friedman06ed2a52009-10-20 08:27:19 +00003581 // Promote to void*.
Eli Friedmanb0bc5592009-11-17 01:22:05 +00003582 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00003583 return destType;
3584 }
3585
3586 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3587 // Two identical pointer types are always compatible.
3588 return LHSTy;
3589 }
3590 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
3591 rhptee.getUnqualifiedType())) {
3592 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
3593 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3594 // In this situation, we assume void* type. No especially good
3595 // reason, but this is what gcc does, and we do have to pick
3596 // to get a consistent AST.
3597 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Eli Friedman06ed2a52009-10-20 08:27:19 +00003598 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
3599 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00003600 return incompatTy;
3601 }
3602 // The pointer types are compatible.
3603 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
3604 // differently qualified versions of compatible types, the result type is
3605 // a pointer to an appropriately qualified version of the *composite*
3606 // type.
3607 // FIXME: Need to calculate the composite type.
3608 // FIXME: Need to add qualifiers
Eli Friedman06ed2a52009-10-20 08:27:19 +00003609 ImpCastExprToType(LHS, LHSTy, CastExpr::CK_BitCast);
3610 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00003611 return LHSTy;
3612 }
Mike Stump11289f42009-09-09 15:08:12 +00003613
Steve Naroff05efa972009-07-01 14:36:47 +00003614 // GCC compatibility: soften pointer/integer mismatch.
3615 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
3616 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
3617 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00003618 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_IntegralToPointer);
Steve Naroff05efa972009-07-01 14:36:47 +00003619 return RHSTy;
3620 }
3621 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
3622 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
3623 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00003624 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_IntegralToPointer);
Steve Naroff05efa972009-07-01 14:36:47 +00003625 return LHSTy;
3626 }
Daniel Dunbar484603b2008-09-11 23:12:46 +00003627
Chris Lattnere2949f42008-01-06 22:42:25 +00003628 // Otherwise, the operands are not compatible.
Chris Lattner432cff52009-02-18 04:28:32 +00003629 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3630 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Steve Naroffa78fe7e2007-05-16 19:47:19 +00003631 return QualType();
Steve Narofff8a28c52007-05-15 20:29:32 +00003632}
3633
Steve Naroff83895f72007-09-16 03:34:24 +00003634/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattnere168f762006-11-10 05:29:30 +00003635/// in the case of a the GNU conditional expr extension.
Sebastian Redlb5d49352009-01-19 22:31:54 +00003636Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
3637 SourceLocation ColonLoc,
3638 ExprArg Cond, ExprArg LHS,
3639 ExprArg RHS) {
3640 Expr *CondExpr = (Expr *) Cond.get();
3641 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
Chris Lattner2ab40a62007-11-26 01:40:58 +00003642
3643 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
3644 // was the condition.
3645 bool isLHSNull = LHSExpr == 0;
3646 if (isLHSNull)
3647 LHSExpr = CondExpr;
Sebastian Redlb5d49352009-01-19 22:31:54 +00003648
3649 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
Chris Lattnerdaaa9f22007-07-16 21:39:03 +00003650 RHSExpr, QuestionLoc);
Steve Narofff8a28c52007-05-15 20:29:32 +00003651 if (result.isNull())
Sebastian Redlb5d49352009-01-19 22:31:54 +00003652 return ExprError();
3653
3654 Cond.release();
3655 LHS.release();
3656 RHS.release();
Douglas Gregor7e112b02009-08-26 14:37:04 +00003657 return Owned(new (Context) ConditionalOperator(CondExpr, QuestionLoc,
Steve Narofff6009ed2009-01-21 00:14:39 +00003658 isLHSNull ? 0 : LHSExpr,
Douglas Gregor7e112b02009-08-26 14:37:04 +00003659 ColonLoc, RHSExpr, result));
Chris Lattnere168f762006-11-10 05:29:30 +00003660}
3661
Steve Naroff3f597292007-05-11 22:18:03 +00003662// CheckPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump4e1f26a2009-02-19 03:04:26 +00003663// being closely modeled after the C99 spec:-). The odd characteristic of this
Steve Naroff3f597292007-05-11 22:18:03 +00003664// routine is it effectively iqnores the qualifiers on the top level pointee.
3665// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
3666// FIXME: add a couple examples in this comment.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003667Sema::AssignConvertType
Steve Naroff98cf3e92007-06-06 18:38:38 +00003668Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
Steve Naroff3f597292007-05-11 22:18:03 +00003669 QualType lhptee, rhptee;
Mike Stump4e1f26a2009-02-19 03:04:26 +00003670
David Chisnall9f57c292009-08-17 16:35:33 +00003671 if ((lhsType->isObjCClassType() &&
3672 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
3673 (rhsType->isObjCClassType() &&
3674 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
3675 return Compatible;
3676 }
3677
Steve Naroff1f4d7272007-05-11 04:00:31 +00003678 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003679 lhptee = lhsType->getAs<PointerType>()->getPointeeType();
3680 rhptee = rhsType->getAs<PointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00003681
Steve Naroff1f4d7272007-05-11 04:00:31 +00003682 // make sure we operate on the canonical type
Chris Lattner574dee62008-07-26 22:17:49 +00003683 lhptee = Context.getCanonicalType(lhptee);
3684 rhptee = Context.getCanonicalType(rhptee);
Steve Naroff1f4d7272007-05-11 04:00:31 +00003685
Chris Lattner9bad62c2008-01-04 18:04:52 +00003686 AssignConvertType ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00003687
3688 // C99 6.5.16.1p1: This following citation is common to constraints
3689 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
3690 // qualifiers of the type *pointed to* by the right;
Fariborz Jahanianece85822009-02-17 18:27:45 +00003691 // FIXME: Handle ExtQualType
Douglas Gregor9a657932008-10-21 23:43:52 +00003692 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner9bad62c2008-01-04 18:04:52 +00003693 ConvTy = CompatiblePointerDiscardsQualifiers;
Steve Naroff3f597292007-05-11 22:18:03 +00003694
Mike Stump4e1f26a2009-02-19 03:04:26 +00003695 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
3696 // incomplete type and the other is a pointer to a qualified or unqualified
Steve Naroff3f597292007-05-11 22:18:03 +00003697 // version of void...
Chris Lattner0a788432008-01-03 22:56:36 +00003698 if (lhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00003699 if (rhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00003700 return ConvTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00003701
Chris Lattner0a788432008-01-03 22:56:36 +00003702 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00003703 assert(rhptee->isFunctionType());
3704 return FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00003705 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00003706
Chris Lattner0a788432008-01-03 22:56:36 +00003707 if (rhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00003708 if (lhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00003709 return ConvTy;
Chris Lattner0a788432008-01-03 22:56:36 +00003710
3711 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00003712 assert(lhptee->isFunctionType());
3713 return FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00003714 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00003715 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Steve Naroff3f597292007-05-11 22:18:03 +00003716 // unqualified versions of compatible types, ...
Eli Friedman80160bd2009-03-22 23:59:44 +00003717 lhptee = lhptee.getUnqualifiedType();
3718 rhptee = rhptee.getUnqualifiedType();
3719 if (!Context.typesAreCompatible(lhptee, rhptee)) {
3720 // Check if the pointee types are compatible ignoring the sign.
3721 // We explicitly check for char so that we catch "char" vs
3722 // "unsigned char" on systems where "char" is unsigned.
Chris Lattnerec3a1562009-10-17 20:33:28 +00003723 if (lhptee->isCharType())
Eli Friedman80160bd2009-03-22 23:59:44 +00003724 lhptee = Context.UnsignedCharTy;
Chris Lattnerec3a1562009-10-17 20:33:28 +00003725 else if (lhptee->isSignedIntegerType())
Eli Friedman80160bd2009-03-22 23:59:44 +00003726 lhptee = Context.getCorrespondingUnsignedType(lhptee);
Chris Lattnerec3a1562009-10-17 20:33:28 +00003727
3728 if (rhptee->isCharType())
Eli Friedman80160bd2009-03-22 23:59:44 +00003729 rhptee = Context.UnsignedCharTy;
Chris Lattnerec3a1562009-10-17 20:33:28 +00003730 else if (rhptee->isSignedIntegerType())
Eli Friedman80160bd2009-03-22 23:59:44 +00003731 rhptee = Context.getCorrespondingUnsignedType(rhptee);
Chris Lattnerec3a1562009-10-17 20:33:28 +00003732
Eli Friedman80160bd2009-03-22 23:59:44 +00003733 if (lhptee == rhptee) {
3734 // Types are compatible ignoring the sign. Qualifier incompatibility
3735 // takes priority over sign incompatibility because the sign
3736 // warning can be disabled.
3737 if (ConvTy != Compatible)
3738 return ConvTy;
3739 return IncompatiblePointerSign;
3740 }
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00003741
3742 // If we are a multi-level pointer, it's possible that our issue is simply
3743 // one of qualification - e.g. char ** -> const char ** is not allowed. If
3744 // the eventual target type is the same and the pointers have the same
3745 // level of indirection, this must be the issue.
3746 if (lhptee->isPointerType() && rhptee->isPointerType()) {
3747 do {
3748 lhptee = lhptee->getAs<PointerType>()->getPointeeType();
3749 rhptee = rhptee->getAs<PointerType>()->getPointeeType();
3750
3751 lhptee = Context.getCanonicalType(lhptee);
3752 rhptee = Context.getCanonicalType(rhptee);
3753 } while (lhptee->isPointerType() && rhptee->isPointerType());
3754
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003755 if (Context.hasSameUnqualifiedType(lhptee, rhptee))
Alexis Hunt6f3de502009-11-08 07:46:34 +00003756 return IncompatibleNestedPointerQualifiers;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00003757 }
3758
Eli Friedman80160bd2009-03-22 23:59:44 +00003759 // General pointer incompatibility takes priority over qualifiers.
Mike Stump11289f42009-09-09 15:08:12 +00003760 return IncompatiblePointer;
Eli Friedman80160bd2009-03-22 23:59:44 +00003761 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00003762 return ConvTy;
Steve Naroff1f4d7272007-05-11 04:00:31 +00003763}
3764
Steve Naroff081c7422008-09-04 15:10:53 +00003765/// CheckBlockPointerTypesForAssignment - This routine determines whether two
3766/// block pointer types are compatible or whether a block and normal pointer
3767/// are compatible. It is more restrict than comparing two function pointer
3768// types.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003769Sema::AssignConvertType
3770Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
Steve Naroff081c7422008-09-04 15:10:53 +00003771 QualType rhsType) {
3772 QualType lhptee, rhptee;
Mike Stump4e1f26a2009-02-19 03:04:26 +00003773
Steve Naroff081c7422008-09-04 15:10:53 +00003774 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003775 lhptee = lhsType->getAs<BlockPointerType>()->getPointeeType();
3776 rhptee = rhsType->getAs<BlockPointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00003777
Steve Naroff081c7422008-09-04 15:10:53 +00003778 // make sure we operate on the canonical type
3779 lhptee = Context.getCanonicalType(lhptee);
3780 rhptee = Context.getCanonicalType(rhptee);
Mike Stump4e1f26a2009-02-19 03:04:26 +00003781
Steve Naroff081c7422008-09-04 15:10:53 +00003782 AssignConvertType ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00003783
Steve Naroff081c7422008-09-04 15:10:53 +00003784 // For blocks we enforce that qualifiers are identical.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003785 if (lhptee.getLocalCVRQualifiers() != rhptee.getLocalCVRQualifiers())
Steve Naroff081c7422008-09-04 15:10:53 +00003786 ConvTy = CompatiblePointerDiscardsQualifiers;
Mike Stump4e1f26a2009-02-19 03:04:26 +00003787
Eli Friedmana6638ca2009-06-08 05:08:54 +00003788 if (!Context.typesAreCompatible(lhptee, rhptee))
Mike Stump4e1f26a2009-02-19 03:04:26 +00003789 return IncompatibleBlockPointer;
Steve Naroff081c7422008-09-04 15:10:53 +00003790 return ConvTy;
3791}
3792
Mike Stump4e1f26a2009-02-19 03:04:26 +00003793/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
3794/// has code to accommodate several GCC extensions when type checking
Steve Naroff17f76e02007-05-03 21:03:48 +00003795/// pointers. Here are some objectionable examples that GCC considers warnings:
3796///
3797/// int a, *pint;
3798/// short *pshort;
3799/// struct foo *pfoo;
3800///
3801/// pint = pshort; // warning: assignment from incompatible pointer type
3802/// a = pint; // warning: assignment makes integer from pointer without a cast
3803/// pint = a; // warning: assignment makes pointer from integer without a cast
3804/// pint = pfoo; // warning: assignment from incompatible pointer type
3805///
3806/// As a result, the code for dealing with pointers is more complex than the
Mike Stump4e1f26a2009-02-19 03:04:26 +00003807/// C99 spec dictates.
Steve Naroff17f76e02007-05-03 21:03:48 +00003808///
Chris Lattner9bad62c2008-01-04 18:04:52 +00003809Sema::AssignConvertType
Steve Naroff98cf3e92007-06-06 18:38:38 +00003810Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattnera52c2f22008-01-04 23:18:45 +00003811 // Get canonical types. We're not formatting these types, just comparing
3812 // them.
Chris Lattner574dee62008-07-26 22:17:49 +00003813 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
3814 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman3360d892008-05-30 18:07:22 +00003815
3816 if (lhsType == rhsType)
Chris Lattnerf5c973d2008-01-07 17:51:46 +00003817 return Compatible; // Common case: fast path an exact match.
Steve Naroff44fd8ff2007-07-24 21:46:40 +00003818
David Chisnall9f57c292009-08-17 16:35:33 +00003819 if ((lhsType->isObjCClassType() &&
3820 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
3821 (rhsType->isObjCClassType() &&
3822 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
3823 return Compatible;
3824 }
3825
Douglas Gregor6b754842008-10-28 00:22:11 +00003826 // If the left-hand side is a reference type, then we are in a
3827 // (rare!) case where we've allowed the use of references in C,
3828 // e.g., as a parameter type in a built-in function. In this case,
3829 // just make sure that the type referenced is compatible with the
3830 // right-hand side type. The caller is responsible for adjusting
3831 // lhsType so that the resulting expression does not have reference
3832 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003833 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
Douglas Gregor6b754842008-10-28 00:22:11 +00003834 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlsson24ebce62007-10-12 23:56:29 +00003835 return Compatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00003836 return Incompatible;
Fariborz Jahaniana1e34202007-12-19 17:45:58 +00003837 }
Nate Begemanbd956c42009-06-28 02:36:38 +00003838 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
3839 // to the same ExtVector type.
3840 if (lhsType->isExtVectorType()) {
3841 if (rhsType->isExtVectorType())
3842 return lhsType == rhsType ? Compatible : Incompatible;
3843 if (!rhsType->isVectorType() && rhsType->isArithmeticType())
3844 return Compatible;
3845 }
Mike Stump11289f42009-09-09 15:08:12 +00003846
Nate Begeman191a6b12008-07-14 18:02:46 +00003847 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begeman191a6b12008-07-14 18:02:46 +00003848 // If we are allowing lax vector conversions, and LHS and RHS are both
Mike Stump4e1f26a2009-02-19 03:04:26 +00003849 // vectors, the total size only needs to be the same. This is a bitcast;
Nate Begeman191a6b12008-07-14 18:02:46 +00003850 // no bits are changed but the result type is different.
Chris Lattner881a2122008-01-04 23:32:24 +00003851 if (getLangOptions().LaxVectorConversions &&
3852 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begeman191a6b12008-07-14 18:02:46 +00003853 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
Anders Carlssondb5a9b62009-01-30 23:17:46 +00003854 return IncompatibleVectors;
Chris Lattner881a2122008-01-04 23:32:24 +00003855 }
3856 return Incompatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00003857 }
Eli Friedman3360d892008-05-30 18:07:22 +00003858
Chris Lattner881a2122008-01-04 23:32:24 +00003859 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Steve Naroff98cf3e92007-06-06 18:38:38 +00003860 return Compatible;
Eli Friedman3360d892008-05-30 18:07:22 +00003861
Chris Lattnerec646832008-04-07 06:49:41 +00003862 if (isa<PointerType>(lhsType)) {
Steve Naroff98cf3e92007-06-06 18:38:38 +00003863 if (rhsType->isIntegerType())
Chris Lattner940cfeb2008-01-04 18:22:42 +00003864 return IntToPointer;
Eli Friedman3360d892008-05-30 18:07:22 +00003865
Chris Lattnerec646832008-04-07 06:49:41 +00003866 if (isa<PointerType>(rhsType))
Steve Naroff98cf3e92007-06-06 18:38:38 +00003867 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stump4e1f26a2009-02-19 03:04:26 +00003868
Steve Naroffaccc4882009-07-20 17:56:53 +00003869 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00003870 if (isa<ObjCObjectPointerType>(rhsType)) {
Steve Naroffaccc4882009-07-20 17:56:53 +00003871 if (lhsType->isVoidPointerType()) // an exception to the rule.
3872 return Compatible;
3873 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00003874 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003875 if (rhsType->getAs<BlockPointerType>()) {
3876 if (lhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregore7dd1452008-11-27 00:44:28 +00003877 return Compatible;
Steve Naroff32d072c2008-09-29 18:10:17 +00003878
3879 // Treat block pointers as objects.
Steve Naroff7cae42b2009-07-10 23:34:53 +00003880 if (getLangOptions().ObjC1 && lhsType->isObjCIdType())
Steve Naroff32d072c2008-09-29 18:10:17 +00003881 return Compatible;
3882 }
Steve Naroff081c7422008-09-04 15:10:53 +00003883 return Incompatible;
3884 }
3885
3886 if (isa<BlockPointerType>(lhsType)) {
3887 if (rhsType->isIntegerType())
Eli Friedman8163b7a2009-02-25 04:20:42 +00003888 return IntToBlockPointer;
Mike Stump4e1f26a2009-02-19 03:04:26 +00003889
Steve Naroff32d072c2008-09-29 18:10:17 +00003890 // Treat block pointers as objects.
Steve Naroff7cae42b2009-07-10 23:34:53 +00003891 if (getLangOptions().ObjC1 && rhsType->isObjCIdType())
Steve Naroff32d072c2008-09-29 18:10:17 +00003892 return Compatible;
3893
Steve Naroff081c7422008-09-04 15:10:53 +00003894 if (rhsType->isBlockPointerType())
3895 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
Mike Stump4e1f26a2009-02-19 03:04:26 +00003896
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003897 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff081c7422008-09-04 15:10:53 +00003898 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregore7dd1452008-11-27 00:44:28 +00003899 return Compatible;
Steve Naroff081c7422008-09-04 15:10:53 +00003900 }
Chris Lattnera52c2f22008-01-04 23:18:45 +00003901 return Incompatible;
3902 }
3903
Steve Naroff7cae42b2009-07-10 23:34:53 +00003904 if (isa<ObjCObjectPointerType>(lhsType)) {
3905 if (rhsType->isIntegerType())
3906 return IntToPointer;
Mike Stump11289f42009-09-09 15:08:12 +00003907
Steve Naroffaccc4882009-07-20 17:56:53 +00003908 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00003909 if (isa<PointerType>(rhsType)) {
Steve Naroffaccc4882009-07-20 17:56:53 +00003910 if (rhsType->isVoidPointerType()) // an exception to the rule.
3911 return Compatible;
3912 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00003913 }
3914 if (rhsType->isObjCObjectPointerType()) {
Steve Naroff1329fa02009-07-15 18:40:39 +00003915 if (lhsType->isObjCBuiltinType() || rhsType->isObjCBuiltinType())
3916 return Compatible;
Steve Naroffaccc4882009-07-20 17:56:53 +00003917 if (Context.typesAreCompatible(lhsType, rhsType))
3918 return Compatible;
Steve Naroff8e6aee52009-07-23 01:01:38 +00003919 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
3920 return IncompatibleObjCQualifiedId;
Steve Naroffaccc4882009-07-20 17:56:53 +00003921 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00003922 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003923 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003924 if (RHSPT->getPointeeType()->isVoidType())
3925 return Compatible;
3926 }
3927 // Treat block pointers as objects.
3928 if (rhsType->isBlockPointerType())
3929 return Compatible;
3930 return Incompatible;
3931 }
Chris Lattnerec646832008-04-07 06:49:41 +00003932 if (isa<PointerType>(rhsType)) {
Steve Naroff98cf3e92007-06-06 18:38:38 +00003933 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedman3360d892008-05-30 18:07:22 +00003934 if (lhsType == Context.BoolTy)
3935 return Compatible;
3936
3937 if (lhsType->isIntegerType())
Chris Lattner940cfeb2008-01-04 18:22:42 +00003938 return PointerToInt;
Steve Naroff98cf3e92007-06-06 18:38:38 +00003939
Mike Stump4e1f26a2009-02-19 03:04:26 +00003940 if (isa<PointerType>(lhsType))
Steve Naroff98cf3e92007-06-06 18:38:38 +00003941 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stump4e1f26a2009-02-19 03:04:26 +00003942
3943 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003944 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregore7dd1452008-11-27 00:44:28 +00003945 return Compatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00003946 return Incompatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00003947 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00003948 if (isa<ObjCObjectPointerType>(rhsType)) {
3949 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
3950 if (lhsType == Context.BoolTy)
3951 return Compatible;
3952
3953 if (lhsType->isIntegerType())
3954 return PointerToInt;
3955
Steve Naroffaccc4882009-07-20 17:56:53 +00003956 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00003957 if (isa<PointerType>(lhsType)) {
Steve Naroffaccc4882009-07-20 17:56:53 +00003958 if (lhsType->isVoidPointerType()) // an exception to the rule.
3959 return Compatible;
3960 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00003961 }
3962 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003963 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00003964 return Compatible;
3965 return Incompatible;
3966 }
Eli Friedman3360d892008-05-30 18:07:22 +00003967
Chris Lattnera52c2f22008-01-04 23:18:45 +00003968 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattnerec646832008-04-07 06:49:41 +00003969 if (Context.typesAreCompatible(lhsType, rhsType))
Steve Naroff98cf3e92007-06-06 18:38:38 +00003970 return Compatible;
Bill Wendling216423b2007-05-30 06:30:29 +00003971 }
Steve Naroff98cf3e92007-06-06 18:38:38 +00003972 return Incompatible;
Steve Naroff9eb24652007-05-02 21:58:15 +00003973}
3974
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00003975/// \brief Constructs a transparent union from an expression that is
3976/// used to initialize the transparent union.
Mike Stump11289f42009-09-09 15:08:12 +00003977static void ConstructTransparentUnion(ASTContext &C, Expr *&E,
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00003978 QualType UnionType, FieldDecl *Field) {
3979 // Build an initializer list that designates the appropriate member
3980 // of the transparent union.
3981 InitListExpr *Initializer = new (C) InitListExpr(SourceLocation(),
3982 &E, 1,
3983 SourceLocation());
3984 Initializer->setType(UnionType);
3985 Initializer->setInitializedFieldInUnion(Field);
3986
3987 // Build a compound literal constructing a value of the transparent
3988 // union type from this initializer list.
3989 E = new (C) CompoundLiteralExpr(SourceLocation(), UnionType, Initializer,
3990 false);
3991}
3992
3993Sema::AssignConvertType
3994Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) {
3995 QualType FromType = rExpr->getType();
3996
Mike Stump11289f42009-09-09 15:08:12 +00003997 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00003998 // transparent_union GCC extension.
3999 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004000 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004001 return Incompatible;
4002
4003 // The field to initialize within the transparent union.
4004 RecordDecl *UD = UT->getDecl();
4005 FieldDecl *InitField = 0;
4006 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004007 for (RecordDecl::field_iterator it = UD->field_begin(),
4008 itend = UD->field_end();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004009 it != itend; ++it) {
4010 if (it->getType()->isPointerType()) {
4011 // If the transparent union contains a pointer type, we allow:
4012 // 1) void pointer
4013 // 2) null pointer constant
4014 if (FromType->isPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004015 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004016 ImpCastExprToType(rExpr, it->getType(), CastExpr::CK_BitCast);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004017 InitField = *it;
4018 break;
4019 }
Mike Stump11289f42009-09-09 15:08:12 +00004020
Douglas Gregor56751b52009-09-25 04:25:58 +00004021 if (rExpr->isNullPointerConstant(Context,
4022 Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004023 ImpCastExprToType(rExpr, it->getType(), CastExpr::CK_IntegralToPointer);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004024 InitField = *it;
4025 break;
4026 }
4027 }
4028
4029 if (CheckAssignmentConstraints(it->getType(), rExpr->getType())
4030 == Compatible) {
4031 InitField = *it;
4032 break;
4033 }
4034 }
4035
4036 if (!InitField)
4037 return Incompatible;
4038
4039 ConstructTransparentUnion(Context, rExpr, ArgType, InitField);
4040 return Compatible;
4041}
4042
Chris Lattner9bad62c2008-01-04 18:04:52 +00004043Sema::AssignConvertType
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00004044Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor9a657932008-10-21 23:43:52 +00004045 if (getLangOptions().CPlusPlus) {
4046 if (!lhsType->isRecordType()) {
4047 // C++ 5.17p3: If the left operand is not of class type, the
4048 // expression is implicitly converted (C++ 4) to the
4049 // cv-unqualified type of the left operand.
Douglas Gregor47d3f272008-12-19 17:40:08 +00004050 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
4051 "assigning"))
Douglas Gregor9a657932008-10-21 23:43:52 +00004052 return Incompatible;
Chris Lattner0d5640c2009-04-12 09:02:39 +00004053 return Compatible;
Douglas Gregor9a657932008-10-21 23:43:52 +00004054 }
4055
4056 // FIXME: Currently, we fall through and treat C++ classes like C
4057 // structures.
4058 }
4059
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00004060 // C99 6.5.16.1p1: the left operand is a pointer and the right is
4061 // a null pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00004062 if ((lhsType->isPointerType() ||
4063 lhsType->isObjCObjectPointerType() ||
Mike Stump4e1f26a2009-02-19 03:04:26 +00004064 lhsType->isBlockPointerType())
Douglas Gregor56751b52009-09-25 04:25:58 +00004065 && rExpr->isNullPointerConstant(Context,
4066 Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004067 ImpCastExprToType(rExpr, lhsType, CastExpr::CK_Unknown);
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00004068 return Compatible;
4069 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004070
Chris Lattnere6dcd502007-10-16 02:55:40 +00004071 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00004072 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregora121b752009-11-03 16:56:39 +00004073 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00004074 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattnere6dcd502007-10-16 02:55:40 +00004075 //
Mike Stump4e1f26a2009-02-19 03:04:26 +00004076 // Suppress this for references: C++ 8.5.3p5.
Chris Lattnere6dcd502007-10-16 02:55:40 +00004077 if (!lhsType->isReferenceType())
4078 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00004079
Chris Lattner9bad62c2008-01-04 18:04:52 +00004080 Sema::AssignConvertType result =
4081 CheckAssignmentConstraints(lhsType, rExpr->getType());
Mike Stump4e1f26a2009-02-19 03:04:26 +00004082
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00004083 // C99 6.5.16.1p2: The value of the right operand is converted to the
4084 // type of the assignment expression.
Douglas Gregor6b754842008-10-28 00:22:11 +00004085 // CheckAssignmentConstraints allows the left-hand side to be a reference,
4086 // so that we can use references in built-in functions even in C.
4087 // The getNonReferenceType() call makes sure that the resulting expression
4088 // does not have reference type.
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004089 if (result != Incompatible && rExpr->getType() != lhsType)
Eli Friedman06ed2a52009-10-20 08:27:19 +00004090 ImpCastExprToType(rExpr, lhsType.getNonReferenceType(),
4091 CastExpr::CK_Unknown);
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00004092 return result;
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00004093}
4094
Chris Lattner326f7572008-11-18 01:30:42 +00004095QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattner377d1f82008-11-18 22:52:51 +00004096 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattner6a2ed6f2008-11-23 09:13:29 +00004097 << lex->getType() << rex->getType()
Chris Lattner377d1f82008-11-18 22:52:51 +00004098 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner5c11c412007-12-12 05:47:28 +00004099 return QualType();
Steve Naroff6f49f5d2007-05-29 14:23:36 +00004100}
4101
Mike Stump4e1f26a2009-02-19 03:04:26 +00004102inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Steve Naroff7a5af782007-07-13 16:58:59 +00004103 Expr *&rex) {
Mike Stump4e1f26a2009-02-19 03:04:26 +00004104 // For conversion purposes, we ignore any qualifiers.
Nate Begeman002e4bd2008-04-04 01:30:25 +00004105 // For example, "const float" and "float" are equivalent.
Chris Lattner574dee62008-07-26 22:17:49 +00004106 QualType lhsType =
4107 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
4108 QualType rhsType =
4109 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004110
Nate Begeman191a6b12008-07-14 18:02:46 +00004111 // If the vector types are identical, return.
Nate Begeman002e4bd2008-04-04 01:30:25 +00004112 if (lhsType == rhsType)
Steve Naroff84ff4b42007-07-09 21:31:10 +00004113 return lhsType;
Nate Begeman330aaa72007-12-30 02:59:45 +00004114
Nate Begeman191a6b12008-07-14 18:02:46 +00004115 // Handle the case of a vector & extvector type of the same size and element
4116 // type. It would be nice if we only had one vector type someday.
Anders Carlssondb5a9b62009-01-30 23:17:46 +00004117 if (getLangOptions().LaxVectorConversions) {
4118 // FIXME: Should we warn here?
John McCall9dd450b2009-09-21 23:43:11 +00004119 if (const VectorType *LV = lhsType->getAs<VectorType>()) {
4120 if (const VectorType *RV = rhsType->getAs<VectorType>())
Nate Begeman191a6b12008-07-14 18:02:46 +00004121 if (LV->getElementType() == RV->getElementType() &&
Anders Carlssondb5a9b62009-01-30 23:17:46 +00004122 LV->getNumElements() == RV->getNumElements()) {
Nate Begeman191a6b12008-07-14 18:02:46 +00004123 return lhsType->isExtVectorType() ? lhsType : rhsType;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00004124 }
4125 }
4126 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004127
Nate Begemanbd956c42009-06-28 02:36:38 +00004128 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
4129 // swap back (so that we don't reverse the inputs to a subtract, for instance.
4130 bool swapped = false;
4131 if (rhsType->isExtVectorType()) {
4132 swapped = true;
4133 std::swap(rex, lex);
4134 std::swap(rhsType, lhsType);
4135 }
Mike Stump11289f42009-09-09 15:08:12 +00004136
Nate Begeman886448d2009-06-28 19:12:57 +00004137 // Handle the case of an ext vector and scalar.
John McCall9dd450b2009-09-21 23:43:11 +00004138 if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) {
Nate Begemanbd956c42009-06-28 02:36:38 +00004139 QualType EltTy = LV->getElementType();
4140 if (EltTy->isIntegralType() && rhsType->isIntegralType()) {
4141 if (Context.getIntegerTypeOrder(EltTy, rhsType) >= 0) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004142 ImpCastExprToType(rex, lhsType, CastExpr::CK_IntegralCast);
Nate Begemanbd956c42009-06-28 02:36:38 +00004143 if (swapped) std::swap(rex, lex);
4144 return lhsType;
4145 }
4146 }
4147 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
4148 rhsType->isRealFloatingType()) {
4149 if (Context.getFloatingTypeOrder(EltTy, rhsType) >= 0) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004150 ImpCastExprToType(rex, lhsType, CastExpr::CK_FloatingCast);
Nate Begemanbd956c42009-06-28 02:36:38 +00004151 if (swapped) std::swap(rex, lex);
4152 return lhsType;
4153 }
Nate Begeman330aaa72007-12-30 02:59:45 +00004154 }
4155 }
Mike Stump11289f42009-09-09 15:08:12 +00004156
Nate Begeman886448d2009-06-28 19:12:57 +00004157 // Vectors of different size or scalar and non-ext-vector are errors.
Chris Lattner377d1f82008-11-18 22:52:51 +00004158 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004159 << lex->getType() << rex->getType()
Chris Lattner377d1f82008-11-18 22:52:51 +00004160 << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff84ff4b42007-07-09 21:31:10 +00004161 return QualType();
Sebastian Redl112a97662009-02-07 00:15:38 +00004162}
4163
Steve Naroff218bc2b2007-05-04 21:54:46 +00004164inline QualType Sema::CheckMultiplyDivideOperands(
Mike Stump11289f42009-09-09 15:08:12 +00004165 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Daniel Dunbar060d5e22009-01-05 22:42:10 +00004166 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner326f7572008-11-18 01:30:42 +00004167 return CheckVectorOperands(Loc, lex, rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004168
Steve Naroffbe4c4d12007-08-24 19:07:16 +00004169 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004170
Steve Naroffdbd9e892007-07-17 00:58:39 +00004171 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroffbe4c4d12007-08-24 19:07:16 +00004172 return compType;
Chris Lattner326f7572008-11-18 01:30:42 +00004173 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00004174}
4175
Steve Naroff218bc2b2007-05-04 21:54:46 +00004176inline QualType Sema::CheckRemainderOperands(
Mike Stump11289f42009-09-09 15:08:12 +00004177 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Daniel Dunbar0d2bfec2009-01-05 22:55:36 +00004178 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4179 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
4180 return CheckVectorOperands(Loc, lex, rex);
4181 return InvalidOperands(Loc, lex, rex);
4182 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00004183
Steve Naroffbe4c4d12007-08-24 19:07:16 +00004184 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004185
Steve Naroffdbd9e892007-07-17 00:58:39 +00004186 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroffbe4c4d12007-08-24 19:07:16 +00004187 return compType;
Chris Lattner326f7572008-11-18 01:30:42 +00004188 return InvalidOperands(Loc, lex, rex);
Steve Naroff218bc2b2007-05-04 21:54:46 +00004189}
4190
4191inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Mike Stump11289f42009-09-09 15:08:12 +00004192 Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004193 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4194 QualType compType = CheckVectorOperands(Loc, lex, rex);
4195 if (CompLHSTy) *CompLHSTy = compType;
4196 return compType;
4197 }
Steve Naroff7a5af782007-07-13 16:58:59 +00004198
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004199 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Eli Friedman8e122982008-05-18 18:08:51 +00004200
Steve Naroffe4718892007-04-27 18:30:00 +00004201 // handle the common case first (both operands are arithmetic).
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004202 if (lex->getType()->isArithmeticType() &&
4203 rex->getType()->isArithmeticType()) {
4204 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00004205 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004206 }
Steve Naroff218bc2b2007-05-04 21:54:46 +00004207
Eli Friedman8e122982008-05-18 18:08:51 +00004208 // Put any potential pointer into PExp
4209 Expr* PExp = lex, *IExp = rex;
Steve Naroff6b712a72009-07-14 18:25:06 +00004210 if (IExp->getType()->isAnyPointerType())
Eli Friedman8e122982008-05-18 18:08:51 +00004211 std::swap(PExp, IExp);
4212
Steve Naroff6b712a72009-07-14 18:25:06 +00004213 if (PExp->getType()->isAnyPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00004214
Eli Friedman8e122982008-05-18 18:08:51 +00004215 if (IExp->getType()->isIntegerType()) {
Steve Naroffaacd4cc2009-07-13 21:20:41 +00004216 QualType PointeeTy = PExp->getType()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00004217
Chris Lattner12bdebb2009-04-24 23:50:08 +00004218 // Check for arithmetic on pointers to incomplete types.
4219 if (PointeeTy->isVoidType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00004220 if (getLangOptions().CPlusPlus) {
4221 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
Chris Lattner3b054132008-11-19 05:08:23 +00004222 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregordd430f72009-01-19 19:26:10 +00004223 return QualType();
Eli Friedman8e122982008-05-18 18:08:51 +00004224 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00004225
4226 // GNU extension: arithmetic on pointer to void
4227 Diag(Loc, diag::ext_gnu_void_ptr)
4228 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner12bdebb2009-04-24 23:50:08 +00004229 } else if (PointeeTy->isFunctionType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00004230 if (getLangOptions().CPlusPlus) {
4231 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
4232 << lex->getType() << lex->getSourceRange();
4233 return QualType();
4234 }
4235
4236 // GNU extension: arithmetic on pointer to function
4237 Diag(Loc, diag::ext_gnu_ptr_func_arith)
4238 << lex->getType() << lex->getSourceRange();
Steve Naroffa63372d2009-07-13 21:32:29 +00004239 } else {
Steve Naroffaacd4cc2009-07-13 21:20:41 +00004240 // Check if we require a complete type.
Mike Stump11289f42009-09-09 15:08:12 +00004241 if (((PExp->getType()->isPointerType() &&
Steve Naroffa63372d2009-07-13 21:32:29 +00004242 !PExp->getType()->isDependentType()) ||
Steve Naroffaacd4cc2009-07-13 21:20:41 +00004243 PExp->getType()->isObjCObjectPointerType()) &&
4244 RequireCompleteType(Loc, PointeeTy,
Mike Stump11289f42009-09-09 15:08:12 +00004245 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
4246 << PExp->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00004247 << PExp->getType()))
Steve Naroffaacd4cc2009-07-13 21:20:41 +00004248 return QualType();
4249 }
Chris Lattner12bdebb2009-04-24 23:50:08 +00004250 // Diagnose bad cases where we step over interface counts.
4251 if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4252 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
4253 << PointeeTy << PExp->getSourceRange();
4254 return QualType();
4255 }
Mike Stump11289f42009-09-09 15:08:12 +00004256
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004257 if (CompLHSTy) {
Eli Friedman629ffb92009-08-20 04:21:42 +00004258 QualType LHSTy = Context.isPromotableBitField(lex);
4259 if (LHSTy.isNull()) {
4260 LHSTy = lex->getType();
4261 if (LHSTy->isPromotableIntegerType())
4262 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregord2c2d172009-05-02 00:36:19 +00004263 }
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004264 *CompLHSTy = LHSTy;
4265 }
Eli Friedman8e122982008-05-18 18:08:51 +00004266 return PExp->getType();
4267 }
4268 }
4269
Chris Lattner326f7572008-11-18 01:30:42 +00004270 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00004271}
4272
Chris Lattner2a3569b2008-04-07 05:30:13 +00004273// C99 6.5.6
4274QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004275 SourceLocation Loc, QualType* CompLHSTy) {
4276 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4277 QualType compType = CheckVectorOperands(Loc, lex, rex);
4278 if (CompLHSTy) *CompLHSTy = compType;
4279 return compType;
4280 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004281
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004282 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004283
Chris Lattner4d62f422007-12-09 21:53:25 +00004284 // Enforce type constraints: C99 6.5.6p3.
Mike Stump4e1f26a2009-02-19 03:04:26 +00004285
Chris Lattner4d62f422007-12-09 21:53:25 +00004286 // Handle the common case first (both operands are arithmetic).
Mike Stumpf70bcf72009-05-07 18:43:07 +00004287 if (lex->getType()->isArithmeticType()
4288 && rex->getType()->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004289 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00004290 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004291 }
Mike Stump11289f42009-09-09 15:08:12 +00004292
Chris Lattner4d62f422007-12-09 21:53:25 +00004293 // Either ptr - int or ptr - ptr.
Steve Naroff6b712a72009-07-14 18:25:06 +00004294 if (lex->getType()->isAnyPointerType()) {
Steve Naroff4eed7a12009-07-13 17:19:15 +00004295 QualType lpointee = lex->getType()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004296
Douglas Gregorac1fb652009-03-24 19:52:54 +00004297 // The LHS must be an completely-defined object type.
Douglas Gregorf6cd9282009-01-23 00:36:41 +00004298
Douglas Gregorac1fb652009-03-24 19:52:54 +00004299 bool ComplainAboutVoid = false;
4300 Expr *ComplainAboutFunc = 0;
4301 if (lpointee->isVoidType()) {
4302 if (getLangOptions().CPlusPlus) {
4303 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
4304 << lex->getSourceRange() << rex->getSourceRange();
4305 return QualType();
4306 }
4307
4308 // GNU C extension: arithmetic on pointer to void
4309 ComplainAboutVoid = true;
4310 } else if (lpointee->isFunctionType()) {
4311 if (getLangOptions().CPlusPlus) {
4312 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004313 << lex->getType() << lex->getSourceRange();
Chris Lattner4d62f422007-12-09 21:53:25 +00004314 return QualType();
4315 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00004316
4317 // GNU C extension: arithmetic on pointer to function
4318 ComplainAboutFunc = lex;
4319 } else if (!lpointee->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00004320 RequireCompleteType(Loc, lpointee,
Anders Carlsson029fc692009-08-26 22:59:12 +00004321 PDiag(diag::err_typecheck_sub_ptr_object)
Mike Stump11289f42009-09-09 15:08:12 +00004322 << lex->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00004323 << lex->getType()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00004324 return QualType();
Chris Lattner4d62f422007-12-09 21:53:25 +00004325
Chris Lattner12bdebb2009-04-24 23:50:08 +00004326 // Diagnose bad cases where we step over interface counts.
4327 if (lpointee->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4328 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
4329 << lpointee << lex->getSourceRange();
4330 return QualType();
4331 }
Mike Stump11289f42009-09-09 15:08:12 +00004332
Chris Lattner4d62f422007-12-09 21:53:25 +00004333 // The result type of a pointer-int computation is the pointer type.
Douglas Gregorac1fb652009-03-24 19:52:54 +00004334 if (rex->getType()->isIntegerType()) {
4335 if (ComplainAboutVoid)
4336 Diag(Loc, diag::ext_gnu_void_ptr)
4337 << lex->getSourceRange() << rex->getSourceRange();
4338 if (ComplainAboutFunc)
4339 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump11289f42009-09-09 15:08:12 +00004340 << ComplainAboutFunc->getType()
Douglas Gregorac1fb652009-03-24 19:52:54 +00004341 << ComplainAboutFunc->getSourceRange();
4342
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004343 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00004344 return lex->getType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00004345 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004346
Chris Lattner4d62f422007-12-09 21:53:25 +00004347 // Handle pointer-pointer subtractions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004348 if (const PointerType *RHSPTy = rex->getType()->getAs<PointerType>()) {
Eli Friedman1974e532008-02-08 01:19:44 +00004349 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004350
Douglas Gregorac1fb652009-03-24 19:52:54 +00004351 // RHS must be a completely-type object type.
4352 // Handle the GNU void* extension.
4353 if (rpointee->isVoidType()) {
4354 if (getLangOptions().CPlusPlus) {
4355 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
4356 << lex->getSourceRange() << rex->getSourceRange();
4357 return QualType();
4358 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004359
Douglas Gregorac1fb652009-03-24 19:52:54 +00004360 ComplainAboutVoid = true;
4361 } else if (rpointee->isFunctionType()) {
4362 if (getLangOptions().CPlusPlus) {
4363 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004364 << rex->getType() << rex->getSourceRange();
Chris Lattner4d62f422007-12-09 21:53:25 +00004365 return QualType();
4366 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00004367
4368 // GNU extension: arithmetic on pointer to function
4369 if (!ComplainAboutFunc)
4370 ComplainAboutFunc = rex;
4371 } else if (!rpointee->isDependentType() &&
4372 RequireCompleteType(Loc, rpointee,
Anders Carlsson029fc692009-08-26 22:59:12 +00004373 PDiag(diag::err_typecheck_sub_ptr_object)
4374 << rex->getSourceRange()
4375 << rex->getType()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00004376 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004377
Eli Friedman168fe152009-05-16 13:54:38 +00004378 if (getLangOptions().CPlusPlus) {
4379 // Pointee types must be the same: C++ [expr.add]
4380 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
4381 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
4382 << lex->getType() << rex->getType()
4383 << lex->getSourceRange() << rex->getSourceRange();
4384 return QualType();
4385 }
4386 } else {
4387 // Pointee types must be compatible C99 6.5.6p3
4388 if (!Context.typesAreCompatible(
4389 Context.getCanonicalType(lpointee).getUnqualifiedType(),
4390 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
4391 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
4392 << lex->getType() << rex->getType()
4393 << lex->getSourceRange() << rex->getSourceRange();
4394 return QualType();
4395 }
Chris Lattner4d62f422007-12-09 21:53:25 +00004396 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004397
Douglas Gregorac1fb652009-03-24 19:52:54 +00004398 if (ComplainAboutVoid)
4399 Diag(Loc, diag::ext_gnu_void_ptr)
4400 << lex->getSourceRange() << rex->getSourceRange();
4401 if (ComplainAboutFunc)
4402 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump11289f42009-09-09 15:08:12 +00004403 << ComplainAboutFunc->getType()
Douglas Gregorac1fb652009-03-24 19:52:54 +00004404 << ComplainAboutFunc->getSourceRange();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004405
4406 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00004407 return Context.getPointerDiffType();
4408 }
4409 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004410
Chris Lattner326f7572008-11-18 01:30:42 +00004411 return InvalidOperands(Loc, lex, rex);
Steve Naroff218bc2b2007-05-04 21:54:46 +00004412}
4413
Chris Lattner2a3569b2008-04-07 05:30:13 +00004414// C99 6.5.7
Chris Lattner326f7572008-11-18 01:30:42 +00004415QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattner2a3569b2008-04-07 05:30:13 +00004416 bool isCompAssign) {
Chris Lattner5c11c412007-12-12 05:47:28 +00004417 // C99 6.5.7p2: Each of the operands shall have integer type.
4418 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner326f7572008-11-18 01:30:42 +00004419 return InvalidOperands(Loc, lex, rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004420
Nate Begemane46ee9a2009-10-25 02:26:48 +00004421 // Vector shifts promote their scalar inputs to vector type.
4422 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
4423 return CheckVectorOperands(Loc, lex, rex);
4424
Chris Lattner5c11c412007-12-12 05:47:28 +00004425 // Shifts don't perform usual arithmetic conversions, they just do integer
4426 // promotions on each operand. C99 6.5.7p3
Eli Friedman629ffb92009-08-20 04:21:42 +00004427 QualType LHSTy = Context.isPromotableBitField(lex);
4428 if (LHSTy.isNull()) {
4429 LHSTy = lex->getType();
4430 if (LHSTy->isPromotableIntegerType())
4431 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregord2c2d172009-05-02 00:36:19 +00004432 }
Chris Lattner3c133402007-12-13 07:28:16 +00004433 if (!isCompAssign)
Eli Friedman06ed2a52009-10-20 08:27:19 +00004434 ImpCastExprToType(lex, LHSTy, CastExpr::CK_IntegralCast);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004435
Chris Lattner5c11c412007-12-12 05:47:28 +00004436 UsualUnaryConversions(rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004437
Ryan Flynnf53fab82009-08-07 16:20:20 +00004438 // Sanity-check shift operands
4439 llvm::APSInt Right;
4440 // Check right/shifter operand
Daniel Dunbar687fa862009-09-17 06:31:27 +00004441 if (!rex->isValueDependent() &&
4442 rex->isIntegerConstantExpr(Right, Context)) {
Ryan Flynn2f085712009-08-08 19:18:23 +00004443 if (Right.isNegative())
Ryan Flynnf53fab82009-08-07 16:20:20 +00004444 Diag(Loc, diag::warn_shift_negative) << rex->getSourceRange();
4445 else {
4446 llvm::APInt LeftBits(Right.getBitWidth(),
4447 Context.getTypeSize(lex->getType()));
4448 if (Right.uge(LeftBits))
4449 Diag(Loc, diag::warn_shift_gt_typewidth) << rex->getSourceRange();
4450 }
4451 }
4452
Chris Lattner5c11c412007-12-12 05:47:28 +00004453 // "The type of the result is that of the promoted left operand."
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004454 return LHSTy;
Steve Naroff26c8ea52007-03-21 21:08:52 +00004455}
4456
John McCall99ce6bf2009-11-06 08:49:08 +00004457/// \brief Implements -Wsign-compare.
4458///
4459/// \param lex the left-hand expression
4460/// \param rex the right-hand expression
4461/// \param OpLoc the location of the joining operator
John McCalle46fd852009-11-06 08:53:51 +00004462/// \param Equality whether this is an "equality-like" join, which
4463/// suppresses the warning in some cases
John McCall1fa36b72009-11-05 09:23:39 +00004464void Sema::CheckSignCompare(Expr *lex, Expr *rex, SourceLocation OpLoc,
John McCall99ce6bf2009-11-06 08:49:08 +00004465 const PartialDiagnostic &PD, bool Equality) {
John McCalle2c91e62009-11-06 18:16:06 +00004466 // Don't warn if we're in an unevaluated context.
4467 if (ExprEvalContext == Unevaluated)
4468 return;
4469
John McCall644a4182009-11-05 00:40:04 +00004470 QualType lt = lex->getType(), rt = rex->getType();
4471
4472 // Only warn if both operands are integral.
4473 if (!lt->isIntegerType() || !rt->isIntegerType())
4474 return;
4475
Sebastian Redl0b7c85f2009-11-05 21:09:23 +00004476 // If either expression is value-dependent, don't warn. We'll get another
4477 // chance at instantiation time.
4478 if (lex->isValueDependent() || rex->isValueDependent())
4479 return;
4480
John McCall644a4182009-11-05 00:40:04 +00004481 // The rule is that the signed operand becomes unsigned, so isolate the
4482 // signed operand.
John McCall99ce6bf2009-11-06 08:49:08 +00004483 Expr *signedOperand, *unsignedOperand;
John McCall644a4182009-11-05 00:40:04 +00004484 if (lt->isSignedIntegerType()) {
4485 if (rt->isSignedIntegerType()) return;
4486 signedOperand = lex;
John McCall99ce6bf2009-11-06 08:49:08 +00004487 unsignedOperand = rex;
John McCall644a4182009-11-05 00:40:04 +00004488 } else {
4489 if (!rt->isSignedIntegerType()) return;
4490 signedOperand = rex;
John McCall99ce6bf2009-11-06 08:49:08 +00004491 unsignedOperand = lex;
John McCall644a4182009-11-05 00:40:04 +00004492 }
4493
John McCall99ce6bf2009-11-06 08:49:08 +00004494 // If the unsigned type is strictly smaller than the signed type,
John McCalle46fd852009-11-06 08:53:51 +00004495 // then (1) the result type will be signed and (2) the unsigned
4496 // value will fit fully within the signed type, and thus the result
John McCall99ce6bf2009-11-06 08:49:08 +00004497 // of the comparison will be exact.
4498 if (Context.getIntWidth(signedOperand->getType()) >
4499 Context.getIntWidth(unsignedOperand->getType()))
4500 return;
4501
John McCall644a4182009-11-05 00:40:04 +00004502 // If the value is a non-negative integer constant, then the
4503 // signed->unsigned conversion won't change it.
4504 llvm::APSInt value;
John McCall1fa36b72009-11-05 09:23:39 +00004505 if (signedOperand->isIntegerConstantExpr(value, Context)) {
John McCall644a4182009-11-05 00:40:04 +00004506 assert(value.isSigned() && "result of signed expression not signed");
4507
4508 if (value.isNonNegative())
4509 return;
4510 }
4511
John McCall99ce6bf2009-11-06 08:49:08 +00004512 if (Equality) {
4513 // For (in)equality comparisons, if the unsigned operand is a
John McCalle46fd852009-11-06 08:53:51 +00004514 // constant which cannot collide with a overflowed signed operand,
4515 // then reinterpreting the signed operand as unsigned will not
4516 // change the result of the comparison.
John McCall99ce6bf2009-11-06 08:49:08 +00004517 if (unsignedOperand->isIntegerConstantExpr(value, Context)) {
4518 assert(!value.isSigned() && "result of unsigned expression is signed");
4519
4520 // 2's complement: test the top bit.
4521 if (value.isNonNegative())
4522 return;
4523 }
4524 }
4525
John McCall1fa36b72009-11-05 09:23:39 +00004526 Diag(OpLoc, PD)
John McCall644a4182009-11-05 00:40:04 +00004527 << lex->getType() << rex->getType()
4528 << lex->getSourceRange() << rex->getSourceRange();
4529}
4530
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00004531// C99 6.5.8, C++ [expr.rel]
Chris Lattner326f7572008-11-18 01:30:42 +00004532QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Douglas Gregor7a5bc762009-04-06 18:45:53 +00004533 unsigned OpaqueOpc, bool isRelational) {
4534 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)OpaqueOpc;
4535
Nate Begeman191a6b12008-07-14 18:02:46 +00004536 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner326f7572008-11-18 01:30:42 +00004537 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004538
John McCall99ce6bf2009-11-06 08:49:08 +00004539 CheckSignCompare(lex, rex, Loc, diag::warn_mixed_sign_comparison,
4540 (Opc == BinaryOperator::EQ || Opc == BinaryOperator::NE));
John McCall644a4182009-11-05 00:40:04 +00004541
Chris Lattnerb620c342007-08-26 01:18:55 +00004542 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroff47fea352007-08-10 18:26:40 +00004543 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
4544 UsualArithmeticConversions(lex, rex);
4545 else {
4546 UsualUnaryConversions(lex);
4547 UsualUnaryConversions(rex);
4548 }
Steve Naroff31090012007-07-16 21:54:35 +00004549 QualType lType = lex->getType();
4550 QualType rType = rex->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004551
Mike Stumpf70bcf72009-05-07 18:43:07 +00004552 if (!lType->isFloatingType()
4553 && !(lType->isBlockPointerType() && isRelational)) {
Chris Lattner222b8bd2009-03-08 19:39:53 +00004554 // For non-floating point types, check for self-comparisons of the form
4555 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
4556 // often indicate logic errors in the program.
Mike Stump11289f42009-09-09 15:08:12 +00004557 // NOTE: Don't warn about comparisons of enum constants. These can arise
Ted Kremenekde9e9682009-03-20 19:57:37 +00004558 // from macro expansions, and are usually quite deliberate.
Chris Lattner222b8bd2009-03-08 19:39:53 +00004559 Expr *LHSStripped = lex->IgnoreParens();
4560 Expr *RHSStripped = rex->IgnoreParens();
4561 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped))
4562 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped))
Ted Kremenek9ffbe412009-03-20 18:35:45 +00004563 if (DRL->getDecl() == DRR->getDecl() &&
4564 !isa<EnumConstantDecl>(DRL->getDecl()))
Mike Stump4e1f26a2009-02-19 03:04:26 +00004565 Diag(Loc, diag::warn_selfcomparison);
Mike Stump11289f42009-09-09 15:08:12 +00004566
Chris Lattner222b8bd2009-03-08 19:39:53 +00004567 if (isa<CastExpr>(LHSStripped))
4568 LHSStripped = LHSStripped->IgnoreParenCasts();
4569 if (isa<CastExpr>(RHSStripped))
4570 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00004571
Chris Lattner222b8bd2009-03-08 19:39:53 +00004572 // Warn about comparisons against a string constant (unless the other
4573 // operand is null), the user probably wants strcmp.
Douglas Gregor7a5bc762009-04-06 18:45:53 +00004574 Expr *literalString = 0;
4575 Expr *literalStringStripped = 0;
Chris Lattner222b8bd2009-03-08 19:39:53 +00004576 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Douglas Gregor56751b52009-09-25 04:25:58 +00004577 !RHSStripped->isNullPointerConstant(Context,
4578 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregor7a5bc762009-04-06 18:45:53 +00004579 literalString = lex;
4580 literalStringStripped = LHSStripped;
Mike Stump12b8ce12009-08-04 21:02:39 +00004581 } else if ((isa<StringLiteral>(RHSStripped) ||
4582 isa<ObjCEncodeExpr>(RHSStripped)) &&
Douglas Gregor56751b52009-09-25 04:25:58 +00004583 !LHSStripped->isNullPointerConstant(Context,
4584 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregor7a5bc762009-04-06 18:45:53 +00004585 literalString = rex;
4586 literalStringStripped = RHSStripped;
4587 }
4588
4589 if (literalString) {
4590 std::string resultComparison;
4591 switch (Opc) {
4592 case BinaryOperator::LT: resultComparison = ") < 0"; break;
4593 case BinaryOperator::GT: resultComparison = ") > 0"; break;
4594 case BinaryOperator::LE: resultComparison = ") <= 0"; break;
4595 case BinaryOperator::GE: resultComparison = ") >= 0"; break;
4596 case BinaryOperator::EQ: resultComparison = ") == 0"; break;
4597 case BinaryOperator::NE: resultComparison = ") != 0"; break;
4598 default: assert(false && "Invalid comparison operator");
4599 }
4600 Diag(Loc, diag::warn_stringcompare)
4601 << isa<ObjCEncodeExpr>(literalStringStripped)
4602 << literalString->getSourceRange()
Douglas Gregor170512f2009-04-01 23:51:29 +00004603 << CodeModificationHint::CreateReplacement(SourceRange(Loc), ", ")
4604 << CodeModificationHint::CreateInsertion(lex->getLocStart(),
4605 "strcmp(")
4606 << CodeModificationHint::CreateInsertion(
4607 PP.getLocForEndOfToken(rex->getLocEnd()),
Douglas Gregor7a5bc762009-04-06 18:45:53 +00004608 resultComparison);
4609 }
Ted Kremeneke451eae2007-10-29 16:58:49 +00004610 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004611
Douglas Gregorca63811b2008-11-19 03:25:36 +00004612 // The result of comparisons is 'bool' in C++, 'int' in C.
Chris Lattner222b8bd2009-03-08 19:39:53 +00004613 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy :Context.IntTy;
Douglas Gregorca63811b2008-11-19 03:25:36 +00004614
Chris Lattnerb620c342007-08-26 01:18:55 +00004615 if (isRelational) {
4616 if (lType->isRealType() && rType->isRealType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00004617 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00004618 } else {
Ted Kremeneke2763b02007-10-29 17:13:39 +00004619 // Check for comparisons of floating point operands using != and ==.
Ted Kremeneke2763b02007-10-29 17:13:39 +00004620 if (lType->isFloatingType()) {
Chris Lattner222b8bd2009-03-08 19:39:53 +00004621 assert(rType->isFloatingType());
Chris Lattner326f7572008-11-18 01:30:42 +00004622 CheckFloatComparison(Loc,lex,rex);
Ted Kremenekd4ecc6d2007-10-29 16:40:01 +00004623 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004624
Chris Lattnerb620c342007-08-26 01:18:55 +00004625 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00004626 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00004627 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004628
Douglas Gregor56751b52009-09-25 04:25:58 +00004629 bool LHSIsNull = lex->isNullPointerConstant(Context,
4630 Expr::NPC_ValueDependentIsNull);
4631 bool RHSIsNull = rex->isNullPointerConstant(Context,
4632 Expr::NPC_ValueDependentIsNull);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004633
Chris Lattnerb620c342007-08-26 01:18:55 +00004634 // All of the following pointer related warnings are GCC extensions, except
4635 // when handling null pointer constants. One day, we can consider making them
4636 // errors (when -pedantic-errors is enabled).
Steve Naroff808eb8f2007-08-27 04:08:11 +00004637 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner3a0702e2008-04-03 05:07:25 +00004638 QualType LCanPointeeTy =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004639 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattner3a0702e2008-04-03 05:07:25 +00004640 QualType RCanPointeeTy =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004641 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stump4e1f26a2009-02-19 03:04:26 +00004642
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00004643 if (getLangOptions().CPlusPlus) {
Eli Friedman16c209612009-08-23 00:27:47 +00004644 if (LCanPointeeTy == RCanPointeeTy)
4645 return ResultTy;
4646
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00004647 // C++ [expr.rel]p2:
4648 // [...] Pointer conversions (4.10) and qualification
4649 // conversions (4.4) are performed on pointer operands (or on
4650 // a pointer operand and a null pointer constant) to bring
4651 // them to their composite pointer type. [...]
4652 //
Douglas Gregorb00b10e2009-08-24 17:42:35 +00004653 // C++ [expr.eq]p1 uses the same notion for (in)equality
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00004654 // comparisons of pointers.
Douglas Gregorb8420462009-05-05 04:50:50 +00004655 QualType T = FindCompositePointerType(lex, rex);
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00004656 if (T.isNull()) {
4657 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
4658 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4659 return QualType();
4660 }
4661
Eli Friedman06ed2a52009-10-20 08:27:19 +00004662 ImpCastExprToType(lex, T, CastExpr::CK_BitCast);
4663 ImpCastExprToType(rex, T, CastExpr::CK_BitCast);
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00004664 return ResultTy;
4665 }
Eli Friedman16c209612009-08-23 00:27:47 +00004666 // C99 6.5.9p2 and C99 6.5.8p2
4667 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
4668 RCanPointeeTy.getUnqualifiedType())) {
4669 // Valid unless a relational comparison of function pointers
4670 if (isRelational && LCanPointeeTy->isFunctionType()) {
4671 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
4672 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4673 }
4674 } else if (!isRelational &&
4675 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
4676 // Valid unless comparison between non-null pointer and function pointer
4677 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
4678 && !LHSIsNull && !RHSIsNull) {
4679 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
4680 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4681 }
4682 } else {
4683 // Invalid
Chris Lattner377d1f82008-11-18 22:52:51 +00004684 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004685 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff75c17232007-06-13 21:41:08 +00004686 }
Eli Friedman16c209612009-08-23 00:27:47 +00004687 if (LCanPointeeTy != RCanPointeeTy)
Eli Friedman06ed2a52009-10-20 08:27:19 +00004688 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00004689 return ResultTy;
Steve Naroffcdee44c2007-08-16 21:48:38 +00004690 }
Mike Stump11289f42009-09-09 15:08:12 +00004691
Sebastian Redl576fd422009-05-10 18:38:11 +00004692 if (getLangOptions().CPlusPlus) {
Mike Stump11289f42009-09-09 15:08:12 +00004693 // Comparison of pointers with null pointer constants and equality
Douglas Gregorb00b10e2009-08-24 17:42:35 +00004694 // comparisons of member pointers to null pointer constants.
Mike Stump11289f42009-09-09 15:08:12 +00004695 if (RHSIsNull &&
Douglas Gregorb00b10e2009-08-24 17:42:35 +00004696 (lType->isPointerType() ||
4697 (!isRelational && lType->isMemberPointerType()))) {
Anders Carlsson83133d92009-08-24 18:03:14 +00004698 ImpCastExprToType(rex, lType, CastExpr::CK_NullToMemberPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00004699 return ResultTy;
4700 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00004701 if (LHSIsNull &&
4702 (rType->isPointerType() ||
4703 (!isRelational && rType->isMemberPointerType()))) {
Anders Carlsson83133d92009-08-24 18:03:14 +00004704 ImpCastExprToType(lex, rType, CastExpr::CK_NullToMemberPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00004705 return ResultTy;
4706 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00004707
4708 // Comparison of member pointers.
Mike Stump11289f42009-09-09 15:08:12 +00004709 if (!isRelational &&
Douglas Gregorb00b10e2009-08-24 17:42:35 +00004710 lType->isMemberPointerType() && rType->isMemberPointerType()) {
4711 // C++ [expr.eq]p2:
Mike Stump11289f42009-09-09 15:08:12 +00004712 // In addition, pointers to members can be compared, or a pointer to
4713 // member and a null pointer constant. Pointer to member conversions
4714 // (4.11) and qualification conversions (4.4) are performed to bring
4715 // them to a common type. If one operand is a null pointer constant,
4716 // the common type is the type of the other operand. Otherwise, the
4717 // common type is a pointer to member type similar (4.4) to the type
4718 // of one of the operands, with a cv-qualification signature (4.4)
4719 // that is the union of the cv-qualification signatures of the operand
Douglas Gregorb00b10e2009-08-24 17:42:35 +00004720 // types.
4721 QualType T = FindCompositePointerType(lex, rex);
4722 if (T.isNull()) {
4723 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
4724 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4725 return QualType();
4726 }
Mike Stump11289f42009-09-09 15:08:12 +00004727
Eli Friedman06ed2a52009-10-20 08:27:19 +00004728 ImpCastExprToType(lex, T, CastExpr::CK_BitCast);
4729 ImpCastExprToType(rex, T, CastExpr::CK_BitCast);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00004730 return ResultTy;
4731 }
Mike Stump11289f42009-09-09 15:08:12 +00004732
Douglas Gregorb00b10e2009-08-24 17:42:35 +00004733 // Comparison of nullptr_t with itself.
Sebastian Redl576fd422009-05-10 18:38:11 +00004734 if (lType->isNullPtrType() && rType->isNullPtrType())
4735 return ResultTy;
4736 }
Mike Stump11289f42009-09-09 15:08:12 +00004737
Steve Naroff081c7422008-09-04 15:10:53 +00004738 // Handle block pointer types.
Mike Stump1b821b42009-05-07 03:14:14 +00004739 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004740 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
4741 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004742
Steve Naroff081c7422008-09-04 15:10:53 +00004743 if (!LHSIsNull && !RHSIsNull &&
Eli Friedmana6638ca2009-06-08 05:08:54 +00004744 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00004745 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004746 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff081c7422008-09-04 15:10:53 +00004747 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00004748 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00004749 return ResultTy;
Steve Naroff081c7422008-09-04 15:10:53 +00004750 }
Steve Naroffe18f94c2008-09-28 01:11:11 +00004751 // Allow block pointers to be compared with null pointer constants.
Mike Stump1b821b42009-05-07 03:14:14 +00004752 if (!isRelational
4753 && ((lType->isBlockPointerType() && rType->isPointerType())
4754 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Naroffe18f94c2008-09-28 01:11:11 +00004755 if (!LHSIsNull && !RHSIsNull) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004756 if (!((rType->isPointerType() && rType->getAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00004757 ->getPointeeType()->isVoidType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004758 || (lType->isPointerType() && lType->getAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00004759 ->getPointeeType()->isVoidType())))
4760 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
4761 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroffe18f94c2008-09-28 01:11:11 +00004762 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00004763 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00004764 return ResultTy;
Steve Naroffe18f94c2008-09-28 01:11:11 +00004765 }
Steve Naroff081c7422008-09-04 15:10:53 +00004766
Steve Naroff7cae42b2009-07-10 23:34:53 +00004767 if ((lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType())) {
Steve Naroff1d4a9a32008-10-27 10:33:19 +00004768 if (lType->isPointerType() || rType->isPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004769 const PointerType *LPT = lType->getAs<PointerType>();
4770 const PointerType *RPT = rType->getAs<PointerType>();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004771 bool LPtrToVoid = LPT ?
Steve Naroff753567f2008-11-17 19:49:16 +00004772 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004773 bool RPtrToVoid = RPT ?
Steve Naroff753567f2008-11-17 19:49:16 +00004774 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004775
Steve Naroff753567f2008-11-17 19:49:16 +00004776 if (!LPtrToVoid && !RPtrToVoid &&
4777 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00004778 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004779 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff1d4a9a32008-10-27 10:33:19 +00004780 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00004781 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00004782 return ResultTy;
Steve Naroffea54d9e2008-10-20 18:19:10 +00004783 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00004784 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00004785 if (!Context.areComparableObjCPointerTypes(lType, rType))
Steve Naroff7cae42b2009-07-10 23:34:53 +00004786 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
4787 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00004788 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00004789 return ResultTy;
Steve Naroffb788d9b2008-06-03 14:04:54 +00004790 }
Fariborz Jahanian134cbef2007-12-20 01:06:58 +00004791 }
Steve Naroff6b712a72009-07-14 18:25:06 +00004792 if (lType->isAnyPointerType() && rType->isIntegerType()) {
Chris Lattnerd99bd522009-08-23 00:03:44 +00004793 unsigned DiagID = 0;
4794 if (RHSIsNull) {
4795 if (isRelational)
4796 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
4797 } else if (isRelational)
4798 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
4799 else
4800 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump11289f42009-09-09 15:08:12 +00004801
Chris Lattnerd99bd522009-08-23 00:03:44 +00004802 if (DiagID) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00004803 Diag(Loc, DiagID)
Chris Lattnerd466ea12009-06-30 06:24:05 +00004804 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf8344db2009-08-22 18:58:31 +00004805 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00004806 ImpCastExprToType(rex, lType, CastExpr::CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00004807 return ResultTy;
Steve Naroffcdee44c2007-08-16 21:48:38 +00004808 }
Steve Naroff6b712a72009-07-14 18:25:06 +00004809 if (lType->isIntegerType() && rType->isAnyPointerType()) {
Chris Lattnerd99bd522009-08-23 00:03:44 +00004810 unsigned DiagID = 0;
4811 if (LHSIsNull) {
4812 if (isRelational)
4813 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
4814 } else if (isRelational)
4815 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
4816 else
4817 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump11289f42009-09-09 15:08:12 +00004818
Chris Lattnerd99bd522009-08-23 00:03:44 +00004819 if (DiagID) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00004820 Diag(Loc, DiagID)
Chris Lattnerd466ea12009-06-30 06:24:05 +00004821 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf8344db2009-08-22 18:58:31 +00004822 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00004823 ImpCastExprToType(lex, rType, CastExpr::CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00004824 return ResultTy;
Steve Naroff043d45d2007-05-15 02:32:35 +00004825 }
Steve Naroff4b191572008-09-04 16:56:14 +00004826 // Handle block pointers.
Mike Stumpf70bcf72009-05-07 18:43:07 +00004827 if (!isRelational && RHSIsNull
4828 && lType->isBlockPointerType() && rType->isIntegerType()) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004829 ImpCastExprToType(rex, lType, CastExpr::CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00004830 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00004831 }
Mike Stumpf70bcf72009-05-07 18:43:07 +00004832 if (!isRelational && LHSIsNull
4833 && lType->isIntegerType() && rType->isBlockPointerType()) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004834 ImpCastExprToType(lex, rType, CastExpr::CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00004835 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00004836 }
Chris Lattner326f7572008-11-18 01:30:42 +00004837 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00004838}
4839
Nate Begeman191a6b12008-07-14 18:02:46 +00004840/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump4e1f26a2009-02-19 03:04:26 +00004841/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begeman191a6b12008-07-14 18:02:46 +00004842/// like a scalar comparison, a vector comparison produces a vector of integer
4843/// types.
4844QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner326f7572008-11-18 01:30:42 +00004845 SourceLocation Loc,
Nate Begeman191a6b12008-07-14 18:02:46 +00004846 bool isRelational) {
4847 // Check to make sure we're operating on vectors of the same type and width,
4848 // Allowing one side to be a scalar of element type.
Chris Lattner326f7572008-11-18 01:30:42 +00004849 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begeman191a6b12008-07-14 18:02:46 +00004850 if (vType.isNull())
4851 return vType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004852
Nate Begeman191a6b12008-07-14 18:02:46 +00004853 QualType lType = lex->getType();
4854 QualType rType = rex->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004855
Nate Begeman191a6b12008-07-14 18:02:46 +00004856 // For non-floating point types, check for self-comparisons of the form
4857 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
4858 // often indicate logic errors in the program.
4859 if (!lType->isFloatingType()) {
4860 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
4861 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
4862 if (DRL->getDecl() == DRR->getDecl())
Mike Stump4e1f26a2009-02-19 03:04:26 +00004863 Diag(Loc, diag::warn_selfcomparison);
Nate Begeman191a6b12008-07-14 18:02:46 +00004864 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004865
Nate Begeman191a6b12008-07-14 18:02:46 +00004866 // Check for comparisons of floating point operands using != and ==.
4867 if (!isRelational && lType->isFloatingType()) {
4868 assert (rType->isFloatingType());
Chris Lattner326f7572008-11-18 01:30:42 +00004869 CheckFloatComparison(Loc,lex,rex);
Nate Begeman191a6b12008-07-14 18:02:46 +00004870 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004871
Nate Begeman191a6b12008-07-14 18:02:46 +00004872 // Return the type for the comparison, which is the same as vector type for
4873 // integer vectors, or an integer type of identical size and number of
4874 // elements for floating point vectors.
4875 if (lType->isIntegerType())
4876 return lType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004877
John McCall9dd450b2009-09-21 23:43:11 +00004878 const VectorType *VTy = lType->getAs<VectorType>();
Nate Begeman191a6b12008-07-14 18:02:46 +00004879 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004880 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begeman191a6b12008-07-14 18:02:46 +00004881 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattner5d688962009-03-31 07:46:52 +00004882 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004883 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
4884
Mike Stump4e1f26a2009-02-19 03:04:26 +00004885 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004886 "Unhandled vector element size in vector compare");
Nate Begeman191a6b12008-07-14 18:02:46 +00004887 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
4888}
4889
Steve Naroff218bc2b2007-05-04 21:54:46 +00004890inline QualType Sema::CheckBitwiseOperands(
Mike Stump11289f42009-09-09 15:08:12 +00004891 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Steve Naroff94a5aca2007-07-16 22:23:01 +00004892 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner326f7572008-11-18 01:30:42 +00004893 return CheckVectorOperands(Loc, lex, rex);
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00004894
Steve Naroffbe4c4d12007-08-24 19:07:16 +00004895 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004896
Steve Naroffdbd9e892007-07-17 00:58:39 +00004897 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroffbe4c4d12007-08-24 19:07:16 +00004898 return compType;
Chris Lattner326f7572008-11-18 01:30:42 +00004899 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00004900}
4901
Steve Naroff218bc2b2007-05-04 21:54:46 +00004902inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Mike Stump11289f42009-09-09 15:08:12 +00004903 Expr *&lex, Expr *&rex, SourceLocation Loc) {
Steve Naroff31090012007-07-16 21:54:35 +00004904 UsualUnaryConversions(lex);
4905 UsualUnaryConversions(rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004906
Anders Carlsson35a99d92009-10-16 01:44:21 +00004907 if (!lex->getType()->isScalarType() || !rex->getType()->isScalarType())
4908 return InvalidOperands(Loc, lex, rex);
4909
4910 if (Context.getLangOptions().CPlusPlus) {
4911 // C++ [expr.log.and]p2
4912 // C++ [expr.log.or]p2
4913 return Context.BoolTy;
4914 }
4915
4916 return Context.IntTy;
Steve Naroffae4143e2007-04-26 20:39:23 +00004917}
4918
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00004919/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
4920/// is a read-only property; return true if so. A readonly property expression
4921/// depends on various declarations and thus must be treated specially.
4922///
Mike Stump11289f42009-09-09 15:08:12 +00004923static bool IsReadonlyProperty(Expr *E, Sema &S) {
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00004924 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
4925 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
4926 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
4927 QualType BaseType = PropExpr->getBase()->getType();
Mike Stump11289f42009-09-09 15:08:12 +00004928 if (const ObjCObjectPointerType *OPT =
Steve Naroff7cae42b2009-07-10 23:34:53 +00004929 BaseType->getAsObjCInterfacePointerType())
4930 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
4931 if (S.isPropertyReadonly(PDecl, IFace))
4932 return true;
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00004933 }
4934 }
4935 return false;
4936}
4937
Chris Lattner30bd3272008-11-18 01:22:49 +00004938/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
4939/// emit an error and return true. If so, return false.
4940static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00004941 SourceLocation OrigLoc = Loc;
Mike Stump11289f42009-09-09 15:08:12 +00004942 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00004943 &Loc);
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00004944 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
4945 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattner30bd3272008-11-18 01:22:49 +00004946 if (IsLV == Expr::MLV_Valid)
4947 return false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004948
Chris Lattner30bd3272008-11-18 01:22:49 +00004949 unsigned Diag = 0;
4950 bool NeedType = false;
4951 switch (IsLV) { // C99 6.5.16p2
4952 default: assert(0 && "Unknown result from isModifiableLvalue!");
4953 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004954 case Expr::MLV_ArrayType:
Chris Lattner30bd3272008-11-18 01:22:49 +00004955 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
4956 NeedType = true;
4957 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004958 case Expr::MLV_NotObjectType:
Chris Lattner30bd3272008-11-18 01:22:49 +00004959 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
4960 NeedType = true;
4961 break;
Chris Lattner9b3bbe92008-11-17 19:51:54 +00004962 case Expr::MLV_LValueCast:
Chris Lattner30bd3272008-11-18 01:22:49 +00004963 Diag = diag::err_typecheck_lvalue_casts_not_supported;
4964 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00004965 case Expr::MLV_InvalidExpression:
Chris Lattner30bd3272008-11-18 01:22:49 +00004966 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
4967 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00004968 case Expr::MLV_IncompleteType:
4969 case Expr::MLV_IncompleteVoidType:
Douglas Gregored0cfbd2009-03-09 16:13:40 +00004970 return S.RequireCompleteType(Loc, E->getType(),
Anders Carlssond624e162009-08-26 23:45:07 +00004971 PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
4972 << E->getSourceRange());
Chris Lattner9bad62c2008-01-04 18:04:52 +00004973 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner30bd3272008-11-18 01:22:49 +00004974 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
4975 break;
Steve Naroffba756cb2008-09-26 14:41:28 +00004976 case Expr::MLV_NotBlockQualified:
Chris Lattner30bd3272008-11-18 01:22:49 +00004977 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
4978 break;
Fariborz Jahanian8a1810f2008-11-22 18:39:36 +00004979 case Expr::MLV_ReadonlyProperty:
4980 Diag = diag::error_readonly_property_assignment;
4981 break;
Fariborz Jahanian5118c412008-11-22 20:25:50 +00004982 case Expr::MLV_NoSetterProperty:
4983 Diag = diag::error_nosetter_property_assignment;
4984 break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00004985 }
Steve Naroffad373bd2007-07-31 12:34:36 +00004986
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00004987 SourceRange Assign;
4988 if (Loc != OrigLoc)
4989 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattner30bd3272008-11-18 01:22:49 +00004990 if (NeedType)
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00004991 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00004992 else
Mike Stump11289f42009-09-09 15:08:12 +00004993 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00004994 return true;
4995}
4996
4997
4998
4999// C99 6.5.16.1
Chris Lattner326f7572008-11-18 01:30:42 +00005000QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
5001 SourceLocation Loc,
5002 QualType CompoundType) {
5003 // Verify that LHS is a modifiable lvalue, and emit error if not.
5004 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner30bd3272008-11-18 01:22:49 +00005005 return QualType();
Chris Lattner326f7572008-11-18 01:30:42 +00005006
5007 QualType LHSType = LHS->getType();
5008 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005009
Chris Lattner9bad62c2008-01-04 18:04:52 +00005010 AssignConvertType ConvTy;
Chris Lattner326f7572008-11-18 01:30:42 +00005011 if (CompoundType.isNull()) {
Chris Lattnerea714382008-08-21 18:04:13 +00005012 // Simple assignment "x = y".
Chris Lattner326f7572008-11-18 01:30:42 +00005013 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Fariborz Jahanian255c0952009-01-13 23:34:40 +00005014 // Special case of NSObject attributes on c-style pointer types.
5015 if (ConvTy == IncompatiblePointer &&
5016 ((Context.isObjCNSObjectType(LHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00005017 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanian255c0952009-01-13 23:34:40 +00005018 (Context.isObjCNSObjectType(RHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00005019 LHSType->isObjCObjectPointerType())))
Fariborz Jahanian255c0952009-01-13 23:34:40 +00005020 ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005021
Chris Lattnerea714382008-08-21 18:04:13 +00005022 // If the RHS is a unary plus or minus, check to see if they = and + are
5023 // right next to each other. If so, the user may have typo'd "x =+ 4"
5024 // instead of "x += 4".
Chris Lattner326f7572008-11-18 01:30:42 +00005025 Expr *RHSCheck = RHS;
Chris Lattnerea714382008-08-21 18:04:13 +00005026 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
5027 RHSCheck = ICE->getSubExpr();
5028 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
5029 if ((UO->getOpcode() == UnaryOperator::Plus ||
5030 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner326f7572008-11-18 01:30:42 +00005031 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattnerea714382008-08-21 18:04:13 +00005032 // Only if the two operators are exactly adjacent.
Chris Lattner36c39c92009-03-08 06:51:10 +00005033 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
5034 // And there is a space or other character before the subexpr of the
5035 // unary +/-. We don't want to warn on "x=-1".
Chris Lattnered9f14c2009-03-09 07:11:10 +00005036 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
5037 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattner29e812b2008-11-20 06:06:08 +00005038 Diag(Loc, diag::warn_not_compound_assign)
5039 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
5040 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner36c39c92009-03-08 06:51:10 +00005041 }
Chris Lattnerea714382008-08-21 18:04:13 +00005042 }
5043 } else {
5044 // Compound assignment "x += y"
Eli Friedmanb05c41e2009-05-16 05:56:02 +00005045 ConvTy = CheckAssignmentConstraints(LHSType, RHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00005046 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00005047
Chris Lattner326f7572008-11-18 01:30:42 +00005048 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
5049 RHS, "assigning"))
Chris Lattner9bad62c2008-01-04 18:04:52 +00005050 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005051
Steve Naroff98cf3e92007-06-06 18:38:38 +00005052 // C99 6.5.16p3: The type of an assignment expression is the type of the
5053 // left operand unless the left operand has qualified type, in which case
Mike Stump4e1f26a2009-02-19 03:04:26 +00005054 // it is the unqualified version of the type of the left operand.
Steve Naroff98cf3e92007-06-06 18:38:38 +00005055 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
5056 // is converted to the type of the assignment expression (above).
Chris Lattnerf17bd422007-08-30 17:45:32 +00005057 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregord2c2d172009-05-02 00:36:19 +00005058 // operand.
Chris Lattner326f7572008-11-18 01:30:42 +00005059 return LHSType.getUnqualifiedType();
Steve Naroffae4143e2007-04-26 20:39:23 +00005060}
5061
Chris Lattner326f7572008-11-18 01:30:42 +00005062// C99 6.5.17
5063QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
Chris Lattnerf6e1e302008-07-25 20:54:07 +00005064 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner326f7572008-11-18 01:30:42 +00005065 DefaultFunctionArrayConversion(RHS);
Eli Friedmanba961a92009-03-23 00:24:07 +00005066
5067 // FIXME: Check that RHS type is complete in C mode (it's legal for it to be
5068 // incomplete in C++).
5069
Chris Lattner326f7572008-11-18 01:30:42 +00005070 return RHS->getType();
Steve Naroff95af0132007-03-30 23:47:58 +00005071}
5072
Steve Naroff7a5af782007-07-13 16:58:59 +00005073/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
5074/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redle10c2c32008-12-20 09:35:34 +00005075QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
5076 bool isInc) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005077 if (Op->isTypeDependent())
5078 return Context.DependentTy;
5079
Chris Lattner6b0cf142008-11-21 07:05:48 +00005080 QualType ResType = Op->getType();
5081 assert(!ResType.isNull() && "no type for increment/decrement expression");
Steve Naroffd50c88e2007-04-05 21:15:20 +00005082
Sebastian Redle10c2c32008-12-20 09:35:34 +00005083 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
5084 // Decrement of bool is not allowed.
5085 if (!isInc) {
5086 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
5087 return QualType();
5088 }
5089 // Increment of bool sets it to true, but is deprecated.
5090 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
5091 } else if (ResType->isRealType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00005092 // OK!
Steve Naroff6b712a72009-07-14 18:25:06 +00005093 } else if (ResType->isAnyPointerType()) {
5094 QualType PointeeTy = ResType->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00005095
Chris Lattner6b0cf142008-11-21 07:05:48 +00005096 // C99 6.5.2.4p2, 6.5.6p2
Steve Naroff7cae42b2009-07-10 23:34:53 +00005097 if (PointeeTy->isVoidType()) {
Douglas Gregorf6cd9282009-01-23 00:36:41 +00005098 if (getLangOptions().CPlusPlus) {
5099 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
5100 << Op->getSourceRange();
5101 return QualType();
5102 }
5103
5104 // Pointer to void is a GNU extension in C.
Chris Lattner6b0cf142008-11-21 07:05:48 +00005105 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005106 } else if (PointeeTy->isFunctionType()) {
Douglas Gregorf6cd9282009-01-23 00:36:41 +00005107 if (getLangOptions().CPlusPlus) {
5108 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
5109 << Op->getType() << Op->getSourceRange();
5110 return QualType();
5111 }
5112
5113 Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005114 << ResType << Op->getSourceRange();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005115 } else if (RequireCompleteType(OpLoc, PointeeTy,
Anders Carlsson029fc692009-08-26 22:59:12 +00005116 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
Mike Stump11289f42009-09-09 15:08:12 +00005117 << Op->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00005118 << ResType))
Douglas Gregordd430f72009-01-19 19:26:10 +00005119 return QualType();
Fariborz Jahanianca75db72009-07-16 17:59:14 +00005120 // Diagnose bad cases where we step over interface counts.
5121 else if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
5122 Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
5123 << PointeeTy << Op->getSourceRange();
5124 return QualType();
5125 }
Chris Lattner6b0cf142008-11-21 07:05:48 +00005126 } else if (ResType->isComplexType()) {
5127 // C99 does not support ++/-- on complex types, we allow as an extension.
5128 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005129 << ResType << Op->getSourceRange();
Chris Lattner6b0cf142008-11-21 07:05:48 +00005130 } else {
5131 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005132 << ResType << Op->getSourceRange();
Chris Lattner6b0cf142008-11-21 07:05:48 +00005133 return QualType();
Steve Naroff46ba1eb2007-04-03 23:13:13 +00005134 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005135 // At this point, we know we have a real, complex or pointer type.
Steve Naroff9e1e5512007-08-23 21:37:33 +00005136 // Now make sure the operand is a modifiable lvalue.
Chris Lattner6b0cf142008-11-21 07:05:48 +00005137 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Steve Naroff35d85152007-05-07 00:24:15 +00005138 return QualType();
Chris Lattner6b0cf142008-11-21 07:05:48 +00005139 return ResType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00005140}
5141
Anders Carlsson806700f2008-02-01 07:15:58 +00005142/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Steve Naroff47500512007-04-19 23:00:49 +00005143/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb692ef42008-08-04 20:02:37 +00005144/// where the declaration is needed for type checking. We only need to
5145/// handle cases when the expression references a function designator
5146/// or is an lvalue. Here are some examples:
5147/// - &(x) => x
5148/// - &*****f => f for f a function designator.
5149/// - &s.xx => s
5150/// - &s.zz[1].yy -> s, if zz is an array
5151/// - *(x + 1) -> x, if x is an array
5152/// - &"123"[2] -> 0
5153/// - & __real__ x -> x
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005154static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00005155 switch (E->getStmtClass()) {
Steve Naroff47500512007-04-19 23:00:49 +00005156 case Stmt::DeclRefExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00005157 return cast<DeclRefExpr>(E)->getDecl();
Steve Naroff47500512007-04-19 23:00:49 +00005158 case Stmt::MemberExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00005159 // If this is an arrow operator, the address is an offset from
5160 // the base's value, so the object the base refers to is
5161 // irrelevant.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00005162 if (cast<MemberExpr>(E)->isArrow())
Chris Lattner48d52842007-11-16 17:46:48 +00005163 return 0;
Eli Friedman3a1e6922009-04-20 08:23:18 +00005164 // Otherwise, the expression refers to a part of the base
Chris Lattner24d5bfe2008-04-02 04:24:33 +00005165 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson806700f2008-02-01 07:15:58 +00005166 case Stmt::ArraySubscriptExprClass: {
Mike Stump87c57ac2009-05-16 07:39:55 +00005167 // FIXME: This code shouldn't be necessary! We should catch the implicit
5168 // promotion of register arrays earlier.
Eli Friedman3a1e6922009-04-20 08:23:18 +00005169 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
5170 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
5171 if (ICE->getSubExpr()->getType()->isArrayType())
5172 return getPrimaryDecl(ICE->getSubExpr());
5173 }
5174 return 0;
Anders Carlsson806700f2008-02-01 07:15:58 +00005175 }
Daniel Dunbarb692ef42008-08-04 20:02:37 +00005176 case Stmt::UnaryOperatorClass: {
5177 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005178
Daniel Dunbarb692ef42008-08-04 20:02:37 +00005179 switch(UO->getOpcode()) {
Daniel Dunbarb692ef42008-08-04 20:02:37 +00005180 case UnaryOperator::Real:
5181 case UnaryOperator::Imag:
5182 case UnaryOperator::Extension:
5183 return getPrimaryDecl(UO->getSubExpr());
5184 default:
5185 return 0;
5186 }
5187 }
Steve Naroff47500512007-04-19 23:00:49 +00005188 case Stmt::ParenExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00005189 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattner48d52842007-11-16 17:46:48 +00005190 case Stmt::ImplicitCastExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00005191 // If the result of an implicit cast is an l-value, we care about
5192 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00005193 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Steve Naroff47500512007-04-19 23:00:49 +00005194 default:
5195 return 0;
5196 }
5197}
5198
5199/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump4e1f26a2009-02-19 03:04:26 +00005200/// designator or an lvalue designating an object. If it is an lvalue, the
Steve Naroff47500512007-04-19 23:00:49 +00005201/// object cannot be declared with storage class register or be a bit field.
Mike Stump4e1f26a2009-02-19 03:04:26 +00005202/// Note: The usual conversions are *not* applied to the operand of the &
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005203/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump4e1f26a2009-02-19 03:04:26 +00005204/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregorcd695e52008-11-10 20:40:00 +00005205/// we allow the '&' but retain the overloaded-function type.
Steve Naroff35d85152007-05-07 00:24:15 +00005206QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Eli Friedman3a1e6922009-04-20 08:23:18 +00005207 // Make sure to ignore parentheses in subsequent checks
5208 op = op->IgnoreParens();
5209
Douglas Gregor19b8c4f2008-12-17 22:52:20 +00005210 if (op->isTypeDependent())
5211 return Context.DependentTy;
5212
Steve Naroff826e91a2008-01-13 17:10:08 +00005213 if (getLangOptions().C99) {
5214 // Implement C99-only parts of addressof rules.
5215 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
5216 if (uOp->getOpcode() == UnaryOperator::Deref)
5217 // Per C99 6.5.3.2, the address of a deref always returns a valid result
5218 // (assuming the deref expression is valid).
5219 return uOp->getSubExpr()->getType();
5220 }
5221 // Technically, there should be a check for array subscript
5222 // expressions here, but the result of one is always an lvalue anyway.
5223 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005224 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner67315442008-07-26 21:30:36 +00005225 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes17f345f2008-12-16 22:59:47 +00005226
Eli Friedmance7f9002009-05-16 23:27:50 +00005227 if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
5228 // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00005229 // The operand must be either an l-value or a function designator
Eli Friedmance7f9002009-05-16 23:27:50 +00005230 if (!op->getType()->isFunctionType()) {
Chris Lattner48d52842007-11-16 17:46:48 +00005231 // FIXME: emit more specific diag...
Chris Lattnerf490e152008-11-19 05:27:50 +00005232 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
5233 << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00005234 return QualType();
5235 }
Douglas Gregor71235ec2009-05-02 02:18:30 +00005236 } else if (op->getBitField()) { // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00005237 // The operand cannot be a bit-field
5238 Diag(OpLoc, diag::err_typecheck_address_of)
5239 << "bit-field" << op->getSourceRange();
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00005240 return QualType();
Nate Begemana6b47a42009-02-15 22:45:20 +00005241 } else if (isa<ExtVectorElementExpr>(op) || (isa<ArraySubscriptExpr>(op) &&
5242 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType())){
Eli Friedman3a1e6922009-04-20 08:23:18 +00005243 // The operand cannot be an element of a vector
Chris Lattner29e812b2008-11-20 06:06:08 +00005244 Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemana6b47a42009-02-15 22:45:20 +00005245 << "vector element" << op->getSourceRange();
Steve Naroffb96e4ab62008-02-29 23:30:25 +00005246 return QualType();
Fariborz Jahanian385db802009-07-07 18:50:52 +00005247 } else if (isa<ObjCPropertyRefExpr>(op)) {
5248 // cannot take address of a property expression.
5249 Diag(OpLoc, diag::err_typecheck_address_of)
5250 << "property expression" << op->getSourceRange();
5251 return QualType();
Anders Carlsson3fa58d12009-09-14 23:15:26 +00005252 } else if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(op)) {
5253 // FIXME: Can LHS ever be null here?
Anders Carlsson01ccf992009-09-15 16:03:44 +00005254 if (!CheckAddressOfOperand(CO->getTrueExpr(), OpLoc).isNull())
5255 return CheckAddressOfOperand(CO->getFalseExpr(), OpLoc);
Steve Naroffb96e4ab62008-02-29 23:30:25 +00005256 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump4e1f26a2009-02-19 03:04:26 +00005257 // We have an lvalue with a decl. Make sure the decl is not declared
Steve Naroff47500512007-04-19 23:00:49 +00005258 // with the register storage-class specifier.
5259 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Steve Naroff35d85152007-05-07 00:24:15 +00005260 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattner29e812b2008-11-20 06:06:08 +00005261 Diag(OpLoc, diag::err_typecheck_address_of)
5262 << "register variable" << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00005263 return QualType();
5264 }
Douglas Gregor9b146582009-07-08 20:55:45 +00005265 } else if (isa<OverloadedFunctionDecl>(dcl) ||
5266 isa<FunctionTemplateDecl>(dcl)) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00005267 return Context.OverloadTy;
Anders Carlsson0b675f52009-07-08 21:45:58 +00005268 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(dcl)) {
Douglas Gregor9aa8b552008-12-10 21:26:49 +00005269 // Okay: we can take the address of a field.
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00005270 // Could be a pointer to member, though, if there is an explicit
5271 // scope qualifier for the class.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00005272 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00005273 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlsson0b675f52009-07-08 21:45:58 +00005274 if (Ctx && Ctx->isRecord()) {
5275 if (FD->getType()->isReferenceType()) {
Mike Stump11289f42009-09-09 15:08:12 +00005276 Diag(OpLoc,
Anders Carlsson0b675f52009-07-08 21:45:58 +00005277 diag::err_cannot_form_pointer_to_member_of_reference_type)
5278 << FD->getDeclName() << FD->getType();
5279 return QualType();
5280 }
Mike Stump11289f42009-09-09 15:08:12 +00005281
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00005282 return Context.getMemberPointerType(op->getType(),
5283 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlsson0b675f52009-07-08 21:45:58 +00005284 }
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00005285 }
Anders Carlsson5b535762009-05-16 21:43:42 +00005286 } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(dcl)) {
Nuno Lopes5773a1b2008-12-16 22:58:26 +00005287 // Okay: we can take the address of a function.
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005288 // As above.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00005289 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier() &&
5290 MD->isInstance())
Anders Carlsson5b535762009-05-16 21:43:42 +00005291 return Context.getMemberPointerType(op->getType(),
5292 Context.getTypeDeclType(MD->getParent()).getTypePtr());
5293 } else if (!isa<FunctionDecl>(dcl))
Steve Narofff633d092007-04-25 19:01:39 +00005294 assert(0 && "Unknown/unexpected decl type");
Steve Naroff47500512007-04-19 23:00:49 +00005295 }
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005296
Eli Friedmance7f9002009-05-16 23:27:50 +00005297 if (lval == Expr::LV_IncompleteVoidType) {
5298 // Taking the address of a void variable is technically illegal, but we
5299 // allow it in cases which are otherwise valid.
5300 // Example: "extern void x; void* y = &x;".
5301 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
5302 }
5303
Steve Naroff47500512007-04-19 23:00:49 +00005304 // If the operand has type "type", the result has type "pointer to type".
Steve Naroff35d85152007-05-07 00:24:15 +00005305 return Context.getPointerType(op->getType());
Steve Naroff47500512007-04-19 23:00:49 +00005306}
5307
Chris Lattner6a2ed6f2008-11-23 09:13:29 +00005308QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005309 if (Op->isTypeDependent())
5310 return Context.DependentTy;
5311
Chris Lattner6a2ed6f2008-11-23 09:13:29 +00005312 UsualUnaryConversions(Op);
5313 QualType Ty = Op->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005314
Chris Lattner6a2ed6f2008-11-23 09:13:29 +00005315 // Note that per both C89 and C99, this is always legal, even if ptype is an
5316 // incomplete type or void. It would be possible to warn about dereferencing
5317 // a void pointer, but it's completely well-defined, and such a warning is
5318 // unlikely to catch any mistakes.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005319 if (const PointerType *PT = Ty->getAs<PointerType>())
Steve Naroff826e91a2008-01-13 17:10:08 +00005320 return PT->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005321
John McCall9dd450b2009-09-21 23:43:11 +00005322 if (const ObjCObjectPointerType *OPT = Ty->getAs<ObjCObjectPointerType>())
Fariborz Jahanianf15d4b62009-09-03 00:43:07 +00005323 return OPT->getPointeeType();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005324
Chris Lattner29e812b2008-11-20 06:06:08 +00005325 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner6a2ed6f2008-11-23 09:13:29 +00005326 << Ty << Op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00005327 return QualType();
Steve Naroff1926c832007-04-24 00:23:05 +00005328}
Steve Naroff218bc2b2007-05-04 21:54:46 +00005329
5330static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
5331 tok::TokenKind Kind) {
5332 BinaryOperator::Opcode Opc;
5333 switch (Kind) {
5334 default: assert(0 && "Unknown binop!");
Sebastian Redl112a97662009-02-07 00:15:38 +00005335 case tok::periodstar: Opc = BinaryOperator::PtrMemD; break;
5336 case tok::arrowstar: Opc = BinaryOperator::PtrMemI; break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00005337 case tok::star: Opc = BinaryOperator::Mul; break;
5338 case tok::slash: Opc = BinaryOperator::Div; break;
5339 case tok::percent: Opc = BinaryOperator::Rem; break;
5340 case tok::plus: Opc = BinaryOperator::Add; break;
5341 case tok::minus: Opc = BinaryOperator::Sub; break;
5342 case tok::lessless: Opc = BinaryOperator::Shl; break;
5343 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
5344 case tok::lessequal: Opc = BinaryOperator::LE; break;
5345 case tok::less: Opc = BinaryOperator::LT; break;
5346 case tok::greaterequal: Opc = BinaryOperator::GE; break;
5347 case tok::greater: Opc = BinaryOperator::GT; break;
5348 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
5349 case tok::equalequal: Opc = BinaryOperator::EQ; break;
5350 case tok::amp: Opc = BinaryOperator::And; break;
5351 case tok::caret: Opc = BinaryOperator::Xor; break;
5352 case tok::pipe: Opc = BinaryOperator::Or; break;
5353 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
5354 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
5355 case tok::equal: Opc = BinaryOperator::Assign; break;
5356 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
5357 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
5358 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
5359 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
5360 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
5361 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
5362 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
5363 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
5364 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
5365 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
5366 case tok::comma: Opc = BinaryOperator::Comma; break;
5367 }
5368 return Opc;
5369}
5370
Steve Naroff35d85152007-05-07 00:24:15 +00005371static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
5372 tok::TokenKind Kind) {
5373 UnaryOperator::Opcode Opc;
5374 switch (Kind) {
5375 default: assert(0 && "Unknown unary op!");
5376 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
5377 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
5378 case tok::amp: Opc = UnaryOperator::AddrOf; break;
5379 case tok::star: Opc = UnaryOperator::Deref; break;
5380 case tok::plus: Opc = UnaryOperator::Plus; break;
5381 case tok::minus: Opc = UnaryOperator::Minus; break;
5382 case tok::tilde: Opc = UnaryOperator::Not; break;
5383 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Steve Naroff35d85152007-05-07 00:24:15 +00005384 case tok::kw___real: Opc = UnaryOperator::Real; break;
5385 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
Chris Lattnerd0f76512007-06-08 22:16:53 +00005386 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
Steve Naroff35d85152007-05-07 00:24:15 +00005387 }
5388 return Opc;
5389}
5390
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00005391/// CreateBuiltinBinOp - Creates a new built-in binary operation with
5392/// operator @p Opc at location @c TokLoc. This routine only supports
5393/// built-in operations; ActOnBinOp handles overloaded operators.
Sebastian Redlb5d49352009-01-19 22:31:54 +00005394Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
5395 unsigned Op,
5396 Expr *lhs, Expr *rhs) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005397 QualType ResultTy; // Result type of the binary operator.
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00005398 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005399 // The following two variables are used for compound assignment operators
5400 QualType CompLHSTy; // Type of LHS after promotions for computation
5401 QualType CompResultTy; // Type of computation result
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00005402
5403 switch (Opc) {
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00005404 case BinaryOperator::Assign:
5405 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
5406 break;
Sebastian Redl112a97662009-02-07 00:15:38 +00005407 case BinaryOperator::PtrMemD:
5408 case BinaryOperator::PtrMemI:
5409 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
5410 Opc == BinaryOperator::PtrMemI);
5411 break;
5412 case BinaryOperator::Mul:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00005413 case BinaryOperator::Div:
5414 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
5415 break;
5416 case BinaryOperator::Rem:
5417 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
5418 break;
5419 case BinaryOperator::Add:
5420 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
5421 break;
5422 case BinaryOperator::Sub:
5423 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
5424 break;
Sebastian Redl112a97662009-02-07 00:15:38 +00005425 case BinaryOperator::Shl:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00005426 case BinaryOperator::Shr:
5427 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
5428 break;
5429 case BinaryOperator::LE:
5430 case BinaryOperator::LT:
5431 case BinaryOperator::GE:
5432 case BinaryOperator::GT:
Douglas Gregor7a5bc762009-04-06 18:45:53 +00005433 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00005434 break;
5435 case BinaryOperator::EQ:
5436 case BinaryOperator::NE:
Douglas Gregor7a5bc762009-04-06 18:45:53 +00005437 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00005438 break;
5439 case BinaryOperator::And:
5440 case BinaryOperator::Xor:
5441 case BinaryOperator::Or:
5442 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
5443 break;
5444 case BinaryOperator::LAnd:
5445 case BinaryOperator::LOr:
5446 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
5447 break;
5448 case BinaryOperator::MulAssign:
5449 case BinaryOperator::DivAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005450 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
5451 CompLHSTy = CompResultTy;
5452 if (!CompResultTy.isNull())
5453 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00005454 break;
5455 case BinaryOperator::RemAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005456 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
5457 CompLHSTy = CompResultTy;
5458 if (!CompResultTy.isNull())
5459 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00005460 break;
5461 case BinaryOperator::AddAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005462 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
5463 if (!CompResultTy.isNull())
5464 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00005465 break;
5466 case BinaryOperator::SubAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005467 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
5468 if (!CompResultTy.isNull())
5469 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00005470 break;
5471 case BinaryOperator::ShlAssign:
5472 case BinaryOperator::ShrAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005473 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
5474 CompLHSTy = CompResultTy;
5475 if (!CompResultTy.isNull())
5476 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00005477 break;
5478 case BinaryOperator::AndAssign:
5479 case BinaryOperator::XorAssign:
5480 case BinaryOperator::OrAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005481 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
5482 CompLHSTy = CompResultTy;
5483 if (!CompResultTy.isNull())
5484 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00005485 break;
5486 case BinaryOperator::Comma:
5487 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
5488 break;
5489 }
5490 if (ResultTy.isNull())
Sebastian Redlb5d49352009-01-19 22:31:54 +00005491 return ExprError();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005492 if (CompResultTy.isNull())
Steve Narofff6009ed2009-01-21 00:14:39 +00005493 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
5494 else
5495 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005496 CompLHSTy, CompResultTy,
5497 OpLoc));
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00005498}
5499
Sebastian Redl44615072009-10-27 12:10:02 +00005500/// SuggestParentheses - Emit a diagnostic together with a fixit hint that wraps
5501/// ParenRange in parentheses.
Sebastian Redl4afb7c582009-10-26 17:01:32 +00005502static void SuggestParentheses(Sema &Self, SourceLocation Loc,
5503 const PartialDiagnostic &PD,
5504 SourceRange ParenRange)
5505{
5506 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
5507 if (!ParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
5508 // We can't display the parentheses, so just dig the
5509 // warning/error and return.
5510 Self.Diag(Loc, PD);
5511 return;
5512 }
5513
5514 Self.Diag(Loc, PD)
5515 << CodeModificationHint::CreateInsertion(ParenRange.getBegin(), "(")
5516 << CodeModificationHint::CreateInsertion(EndLoc, ")");
5517}
5518
Sebastian Redl44615072009-10-27 12:10:02 +00005519/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
5520/// operators are mixed in a way that suggests that the programmer forgot that
5521/// comparison operators have higher precedence. The most typical example of
5522/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
Sebastian Redl43028242009-10-26 15:24:15 +00005523static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperator::Opcode Opc,
5524 SourceLocation OpLoc,Expr *lhs,Expr *rhs){
Sebastian Redl44615072009-10-27 12:10:02 +00005525 typedef BinaryOperator BinOp;
5526 BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1),
5527 rhsopc = static_cast<BinOp::Opcode>(-1);
5528 if (BinOp *BO = dyn_cast<BinOp>(lhs))
Sebastian Redl43028242009-10-26 15:24:15 +00005529 lhsopc = BO->getOpcode();
Sebastian Redl44615072009-10-27 12:10:02 +00005530 if (BinOp *BO = dyn_cast<BinOp>(rhs))
Sebastian Redl43028242009-10-26 15:24:15 +00005531 rhsopc = BO->getOpcode();
5532
5533 // Subs are not binary operators.
5534 if (lhsopc == -1 && rhsopc == -1)
5535 return;
5536
5537 // Bitwise operations are sometimes used as eager logical ops.
5538 // Don't diagnose this.
Sebastian Redl44615072009-10-27 12:10:02 +00005539 if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) &&
5540 (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc)))
Sebastian Redl43028242009-10-26 15:24:15 +00005541 return;
5542
Sebastian Redl44615072009-10-27 12:10:02 +00005543 if (BinOp::isComparisonOp(lhsopc))
Sebastian Redl4afb7c582009-10-26 17:01:32 +00005544 SuggestParentheses(Self, OpLoc,
5545 PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redl44615072009-10-27 12:10:02 +00005546 << SourceRange(lhs->getLocStart(), OpLoc)
5547 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(lhsopc),
5548 SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(), rhs->getLocEnd()));
5549 else if (BinOp::isComparisonOp(rhsopc))
Sebastian Redl4afb7c582009-10-26 17:01:32 +00005550 SuggestParentheses(Self, OpLoc,
5551 PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redl44615072009-10-27 12:10:02 +00005552 << SourceRange(OpLoc, rhs->getLocEnd())
5553 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(rhsopc),
5554 SourceRange(lhs->getLocEnd(), cast<BinOp>(rhs)->getLHS()->getLocStart()));
Sebastian Redl43028242009-10-26 15:24:15 +00005555}
5556
5557/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
5558/// precedence. This currently diagnoses only "arg1 'bitwise' arg2 'eq' arg3".
5559/// But it could also warn about arg1 && arg2 || arg3, as GCC 4.3+ does.
5560static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperator::Opcode Opc,
5561 SourceLocation OpLoc, Expr *lhs, Expr *rhs){
Sebastian Redl44615072009-10-27 12:10:02 +00005562 if (BinaryOperator::isBitwiseOp(Opc))
Sebastian Redl43028242009-10-26 15:24:15 +00005563 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs);
5564}
5565
Steve Naroff218bc2b2007-05-04 21:54:46 +00005566// Binary Operators. 'Tok' is the token for the operator.
Sebastian Redlb5d49352009-01-19 22:31:54 +00005567Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
5568 tok::TokenKind Kind,
5569 ExprArg LHS, ExprArg RHS) {
Steve Naroff218bc2b2007-05-04 21:54:46 +00005570 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
Anders Carlssonb781bcd2009-05-01 19:49:17 +00005571 Expr *lhs = LHS.takeAs<Expr>(), *rhs = RHS.takeAs<Expr>();
Steve Naroff218bc2b2007-05-04 21:54:46 +00005572
Steve Naroff83895f72007-09-16 03:34:24 +00005573 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
5574 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Steve Naroff218bc2b2007-05-04 21:54:46 +00005575
Sebastian Redl43028242009-10-26 15:24:15 +00005576 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
5577 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs);
5578
Douglas Gregor5287f092009-11-05 00:51:44 +00005579 return BuildBinOp(S, TokLoc, Opc, lhs, rhs);
5580}
5581
5582Action::OwningExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
5583 BinaryOperator::Opcode Opc,
5584 Expr *lhs, Expr *rhs) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005585 if (getLangOptions().CPlusPlus &&
Mike Stump11289f42009-09-09 15:08:12 +00005586 (lhs->getType()->isOverloadableType() ||
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005587 rhs->getType()->isOverloadableType())) {
5588 // Find all of the overloaded operators visible from this
5589 // point. We perform both an operator-name lookup from the local
5590 // scope and an argument-dependent lookup based on the types of
5591 // the arguments.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00005592 FunctionSet Functions;
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005593 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
5594 if (OverOp != OO_None) {
Douglas Gregor5287f092009-11-05 00:51:44 +00005595 if (S)
5596 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
5597 Functions);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005598 Expr *Args[2] = { lhs, rhs };
Mike Stump11289f42009-09-09 15:08:12 +00005599 DeclarationName OpName
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005600 = Context.DeclarationNames.getCXXOperatorName(OverOp);
Sebastian Redlc057f422009-10-23 19:23:15 +00005601 ArgumentDependentLookup(OpName, /*Operator*/true, Args, 2, Functions);
Douglas Gregora11693b2008-11-12 17:17:38 +00005602 }
Douglas Gregor5287f092009-11-05 00:51:44 +00005603
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005604 // Build the (potentially-overloaded, potentially-dependent)
5605 // binary operation.
Douglas Gregor5287f092009-11-05 00:51:44 +00005606 return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs);
Sebastian Redlb5d49352009-01-19 22:31:54 +00005607 }
Douglas Gregor5287f092009-11-05 00:51:44 +00005608
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00005609 // Build a built-in binary operation.
Douglas Gregor5287f092009-11-05 00:51:44 +00005610 return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs);
Steve Naroff218bc2b2007-05-04 21:54:46 +00005611}
5612
Douglas Gregor084d8552009-03-13 23:49:33 +00005613Action::OwningExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00005614 unsigned OpcIn,
Douglas Gregor084d8552009-03-13 23:49:33 +00005615 ExprArg InputArg) {
5616 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregord08452f2008-11-19 15:42:04 +00005617
Mike Stump87c57ac2009-05-16 07:39:55 +00005618 // FIXME: Input is modified below, but InputArg is not updated appropriately.
Douglas Gregor084d8552009-03-13 23:49:33 +00005619 Expr *Input = (Expr *)InputArg.get();
Steve Naroff35d85152007-05-07 00:24:15 +00005620 QualType resultType;
5621 switch (Opc) {
Douglas Gregor084d8552009-03-13 23:49:33 +00005622 case UnaryOperator::OffsetOf:
5623 assert(false && "Invalid unary operator");
5624 break;
5625
Steve Naroff35d85152007-05-07 00:24:15 +00005626 case UnaryOperator::PreInc:
5627 case UnaryOperator::PreDec:
Eli Friedman6aea5752009-07-22 22:25:00 +00005628 case UnaryOperator::PostInc:
5629 case UnaryOperator::PostDec:
Sebastian Redle10c2c32008-12-20 09:35:34 +00005630 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
Eli Friedman6aea5752009-07-22 22:25:00 +00005631 Opc == UnaryOperator::PreInc ||
5632 Opc == UnaryOperator::PostInc);
Steve Naroff35d85152007-05-07 00:24:15 +00005633 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005634 case UnaryOperator::AddrOf:
Chris Lattner86554282007-06-08 22:32:33 +00005635 resultType = CheckAddressOfOperand(Input, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00005636 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005637 case UnaryOperator::Deref:
Steve Naroffb7235642007-12-18 04:06:57 +00005638 DefaultFunctionArrayConversion(Input);
Chris Lattner86554282007-06-08 22:32:33 +00005639 resultType = CheckIndirectionOperand(Input, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00005640 break;
5641 case UnaryOperator::Plus:
5642 case UnaryOperator::Minus:
Steve Naroff31090012007-07-16 21:54:35 +00005643 UsualUnaryConversions(Input);
5644 resultType = Input->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005645 if (resultType->isDependentType())
5646 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00005647 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
5648 break;
5649 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
5650 resultType->isEnumeralType())
5651 break;
5652 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
5653 Opc == UnaryOperator::Plus &&
5654 resultType->isPointerType())
5655 break;
5656
Sebastian Redlc215cfc2009-01-19 00:08:26 +00005657 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5658 << resultType << Input->getSourceRange());
Steve Naroff35d85152007-05-07 00:24:15 +00005659 case UnaryOperator::Not: // bitwise complement
Steve Naroff31090012007-07-16 21:54:35 +00005660 UsualUnaryConversions(Input);
5661 resultType = Input->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005662 if (resultType->isDependentType())
5663 break;
Chris Lattner0d707612008-07-25 23:52:49 +00005664 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
5665 if (resultType->isComplexType() || resultType->isComplexIntegerType())
5666 // C99 does not support '~' for complex conjugation.
Chris Lattner29e812b2008-11-20 06:06:08 +00005667 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005668 << resultType << Input->getSourceRange();
Chris Lattner0d707612008-07-25 23:52:49 +00005669 else if (!resultType->isIntegerType())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00005670 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5671 << resultType << Input->getSourceRange());
Steve Naroff35d85152007-05-07 00:24:15 +00005672 break;
5673 case UnaryOperator::LNot: // logical negation
Steve Naroff71b59a92007-06-04 22:22:31 +00005674 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Steve Naroff31090012007-07-16 21:54:35 +00005675 DefaultFunctionArrayConversion(Input);
5676 resultType = Input->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005677 if (resultType->isDependentType())
5678 break;
Steve Naroff35d85152007-05-07 00:24:15 +00005679 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redlc215cfc2009-01-19 00:08:26 +00005680 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5681 << resultType << Input->getSourceRange());
Chris Lattnerbe31ed82007-06-02 19:11:33 +00005682 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00005683 // In C++, it's bool. C++ 5.3.1p8
5684 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Steve Naroff35d85152007-05-07 00:24:15 +00005685 break;
Chris Lattner30b5dd02007-08-24 21:16:53 +00005686 case UnaryOperator::Real:
Chris Lattner30b5dd02007-08-24 21:16:53 +00005687 case UnaryOperator::Imag:
Chris Lattner709322b2009-02-17 08:12:06 +00005688 resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real);
Chris Lattner30b5dd02007-08-24 21:16:53 +00005689 break;
Chris Lattner86554282007-06-08 22:32:33 +00005690 case UnaryOperator::Extension:
Chris Lattner86554282007-06-08 22:32:33 +00005691 resultType = Input->getType();
Steve Naroff043d45d2007-05-15 02:32:35 +00005692 break;
Steve Naroff35d85152007-05-07 00:24:15 +00005693 }
5694 if (resultType.isNull())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00005695 return ExprError();
Douglas Gregor084d8552009-03-13 23:49:33 +00005696
5697 InputArg.release();
Steve Narofff6009ed2009-01-21 00:14:39 +00005698 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
Steve Naroff35d85152007-05-07 00:24:15 +00005699}
Chris Lattnereefa10e2007-05-28 06:56:27 +00005700
Douglas Gregor5287f092009-11-05 00:51:44 +00005701Action::OwningExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
5702 UnaryOperator::Opcode Opc,
5703 ExprArg input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00005704 Expr *Input = (Expr*)input.get();
Anders Carlsson461a2c02009-11-14 21:26:41 +00005705 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
5706 Opc != UnaryOperator::Extension) {
Douglas Gregor084d8552009-03-13 23:49:33 +00005707 // Find all of the overloaded operators visible from this
5708 // point. We perform both an operator-name lookup from the local
5709 // scope and an argument-dependent lookup based on the types of
5710 // the arguments.
5711 FunctionSet Functions;
5712 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
5713 if (OverOp != OO_None) {
Douglas Gregor5287f092009-11-05 00:51:44 +00005714 if (S)
5715 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
5716 Functions);
Mike Stump11289f42009-09-09 15:08:12 +00005717 DeclarationName OpName
Douglas Gregor084d8552009-03-13 23:49:33 +00005718 = Context.DeclarationNames.getCXXOperatorName(OverOp);
Sebastian Redlc057f422009-10-23 19:23:15 +00005719 ArgumentDependentLookup(OpName, /*Operator*/true, &Input, 1, Functions);
Douglas Gregor084d8552009-03-13 23:49:33 +00005720 }
Douglas Gregor5287f092009-11-05 00:51:44 +00005721
Douglas Gregor084d8552009-03-13 23:49:33 +00005722 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, move(input));
5723 }
Douglas Gregor5287f092009-11-05 00:51:44 +00005724
Douglas Gregor084d8552009-03-13 23:49:33 +00005725 return CreateBuiltinUnaryOp(OpLoc, Opc, move(input));
5726}
5727
Douglas Gregor5287f092009-11-05 00:51:44 +00005728// Unary Operators. 'Tok' is the token for the operator.
5729Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
5730 tok::TokenKind Op, ExprArg input) {
5731 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), move(input));
5732}
5733
Steve Naroff66356bd2007-09-16 14:56:35 +00005734/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005735Sema::OwningExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
5736 SourceLocation LabLoc,
5737 IdentifierInfo *LabelII) {
Chris Lattnereefa10e2007-05-28 06:56:27 +00005738 // Look up the record for this label identifier.
Chris Lattner3318e862009-04-18 20:01:55 +00005739 LabelStmt *&LabelDecl = getLabelMap()[LabelII];
Mike Stump4e1f26a2009-02-19 03:04:26 +00005740
Daniel Dunbar88402ce2008-08-04 16:51:22 +00005741 // If we haven't seen this label yet, create a forward reference. It
5742 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Steve Naroff846b1ec2009-03-13 15:38:40 +00005743 if (LabelDecl == 0)
Steve Narofff6009ed2009-01-21 00:14:39 +00005744 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005745
Chris Lattnereefa10e2007-05-28 06:56:27 +00005746 // Create the AST node. The address of a label always has type 'void*'.
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005747 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
5748 Context.getPointerType(Context.VoidTy)));
Chris Lattnereefa10e2007-05-28 06:56:27 +00005749}
5750
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005751Sema::OwningExprResult
5752Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtArg substmt,
5753 SourceLocation RPLoc) { // "({..})"
5754 Stmt *SubStmt = static_cast<Stmt*>(substmt.get());
Chris Lattner366727f2007-07-24 16:58:17 +00005755 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
5756 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
5757
Eli Friedman52cc0162009-01-24 23:09:00 +00005758 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Chris Lattnera69b0762009-04-25 19:11:05 +00005759 if (isFileScope)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005760 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedman52cc0162009-01-24 23:09:00 +00005761
Chris Lattner366727f2007-07-24 16:58:17 +00005762 // FIXME: there are a variety of strange constraints to enforce here, for
5763 // example, it is not possible to goto into a stmt expression apparently.
5764 // More semantic analysis is needed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00005765
Chris Lattner366727f2007-07-24 16:58:17 +00005766 // If there are sub stmts in the compound stmt, take the type of the last one
5767 // as the type of the stmtexpr.
5768 QualType Ty = Context.VoidTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005769
Chris Lattner944d3062008-07-26 19:51:01 +00005770 if (!Compound->body_empty()) {
5771 Stmt *LastStmt = Compound->body_back();
5772 // If LastStmt is a label, skip down through into the body.
5773 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
5774 LastStmt = Label->getSubStmt();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005775
Chris Lattner944d3062008-07-26 19:51:01 +00005776 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattner366727f2007-07-24 16:58:17 +00005777 Ty = LastExpr->getType();
Chris Lattner944d3062008-07-26 19:51:01 +00005778 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005779
Eli Friedmanba961a92009-03-23 00:24:07 +00005780 // FIXME: Check that expression type is complete/non-abstract; statement
5781 // expressions are not lvalues.
5782
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005783 substmt.release();
5784 return Owned(new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc));
Chris Lattner366727f2007-07-24 16:58:17 +00005785}
Steve Naroff78864672007-08-01 22:05:33 +00005786
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005787Sema::OwningExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
5788 SourceLocation BuiltinLoc,
5789 SourceLocation TypeLoc,
5790 TypeTy *argty,
5791 OffsetOfComponent *CompPtr,
5792 unsigned NumComponents,
5793 SourceLocation RPLoc) {
5794 // FIXME: This function leaks all expressions in the offset components on
5795 // error.
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00005796 // FIXME: Preserve type source info.
5797 QualType ArgTy = GetTypeFromParser(argty);
Chris Lattnerf17bd422007-08-30 17:45:32 +00005798 assert(!ArgTy.isNull() && "Missing type argument!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00005799
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005800 bool Dependent = ArgTy->isDependentType();
5801
Chris Lattnerf17bd422007-08-30 17:45:32 +00005802 // We must have at least one component that refers to the type, and the first
5803 // one is known to be a field designator. Verify that the ArgTy represents
5804 // a struct/union/class.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005805 if (!Dependent && !ArgTy->isRecordType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005806 return ExprError(Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005807
Eli Friedmanba961a92009-03-23 00:24:07 +00005808 // FIXME: Type must be complete per C99 7.17p3 because a declaring a variable
5809 // with an incomplete type would be illegal.
Douglas Gregor26897462009-03-11 16:48:53 +00005810
Eli Friedman988a16b2009-02-27 06:44:11 +00005811 // Otherwise, create a null pointer as the base, and iteratively process
5812 // the offsetof designators.
5813 QualType ArgTyPtr = Context.getPointerType(ArgTy);
5814 Expr* Res = new (Context) ImplicitValueInitExpr(ArgTyPtr);
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005815 Res = new (Context) UnaryOperator(Res, UnaryOperator::Deref,
Eli Friedman988a16b2009-02-27 06:44:11 +00005816 ArgTy, SourceLocation());
Eli Friedman16c88df2009-01-26 01:33:06 +00005817
Chris Lattner78502cf2007-08-31 21:49:13 +00005818 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
5819 // GCC extension, diagnose them.
Eli Friedman988a16b2009-02-27 06:44:11 +00005820 // FIXME: This diagnostic isn't actually visible because the location is in
5821 // a system header!
Chris Lattner78502cf2007-08-31 21:49:13 +00005822 if (NumComponents != 1)
Chris Lattnerf490e152008-11-19 05:27:50 +00005823 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
5824 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005825
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005826 if (!Dependent) {
Eli Friedman8469bc72009-05-03 21:22:18 +00005827 bool DidWarnAboutNonPOD = false;
Mike Stump11289f42009-09-09 15:08:12 +00005828
John McCall9eff4e62009-11-04 03:03:43 +00005829 if (RequireCompleteType(TypeLoc, Res->getType(),
5830 diag::err_offsetof_incomplete_type))
5831 return ExprError();
5832
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005833 // FIXME: Dependent case loses a lot of information here. And probably
5834 // leaks like a sieve.
5835 for (unsigned i = 0; i != NumComponents; ++i) {
5836 const OffsetOfComponent &OC = CompPtr[i];
5837 if (OC.isBrackets) {
5838 // Offset of an array sub-field. TODO: Should we allow vector elements?
5839 const ArrayType *AT = Context.getAsArrayType(Res->getType());
5840 if (!AT) {
5841 Res->Destroy(Context);
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005842 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
5843 << Res->getType());
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005844 }
5845
5846 // FIXME: C++: Verify that operator[] isn't overloaded.
5847
Eli Friedman988a16b2009-02-27 06:44:11 +00005848 // Promote the array so it looks more like a normal array subscript
5849 // expression.
5850 DefaultFunctionArrayConversion(Res);
5851
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005852 // C99 6.5.2.1p1
5853 Expr *Idx = static_cast<Expr*>(OC.U.E);
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005854 // FIXME: Leaks Res
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005855 if (!Idx->isTypeDependent() && !Idx->getType()->isIntegerType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005856 return ExprError(Diag(Idx->getLocStart(),
Chris Lattner003af242009-04-25 22:50:55 +00005857 diag::err_typecheck_subscript_not_integer)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005858 << Idx->getSourceRange());
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005859
5860 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
5861 OC.LocEnd);
5862 continue;
Chris Lattnerf17bd422007-08-30 17:45:32 +00005863 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005864
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005865 const RecordType *RC = Res->getType()->getAs<RecordType>();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005866 if (!RC) {
5867 Res->Destroy(Context);
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005868 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
5869 << Res->getType());
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005870 }
Chris Lattner98dbf0a2007-08-30 17:59:59 +00005871
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005872 // Get the decl corresponding to this.
5873 RecordDecl *RD = RC->getDecl();
Anders Carlsson2bbb86b2009-05-01 23:20:30 +00005874 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
Anders Carlsson38ebcaa2009-05-02 18:36:10 +00005875 if (!CRD->isPOD() && !DidWarnAboutNonPOD) {
Anders Carlsson8b98d022009-05-02 17:45:47 +00005876 ExprError(Diag(BuiltinLoc, diag::warn_offsetof_non_pod_type)
5877 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
5878 << Res->getType());
Anders Carlsson38ebcaa2009-05-02 18:36:10 +00005879 DidWarnAboutNonPOD = true;
5880 }
Anders Carlsson2bbb86b2009-05-01 23:20:30 +00005881 }
Mike Stump11289f42009-09-09 15:08:12 +00005882
John McCall27b18f82009-11-17 02:14:36 +00005883 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
5884 LookupQualifiedName(R, RD);
John McCall9f3059a2009-10-09 21:13:30 +00005885
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005886 FieldDecl *MemberDecl
John McCall9f3059a2009-10-09 21:13:30 +00005887 = dyn_cast_or_null<FieldDecl>(R.getAsSingleDecl(Context));
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005888 // FIXME: Leaks Res
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005889 if (!MemberDecl)
Douglas Gregore40876a2009-10-13 21:16:44 +00005890 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
5891 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, OC.LocEnd));
Mike Stump4e1f26a2009-02-19 03:04:26 +00005892
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005893 // FIXME: C++: Verify that MemberDecl isn't a static field.
5894 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman64fc3c62009-04-26 20:50:44 +00005895 if (cast<RecordDecl>(MemberDecl->getDeclContext())->isAnonymousStructOrUnion()) {
Anders Carlsson3cbc8592009-05-01 19:30:39 +00005896 Res = BuildAnonymousStructUnionMemberReference(
John McCall7e1d6d72009-11-11 03:23:23 +00005897 OC.LocEnd, MemberDecl, Res, OC.LocEnd).takeAs<Expr>();
Eli Friedman64fc3c62009-04-26 20:50:44 +00005898 } else {
5899 // MemberDecl->getType() doesn't get the right qualifiers, but it
5900 // doesn't matter here.
5901 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
5902 MemberDecl->getType().getNonReferenceType());
5903 }
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005904 }
Chris Lattnerf17bd422007-08-30 17:45:32 +00005905 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005906
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005907 return Owned(new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
5908 Context.getSizeType(), BuiltinLoc));
Chris Lattnerf17bd422007-08-30 17:45:32 +00005909}
5910
5911
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005912Sema::OwningExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
5913 TypeTy *arg1,TypeTy *arg2,
5914 SourceLocation RPLoc) {
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00005915 // FIXME: Preserve type source info.
5916 QualType argT1 = GetTypeFromParser(arg1);
5917 QualType argT2 = GetTypeFromParser(arg2);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005918
Steve Naroff78864672007-08-01 22:05:33 +00005919 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
Mike Stump4e1f26a2009-02-19 03:04:26 +00005920
Douglas Gregorf907cbf2009-05-19 22:28:02 +00005921 if (getLangOptions().CPlusPlus) {
5922 Diag(BuiltinLoc, diag::err_types_compatible_p_in_cplusplus)
5923 << SourceRange(BuiltinLoc, RPLoc);
5924 return ExprError();
5925 }
5926
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005927 return Owned(new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc,
5928 argT1, argT2, RPLoc));
Steve Naroff78864672007-08-01 22:05:33 +00005929}
5930
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005931Sema::OwningExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
5932 ExprArg cond,
5933 ExprArg expr1, ExprArg expr2,
5934 SourceLocation RPLoc) {
5935 Expr *CondExpr = static_cast<Expr*>(cond.get());
5936 Expr *LHSExpr = static_cast<Expr*>(expr1.get());
5937 Expr *RHSExpr = static_cast<Expr*>(expr2.get());
Mike Stump4e1f26a2009-02-19 03:04:26 +00005938
Steve Naroff9efdabc2007-08-03 21:21:27 +00005939 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
5940
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005941 QualType resType;
Douglas Gregor56751b52009-09-25 04:25:58 +00005942 bool ValueDependent = false;
Douglas Gregor0df91122009-05-19 22:43:30 +00005943 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005944 resType = Context.DependentTy;
Douglas Gregor56751b52009-09-25 04:25:58 +00005945 ValueDependent = true;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005946 } else {
5947 // The conditional expression is required to be a constant expression.
5948 llvm::APSInt condEval(32);
5949 SourceLocation ExpLoc;
5950 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005951 return ExprError(Diag(ExpLoc,
5952 diag::err_typecheck_choose_expr_requires_constant)
5953 << CondExpr->getSourceRange());
Steve Naroff9efdabc2007-08-03 21:21:27 +00005954
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005955 // If the condition is > zero, then the AST type is the same as the LSHExpr.
5956 resType = condEval.getZExtValue() ? LHSExpr->getType() : RHSExpr->getType();
Douglas Gregor56751b52009-09-25 04:25:58 +00005957 ValueDependent = condEval.getZExtValue() ? LHSExpr->isValueDependent()
5958 : RHSExpr->isValueDependent();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005959 }
5960
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005961 cond.release(); expr1.release(); expr2.release();
5962 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
Douglas Gregor56751b52009-09-25 04:25:58 +00005963 resType, RPLoc,
5964 resType->isDependentType(),
5965 ValueDependent));
Steve Naroff9efdabc2007-08-03 21:21:27 +00005966}
5967
Steve Naroffc540d662008-09-03 18:15:37 +00005968//===----------------------------------------------------------------------===//
5969// Clang Extensions.
5970//===----------------------------------------------------------------------===//
5971
5972/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff1d95e5a2008-10-10 01:28:17 +00005973void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroffc540d662008-09-03 18:15:37 +00005974 // Analyze block parameters.
5975 BlockSemaInfo *BSI = new BlockSemaInfo();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005976
Steve Naroffc540d662008-09-03 18:15:37 +00005977 // Add BSI to CurBlock.
5978 BSI->PrevBlockInfo = CurBlock;
5979 CurBlock = BSI;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005980
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00005981 BSI->ReturnType = QualType();
Steve Naroffc540d662008-09-03 18:15:37 +00005982 BSI->TheScope = BlockScope;
Mike Stumpa6703322009-02-19 22:01:56 +00005983 BSI->hasBlockDeclRefExprs = false;
Daniel Dunbarb9a68612009-07-29 01:59:17 +00005984 BSI->hasPrototype = false;
Chris Lattner45542ea2009-04-19 05:28:12 +00005985 BSI->SavedFunctionNeedsScopeChecking = CurFunctionNeedsScopeChecking;
5986 CurFunctionNeedsScopeChecking = false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005987
Steve Naroff1d95e5a2008-10-10 01:28:17 +00005988 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Douglas Gregor91f84212008-12-11 16:49:14 +00005989 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff1d95e5a2008-10-10 01:28:17 +00005990}
5991
Mike Stump82f071f2009-02-04 22:31:32 +00005992void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpf70bcf72009-05-07 18:43:07 +00005993 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
Mike Stump82f071f2009-02-04 22:31:32 +00005994
5995 if (ParamInfo.getNumTypeObjects() == 0
5996 || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) {
Douglas Gregor758a8692009-06-17 21:51:59 +00005997 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
Mike Stump82f071f2009-02-04 22:31:32 +00005998 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
5999
Mike Stumpd456c482009-04-28 01:10:27 +00006000 if (T->isArrayType()) {
6001 Diag(ParamInfo.getSourceRange().getBegin(),
6002 diag::err_block_returns_array);
6003 return;
6004 }
6005
Mike Stump82f071f2009-02-04 22:31:32 +00006006 // The parameter list is optional, if there was none, assume ().
6007 if (!T->isFunctionType())
6008 T = Context.getFunctionType(T, NULL, 0, 0, 0);
6009
6010 CurBlock->hasPrototype = true;
6011 CurBlock->isVariadic = false;
Fariborz Jahanian6607b212009-05-14 20:53:39 +00006012 // Check for a valid sentinel attribute on this block.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00006013 if (CurBlock->TheDecl->getAttr<SentinelAttr>()) {
Mike Stump11289f42009-09-09 15:08:12 +00006014 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian6802ed92009-05-15 21:18:04 +00006015 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian6607b212009-05-14 20:53:39 +00006016 // FIXME: remove the attribute.
6017 }
John McCall9dd450b2009-09-21 23:43:11 +00006018 QualType RetTy = T.getTypePtr()->getAs<FunctionType>()->getResultType();
Mike Stump11289f42009-09-09 15:08:12 +00006019
Chris Lattner6de05082009-04-11 19:27:54 +00006020 // Do not allow returning a objc interface by-value.
6021 if (RetTy->isObjCInterfaceType()) {
6022 Diag(ParamInfo.getSourceRange().getBegin(),
6023 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
6024 return;
6025 }
Mike Stump82f071f2009-02-04 22:31:32 +00006026 return;
6027 }
6028
Steve Naroffc540d662008-09-03 18:15:37 +00006029 // Analyze arguments to block.
6030 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
6031 "Not a function declarator!");
6032 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006033
Steve Naroff1d95e5a2008-10-10 01:28:17 +00006034 CurBlock->hasPrototype = FTI.hasPrototype;
6035 CurBlock->isVariadic = true;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006036
Steve Naroffc540d662008-09-03 18:15:37 +00006037 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
6038 // no arguments, not a function that takes a single void argument.
6039 if (FTI.hasPrototype &&
6040 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
Chris Lattner83f095c2009-03-28 19:18:32 +00006041 (!FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType().getCVRQualifiers()&&
6042 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType())) {
Steve Naroffc540d662008-09-03 18:15:37 +00006043 // empty arg list, don't push any params.
Steve Naroff1d95e5a2008-10-10 01:28:17 +00006044 CurBlock->isVariadic = false;
Steve Naroffc540d662008-09-03 18:15:37 +00006045 } else if (FTI.hasPrototype) {
6046 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Chris Lattner83f095c2009-03-28 19:18:32 +00006047 CurBlock->Params.push_back(FTI.ArgInfo[i].Param.getAs<ParmVarDecl>());
Steve Naroff1d95e5a2008-10-10 01:28:17 +00006048 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroffc540d662008-09-03 18:15:37 +00006049 }
Jay Foad7d0479f2009-05-21 09:52:38 +00006050 CurBlock->TheDecl->setParams(Context, CurBlock->Params.data(),
Chris Lattner6de05082009-04-11 19:27:54 +00006051 CurBlock->Params.size());
Fariborz Jahanian960910a2009-05-19 17:08:59 +00006052 CurBlock->TheDecl->setIsVariadic(CurBlock->isVariadic);
Douglas Gregor758a8692009-06-17 21:51:59 +00006053 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
Steve Naroff1d95e5a2008-10-10 01:28:17 +00006054 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
6055 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
6056 // If this has an identifier, add it to the scope stack.
6057 if ((*AI)->getIdentifier())
6058 PushOnScopeChains(*AI, CurBlock->TheScope);
Chris Lattner6de05082009-04-11 19:27:54 +00006059
Fariborz Jahanian6607b212009-05-14 20:53:39 +00006060 // Check for a valid sentinel attribute on this block.
Mike Stump11289f42009-09-09 15:08:12 +00006061 if (!CurBlock->isVariadic &&
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00006062 CurBlock->TheDecl->getAttr<SentinelAttr>()) {
Mike Stump11289f42009-09-09 15:08:12 +00006063 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian6802ed92009-05-15 21:18:04 +00006064 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian6607b212009-05-14 20:53:39 +00006065 // FIXME: remove the attribute.
6066 }
Mike Stump11289f42009-09-09 15:08:12 +00006067
Chris Lattner6de05082009-04-11 19:27:54 +00006068 // Analyze the return type.
6069 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
John McCall9dd450b2009-09-21 23:43:11 +00006070 QualType RetTy = T->getAs<FunctionType>()->getResultType();
Mike Stump11289f42009-09-09 15:08:12 +00006071
Chris Lattner6de05082009-04-11 19:27:54 +00006072 // Do not allow returning a objc interface by-value.
6073 if (RetTy->isObjCInterfaceType()) {
6074 Diag(ParamInfo.getSourceRange().getBegin(),
6075 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
6076 } else if (!RetTy->isDependentType())
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00006077 CurBlock->ReturnType = RetTy;
Steve Naroffc540d662008-09-03 18:15:37 +00006078}
6079
6080/// ActOnBlockError - If there is an error parsing a block, this callback
6081/// is invoked to pop the information about the block from the action impl.
6082void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
6083 // Ensure that CurBlock is deleted.
6084 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006085
Chris Lattner45542ea2009-04-19 05:28:12 +00006086 CurFunctionNeedsScopeChecking = CurBlock->SavedFunctionNeedsScopeChecking;
6087
Steve Naroffc540d662008-09-03 18:15:37 +00006088 // Pop off CurBlock, handle nested blocks.
Chris Lattner41b86942009-04-21 22:38:46 +00006089 PopDeclContext();
Steve Naroffc540d662008-09-03 18:15:37 +00006090 CurBlock = CurBlock->PrevBlockInfo;
Steve Naroffc540d662008-09-03 18:15:37 +00006091 // FIXME: Delete the ParmVarDecl objects as well???
Steve Naroffc540d662008-09-03 18:15:37 +00006092}
6093
6094/// ActOnBlockStmtExpr - This is called when the body of a block statement
6095/// literal was successfully completed. ^(int x){...}
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006096Sema::OwningExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
6097 StmtArg body, Scope *CurScope) {
Chris Lattner9eac9312009-03-27 04:18:06 +00006098 // If blocks are disabled, emit an error.
6099 if (!LangOpts.Blocks)
6100 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump11289f42009-09-09 15:08:12 +00006101
Steve Naroffc540d662008-09-03 18:15:37 +00006102 // Ensure that CurBlock is deleted.
6103 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
Steve Naroffc540d662008-09-03 18:15:37 +00006104
Steve Naroff1d95e5a2008-10-10 01:28:17 +00006105 PopDeclContext();
6106
Steve Naroffc540d662008-09-03 18:15:37 +00006107 // Pop off CurBlock, handle nested blocks.
6108 CurBlock = CurBlock->PrevBlockInfo;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006109
Steve Naroffc540d662008-09-03 18:15:37 +00006110 QualType RetTy = Context.VoidTy;
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00006111 if (!BSI->ReturnType.isNull())
6112 RetTy = BSI->ReturnType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006113
Steve Naroffc540d662008-09-03 18:15:37 +00006114 llvm::SmallVector<QualType, 8> ArgTypes;
6115 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
6116 ArgTypes.push_back(BSI->Params[i]->getType());
Mike Stump4e1f26a2009-02-19 03:04:26 +00006117
Mike Stump3bf1ab42009-07-28 22:04:01 +00006118 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroffc540d662008-09-03 18:15:37 +00006119 QualType BlockTy;
6120 if (!BSI->hasPrototype)
Mike Stump3bf1ab42009-07-28 22:04:01 +00006121 BlockTy = Context.getFunctionType(RetTy, 0, 0, false, 0, false, false, 0, 0,
6122 NoReturn);
Steve Naroffc540d662008-09-03 18:15:37 +00006123 else
Jay Foad7d0479f2009-05-21 09:52:38 +00006124 BlockTy = Context.getFunctionType(RetTy, ArgTypes.data(), ArgTypes.size(),
Mike Stump3bf1ab42009-07-28 22:04:01 +00006125 BSI->isVariadic, 0, false, false, 0, 0,
6126 NoReturn);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006127
Eli Friedmanba961a92009-03-23 00:24:07 +00006128 // FIXME: Check that return/parameter types are complete/non-abstract
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006129 DiagnoseUnusedParameters(BSI->Params.begin(), BSI->Params.end());
Steve Naroffc540d662008-09-03 18:15:37 +00006130 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006131
Chris Lattner45542ea2009-04-19 05:28:12 +00006132 // If needed, diagnose invalid gotos and switches in the block.
6133 if (CurFunctionNeedsScopeChecking)
6134 DiagnoseInvalidJumps(static_cast<CompoundStmt*>(body.get()));
6135 CurFunctionNeedsScopeChecking = BSI->SavedFunctionNeedsScopeChecking;
Mike Stump11289f42009-09-09 15:08:12 +00006136
Anders Carlssonb781bcd2009-05-01 19:49:17 +00006137 BSI->TheDecl->setBody(body.takeAs<CompoundStmt>());
Mike Stump3bf1ab42009-07-28 22:04:01 +00006138 CheckFallThroughForBlock(BlockTy, BSI->TheDecl->getBody());
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006139 return Owned(new (Context) BlockExpr(BSI->TheDecl, BlockTy,
6140 BSI->hasBlockDeclRefExprs));
Steve Naroffc540d662008-09-03 18:15:37 +00006141}
6142
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006143Sema::OwningExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
6144 ExprArg expr, TypeTy *type,
6145 SourceLocation RPLoc) {
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00006146 QualType T = GetTypeFromParser(type);
Chris Lattner56382aa2009-04-05 15:49:53 +00006147 Expr *E = static_cast<Expr*>(expr.get());
6148 Expr *OrigExpr = E;
Mike Stump11289f42009-09-09 15:08:12 +00006149
Anders Carlsson7e13ab82007-10-15 20:28:48 +00006150 InitBuiltinVaListType();
Eli Friedman121ba0c2008-08-09 23:32:40 +00006151
6152 // Get the va_list type
6153 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedmane2cad652009-05-16 12:46:54 +00006154 if (VaListType->isArrayType()) {
6155 // Deal with implicit array decay; for example, on x86-64,
6156 // va_list is an array, but it's supposed to decay to
6157 // a pointer for va_arg.
Eli Friedman121ba0c2008-08-09 23:32:40 +00006158 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedmane2cad652009-05-16 12:46:54 +00006159 // Make sure the input expression also decays appropriately.
6160 UsualUnaryConversions(E);
6161 } else {
6162 // Otherwise, the va_list argument must be an l-value because
6163 // it is modified by va_arg.
Mike Stump11289f42009-09-09 15:08:12 +00006164 if (!E->isTypeDependent() &&
Douglas Gregorad3150c2009-05-19 23:10:31 +00006165 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedmane2cad652009-05-16 12:46:54 +00006166 return ExprError();
6167 }
Eli Friedman121ba0c2008-08-09 23:32:40 +00006168
Douglas Gregorad3150c2009-05-19 23:10:31 +00006169 if (!E->isTypeDependent() &&
6170 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006171 return ExprError(Diag(E->getLocStart(),
6172 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner56382aa2009-04-05 15:49:53 +00006173 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner3f5cd772009-04-05 00:59:53 +00006174 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006175
Eli Friedmanba961a92009-03-23 00:24:07 +00006176 // FIXME: Check that type is complete/non-abstract
Anders Carlsson7e13ab82007-10-15 20:28:48 +00006177 // FIXME: Warn if a non-POD type is passed in.
Mike Stump4e1f26a2009-02-19 03:04:26 +00006178
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006179 expr.release();
6180 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(),
6181 RPLoc));
Anders Carlsson7e13ab82007-10-15 20:28:48 +00006182}
6183
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006184Sema::OwningExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor3be4b122008-11-29 04:51:27 +00006185 // The type of __null will be int or long, depending on the size of
6186 // pointers on the target.
6187 QualType Ty;
6188 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
6189 Ty = Context.IntTy;
6190 else
6191 Ty = Context.LongTy;
6192
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006193 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor3be4b122008-11-29 04:51:27 +00006194}
6195
Anders Carlssonace5d072009-11-10 04:46:30 +00006196static void
6197MakeObjCStringLiteralCodeModificationHint(Sema& SemaRef,
6198 QualType DstType,
6199 Expr *SrcExpr,
6200 CodeModificationHint &Hint) {
6201 if (!SemaRef.getLangOptions().ObjC1)
6202 return;
6203
6204 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
6205 if (!PT)
6206 return;
6207
6208 // Check if the destination is of type 'id'.
6209 if (!PT->isObjCIdType()) {
6210 // Check if the destination is the 'NSString' interface.
6211 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
6212 if (!ID || !ID->getIdentifier()->isStr("NSString"))
6213 return;
6214 }
6215
6216 // Strip off any parens and casts.
6217 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
6218 if (!SL || SL->isWide())
6219 return;
6220
6221 Hint = CodeModificationHint::CreateInsertion(SL->getLocStart(), "@");
6222}
6223
Chris Lattner9bad62c2008-01-04 18:04:52 +00006224bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
6225 SourceLocation Loc,
6226 QualType DstType, QualType SrcType,
6227 Expr *SrcExpr, const char *Flavor) {
6228 // Decode the result (notice that AST's are still created for extensions).
6229 bool isInvalid = false;
6230 unsigned DiagKind;
Anders Carlssonace5d072009-11-10 04:46:30 +00006231 CodeModificationHint Hint;
6232
Chris Lattner9bad62c2008-01-04 18:04:52 +00006233 switch (ConvTy) {
6234 default: assert(0 && "Unknown conversion type");
6235 case Compatible: return false;
Chris Lattner940cfeb2008-01-04 18:22:42 +00006236 case PointerToInt:
Chris Lattner9bad62c2008-01-04 18:04:52 +00006237 DiagKind = diag::ext_typecheck_convert_pointer_int;
6238 break;
Chris Lattner940cfeb2008-01-04 18:22:42 +00006239 case IntToPointer:
6240 DiagKind = diag::ext_typecheck_convert_int_pointer;
6241 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00006242 case IncompatiblePointer:
Anders Carlssonace5d072009-11-10 04:46:30 +00006243 MakeObjCStringLiteralCodeModificationHint(*this, DstType, SrcExpr, Hint);
Chris Lattner9bad62c2008-01-04 18:04:52 +00006244 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
6245 break;
Eli Friedman80160bd2009-03-22 23:59:44 +00006246 case IncompatiblePointerSign:
6247 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
6248 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00006249 case FunctionVoidPointer:
6250 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
6251 break;
6252 case CompatiblePointerDiscardsQualifiers:
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00006253 // If the qualifiers lost were because we were applying the
6254 // (deprecated) C++ conversion from a string literal to a char*
6255 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
6256 // Ideally, this check would be performed in
6257 // CheckPointerTypesForAssignment. However, that would require a
6258 // bit of refactoring (so that the second argument is an
6259 // expression, rather than a type), which should be done as part
6260 // of a larger effort to fix CheckPointerTypesForAssignment for
6261 // C++ semantics.
6262 if (getLangOptions().CPlusPlus &&
6263 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
6264 return false;
Chris Lattner9bad62c2008-01-04 18:04:52 +00006265 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
6266 break;
Alexis Hunt6f3de502009-11-08 07:46:34 +00006267 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanianb98dade2009-11-09 22:16:37 +00006268 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00006269 break;
Steve Naroff081c7422008-09-04 15:10:53 +00006270 case IntToBlockPointer:
6271 DiagKind = diag::err_int_to_block_pointer;
6272 break;
6273 case IncompatibleBlockPointer:
Mike Stumpd79b5a82009-04-21 22:51:42 +00006274 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff081c7422008-09-04 15:10:53 +00006275 break;
Steve Naroff8afa9892008-10-14 22:18:38 +00006276 case IncompatibleObjCQualifiedId:
Mike Stump4e1f26a2009-02-19 03:04:26 +00006277 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff8afa9892008-10-14 22:18:38 +00006278 // it can give a more specific diagnostic.
6279 DiagKind = diag::warn_incompatible_qualified_id;
6280 break;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00006281 case IncompatibleVectors:
6282 DiagKind = diag::warn_incompatible_vectors;
6283 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00006284 case Incompatible:
6285 DiagKind = diag::err_typecheck_convert_incompatible;
6286 isInvalid = true;
6287 break;
6288 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006289
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00006290 Diag(Loc, DiagKind) << DstType << SrcType << Flavor
Anders Carlssonace5d072009-11-10 04:46:30 +00006291 << SrcExpr->getSourceRange() << Hint;
Chris Lattner9bad62c2008-01-04 18:04:52 +00006292 return isInvalid;
6293}
Anders Carlssone54e8a12008-11-30 19:50:32 +00006294
Chris Lattnerc71d08b2009-04-25 21:59:05 +00006295bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedmanbb967cc2009-04-25 22:26:58 +00006296 llvm::APSInt ICEResult;
6297 if (E->isIntegerConstantExpr(ICEResult, Context)) {
6298 if (Result)
6299 *Result = ICEResult;
6300 return false;
6301 }
6302
Anders Carlssone54e8a12008-11-30 19:50:32 +00006303 Expr::EvalResult EvalResult;
6304
Mike Stump4e1f26a2009-02-19 03:04:26 +00006305 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone54e8a12008-11-30 19:50:32 +00006306 EvalResult.HasSideEffects) {
6307 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
6308
6309 if (EvalResult.Diag) {
6310 // We only show the note if it's not the usual "invalid subexpression"
6311 // or if it's actually in a subexpression.
6312 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
6313 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
6314 Diag(EvalResult.DiagLoc, EvalResult.Diag);
6315 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006316
Anders Carlssone54e8a12008-11-30 19:50:32 +00006317 return true;
6318 }
6319
Eli Friedmanbb967cc2009-04-25 22:26:58 +00006320 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
6321 E->getSourceRange();
Anders Carlssone54e8a12008-11-30 19:50:32 +00006322
Eli Friedmanbb967cc2009-04-25 22:26:58 +00006323 if (EvalResult.Diag &&
6324 Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
6325 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006326
Anders Carlssone54e8a12008-11-30 19:50:32 +00006327 if (Result)
6328 *Result = EvalResult.Val.getInt();
6329 return false;
6330}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006331
Mike Stump11289f42009-09-09 15:08:12 +00006332Sema::ExpressionEvaluationContext
6333Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregor0b6a6242009-06-22 20:57:11 +00006334 // Introduce a new set of potentially referenced declarations to the stack.
6335 if (NewContext == PotentiallyPotentiallyEvaluated)
6336 PotentiallyReferencedDeclStack.push_back(PotentiallyReferencedDecls());
Mike Stump11289f42009-09-09 15:08:12 +00006337
Douglas Gregor0b6a6242009-06-22 20:57:11 +00006338 std::swap(ExprEvalContext, NewContext);
6339 return NewContext;
6340}
6341
Mike Stump11289f42009-09-09 15:08:12 +00006342void
Douglas Gregor0b6a6242009-06-22 20:57:11 +00006343Sema::PopExpressionEvaluationContext(ExpressionEvaluationContext OldContext,
6344 ExpressionEvaluationContext NewContext) {
6345 ExprEvalContext = NewContext;
6346
6347 if (OldContext == PotentiallyPotentiallyEvaluated) {
6348 // Mark any remaining declarations in the current position of the stack
6349 // as "referenced". If they were not meant to be referenced, semantic
6350 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
6351 PotentiallyReferencedDecls RemainingDecls;
6352 RemainingDecls.swap(PotentiallyReferencedDeclStack.back());
6353 PotentiallyReferencedDeclStack.pop_back();
Mike Stump11289f42009-09-09 15:08:12 +00006354
Douglas Gregor0b6a6242009-06-22 20:57:11 +00006355 for (PotentiallyReferencedDecls::iterator I = RemainingDecls.begin(),
6356 IEnd = RemainingDecls.end();
6357 I != IEnd; ++I)
6358 MarkDeclarationReferenced(I->first, I->second);
6359 }
6360}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006361
6362/// \brief Note that the given declaration was referenced in the source code.
6363///
6364/// This routine should be invoke whenever a given declaration is referenced
6365/// in the source code, and where that reference occurred. If this declaration
6366/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
6367/// C99 6.9p3), then the declaration will be marked as used.
6368///
6369/// \param Loc the location where the declaration was referenced.
6370///
6371/// \param D the declaration that has been referenced by the source code.
6372void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
6373 assert(D && "No declaration?");
Mike Stump11289f42009-09-09 15:08:12 +00006374
Douglas Gregor77b50e12009-06-22 23:06:13 +00006375 if (D->isUsed())
6376 return;
Mike Stump11289f42009-09-09 15:08:12 +00006377
Douglas Gregor3beaf9b2009-10-08 21:35:42 +00006378 // Mark a parameter or variable declaration "used", regardless of whether we're in a
6379 // template or not. The reason for this is that unevaluated expressions
6380 // (e.g. (void)sizeof()) constitute a use for warning purposes (-Wunused-variables and
6381 // -Wunused-parameters)
6382 if (isa<ParmVarDecl>(D) ||
6383 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod()))
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006384 D->setUsed(true);
Mike Stump11289f42009-09-09 15:08:12 +00006385
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006386 // Do not mark anything as "used" within a dependent context; wait for
6387 // an instantiation.
6388 if (CurContext->isDependentContext())
6389 return;
Mike Stump11289f42009-09-09 15:08:12 +00006390
Douglas Gregor0b6a6242009-06-22 20:57:11 +00006391 switch (ExprEvalContext) {
6392 case Unevaluated:
6393 // We are in an expression that is not potentially evaluated; do nothing.
6394 return;
Mike Stump11289f42009-09-09 15:08:12 +00006395
Douglas Gregor0b6a6242009-06-22 20:57:11 +00006396 case PotentiallyEvaluated:
6397 // We are in a potentially-evaluated expression, so this declaration is
6398 // "used"; handle this below.
6399 break;
Mike Stump11289f42009-09-09 15:08:12 +00006400
Douglas Gregor0b6a6242009-06-22 20:57:11 +00006401 case PotentiallyPotentiallyEvaluated:
6402 // We are in an expression that may be potentially evaluated; queue this
6403 // declaration reference until we know whether the expression is
6404 // potentially evaluated.
6405 PotentiallyReferencedDeclStack.back().push_back(std::make_pair(Loc, D));
6406 return;
6407 }
Mike Stump11289f42009-09-09 15:08:12 +00006408
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006409 // Note that this declaration has been used.
Fariborz Jahanian3a363432009-06-22 17:30:33 +00006410 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Fariborz Jahanian477d2422009-06-22 23:34:40 +00006411 unsigned TypeQuals;
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00006412 if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) {
6413 if (!Constructor->isUsed())
6414 DefineImplicitDefaultConstructor(Loc, Constructor);
Mike Stump11289f42009-09-09 15:08:12 +00006415 } else if (Constructor->isImplicit() &&
Mike Stump12b8ce12009-08-04 21:02:39 +00006416 Constructor->isCopyConstructor(Context, TypeQuals)) {
Fariborz Jahanian477d2422009-06-22 23:34:40 +00006417 if (!Constructor->isUsed())
6418 DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals);
6419 }
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00006420 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
6421 if (Destructor->isImplicit() && !Destructor->isUsed())
6422 DefineImplicitDestructor(Loc, Destructor);
Mike Stump11289f42009-09-09 15:08:12 +00006423
Fariborz Jahanian41f79272009-06-25 21:45:19 +00006424 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
6425 if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
6426 MethodDecl->getOverloadedOperator() == OO_Equal) {
6427 if (!MethodDecl->isUsed())
6428 DefineImplicitOverloadedAssign(Loc, MethodDecl);
6429 }
6430 }
Fariborz Jahanian49796cc72009-06-24 22:09:44 +00006431 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Mike Stump11289f42009-09-09 15:08:12 +00006432 // Implicit instantiation of function templates and member functions of
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00006433 // class templates.
Douglas Gregorafca3b42009-10-27 20:53:28 +00006434 if (!Function->getBody() && Function->isImplicitlyInstantiable()) {
Douglas Gregor06db9f52009-10-12 20:18:28 +00006435 bool AlreadyInstantiated = false;
6436 if (FunctionTemplateSpecializationInfo *SpecInfo
6437 = Function->getTemplateSpecializationInfo()) {
6438 if (SpecInfo->getPointOfInstantiation().isInvalid())
6439 SpecInfo->setPointOfInstantiation(Loc);
Douglas Gregorafca3b42009-10-27 20:53:28 +00006440 else if (SpecInfo->getTemplateSpecializationKind()
6441 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +00006442 AlreadyInstantiated = true;
6443 } else if (MemberSpecializationInfo *MSInfo
6444 = Function->getMemberSpecializationInfo()) {
6445 if (MSInfo->getPointOfInstantiation().isInvalid())
6446 MSInfo->setPointOfInstantiation(Loc);
Douglas Gregorafca3b42009-10-27 20:53:28 +00006447 else if (MSInfo->getTemplateSpecializationKind()
6448 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +00006449 AlreadyInstantiated = true;
6450 }
6451
6452 if (!AlreadyInstantiated)
6453 PendingImplicitInstantiations.push_back(std::make_pair(Function, Loc));
6454 }
6455
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006456 // FIXME: keep track of references to static functions
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006457 Function->setUsed(true);
6458 return;
Douglas Gregor77b50e12009-06-22 23:06:13 +00006459 }
Mike Stump11289f42009-09-09 15:08:12 +00006460
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006461 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00006462 // Implicit instantiation of static data members of class templates.
Mike Stump11289f42009-09-09 15:08:12 +00006463 if (Var->isStaticDataMember() &&
Douglas Gregor06db9f52009-10-12 20:18:28 +00006464 Var->getInstantiatedFromStaticDataMember()) {
6465 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
6466 assert(MSInfo && "Missing member specialization information?");
6467 if (MSInfo->getPointOfInstantiation().isInvalid() &&
6468 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
6469 MSInfo->setPointOfInstantiation(Loc);
6470 PendingImplicitInstantiations.push_back(std::make_pair(Var, Loc));
6471 }
6472 }
Mike Stump11289f42009-09-09 15:08:12 +00006473
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006474 // FIXME: keep track of references to static data?
Douglas Gregora6ef8f02009-07-24 20:34:43 +00006475
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006476 D->setUsed(true);
Douglas Gregora6ef8f02009-07-24 20:34:43 +00006477 return;
Sam Weinigbae69142009-09-11 03:29:30 +00006478 }
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006479}
Anders Carlsson7f84ed92009-10-09 23:51:55 +00006480
6481bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
6482 CallExpr *CE, FunctionDecl *FD) {
6483 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
6484 return false;
6485
6486 PartialDiagnostic Note =
6487 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
6488 << FD->getDeclName() : PDiag();
6489 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
6490
6491 if (RequireCompleteType(Loc, ReturnType,
6492 FD ?
6493 PDiag(diag::err_call_function_incomplete_return)
6494 << CE->getSourceRange() << FD->getDeclName() :
6495 PDiag(diag::err_call_incomplete_return)
6496 << CE->getSourceRange(),
6497 std::make_pair(NoteLoc, Note)))
6498 return true;
6499
6500 return false;
6501}
6502
John McCalld5707ab2009-10-12 21:59:07 +00006503// Diagnose the common s/=/==/ typo. Note that adding parentheses
6504// will prevent this condition from triggering, which is what we want.
6505void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
6506 SourceLocation Loc;
6507
John McCall0506e4a2009-11-11 02:41:58 +00006508 unsigned diagnostic = diag::warn_condition_is_assignment;
6509
John McCalld5707ab2009-10-12 21:59:07 +00006510 if (isa<BinaryOperator>(E)) {
6511 BinaryOperator *Op = cast<BinaryOperator>(E);
6512 if (Op->getOpcode() != BinaryOperator::Assign)
6513 return;
6514
John McCallb0e419e2009-11-12 00:06:05 +00006515 // Greylist some idioms by putting them into a warning subcategory.
6516 if (ObjCMessageExpr *ME
6517 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
6518 Selector Sel = ME->getSelector();
6519
John McCallb0e419e2009-11-12 00:06:05 +00006520 // self = [<foo> init...]
6521 if (isSelfExpr(Op->getLHS())
6522 && Sel.getIdentifierInfoForSlot(0)->getName().startswith("init"))
6523 diagnostic = diag::warn_condition_is_idiomatic_assignment;
6524
6525 // <foo> = [<bar> nextObject]
6526 else if (Sel.isUnarySelector() &&
6527 Sel.getIdentifierInfoForSlot(0)->getName() == "nextObject")
6528 diagnostic = diag::warn_condition_is_idiomatic_assignment;
6529 }
John McCall0506e4a2009-11-11 02:41:58 +00006530
John McCalld5707ab2009-10-12 21:59:07 +00006531 Loc = Op->getOperatorLoc();
6532 } else if (isa<CXXOperatorCallExpr>(E)) {
6533 CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(E);
6534 if (Op->getOperator() != OO_Equal)
6535 return;
6536
6537 Loc = Op->getOperatorLoc();
6538 } else {
6539 // Not an assignment.
6540 return;
6541 }
6542
John McCalld5707ab2009-10-12 21:59:07 +00006543 SourceLocation Open = E->getSourceRange().getBegin();
John McCalle724ae92009-10-12 22:25:59 +00006544 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
John McCalld5707ab2009-10-12 21:59:07 +00006545
John McCall0506e4a2009-11-11 02:41:58 +00006546 Diag(Loc, diagnostic)
John McCalld5707ab2009-10-12 21:59:07 +00006547 << E->getSourceRange()
6548 << CodeModificationHint::CreateInsertion(Open, "(")
6549 << CodeModificationHint::CreateInsertion(Close, ")");
6550}
6551
6552bool Sema::CheckBooleanCondition(Expr *&E, SourceLocation Loc) {
6553 DiagnoseAssignmentAsCondition(E);
6554
6555 if (!E->isTypeDependent()) {
6556 DefaultFunctionArrayConversion(E);
6557
6558 QualType T = E->getType();
6559
6560 if (getLangOptions().CPlusPlus) {
6561 if (CheckCXXBooleanCondition(E)) // C++ 6.4p4
6562 return true;
6563 } else if (!T->isScalarType()) { // C99 6.8.4.1p1
6564 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
6565 << T << E->getSourceRange();
6566 return true;
6567 }
6568 }
6569
6570 return false;
6571}