blob: 66af76d7369df1966346ab37d5359fb558fb5e4e [file] [log] [blame]
Chris Lattner5b183d82006-11-10 05:03:26 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner5b183d82006-11-10 05:03:26 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
John McCall5cebab12009-11-18 07:57:50 +000015#include "Lookup.h"
Chris Lattnercb6a3822006-11-10 06:20:45 +000016#include "clang/AST/ASTContext.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000017#include "clang/AST/DeclObjC.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000018#include "clang/AST/DeclTemplate.h"
Chris Lattneraa9c7ae2008-04-08 04:40:51 +000019#include "clang/AST/ExprCXX.h"
Steve Naroff021ca182008-05-29 21:12:08 +000020#include "clang/AST/ExprObjC.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000021#include "clang/Basic/PartialDiagnostic.h"
Steve Narofff2fb89e2007-03-13 20:29:44 +000022#include "clang/Basic/SourceManager.h"
Chris Lattner5b183d82006-11-10 05:03:26 +000023#include "clang/Basic/TargetInfo.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000024#include "clang/Lex/LiteralSupport.h"
25#include "clang/Lex/Preprocessor.h"
Steve Naroffc540d662008-09-03 18:15:37 +000026#include "clang/Parse/DeclSpec.h"
Chris Lattner07d754a2008-10-26 23:43:26 +000027#include "clang/Parse/Designator.h"
Steve Naroffc540d662008-09-03 18:15:37 +000028#include "clang/Parse/Scope.h"
Douglas Gregorb53edfb2009-11-10 19:49:08 +000029#include "clang/Parse/Template.h"
Chris Lattner5b183d82006-11-10 05:03:26 +000030using namespace clang;
31
David Chisnall9f57c292009-08-17 16:35:33 +000032
Douglas Gregor171c45a2009-02-18 21:56:37 +000033/// \brief Determine whether the use of this declaration is valid, and
34/// emit any corresponding diagnostics.
35///
36/// This routine diagnoses various problems with referencing
37/// declarations that can occur when using a declaration. For example,
38/// it might warn if a deprecated or unavailable declaration is being
39/// used, or produce an error (and return true) if a C++0x deleted
40/// function is being used.
41///
Chris Lattnerb7df3c62009-10-25 22:31:57 +000042/// If IgnoreDeprecated is set to true, this should not want about deprecated
43/// decls.
44///
Douglas Gregor171c45a2009-02-18 21:56:37 +000045/// \returns true if there was an error (this declaration cannot be
46/// referenced), false otherwise.
Chris Lattnerb7df3c62009-10-25 22:31:57 +000047///
John McCall28a6aea2009-11-04 02:18:39 +000048bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc) {
Chris Lattner4bf74fd2009-02-15 22:43:40 +000049 // See if the decl is deprecated.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +000050 if (D->getAttr<DeprecatedAttr>()) {
John McCall28a6aea2009-11-04 02:18:39 +000051 EmitDeprecationWarning(D, Loc);
Chris Lattner4bf74fd2009-02-15 22:43:40 +000052 }
53
Chris Lattnera27dd592009-10-25 17:21:40 +000054 // See if the decl is unavailable
55 if (D->getAttr<UnavailableAttr>()) {
56 Diag(Loc, diag::warn_unavailable) << D->getDeclName();
57 Diag(D->getLocation(), diag::note_unavailable_here) << 0;
58 }
59
Douglas Gregor171c45a2009-02-18 21:56:37 +000060 // See if this is a deleted function.
Douglas Gregorde681d42009-02-24 04:26:15 +000061 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +000062 if (FD->isDeleted()) {
63 Diag(Loc, diag::err_deleted_function_use);
64 Diag(D->getLocation(), diag::note_unavailable_here) << true;
65 return true;
66 }
Douglas Gregorde681d42009-02-24 04:26:15 +000067 }
Douglas Gregor171c45a2009-02-18 21:56:37 +000068
Douglas Gregor171c45a2009-02-18 21:56:37 +000069 return false;
Chris Lattner4bf74fd2009-02-15 22:43:40 +000070}
71
Fariborz Jahanian027b8862009-05-13 18:09:35 +000072/// DiagnoseSentinelCalls - This routine checks on method dispatch calls
Mike Stump11289f42009-09-09 15:08:12 +000073/// (and other functions in future), which have been declared with sentinel
Fariborz Jahanian027b8862009-05-13 18:09:35 +000074/// attribute. It warns if call does not have the sentinel argument.
75///
76void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +000077 Expr **Args, unsigned NumArgs) {
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +000078 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Mike Stump11289f42009-09-09 15:08:12 +000079 if (!attr)
Fariborz Jahanian9e877212009-05-13 23:20:50 +000080 return;
Fariborz Jahanian9e877212009-05-13 23:20:50 +000081 int sentinelPos = attr->getSentinel();
82 int nullPos = attr->getNullPos();
Mike Stump11289f42009-09-09 15:08:12 +000083
Mike Stump87c57ac2009-05-16 07:39:55 +000084 // FIXME. ObjCMethodDecl and FunctionDecl need be derived from the same common
85 // base class. Then we won't be needing two versions of the same code.
Fariborz Jahanian9e877212009-05-13 23:20:50 +000086 unsigned int i = 0;
Fariborz Jahanian4a528032009-05-14 18:00:00 +000087 bool warnNotEnoughArgs = false;
88 int isMethod = 0;
89 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
90 // skip over named parameters.
91 ObjCMethodDecl::param_iterator P, E = MD->param_end();
92 for (P = MD->param_begin(); (P != E && i < NumArgs); ++P) {
93 if (nullPos)
94 --nullPos;
95 else
96 ++i;
97 }
98 warnNotEnoughArgs = (P != E || i >= NumArgs);
99 isMethod = 1;
Mike Stump12b8ce12009-08-04 21:02:39 +0000100 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000101 // skip over named parameters.
102 ObjCMethodDecl::param_iterator P, E = FD->param_end();
103 for (P = FD->param_begin(); (P != E && i < NumArgs); ++P) {
104 if (nullPos)
105 --nullPos;
106 else
107 ++i;
108 }
109 warnNotEnoughArgs = (P != E || i >= NumArgs);
Mike Stump12b8ce12009-08-04 21:02:39 +0000110 } else if (VarDecl *V = dyn_cast<VarDecl>(D)) {
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000111 // block or function pointer call.
112 QualType Ty = V->getType();
113 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +0000114 const FunctionType *FT = Ty->isFunctionPointerType()
John McCall9dd450b2009-09-21 23:43:11 +0000115 ? Ty->getAs<PointerType>()->getPointeeType()->getAs<FunctionType>()
116 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000117 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT)) {
118 unsigned NumArgsInProto = Proto->getNumArgs();
119 unsigned k;
120 for (k = 0; (k != NumArgsInProto && i < NumArgs); k++) {
121 if (nullPos)
122 --nullPos;
123 else
124 ++i;
125 }
126 warnNotEnoughArgs = (k != NumArgsInProto || i >= NumArgs);
127 }
128 if (Ty->isBlockPointerType())
129 isMethod = 2;
Mike Stump12b8ce12009-08-04 21:02:39 +0000130 } else
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000131 return;
Mike Stump12b8ce12009-08-04 21:02:39 +0000132 } else
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000133 return;
134
135 if (warnNotEnoughArgs) {
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000136 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000137 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000138 return;
139 }
140 int sentinel = i;
141 while (sentinelPos > 0 && i < NumArgs-1) {
142 --sentinelPos;
143 ++i;
144 }
145 if (sentinelPos > 0) {
146 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000147 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000148 return;
149 }
150 while (i < NumArgs-1) {
151 ++i;
152 ++sentinel;
153 }
154 Expr *sentinelExpr = Args[sentinel];
Anders Carlsson0b11a3e2009-11-24 17:24:21 +0000155 if (sentinelExpr && (!isa<GNUNullExpr>(sentinelExpr) &&
156 (!sentinelExpr->getType()->isPointerType() ||
157 !sentinelExpr->isNullPointerConstant(Context,
158 Expr::NPC_ValueDependentIsNull)))) {
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000159 Diag(Loc, diag::warn_missing_sentinel) << isMethod;
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000160 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000161 }
162 return;
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000163}
164
Douglas Gregor87f95b02009-02-26 21:00:50 +0000165SourceRange Sema::getExprRange(ExprTy *E) const {
166 Expr *Ex = (Expr *)E;
167 return Ex? Ex->getSourceRange() : SourceRange();
168}
169
Chris Lattner513165e2008-07-25 21:10:04 +0000170//===----------------------------------------------------------------------===//
171// Standard Promotions and Conversions
172//===----------------------------------------------------------------------===//
173
Chris Lattner513165e2008-07-25 21:10:04 +0000174/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
175void Sema::DefaultFunctionArrayConversion(Expr *&E) {
176 QualType Ty = E->getType();
177 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
178
Chris Lattner513165e2008-07-25 21:10:04 +0000179 if (Ty->isFunctionType())
Mike Stump11289f42009-09-09 15:08:12 +0000180 ImpCastExprToType(E, Context.getPointerType(Ty),
Anders Carlsson6904f642009-09-01 20:37:18 +0000181 CastExpr::CK_FunctionToPointerDecay);
Chris Lattner61f60a02008-07-25 21:33:13 +0000182 else if (Ty->isArrayType()) {
183 // In C90 mode, arrays only promote to pointers if the array expression is
184 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
185 // type 'array of type' is converted to an expression that has type 'pointer
186 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
187 // that has type 'array of type' ...". The relevant change is "an lvalue"
188 // (C90) to "an expression" (C99).
Argyrios Kyrtzidis9321c742008-09-11 04:25:59 +0000189 //
190 // C++ 4.2p1:
191 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
192 // T" can be converted to an rvalue of type "pointer to T".
193 //
194 if (getLangOptions().C99 || getLangOptions().CPlusPlus ||
195 E->isLvalue(Context) == Expr::LV_Valid)
Anders Carlsson8fc489d2009-08-07 23:48:20 +0000196 ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
197 CastExpr::CK_ArrayToPointerDecay);
Chris Lattner61f60a02008-07-25 21:33:13 +0000198 }
Chris Lattner513165e2008-07-25 21:10:04 +0000199}
200
201/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump11289f42009-09-09 15:08:12 +0000202/// operators (C99 6.3). The conversions of array and function types are
Chris Lattner513165e2008-07-25 21:10:04 +0000203/// sometimes surpressed. For example, the array->pointer conversion doesn't
204/// apply if the array is an argument to the sizeof or address (&) operators.
205/// In these instances, this routine should *not* be called.
206Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
207 QualType Ty = Expr->getType();
208 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
Mike Stump11289f42009-09-09 15:08:12 +0000209
Douglas Gregor8d9c5092009-05-01 20:41:21 +0000210 // C99 6.3.1.1p2:
211 //
212 // The following may be used in an expression wherever an int or
213 // unsigned int may be used:
214 // - an object or expression with an integer type whose integer
215 // conversion rank is less than or equal to the rank of int
216 // and unsigned int.
217 // - A bit-field of type _Bool, int, signed int, or unsigned int.
218 //
219 // If an int can represent all values of the original type, the
220 // value is converted to an int; otherwise, it is converted to an
221 // unsigned int. These are called the integer promotions. All
222 // other types are unchanged by the integer promotions.
Eli Friedman629ffb92009-08-20 04:21:42 +0000223 QualType PTy = Context.isPromotableBitField(Expr);
224 if (!PTy.isNull()) {
Eli Friedman06ed2a52009-10-20 08:27:19 +0000225 ImpCastExprToType(Expr, PTy, CastExpr::CK_IntegralCast);
Eli Friedman629ffb92009-08-20 04:21:42 +0000226 return Expr;
227 }
Douglas Gregor8d9c5092009-05-01 20:41:21 +0000228 if (Ty->isPromotableIntegerType()) {
Eli Friedman5ae98ee2009-08-19 07:44:53 +0000229 QualType PT = Context.getPromotedIntegerType(Ty);
Eli Friedman06ed2a52009-10-20 08:27:19 +0000230 ImpCastExprToType(Expr, PT, CastExpr::CK_IntegralCast);
Douglas Gregor8d9c5092009-05-01 20:41:21 +0000231 return Expr;
Eli Friedman629ffb92009-08-20 04:21:42 +0000232 }
233
Douglas Gregor8d9c5092009-05-01 20:41:21 +0000234 DefaultFunctionArrayConversion(Expr);
Chris Lattner513165e2008-07-25 21:10:04 +0000235 return Expr;
236}
237
Chris Lattner2ce500f2008-07-25 22:25:12 +0000238/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Mike Stump11289f42009-09-09 15:08:12 +0000239/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner2ce500f2008-07-25 22:25:12 +0000240/// double. All other argument types are converted by UsualUnaryConversions().
241void Sema::DefaultArgumentPromotion(Expr *&Expr) {
242 QualType Ty = Expr->getType();
243 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump11289f42009-09-09 15:08:12 +0000244
Chris Lattner2ce500f2008-07-25 22:25:12 +0000245 // If this is a 'float' (CVR qualified or typedef) promote to double.
John McCall9dd450b2009-09-21 23:43:11 +0000246 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
Chris Lattner2ce500f2008-07-25 22:25:12 +0000247 if (BT->getKind() == BuiltinType::Float)
Eli Friedman06ed2a52009-10-20 08:27:19 +0000248 return ImpCastExprToType(Expr, Context.DoubleTy,
249 CastExpr::CK_FloatingCast);
Mike Stump11289f42009-09-09 15:08:12 +0000250
Chris Lattner2ce500f2008-07-25 22:25:12 +0000251 UsualUnaryConversions(Expr);
252}
253
Chris Lattnera8a7d0f2009-04-12 08:11:20 +0000254/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
255/// will warn if the resulting type is not a POD type, and rejects ObjC
256/// interfaces passed by value. This returns true if the argument type is
257/// completely illegal.
258bool Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT) {
Anders Carlssona7d069d2009-01-16 16:48:51 +0000259 DefaultArgumentPromotion(Expr);
Mike Stump11289f42009-09-09 15:08:12 +0000260
Chris Lattnera8a7d0f2009-04-12 08:11:20 +0000261 if (Expr->getType()->isObjCInterfaceType()) {
Douglas Gregor7ca84af2009-12-12 07:25:49 +0000262 switch (ExprEvalContexts.back().Context ) {
263 case Unevaluated:
264 // The argument will never be evaluated, so don't complain.
265 break;
266
267 case PotentiallyEvaluated:
268 Diag(Expr->getLocStart(),
269 diag::err_cannot_pass_objc_interface_to_vararg)
270 << Expr->getType() << CT;
271 return true;
272
273 case PotentiallyPotentiallyEvaluated:
Douglas Gregorfab31f42009-12-12 07:57:52 +0000274 ExprEvalContexts.back().addDiagnostic(Expr->getLocStart(),
275 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
276 << Expr->getType() << CT);
Douglas Gregor7ca84af2009-12-12 07:25:49 +0000277 break;
278 }
Anders Carlssona7d069d2009-01-16 16:48:51 +0000279 }
Mike Stump11289f42009-09-09 15:08:12 +0000280
Douglas Gregor7ca84af2009-12-12 07:25:49 +0000281 if (!Expr->getType()->isPODType()) {
282 switch (ExprEvalContexts.back().Context ) {
283 case Unevaluated:
284 // The argument will never be evaluated, so don't complain.
285 break;
286
287 case PotentiallyEvaluated:
288 Diag(Expr->getLocStart(), diag::warn_cannot_pass_non_pod_arg_to_vararg)
289 << Expr->getType() << CT;
290 break;
291
292 case PotentiallyPotentiallyEvaluated:
Douglas Gregorfab31f42009-12-12 07:57:52 +0000293 ExprEvalContexts.back().addDiagnostic(Expr->getLocStart(),
294 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
295 << Expr->getType() << CT);
Douglas Gregor7ca84af2009-12-12 07:25:49 +0000296 break;
297 }
298 }
Chris Lattnera8a7d0f2009-04-12 08:11:20 +0000299
300 return false;
Anders Carlssona7d069d2009-01-16 16:48:51 +0000301}
302
303
Chris Lattner513165e2008-07-25 21:10:04 +0000304/// UsualArithmeticConversions - Performs various conversions that are common to
305/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump11289f42009-09-09 15:08:12 +0000306/// routine returns the first non-arithmetic type found. The client is
Chris Lattner513165e2008-07-25 21:10:04 +0000307/// responsible for emitting appropriate error diagnostics.
308/// FIXME: verify the conversion rules for "complex int" are consistent with
309/// GCC.
310QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
311 bool isCompAssign) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +0000312 if (!isCompAssign)
Chris Lattner513165e2008-07-25 21:10:04 +0000313 UsualUnaryConversions(lhsExpr);
Eli Friedman8b7b1b12009-03-28 01:22:36 +0000314
315 UsualUnaryConversions(rhsExpr);
Douglas Gregora11693b2008-11-12 17:17:38 +0000316
Mike Stump11289f42009-09-09 15:08:12 +0000317 // For conversion purposes, we ignore any qualifiers.
Chris Lattner513165e2008-07-25 21:10:04 +0000318 // For example, "const float" and "float" are equivalent.
Chris Lattner574dee62008-07-26 22:17:49 +0000319 QualType lhs =
320 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +0000321 QualType rhs =
Chris Lattner574dee62008-07-26 22:17:49 +0000322 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +0000323
324 // If both types are identical, no conversion is needed.
325 if (lhs == rhs)
326 return lhs;
327
328 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
329 // The caller can deal with this (e.g. pointer + int).
330 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
331 return lhs;
332
Douglas Gregord2c2d172009-05-02 00:36:19 +0000333 // Perform bitfield promotions.
Eli Friedman629ffb92009-08-20 04:21:42 +0000334 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr);
Douglas Gregord2c2d172009-05-02 00:36:19 +0000335 if (!LHSBitfieldPromoteTy.isNull())
336 lhs = LHSBitfieldPromoteTy;
Eli Friedman629ffb92009-08-20 04:21:42 +0000337 QualType RHSBitfieldPromoteTy = Context.isPromotableBitField(rhsExpr);
Douglas Gregord2c2d172009-05-02 00:36:19 +0000338 if (!RHSBitfieldPromoteTy.isNull())
339 rhs = RHSBitfieldPromoteTy;
340
Eli Friedman5ae98ee2009-08-19 07:44:53 +0000341 QualType destType = Context.UsualArithmeticConversionsType(lhs, rhs);
Eli Friedman8b7b1b12009-03-28 01:22:36 +0000342 if (!isCompAssign)
Eli Friedman06ed2a52009-10-20 08:27:19 +0000343 ImpCastExprToType(lhsExpr, destType, CastExpr::CK_Unknown);
344 ImpCastExprToType(rhsExpr, destType, CastExpr::CK_Unknown);
Douglas Gregora11693b2008-11-12 17:17:38 +0000345 return destType;
346}
347
Chris Lattner513165e2008-07-25 21:10:04 +0000348//===----------------------------------------------------------------------===//
349// Semantic Analysis for various Expression Types
350//===----------------------------------------------------------------------===//
351
352
Steve Naroff83895f72007-09-16 03:34:24 +0000353/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner5b183d82006-11-10 05:03:26 +0000354/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
355/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
356/// multiple tokens. However, the common case is that StringToks points to one
357/// string.
Sebastian Redlffbcf962009-01-18 18:53:16 +0000358///
359Action::OwningExprResult
Steve Naroff83895f72007-09-16 03:34:24 +0000360Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner5b183d82006-11-10 05:03:26 +0000361 assert(NumStringToks && "Must have at least one string!");
362
Chris Lattner8a24e582009-01-16 18:51:42 +0000363 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Steve Naroff4f88b312007-03-13 22:37:02 +0000364 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +0000365 return ExprError();
Chris Lattner5b183d82006-11-10 05:03:26 +0000366
Chris Lattner23b7eb62007-06-15 23:05:46 +0000367 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
Chris Lattner5b183d82006-11-10 05:03:26 +0000368 for (unsigned i = 0; i != NumStringToks; ++i)
369 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattner36fc8792008-02-11 00:02:17 +0000370
Chris Lattner36fc8792008-02-11 00:02:17 +0000371 QualType StrTy = Context.CharTy;
Argyrios Kyrtzidiscbad7252008-08-09 17:20:01 +0000372 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattner36fc8792008-02-11 00:02:17 +0000373 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregoraa1e21d2008-09-12 00:47:35 +0000374
375 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
376 if (getLangOptions().CPlusPlus)
377 StrTy.addConst();
Sebastian Redlffbcf962009-01-18 18:53:16 +0000378
Chris Lattner36fc8792008-02-11 00:02:17 +0000379 // Get an array type for the string, according to C99 6.4.5. This includes
380 // the nul terminator character as well as the string length for pascal
381 // strings.
382 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerd42c29f2009-02-26 23:01:51 +0000383 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattner36fc8792008-02-11 00:02:17 +0000384 ArrayType::Normal, 0);
Mike Stump11289f42009-09-09 15:08:12 +0000385
Chris Lattner5b183d82006-11-10 05:03:26 +0000386 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Mike Stump11289f42009-09-09 15:08:12 +0000387 return Owned(StringLiteral::Create(Context, Literal.GetString(),
Chris Lattnerf83b5af2009-02-18 06:40:38 +0000388 Literal.GetStringLength(),
389 Literal.AnyWide, StrTy,
390 &StringTokLocs[0],
391 StringTokLocs.size()));
Chris Lattner5b183d82006-11-10 05:03:26 +0000392}
393
Chris Lattner2a9d9892008-10-20 05:16:36 +0000394/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
395/// CurBlock to VD should cause it to be snapshotted (as we do for auto
396/// variables defined outside the block) or false if this is not needed (e.g.
397/// for values inside the block or for globals).
398///
Chris Lattner497d7b02009-04-21 22:26:47 +0000399/// This also keeps the 'hasBlockDeclRefExprs' in the BlockSemaInfo records
400/// up-to-date.
401///
Chris Lattner2a9d9892008-10-20 05:16:36 +0000402static bool ShouldSnapshotBlockValueReference(BlockSemaInfo *CurBlock,
403 ValueDecl *VD) {
404 // If the value is defined inside the block, we couldn't snapshot it even if
405 // we wanted to.
406 if (CurBlock->TheDecl == VD->getDeclContext())
407 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000408
Chris Lattner2a9d9892008-10-20 05:16:36 +0000409 // If this is an enum constant or function, it is constant, don't snapshot.
410 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
411 return false;
412
413 // If this is a reference to an extern, static, or global variable, no need to
414 // snapshot it.
415 // FIXME: What about 'const' variables in C++?
416 if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
Chris Lattner497d7b02009-04-21 22:26:47 +0000417 if (!Var->hasLocalStorage())
418 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000419
Chris Lattner497d7b02009-04-21 22:26:47 +0000420 // Blocks that have these can't be constant.
421 CurBlock->hasBlockDeclRefExprs = true;
422
423 // If we have nested blocks, the decl may be declared in an outer block (in
424 // which case that outer block doesn't get "hasBlockDeclRefExprs") or it may
425 // be defined outside all of the current blocks (in which case the blocks do
426 // all get the bit). Walk the nesting chain.
427 for (BlockSemaInfo *NextBlock = CurBlock->PrevBlockInfo; NextBlock;
428 NextBlock = NextBlock->PrevBlockInfo) {
429 // If we found the defining block for the variable, don't mark the block as
430 // having a reference outside it.
431 if (NextBlock->TheDecl == VD->getDeclContext())
432 break;
Mike Stump11289f42009-09-09 15:08:12 +0000433
Chris Lattner497d7b02009-04-21 22:26:47 +0000434 // Otherwise, the DeclRef from the inner block causes the outer one to need
435 // a snapshot as well.
436 NextBlock->hasBlockDeclRefExprs = true;
437 }
Mike Stump11289f42009-09-09 15:08:12 +0000438
Chris Lattner2a9d9892008-10-20 05:16:36 +0000439 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000440}
441
Chris Lattner2a9d9892008-10-20 05:16:36 +0000442
443
Douglas Gregor4bd90e52009-10-23 18:54:35 +0000444/// BuildDeclRefExpr - Build a DeclRefExpr.
Anders Carlsson946b86d2009-06-24 00:10:43 +0000445Sema::OwningExprResult
John McCallce546572009-12-08 09:08:17 +0000446Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, SourceLocation Loc,
Sebastian Redl3d3f75a2009-02-03 20:19:35 +0000447 const CXXScopeSpec *SS) {
Anders Carlsson364035d12009-06-26 19:16:07 +0000448 if (Context.getCanonicalType(Ty) == Context.UndeducedAutoTy) {
449 Diag(Loc,
Mike Stump11289f42009-09-09 15:08:12 +0000450 diag::err_auto_variable_cannot_appear_in_own_initializer)
Anders Carlsson364035d12009-06-26 19:16:07 +0000451 << D->getDeclName();
452 return ExprError();
453 }
Mike Stump11289f42009-09-09 15:08:12 +0000454
Anders Carlsson946b86d2009-06-24 00:10:43 +0000455 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
456 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
457 if (const FunctionDecl *FD = MD->getParent()->isLocalClass()) {
458 if (VD->hasLocalStorage() && VD->getDeclContext() != CurContext) {
Mike Stump11289f42009-09-09 15:08:12 +0000459 Diag(Loc, diag::err_reference_to_local_var_in_enclosing_function)
Anders Carlsson946b86d2009-06-24 00:10:43 +0000460 << D->getIdentifier() << FD->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +0000461 Diag(D->getLocation(), diag::note_local_variable_declared_here)
Anders Carlsson946b86d2009-06-24 00:10:43 +0000462 << D->getIdentifier();
463 return ExprError();
464 }
465 }
466 }
467 }
Mike Stump11289f42009-09-09 15:08:12 +0000468
Douglas Gregorc9c02ed2009-06-19 23:52:42 +0000469 MarkDeclarationReferenced(Loc, D);
Mike Stump11289f42009-09-09 15:08:12 +0000470
Douglas Gregor4bd90e52009-10-23 18:54:35 +0000471 return Owned(DeclRefExpr::Create(Context,
472 SS? (NestedNameSpecifier *)SS->getScopeRep() : 0,
473 SS? SS->getRange() : SourceRange(),
Douglas Gregored6c7442009-11-23 11:41:28 +0000474 D, Loc, Ty));
Douglas Gregorc7acfdf2009-01-06 05:10:23 +0000475}
476
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000477/// getObjectForAnonymousRecordDecl - Retrieve the (unnamed) field or
478/// variable corresponding to the anonymous union or struct whose type
479/// is Record.
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000480static Decl *getObjectForAnonymousRecordDecl(ASTContext &Context,
481 RecordDecl *Record) {
Mike Stump11289f42009-09-09 15:08:12 +0000482 assert(Record->isAnonymousStructOrUnion() &&
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000483 "Record must be an anonymous struct or union!");
Mike Stump11289f42009-09-09 15:08:12 +0000484
Mike Stump87c57ac2009-05-16 07:39:55 +0000485 // FIXME: Once Decls are directly linked together, this will be an O(1)
486 // operation rather than a slow walk through DeclContext's vector (which
487 // itself will be eliminated). DeclGroups might make this even better.
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000488 DeclContext *Ctx = Record->getDeclContext();
Mike Stump11289f42009-09-09 15:08:12 +0000489 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000490 DEnd = Ctx->decls_end();
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000491 D != DEnd; ++D) {
492 if (*D == Record) {
493 // The object for the anonymous struct/union directly
494 // follows its type in the list of declarations.
495 ++D;
496 assert(D != DEnd && "Missing object for anonymous record");
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000497 assert(!cast<NamedDecl>(*D)->getDeclName() && "Decl should be unnamed");
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000498 return *D;
499 }
500 }
501
502 assert(false && "Missing object for anonymous record");
503 return 0;
504}
505
Douglas Gregord5846a12009-04-15 06:41:24 +0000506/// \brief Given a field that represents a member of an anonymous
507/// struct/union, build the path from that field's context to the
508/// actual member.
509///
510/// Construct the sequence of field member references we'll have to
511/// perform to get to the field in the anonymous union/struct. The
512/// list of members is built from the field outward, so traverse it
513/// backwards to go from an object in the current context to the field
514/// we found.
515///
516/// \returns The variable from which the field access should begin,
517/// for an anonymous struct/union that is not a member of another
518/// class. Otherwise, returns NULL.
519VarDecl *Sema::BuildAnonymousStructUnionMemberPath(FieldDecl *Field,
520 llvm::SmallVectorImpl<FieldDecl *> &Path) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000521 assert(Field->getDeclContext()->isRecord() &&
522 cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion()
523 && "Field must be stored inside an anonymous struct or union");
524
Douglas Gregord5846a12009-04-15 06:41:24 +0000525 Path.push_back(Field);
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000526 VarDecl *BaseObject = 0;
527 DeclContext *Ctx = Field->getDeclContext();
528 do {
529 RecordDecl *Record = cast<RecordDecl>(Ctx);
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000530 Decl *AnonObject = getObjectForAnonymousRecordDecl(Context, Record);
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000531 if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject))
Douglas Gregord5846a12009-04-15 06:41:24 +0000532 Path.push_back(AnonField);
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000533 else {
534 BaseObject = cast<VarDecl>(AnonObject);
535 break;
536 }
537 Ctx = Ctx->getParent();
Mike Stump11289f42009-09-09 15:08:12 +0000538 } while (Ctx->isRecord() &&
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000539 cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion());
Douglas Gregord5846a12009-04-15 06:41:24 +0000540
541 return BaseObject;
542}
543
544Sema::OwningExprResult
545Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
546 FieldDecl *Field,
547 Expr *BaseObjectExpr,
548 SourceLocation OpLoc) {
549 llvm::SmallVector<FieldDecl *, 4> AnonFields;
Mike Stump11289f42009-09-09 15:08:12 +0000550 VarDecl *BaseObject = BuildAnonymousStructUnionMemberPath(Field,
Douglas Gregord5846a12009-04-15 06:41:24 +0000551 AnonFields);
552
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000553 // Build the expression that refers to the base object, from
554 // which we will build a sequence of member references to each
555 // of the anonymous union objects and, eventually, the field we
556 // found via name lookup.
557 bool BaseObjectIsPointer = false;
John McCall8ccfcb52009-09-24 19:53:00 +0000558 Qualifiers BaseQuals;
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000559 if (BaseObject) {
560 // BaseObject is an anonymous struct/union variable (and is,
561 // therefore, not part of another non-anonymous record).
Ted Kremenek5a201952009-02-07 01:47:29 +0000562 if (BaseObjectExpr) BaseObjectExpr->Destroy(Context);
Douglas Gregorc9c02ed2009-06-19 23:52:42 +0000563 MarkDeclarationReferenced(Loc, BaseObject);
Steve Narofff6009ed2009-01-21 00:14:39 +0000564 BaseObjectExpr = new (Context) DeclRefExpr(BaseObject,BaseObject->getType(),
Mike Stump4e1f26a2009-02-19 03:04:26 +0000565 SourceLocation());
John McCall8ccfcb52009-09-24 19:53:00 +0000566 BaseQuals
567 = Context.getCanonicalType(BaseObject->getType()).getQualifiers();
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000568 } else if (BaseObjectExpr) {
569 // The caller provided the base object expression. Determine
570 // whether its a pointer and whether it adds any qualifiers to the
571 // anonymous struct/union fields we're looking into.
572 QualType ObjectType = BaseObjectExpr->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000573 if (const PointerType *ObjectPtr = ObjectType->getAs<PointerType>()) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000574 BaseObjectIsPointer = true;
575 ObjectType = ObjectPtr->getPointeeType();
576 }
John McCall8ccfcb52009-09-24 19:53:00 +0000577 BaseQuals
578 = Context.getCanonicalType(ObjectType).getQualifiers();
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000579 } else {
580 // We've found a member of an anonymous struct/union that is
581 // inside a non-anonymous struct/union, so in a well-formed
582 // program our base object expression is "this".
583 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
584 if (!MD->isStatic()) {
Mike Stump11289f42009-09-09 15:08:12 +0000585 QualType AnonFieldType
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000586 = Context.getTagDeclType(
587 cast<RecordDecl>(AnonFields.back()->getDeclContext()));
588 QualType ThisType = Context.getTagDeclType(MD->getParent());
Mike Stump11289f42009-09-09 15:08:12 +0000589 if ((Context.getCanonicalType(AnonFieldType)
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000590 == Context.getCanonicalType(ThisType)) ||
591 IsDerivedFrom(ThisType, AnonFieldType)) {
592 // Our base object expression is "this".
Steve Narofff6009ed2009-01-21 00:14:39 +0000593 BaseObjectExpr = new (Context) CXXThisExpr(SourceLocation(),
Mike Stump4e1f26a2009-02-19 03:04:26 +0000594 MD->getThisType(Context));
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000595 BaseObjectIsPointer = true;
596 }
597 } else {
Sebastian Redlffbcf962009-01-18 18:53:16 +0000598 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
599 << Field->getDeclName());
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000600 }
John McCall8ccfcb52009-09-24 19:53:00 +0000601 BaseQuals = Qualifiers::fromCVRMask(MD->getTypeQualifiers());
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000602 }
603
Mike Stump11289f42009-09-09 15:08:12 +0000604 if (!BaseObjectExpr)
Sebastian Redlffbcf962009-01-18 18:53:16 +0000605 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
606 << Field->getDeclName());
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000607 }
608
609 // Build the implicit member references to the field of the
610 // anonymous struct/union.
611 Expr *Result = BaseObjectExpr;
John McCall8ccfcb52009-09-24 19:53:00 +0000612 Qualifiers ResultQuals = BaseQuals;
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000613 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
614 FI = AnonFields.rbegin(), FIEnd = AnonFields.rend();
615 FI != FIEnd; ++FI) {
616 QualType MemberType = (*FI)->getType();
John McCall8ccfcb52009-09-24 19:53:00 +0000617 Qualifiers MemberTypeQuals =
618 Context.getCanonicalType(MemberType).getQualifiers();
619
620 // CVR attributes from the base are picked up by members,
621 // except that 'mutable' members don't pick up 'const'.
622 if ((*FI)->isMutable())
623 ResultQuals.removeConst();
624
625 // GC attributes are never picked up by members.
626 ResultQuals.removeObjCGCAttr();
627
628 // TR 18037 does not allow fields to be declared with address spaces.
629 assert(!MemberTypeQuals.hasAddressSpace());
630
631 Qualifiers NewQuals = ResultQuals + MemberTypeQuals;
632 if (NewQuals != MemberTypeQuals)
633 MemberType = Context.getQualifiedType(MemberType, NewQuals);
634
Douglas Gregorc9c02ed2009-06-19 23:52:42 +0000635 MarkDeclarationReferenced(Loc, *FI);
Eli Friedman78cde142009-12-04 07:18:51 +0000636 PerformObjectMemberConversion(Result, *FI);
Douglas Gregorc1905232009-08-26 22:36:53 +0000637 // FIXME: Might this end up being a qualified name?
Steve Narofff6009ed2009-01-21 00:14:39 +0000638 Result = new (Context) MemberExpr(Result, BaseObjectIsPointer, *FI,
639 OpLoc, MemberType);
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000640 BaseObjectIsPointer = false;
John McCall8ccfcb52009-09-24 19:53:00 +0000641 ResultQuals = NewQuals;
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000642 }
643
Sebastian Redlffbcf962009-01-18 18:53:16 +0000644 return Owned(Result);
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000645}
646
John McCall10eae182009-11-30 22:42:35 +0000647/// Decomposes the given name into a DeclarationName, its location, and
648/// possibly a list of template arguments.
649///
650/// If this produces template arguments, it is permitted to call
651/// DecomposeTemplateName.
652///
653/// This actually loses a lot of source location information for
654/// non-standard name kinds; we should consider preserving that in
655/// some way.
656static void DecomposeUnqualifiedId(Sema &SemaRef,
657 const UnqualifiedId &Id,
658 TemplateArgumentListInfo &Buffer,
659 DeclarationName &Name,
660 SourceLocation &NameLoc,
661 const TemplateArgumentListInfo *&TemplateArgs) {
662 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
663 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
664 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
665
666 ASTTemplateArgsPtr TemplateArgsPtr(SemaRef,
667 Id.TemplateId->getTemplateArgs(),
668 Id.TemplateId->NumArgs);
669 SemaRef.translateTemplateArguments(TemplateArgsPtr, Buffer);
670 TemplateArgsPtr.release();
671
672 TemplateName TName =
673 Sema::TemplateTy::make(Id.TemplateId->Template).getAsVal<TemplateName>();
674
675 Name = SemaRef.Context.getNameForTemplate(TName);
676 NameLoc = Id.TemplateId->TemplateNameLoc;
677 TemplateArgs = &Buffer;
678 } else {
679 Name = SemaRef.GetNameFromUnqualifiedId(Id);
680 NameLoc = Id.StartLocation;
681 TemplateArgs = 0;
682 }
683}
684
685/// Decompose the given template name into a list of lookup results.
686///
687/// The unqualified ID must name a non-dependent template, which can
688/// be more easily tested by checking whether DecomposeUnqualifiedId
689/// found template arguments.
690static void DecomposeTemplateName(LookupResult &R, const UnqualifiedId &Id) {
691 assert(Id.getKind() == UnqualifiedId::IK_TemplateId);
692 TemplateName TName =
693 Sema::TemplateTy::make(Id.TemplateId->Template).getAsVal<TemplateName>();
694
John McCalle66edc12009-11-24 19:00:30 +0000695 if (TemplateDecl *TD = TName.getAsTemplateDecl())
696 R.addDecl(TD);
John McCalld28ae272009-12-02 08:04:21 +0000697 else if (OverloadedTemplateStorage *OT = TName.getAsOverloadedTemplate())
698 for (OverloadedTemplateStorage::iterator I = OT->begin(), E = OT->end();
699 I != E; ++I)
John McCalle66edc12009-11-24 19:00:30 +0000700 R.addDecl(*I);
John McCalla9ee3252009-11-22 02:49:43 +0000701
John McCalle66edc12009-11-24 19:00:30 +0000702 R.resolveKind();
Douglas Gregora121b752009-11-03 16:56:39 +0000703}
704
John McCall10eae182009-11-30 22:42:35 +0000705static bool IsFullyFormedScope(Sema &SemaRef, CXXRecordDecl *Record) {
706 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
707 E = Record->bases_end(); I != E; ++I) {
708 CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
709 CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
710 if (!BaseRT) return false;
711
712 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
713 if (!BaseRecord->isDefinition() ||
714 !IsFullyFormedScope(SemaRef, BaseRecord))
715 return false;
716 }
717
718 return true;
719}
720
John McCallf786fb12009-11-30 23:50:49 +0000721/// Determines whether we can lookup this id-expression now or whether
722/// we have to wait until template instantiation is complete.
723static bool IsDependentIdExpression(Sema &SemaRef, const CXXScopeSpec &SS) {
John McCall10eae182009-11-30 22:42:35 +0000724 DeclContext *DC = SemaRef.computeDeclContext(SS, false);
John McCall10eae182009-11-30 22:42:35 +0000725
John McCallf786fb12009-11-30 23:50:49 +0000726 // If the qualifier scope isn't computable, it's definitely dependent.
727 if (!DC) return true;
728
729 // If the qualifier scope doesn't name a record, we can always look into it.
730 if (!isa<CXXRecordDecl>(DC)) return false;
731
732 // We can't look into record types unless they're fully-formed.
733 if (!IsFullyFormedScope(SemaRef, cast<CXXRecordDecl>(DC))) return true;
734
John McCall2d74de92009-12-01 22:10:20 +0000735 return false;
736}
John McCallf786fb12009-11-30 23:50:49 +0000737
John McCall2d74de92009-12-01 22:10:20 +0000738/// Determines if the given class is provably not derived from all of
739/// the prospective base classes.
740static bool IsProvablyNotDerivedFrom(Sema &SemaRef,
741 CXXRecordDecl *Record,
742 const llvm::SmallPtrSet<CXXRecordDecl*, 4> &Bases) {
John McCalla6d407c2009-12-01 22:28:41 +0000743 if (Bases.count(Record->getCanonicalDecl()))
John McCall2d74de92009-12-01 22:10:20 +0000744 return false;
745
John McCalla6d407c2009-12-01 22:28:41 +0000746 RecordDecl *RD = Record->getDefinition(SemaRef.Context);
747 if (!RD) return false;
748 Record = cast<CXXRecordDecl>(RD);
749
John McCall2d74de92009-12-01 22:10:20 +0000750 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
751 E = Record->bases_end(); I != E; ++I) {
752 CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
753 CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
754 if (!BaseRT) return false;
755
756 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall2d74de92009-12-01 22:10:20 +0000757 if (!IsProvablyNotDerivedFrom(SemaRef, BaseRecord, Bases))
758 return false;
759 }
760
761 return true;
762}
763
John McCall5af04502009-12-02 20:26:00 +0000764/// Determines if this a C++ class member.
765static bool IsClassMember(NamedDecl *D) {
766 DeclContext *DC = D->getDeclContext();
John McCall1a49e9d2009-12-02 19:59:55 +0000767
John McCall5af04502009-12-02 20:26:00 +0000768 // C++0x [class.mem]p1:
769 // The enumerators of an unscoped enumeration defined in
770 // the class are members of the class.
771 // FIXME: support C++0x scoped enumerations.
772 if (isa<EnumDecl>(DC))
773 DC = DC->getParent();
774
775 return DC->isRecord();
776}
777
778/// Determines if this is an instance member of a class.
779static bool IsInstanceMember(NamedDecl *D) {
780 assert(IsClassMember(D) &&
John McCall2d74de92009-12-01 22:10:20 +0000781 "checking whether non-member is instance member");
782
783 if (isa<FieldDecl>(D)) return true;
784
785 if (isa<CXXMethodDecl>(D))
786 return !cast<CXXMethodDecl>(D)->isStatic();
787
788 if (isa<FunctionTemplateDecl>(D)) {
789 D = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
790 return !cast<CXXMethodDecl>(D)->isStatic();
791 }
792
793 return false;
794}
795
796enum IMAKind {
797 /// The reference is definitely not an instance member access.
798 IMA_Static,
799
800 /// The reference may be an implicit instance member access.
801 IMA_Mixed,
802
803 /// The reference may be to an instance member, but it is invalid if
804 /// so, because the context is not an instance method.
805 IMA_Mixed_StaticContext,
806
807 /// The reference may be to an instance member, but it is invalid if
808 /// so, because the context is from an unrelated class.
809 IMA_Mixed_Unrelated,
810
811 /// The reference is definitely an implicit instance member access.
812 IMA_Instance,
813
814 /// The reference may be to an unresolved using declaration.
815 IMA_Unresolved,
816
817 /// The reference may be to an unresolved using declaration and the
818 /// context is not an instance method.
819 IMA_Unresolved_StaticContext,
820
821 /// The reference is to a member of an anonymous structure in a
822 /// non-class context.
823 IMA_AnonymousMember,
824
825 /// All possible referrents are instance members and the current
826 /// context is not an instance method.
827 IMA_Error_StaticContext,
828
829 /// All possible referrents are instance members of an unrelated
830 /// class.
831 IMA_Error_Unrelated
832};
833
834/// The given lookup names class member(s) and is not being used for
835/// an address-of-member expression. Classify the type of access
836/// according to whether it's possible that this reference names an
837/// instance member. This is best-effort; it is okay to
838/// conservatively answer "yes", in which case some errors will simply
839/// not be caught until template-instantiation.
840static IMAKind ClassifyImplicitMemberAccess(Sema &SemaRef,
841 const LookupResult &R) {
John McCall5af04502009-12-02 20:26:00 +0000842 assert(!R.empty() && IsClassMember(*R.begin()));
John McCall2d74de92009-12-01 22:10:20 +0000843
844 bool isStaticContext =
845 (!isa<CXXMethodDecl>(SemaRef.CurContext) ||
846 cast<CXXMethodDecl>(SemaRef.CurContext)->isStatic());
847
848 if (R.isUnresolvableResult())
849 return isStaticContext ? IMA_Unresolved_StaticContext : IMA_Unresolved;
850
851 // Collect all the declaring classes of instance members we find.
852 bool hasNonInstance = false;
853 llvm::SmallPtrSet<CXXRecordDecl*, 4> Classes;
854 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
855 NamedDecl *D = (*I)->getUnderlyingDecl();
856 if (IsInstanceMember(D)) {
857 CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext());
858
859 // If this is a member of an anonymous record, move out to the
860 // innermost non-anonymous struct or union. If there isn't one,
861 // that's a special case.
862 while (R->isAnonymousStructOrUnion()) {
863 R = dyn_cast<CXXRecordDecl>(R->getParent());
864 if (!R) return IMA_AnonymousMember;
865 }
866 Classes.insert(R->getCanonicalDecl());
867 }
868 else
869 hasNonInstance = true;
870 }
871
872 // If we didn't find any instance members, it can't be an implicit
873 // member reference.
874 if (Classes.empty())
875 return IMA_Static;
876
877 // If the current context is not an instance method, it can't be
878 // an implicit member reference.
879 if (isStaticContext)
880 return (hasNonInstance ? IMA_Mixed_StaticContext : IMA_Error_StaticContext);
881
882 // If we can prove that the current context is unrelated to all the
883 // declaring classes, it can't be an implicit member reference (in
884 // which case it's an error if any of those members are selected).
885 if (IsProvablyNotDerivedFrom(SemaRef,
886 cast<CXXMethodDecl>(SemaRef.CurContext)->getParent(),
887 Classes))
888 return (hasNonInstance ? IMA_Mixed_Unrelated : IMA_Error_Unrelated);
889
890 return (hasNonInstance ? IMA_Mixed : IMA_Instance);
891}
892
893/// Diagnose a reference to a field with no object available.
894static void DiagnoseInstanceReference(Sema &SemaRef,
895 const CXXScopeSpec &SS,
896 const LookupResult &R) {
897 SourceLocation Loc = R.getNameLoc();
898 SourceRange Range(Loc);
899 if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
900
901 if (R.getAsSingle<FieldDecl>()) {
902 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(SemaRef.CurContext)) {
903 if (MD->isStatic()) {
904 // "invalid use of member 'x' in static member function"
905 SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method)
906 << Range << R.getLookupName();
907 return;
908 }
909 }
910
911 SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
912 << R.getLookupName() << Range;
913 return;
914 }
915
916 SemaRef.Diag(Loc, diag::err_member_call_without_object) << Range;
John McCall10eae182009-11-30 22:42:35 +0000917}
918
John McCalle66edc12009-11-24 19:00:30 +0000919Sema::OwningExprResult Sema::ActOnIdExpression(Scope *S,
920 const CXXScopeSpec &SS,
921 UnqualifiedId &Id,
922 bool HasTrailingLParen,
923 bool isAddressOfOperand) {
924 assert(!(isAddressOfOperand && HasTrailingLParen) &&
925 "cannot be direct & operand and have a trailing lparen");
926
927 if (SS.isInvalid())
Douglas Gregored8f2882009-01-30 01:04:22 +0000928 return ExprError();
Douglas Gregor90a1a652009-03-19 17:26:29 +0000929
John McCall10eae182009-11-30 22:42:35 +0000930 TemplateArgumentListInfo TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +0000931
932 // Decompose the UnqualifiedId into the following data.
933 DeclarationName Name;
934 SourceLocation NameLoc;
935 const TemplateArgumentListInfo *TemplateArgs;
John McCall10eae182009-11-30 22:42:35 +0000936 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer,
937 Name, NameLoc, TemplateArgs);
Douglas Gregor90a1a652009-03-19 17:26:29 +0000938
Douglas Gregor4ea80432008-11-18 15:03:34 +0000939 IdentifierInfo *II = Name.getAsIdentifierInfo();
John McCalld14a8642009-11-21 08:51:07 +0000940
John McCalle66edc12009-11-24 19:00:30 +0000941 // C++ [temp.dep.expr]p3:
942 // An id-expression is type-dependent if it contains:
943 // -- a nested-name-specifier that contains a class-name that
944 // names a dependent type.
945 // Determine whether this is a member of an unknown specialization;
946 // we need to handle these differently.
John McCallf786fb12009-11-30 23:50:49 +0000947 if (SS.isSet() && IsDependentIdExpression(*this, SS)) {
John McCalle66edc12009-11-24 19:00:30 +0000948 return ActOnDependentIdExpression(SS, Name, NameLoc,
John McCallcd4b4772009-12-02 03:53:29 +0000949 isAddressOfOperand,
John McCalle66edc12009-11-24 19:00:30 +0000950 TemplateArgs);
951 }
John McCalld14a8642009-11-21 08:51:07 +0000952
John McCalle66edc12009-11-24 19:00:30 +0000953 // Perform the required lookup.
954 LookupResult R(*this, Name, NameLoc, LookupOrdinaryName);
955 if (TemplateArgs) {
John McCalle66edc12009-11-24 19:00:30 +0000956 // Just re-use the lookup done by isTemplateName.
John McCall10eae182009-11-30 22:42:35 +0000957 DecomposeTemplateName(R, Id);
John McCalle66edc12009-11-24 19:00:30 +0000958 } else {
959 LookupParsedName(R, S, &SS, true);
Mike Stump11289f42009-09-09 15:08:12 +0000960
John McCalle66edc12009-11-24 19:00:30 +0000961 // If this reference is in an Objective-C method, then we need to do
962 // some special Objective-C lookup, too.
963 if (!SS.isSet() && II && getCurMethodDecl()) {
964 OwningExprResult E(LookupInObjCMethod(R, S, II));
965 if (E.isInvalid())
966 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +0000967
John McCalle66edc12009-11-24 19:00:30 +0000968 Expr *Ex = E.takeAs<Expr>();
969 if (Ex) return Owned(Ex);
Steve Naroffebf4cb42008-06-02 23:03:37 +0000970 }
Chris Lattner59a25942008-03-31 00:36:02 +0000971 }
Douglas Gregorf15f5d32009-02-16 19:28:42 +0000972
John McCalle66edc12009-11-24 19:00:30 +0000973 if (R.isAmbiguous())
974 return ExprError();
975
Douglas Gregor171c45a2009-02-18 21:56:37 +0000976 // Determine whether this name might be a candidate for
977 // argument-dependent lookup.
John McCalle66edc12009-11-24 19:00:30 +0000978 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor171c45a2009-02-18 21:56:37 +0000979
John McCalle66edc12009-11-24 19:00:30 +0000980 if (R.empty() && !ADL) {
Bill Wendling4073ed52007-02-13 01:51:42 +0000981 // Otherwise, this could be an implicitly declared function reference (legal
John McCalle66edc12009-11-24 19:00:30 +0000982 // in C90, extension in C99, forbidden in C++).
983 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
984 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
985 if (D) R.addDecl(D);
986 }
987
988 // If this name wasn't predeclared and if this is not a function
989 // call, diagnose the problem.
990 if (R.empty()) {
991 if (!SS.isEmpty())
992 return ExprError(Diag(NameLoc, diag::err_no_member)
993 << Name << computeDeclContext(SS, false)
994 << SS.getRange());
Douglas Gregore40876a2009-10-13 21:16:44 +0000995 else if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
Alexis Hunt3d221f22009-11-29 07:34:05 +0000996 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregor4ea80432008-11-18 15:03:34 +0000997 Name.getNameKind() == DeclarationName::CXXConversionFunctionName)
John McCalle66edc12009-11-24 19:00:30 +0000998 return ExprError(Diag(NameLoc, diag::err_undeclared_use)
999 << Name);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00001000 else
John McCalle66edc12009-11-24 19:00:30 +00001001 return ExprError(Diag(NameLoc, diag::err_undeclared_var_use) << Name);
Steve Naroff92e30f82007-04-02 22:35:25 +00001002 }
Chris Lattner17ed4872006-11-20 04:58:19 +00001003 }
Mike Stump11289f42009-09-09 15:08:12 +00001004
John McCalle66edc12009-11-24 19:00:30 +00001005 // This is guaranteed from this point on.
1006 assert(!R.empty() || ADL);
1007
1008 if (VarDecl *Var = R.getAsSingle<VarDecl>()) {
Douglas Gregor3256d042009-06-30 15:47:41 +00001009 // Warn about constructs like:
1010 // if (void *X = foo()) { ... } else { X }.
1011 // In the else block, the pointer is always false.
Mike Stump11289f42009-09-09 15:08:12 +00001012
Douglas Gregor3256d042009-06-30 15:47:41 +00001013 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
1014 Scope *CheckS = S;
Douglas Gregor13a2c032009-11-05 17:49:26 +00001015 while (CheckS && CheckS->getControlParent()) {
Mike Stump11289f42009-09-09 15:08:12 +00001016 if (CheckS->isWithinElse() &&
Douglas Gregor3256d042009-06-30 15:47:41 +00001017 CheckS->getControlParent()->isDeclScope(DeclPtrTy::make(Var))) {
John McCalle66edc12009-11-24 19:00:30 +00001018 ExprError(Diag(NameLoc, diag::warn_value_always_zero)
Douglas Gregor13a2c032009-11-05 17:49:26 +00001019 << Var->getDeclName()
1020 << (Var->getType()->isPointerType()? 2 :
1021 Var->getType()->isBooleanType()? 1 : 0));
Douglas Gregor3256d042009-06-30 15:47:41 +00001022 break;
1023 }
Mike Stump11289f42009-09-09 15:08:12 +00001024
Douglas Gregor13a2c032009-11-05 17:49:26 +00001025 // Move to the parent of this scope.
1026 CheckS = CheckS->getParent();
Douglas Gregor3256d042009-06-30 15:47:41 +00001027 }
1028 }
John McCalle66edc12009-11-24 19:00:30 +00001029 } else if (FunctionDecl *Func = R.getAsSingle<FunctionDecl>()) {
Douglas Gregor3256d042009-06-30 15:47:41 +00001030 if (!getLangOptions().CPlusPlus && !Func->hasPrototype()) {
1031 // C99 DR 316 says that, if a function type comes from a
1032 // function definition (without a prototype), that type is only
1033 // used for checking compatibility. Therefore, when referencing
1034 // the function, we pretend that we don't have the full function
1035 // type.
John McCalle66edc12009-11-24 19:00:30 +00001036 if (DiagnoseUseOfDecl(Func, NameLoc))
Douglas Gregor3256d042009-06-30 15:47:41 +00001037 return ExprError();
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001038
Douglas Gregor3256d042009-06-30 15:47:41 +00001039 QualType T = Func->getType();
1040 QualType NoProtoType = T;
John McCall9dd450b2009-09-21 23:43:11 +00001041 if (const FunctionProtoType *Proto = T->getAs<FunctionProtoType>())
Douglas Gregor3256d042009-06-30 15:47:41 +00001042 NoProtoType = Context.getFunctionNoProtoType(Proto->getResultType());
John McCalle66edc12009-11-24 19:00:30 +00001043 return BuildDeclRefExpr(Func, NoProtoType, NameLoc, &SS);
Douglas Gregor3256d042009-06-30 15:47:41 +00001044 }
1045 }
Mike Stump11289f42009-09-09 15:08:12 +00001046
John McCall2d74de92009-12-01 22:10:20 +00001047 // Check whether this might be a C++ implicit instance member access.
1048 // C++ [expr.prim.general]p6:
1049 // Within the definition of a non-static member function, an
1050 // identifier that names a non-static member is transformed to a
1051 // class member access expression.
1052 // But note that &SomeClass::foo is grammatically distinct, even
1053 // though we don't parse it that way.
John McCall5af04502009-12-02 20:26:00 +00001054 if (!R.empty() && IsClassMember(*R.begin())) {
John McCalle66edc12009-11-24 19:00:30 +00001055 bool isAbstractMemberPointer = (isAddressOfOperand && !SS.isEmpty());
John McCallb53bbd42009-11-22 01:44:31 +00001056
John McCall2d74de92009-12-01 22:10:20 +00001057 if (!isAbstractMemberPointer) {
1058 switch (ClassifyImplicitMemberAccess(*this, R)) {
1059 case IMA_Instance:
1060 return BuildImplicitMemberExpr(SS, R, TemplateArgs, true);
1061
1062 case IMA_AnonymousMember:
1063 assert(R.isSingleResult());
1064 return BuildAnonymousStructUnionMemberReference(R.getNameLoc(),
1065 R.getAsSingle<FieldDecl>());
1066
1067 case IMA_Mixed:
1068 case IMA_Mixed_Unrelated:
1069 case IMA_Unresolved:
1070 return BuildImplicitMemberExpr(SS, R, TemplateArgs, false);
1071
1072 case IMA_Static:
1073 case IMA_Mixed_StaticContext:
1074 case IMA_Unresolved_StaticContext:
1075 break;
1076
1077 case IMA_Error_StaticContext:
1078 case IMA_Error_Unrelated:
1079 DiagnoseInstanceReference(*this, SS, R);
1080 return ExprError();
1081 }
John McCallb53bbd42009-11-22 01:44:31 +00001082 }
1083 }
1084
John McCalle66edc12009-11-24 19:00:30 +00001085 if (TemplateArgs)
1086 return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001087
John McCalle66edc12009-11-24 19:00:30 +00001088 return BuildDeclarationNameExpr(SS, R, ADL);
1089}
1090
John McCall10eae182009-11-30 22:42:35 +00001091/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1092/// declaration name, generally during template instantiation.
1093/// There's a large number of things which don't need to be done along
1094/// this path.
John McCalle66edc12009-11-24 19:00:30 +00001095Sema::OwningExprResult
1096Sema::BuildQualifiedDeclarationNameExpr(const CXXScopeSpec &SS,
1097 DeclarationName Name,
1098 SourceLocation NameLoc) {
1099 DeclContext *DC;
1100 if (!(DC = computeDeclContext(SS, false)) ||
1101 DC->isDependentContext() ||
1102 RequireCompleteDeclContext(SS))
1103 return BuildDependentDeclRefExpr(SS, Name, NameLoc, 0);
1104
1105 LookupResult R(*this, Name, NameLoc, LookupOrdinaryName);
1106 LookupQualifiedName(R, DC);
1107
1108 if (R.isAmbiguous())
1109 return ExprError();
1110
1111 if (R.empty()) {
1112 Diag(NameLoc, diag::err_no_member) << Name << DC << SS.getRange();
1113 return ExprError();
1114 }
1115
1116 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1117}
1118
1119/// LookupInObjCMethod - The parser has read a name in, and Sema has
1120/// detected that we're currently inside an ObjC method. Perform some
1121/// additional lookup.
1122///
1123/// Ideally, most of this would be done by lookup, but there's
1124/// actually quite a lot of extra work involved.
1125///
1126/// Returns a null sentinel to indicate trivial success.
1127Sema::OwningExprResult
1128Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
1129 IdentifierInfo *II) {
1130 SourceLocation Loc = Lookup.getNameLoc();
1131
1132 // There are two cases to handle here. 1) scoped lookup could have failed,
1133 // in which case we should look for an ivar. 2) scoped lookup could have
1134 // found a decl, but that decl is outside the current instance method (i.e.
1135 // a global variable). In these two cases, we do a lookup for an ivar with
1136 // this name, if the lookup sucedes, we replace it our current decl.
1137
1138 // If we're in a class method, we don't normally want to look for
1139 // ivars. But if we don't find anything else, and there's an
1140 // ivar, that's an error.
1141 bool IsClassMethod = getCurMethodDecl()->isClassMethod();
1142
1143 bool LookForIvars;
1144 if (Lookup.empty())
1145 LookForIvars = true;
1146 else if (IsClassMethod)
1147 LookForIvars = false;
1148 else
1149 LookForIvars = (Lookup.isSingleResult() &&
1150 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
1151
1152 if (LookForIvars) {
1153 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
1154 ObjCInterfaceDecl *ClassDeclared;
1155 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1156 // Diagnose using an ivar in a class method.
1157 if (IsClassMethod)
1158 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1159 << IV->getDeclName());
1160
1161 // If we're referencing an invalid decl, just return this as a silent
1162 // error node. The error diagnostic was already emitted on the decl.
1163 if (IV->isInvalidDecl())
1164 return ExprError();
1165
1166 // Check if referencing a field with __attribute__((deprecated)).
1167 if (DiagnoseUseOfDecl(IV, Loc))
1168 return ExprError();
1169
1170 // Diagnose the use of an ivar outside of the declaring class.
1171 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
1172 ClassDeclared != IFace)
1173 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1174
1175 // FIXME: This should use a new expr for a direct reference, don't
1176 // turn this into Self->ivar, just return a BareIVarExpr or something.
1177 IdentifierInfo &II = Context.Idents.get("self");
1178 UnqualifiedId SelfName;
1179 SelfName.setIdentifier(&II, SourceLocation());
1180 CXXScopeSpec SelfScopeSpec;
1181 OwningExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
1182 SelfName, false, false);
1183 MarkDeclarationReferenced(Loc, IV);
1184 return Owned(new (Context)
1185 ObjCIvarRefExpr(IV, IV->getType(), Loc,
1186 SelfExpr.takeAs<Expr>(), true, true));
1187 }
1188 } else if (getCurMethodDecl()->isInstanceMethod()) {
1189 // We should warn if a local variable hides an ivar.
1190 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
1191 ObjCInterfaceDecl *ClassDeclared;
1192 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1193 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
1194 IFace == ClassDeclared)
1195 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
1196 }
1197 }
1198
1199 // Needed to implement property "super.method" notation.
1200 if (Lookup.empty() && II->isStr("super")) {
1201 QualType T;
1202
1203 if (getCurMethodDecl()->isInstanceMethod())
1204 T = Context.getObjCObjectPointerType(Context.getObjCInterfaceType(
1205 getCurMethodDecl()->getClassInterface()));
1206 else
1207 T = Context.getObjCClassType();
1208 return Owned(new (Context) ObjCSuperExpr(Loc, T));
1209 }
1210
1211 // Sentinel value saying that we didn't do anything special.
1212 return Owned((Expr*) 0);
Douglas Gregor3256d042009-06-30 15:47:41 +00001213}
John McCalld14a8642009-11-21 08:51:07 +00001214
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001215/// \brief Cast member's object to its own class if necessary.
Fariborz Jahanian3f150832009-07-29 19:40:11 +00001216bool
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001217Sema::PerformObjectMemberConversion(Expr *&From, NamedDecl *Member) {
1218 if (FieldDecl *FD = dyn_cast<FieldDecl>(Member))
Mike Stump11289f42009-09-09 15:08:12 +00001219 if (CXXRecordDecl *RD =
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001220 dyn_cast<CXXRecordDecl>(FD->getDeclContext())) {
Mike Stump11289f42009-09-09 15:08:12 +00001221 QualType DestType =
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001222 Context.getCanonicalType(Context.getTypeDeclType(RD));
Fariborz Jahanian4b12ed12009-07-29 20:41:46 +00001223 if (DestType->isDependentType() || From->getType()->isDependentType())
1224 return false;
1225 QualType FromRecordType = From->getType();
1226 QualType DestRecordType = DestType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001227 if (FromRecordType->getAs<PointerType>()) {
Fariborz Jahanian4b12ed12009-07-29 20:41:46 +00001228 DestType = Context.getPointerType(DestType);
1229 FromRecordType = FromRecordType->getPointeeType();
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001230 }
Fariborz Jahanian4b12ed12009-07-29 20:41:46 +00001231 if (!Context.hasSameUnqualifiedType(FromRecordType, DestRecordType) &&
1232 CheckDerivedToBaseConversion(FromRecordType,
1233 DestRecordType,
1234 From->getSourceRange().getBegin(),
1235 From->getSourceRange()))
1236 return true;
Anders Carlssona076d142009-07-31 01:23:52 +00001237 ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
1238 /*isLvalue=*/true);
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001239 }
Fariborz Jahanian3f150832009-07-29 19:40:11 +00001240 return false;
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001241}
Douglas Gregor3256d042009-06-30 15:47:41 +00001242
Douglas Gregorf405d7e2009-08-31 23:41:50 +00001243/// \brief Build a MemberExpr AST node.
Mike Stump11289f42009-09-09 15:08:12 +00001244static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow,
Eli Friedman2cfcef62009-12-04 06:40:45 +00001245 const CXXScopeSpec &SS, ValueDecl *Member,
John McCalle66edc12009-11-24 19:00:30 +00001246 SourceLocation Loc, QualType Ty,
1247 const TemplateArgumentListInfo *TemplateArgs = 0) {
1248 NestedNameSpecifier *Qualifier = 0;
1249 SourceRange QualifierRange;
John McCall10eae182009-11-30 22:42:35 +00001250 if (SS.isSet()) {
1251 Qualifier = (NestedNameSpecifier *) SS.getScopeRep();
1252 QualifierRange = SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00001253 }
Mike Stump11289f42009-09-09 15:08:12 +00001254
John McCalle66edc12009-11-24 19:00:30 +00001255 return MemberExpr::Create(C, Base, isArrow, Qualifier, QualifierRange,
1256 Member, Loc, TemplateArgs, Ty);
Douglas Gregorc1905232009-08-26 22:36:53 +00001257}
1258
John McCall2d74de92009-12-01 22:10:20 +00001259/// Builds an implicit member access expression. The current context
1260/// is known to be an instance method, and the given unqualified lookup
1261/// set is known to contain only instance members, at least one of which
1262/// is from an appropriate type.
John McCallb53bbd42009-11-22 01:44:31 +00001263Sema::OwningExprResult
John McCall2d74de92009-12-01 22:10:20 +00001264Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
1265 LookupResult &R,
1266 const TemplateArgumentListInfo *TemplateArgs,
1267 bool IsKnownInstance) {
John McCalle66edc12009-11-24 19:00:30 +00001268 assert(!R.empty() && !R.isAmbiguous());
1269
John McCalld14a8642009-11-21 08:51:07 +00001270 SourceLocation Loc = R.getNameLoc();
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00001271
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001272 // We may have found a field within an anonymous union or struct
1273 // (C++ [class.union]).
Douglas Gregor6493d9c2009-10-22 07:08:30 +00001274 // FIXME: This needs to happen post-isImplicitMemberReference?
John McCalle66edc12009-11-24 19:00:30 +00001275 // FIXME: template-ids inside anonymous structs?
John McCall10eae182009-11-30 22:42:35 +00001276 if (FieldDecl *FD = R.getAsSingle<FieldDecl>())
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001277 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
John McCallb53bbd42009-11-22 01:44:31 +00001278 return BuildAnonymousStructUnionMemberReference(Loc, FD);
Sebastian Redlffbcf962009-01-18 18:53:16 +00001279
John McCall2d74de92009-12-01 22:10:20 +00001280 // If this is known to be an instance access, go ahead and build a
1281 // 'this' expression now.
1282 QualType ThisType = cast<CXXMethodDecl>(CurContext)->getThisType(Context);
1283 Expr *This = 0; // null signifies implicit access
1284 if (IsKnownInstance) {
1285 This = new (Context) CXXThisExpr(SourceLocation(), ThisType);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00001286 }
1287
John McCall2d74de92009-12-01 22:10:20 +00001288 return BuildMemberReferenceExpr(ExprArg(*this, This), ThisType,
1289 /*OpLoc*/ SourceLocation(),
1290 /*IsArrow*/ true,
1291 SS, R, TemplateArgs);
John McCalld14a8642009-11-21 08:51:07 +00001292}
1293
John McCalle66edc12009-11-24 19:00:30 +00001294bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00001295 const LookupResult &R,
1296 bool HasTrailingLParen) {
John McCalld14a8642009-11-21 08:51:07 +00001297 // Only when used directly as the postfix-expression of a call.
1298 if (!HasTrailingLParen)
1299 return false;
1300
1301 // Never if a scope specifier was provided.
John McCalle66edc12009-11-24 19:00:30 +00001302 if (SS.isSet())
John McCalld14a8642009-11-21 08:51:07 +00001303 return false;
1304
1305 // Only in C++ or ObjC++.
John McCallb53bbd42009-11-22 01:44:31 +00001306 if (!getLangOptions().CPlusPlus)
John McCalld14a8642009-11-21 08:51:07 +00001307 return false;
1308
1309 // Turn off ADL when we find certain kinds of declarations during
1310 // normal lookup:
1311 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
1312 NamedDecl *D = *I;
1313
1314 // C++0x [basic.lookup.argdep]p3:
1315 // -- a declaration of a class member
1316 // Since using decls preserve this property, we check this on the
1317 // original decl.
John McCall5af04502009-12-02 20:26:00 +00001318 if (IsClassMember(D))
John McCalld14a8642009-11-21 08:51:07 +00001319 return false;
1320
1321 // C++0x [basic.lookup.argdep]p3:
1322 // -- a block-scope function declaration that is not a
1323 // using-declaration
1324 // NOTE: we also trigger this for function templates (in fact, we
1325 // don't check the decl type at all, since all other decl types
1326 // turn off ADL anyway).
1327 if (isa<UsingShadowDecl>(D))
1328 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1329 else if (D->getDeclContext()->isFunctionOrMethod())
1330 return false;
1331
1332 // C++0x [basic.lookup.argdep]p3:
1333 // -- a declaration that is neither a function or a function
1334 // template
1335 // And also for builtin functions.
1336 if (isa<FunctionDecl>(D)) {
1337 FunctionDecl *FDecl = cast<FunctionDecl>(D);
1338
1339 // But also builtin functions.
1340 if (FDecl->getBuiltinID() && FDecl->isImplicit())
1341 return false;
1342 } else if (!isa<FunctionTemplateDecl>(D))
1343 return false;
1344 }
1345
1346 return true;
1347}
1348
1349
John McCalld14a8642009-11-21 08:51:07 +00001350/// Diagnoses obvious problems with the use of the given declaration
1351/// as an expression. This is only actually called for lookups that
1352/// were not overloaded, and it doesn't promise that the declaration
1353/// will in fact be used.
1354static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
1355 if (isa<TypedefDecl>(D)) {
1356 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
1357 return true;
1358 }
1359
1360 if (isa<ObjCInterfaceDecl>(D)) {
1361 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
1362 return true;
1363 }
1364
1365 if (isa<NamespaceDecl>(D)) {
1366 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
1367 return true;
1368 }
1369
1370 return false;
1371}
1372
1373Sema::OwningExprResult
John McCalle66edc12009-11-24 19:00:30 +00001374Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00001375 LookupResult &R,
1376 bool NeedsADL) {
John McCall3a60c872009-12-08 22:45:53 +00001377 // If this is a single, fully-resolved result and we don't need ADL,
1378 // just build an ordinary singleton decl ref.
1379 if (!NeedsADL && R.isSingleResult())
John McCallb53bbd42009-11-22 01:44:31 +00001380 return BuildDeclarationNameExpr(SS, R.getNameLoc(), R.getFoundDecl());
John McCalld14a8642009-11-21 08:51:07 +00001381
1382 // We only need to check the declaration if there's exactly one
1383 // result, because in the overloaded case the results can only be
1384 // functions and function templates.
John McCallb53bbd42009-11-22 01:44:31 +00001385 if (R.isSingleResult() &&
1386 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCalld14a8642009-11-21 08:51:07 +00001387 return ExprError();
1388
John McCalle66edc12009-11-24 19:00:30 +00001389 bool Dependent
1390 = UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(), 0);
John McCalld14a8642009-11-21 08:51:07 +00001391 UnresolvedLookupExpr *ULE
John McCalle66edc12009-11-24 19:00:30 +00001392 = UnresolvedLookupExpr::Create(Context, Dependent,
1393 (NestedNameSpecifier*) SS.getScopeRep(),
1394 SS.getRange(),
John McCallb53bbd42009-11-22 01:44:31 +00001395 R.getLookupName(), R.getNameLoc(),
1396 NeedsADL, R.isOverloadedResult());
1397 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1398 ULE->addDecl(*I);
John McCalld14a8642009-11-21 08:51:07 +00001399
1400 return Owned(ULE);
1401}
1402
1403
1404/// \brief Complete semantic analysis for a reference to the given declaration.
1405Sema::OwningExprResult
John McCalle66edc12009-11-24 19:00:30 +00001406Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCalld14a8642009-11-21 08:51:07 +00001407 SourceLocation Loc, NamedDecl *D) {
1408 assert(D && "Cannot refer to a NULL declaration");
John McCall283b9012009-11-22 00:44:51 +00001409 assert(!isa<FunctionTemplateDecl>(D) &&
1410 "Cannot refer unambiguously to a function template");
John McCalld14a8642009-11-21 08:51:07 +00001411 DeclarationName Name = D->getDeclName();
1412
1413 if (CheckDeclInExpr(*this, Loc, D))
1414 return ExprError();
Steve Narofff1e53692007-03-23 22:27:02 +00001415
Douglas Gregore7488b92009-12-01 16:58:18 +00001416 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
1417 // Specifically diagnose references to class templates that are missing
1418 // a template argument list.
1419 Diag(Loc, diag::err_template_decl_ref)
1420 << Template << SS.getRange();
1421 Diag(Template->getLocation(), diag::note_template_decl_here);
1422 return ExprError();
1423 }
1424
1425 // Make sure that we're referring to a value.
1426 ValueDecl *VD = dyn_cast<ValueDecl>(D);
1427 if (!VD) {
1428 Diag(Loc, diag::err_ref_non_value)
1429 << D << SS.getRange();
Daniel Dunbar95d40a672009-12-15 04:24:24 +00001430 Diag(D->getLocation(), diag::note_previous_declaration);
Douglas Gregore7488b92009-12-01 16:58:18 +00001431 return ExprError();
1432 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00001433
Douglas Gregor171c45a2009-02-18 21:56:37 +00001434 // Check whether this declaration can be used. Note that we suppress
1435 // this check when we're going to perform argument-dependent lookup
1436 // on this function name, because this might not be the function
1437 // that overload resolution actually selects.
John McCalld14a8642009-11-21 08:51:07 +00001438 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor171c45a2009-02-18 21:56:37 +00001439 return ExprError();
1440
Steve Naroff8de9c3a2008-09-05 22:11:13 +00001441 // Only create DeclRefExpr's for valid Decl's.
1442 if (VD->isInvalidDecl())
Sebastian Redlffbcf962009-01-18 18:53:16 +00001443 return ExprError();
1444
Chris Lattner2a9d9892008-10-20 05:16:36 +00001445 // If the identifier reference is inside a block, and it refers to a value
1446 // that is outside the block, create a BlockDeclRefExpr instead of a
1447 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
1448 // the block is formed.
Steve Naroff8de9c3a2008-09-05 22:11:13 +00001449 //
Chris Lattner2a9d9892008-10-20 05:16:36 +00001450 // We do not do this for things like enum constants, global variables, etc,
1451 // as they do not get snapshotted.
1452 //
1453 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00001454 MarkDeclarationReferenced(Loc, VD);
Eli Friedman7fa3faa2009-03-22 23:00:19 +00001455 QualType ExprTy = VD->getType().getNonReferenceType();
Steve Naroff1d95e5a2008-10-10 01:28:17 +00001456 // The BlocksAttr indicates the variable is bound by-reference.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001457 if (VD->getAttr<BlocksAttr>())
Eli Friedman7fa3faa2009-03-22 23:00:19 +00001458 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, true));
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00001459 // This is to record that a 'const' was actually synthesize and added.
1460 bool constAdded = !ExprTy.isConstQualified();
Steve Naroff1d95e5a2008-10-10 01:28:17 +00001461 // Variable will be bound by-copy, make it const within the closure.
Mike Stump11289f42009-09-09 15:08:12 +00001462
Eli Friedman7fa3faa2009-03-22 23:00:19 +00001463 ExprTy.addConst();
Mike Stump11289f42009-09-09 15:08:12 +00001464 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, false,
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00001465 constAdded));
Steve Naroff1d95e5a2008-10-10 01:28:17 +00001466 }
1467 // If this reference is not in a block or if the referenced variable is
1468 // within the block, create a normal DeclRefExpr.
Douglas Gregor4619e432008-12-05 23:32:09 +00001469
John McCalle66edc12009-11-24 19:00:30 +00001470 return BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc, &SS);
Chris Lattner17ed4872006-11-20 04:58:19 +00001471}
Chris Lattnere168f762006-11-10 05:29:30 +00001472
Sebastian Redlffbcf962009-01-18 18:53:16 +00001473Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
1474 tok::TokenKind Kind) {
Chris Lattner6307f192008-08-10 01:53:14 +00001475 PredefinedExpr::IdentType IT;
Sebastian Redlffbcf962009-01-18 18:53:16 +00001476
Chris Lattnere168f762006-11-10 05:29:30 +00001477 switch (Kind) {
Chris Lattner317e6ba2008-01-12 18:39:25 +00001478 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner6307f192008-08-10 01:53:14 +00001479 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
1480 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
1481 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattnere168f762006-11-10 05:29:30 +00001482 }
Chris Lattner317e6ba2008-01-12 18:39:25 +00001483
Chris Lattnera81a0272008-01-12 08:14:25 +00001484 // Pre-defined identifiers are of type char[x], where x is the length of the
1485 // string.
Mike Stump11289f42009-09-09 15:08:12 +00001486
Anders Carlsson2fb08242009-09-08 18:24:21 +00001487 Decl *currentDecl = getCurFunctionOrMethodDecl();
1488 if (!currentDecl) {
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00001489 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson2fb08242009-09-08 18:24:21 +00001490 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00001491 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00001492
Anders Carlsson0b209a82009-09-11 01:22:35 +00001493 QualType ResTy;
1494 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
1495 ResTy = Context.DependentTy;
1496 } else {
1497 unsigned Length =
1498 PredefinedExpr::ComputeName(Context, IT, currentDecl).length();
Sebastian Redlffbcf962009-01-18 18:53:16 +00001499
Anders Carlsson0b209a82009-09-11 01:22:35 +00001500 llvm::APInt LengthI(32, Length + 1);
John McCall8ccfcb52009-09-24 19:53:00 +00001501 ResTy = Context.CharTy.withConst();
Anders Carlsson0b209a82009-09-11 01:22:35 +00001502 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
1503 }
Steve Narofff6009ed2009-01-21 00:14:39 +00001504 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattnere168f762006-11-10 05:29:30 +00001505}
1506
Sebastian Redlffbcf962009-01-18 18:53:16 +00001507Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00001508 llvm::SmallString<16> CharBuffer;
Steve Naroffae4143e2007-04-26 20:39:23 +00001509 CharBuffer.resize(Tok.getLength());
1510 const char *ThisTokBegin = &CharBuffer[0];
1511 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlffbcf962009-01-18 18:53:16 +00001512
Steve Naroffae4143e2007-04-26 20:39:23 +00001513 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1514 Tok.getLocation(), PP);
1515 if (Literal.hadError())
Sebastian Redlffbcf962009-01-18 18:53:16 +00001516 return ExprError();
Chris Lattneref24b382008-03-01 08:32:21 +00001517
1518 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
1519
Sebastian Redl20614a72009-01-20 22:23:13 +00001520 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
1521 Literal.isWide(),
1522 type, Tok.getLocation()));
Steve Naroffae4143e2007-04-26 20:39:23 +00001523}
1524
Sebastian Redlffbcf962009-01-18 18:53:16 +00001525Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
1526 // Fast path for a single digit (which is quite common). A single digit
Steve Narofff2fb89e2007-03-13 20:29:44 +00001527 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
1528 if (Tok.getLength() == 1) {
Chris Lattner9240b3e2009-01-26 22:36:52 +00001529 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattnerc4c18192009-01-16 07:10:29 +00001530 unsigned IntSize = Context.Target.getIntWidth();
Steve Narofff6009ed2009-01-21 00:14:39 +00001531 return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
Steve Naroff5faaef72009-01-20 19:53:53 +00001532 Context.IntTy, Tok.getLocation()));
Steve Narofff2fb89e2007-03-13 20:29:44 +00001533 }
Ted Kremeneke9814182009-01-13 23:19:12 +00001534
Chris Lattner23b7eb62007-06-15 23:05:46 +00001535 llvm::SmallString<512> IntegerBuffer;
Chris Lattnera1cf5f92008-09-30 20:53:45 +00001536 // Add padding so that NumericLiteralParser can overread by one character.
1537 IntegerBuffer.resize(Tok.getLength()+1);
Steve Naroff8160ea22007-03-06 01:09:46 +00001538 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlffbcf962009-01-18 18:53:16 +00001539
Chris Lattner67ca9252007-05-21 01:08:44 +00001540 // Get the spelling of the token, which eliminates trigraphs, etc.
Steve Naroff8160ea22007-03-06 01:09:46 +00001541 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlffbcf962009-01-18 18:53:16 +00001542
Mike Stump11289f42009-09-09 15:08:12 +00001543 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Steve Naroff451d8f162007-03-12 23:22:38 +00001544 Tok.getLocation(), PP);
Steve Narofff2fb89e2007-03-13 20:29:44 +00001545 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +00001546 return ExprError();
1547
Chris Lattner1c20a172007-08-26 03:42:43 +00001548 Expr *Res;
Sebastian Redlffbcf962009-01-18 18:53:16 +00001549
Chris Lattner1c20a172007-08-26 03:42:43 +00001550 if (Literal.isFloatingLiteral()) {
Chris Lattnerec0a6d92007-09-22 18:29:59 +00001551 QualType Ty;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001552 if (Literal.isFloat)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00001553 Ty = Context.FloatTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001554 else if (!Literal.isLong)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00001555 Ty = Context.DoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001556 else
Chris Lattner7570e9c2008-03-08 08:52:55 +00001557 Ty = Context.LongDoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001558
1559 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
1560
Ted Kremenek3a2c9502007-11-29 00:56:49 +00001561 // isExact will be set by GetFloatValue().
1562 bool isExact = false;
Chris Lattnere4edb8e2009-06-29 17:34:55 +00001563 llvm::APFloat Val = Literal.GetFloatValue(Format, &isExact);
1564 Res = new (Context) FloatingLiteral(Val, isExact, Ty, Tok.getLocation());
Sebastian Redlffbcf962009-01-18 18:53:16 +00001565
Chris Lattner1c20a172007-08-26 03:42:43 +00001566 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00001567 return ExprError();
Chris Lattner1c20a172007-08-26 03:42:43 +00001568 } else {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001569 QualType Ty;
Chris Lattner67ca9252007-05-21 01:08:44 +00001570
Neil Boothac582c52007-08-29 22:00:19 +00001571 // long long is a C99 feature.
1572 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth4a1ee052007-08-29 22:13:52 +00001573 Literal.isLongLong)
Neil Boothac582c52007-08-29 22:00:19 +00001574 Diag(Tok.getLocation(), diag::ext_longlong);
1575
Chris Lattner67ca9252007-05-21 01:08:44 +00001576 // Get the value in the widest-possible width.
Chris Lattner37e05872008-03-05 18:54:05 +00001577 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlffbcf962009-01-18 18:53:16 +00001578
Chris Lattner67ca9252007-05-21 01:08:44 +00001579 if (Literal.GetIntegerValue(ResultVal)) {
1580 // If this value didn't fit into uintmax_t, warn and force to ull.
1581 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001582 Ty = Context.UnsignedLongLongTy;
1583 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner37e05872008-03-05 18:54:05 +00001584 "long long is not intmax_t?");
Steve Naroff09ef4742007-03-09 23:16:33 +00001585 } else {
Chris Lattner67ca9252007-05-21 01:08:44 +00001586 // If this value fits into a ULL, try to figure out what else it fits into
1587 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlffbcf962009-01-18 18:53:16 +00001588
Chris Lattner67ca9252007-05-21 01:08:44 +00001589 // Octal, Hexadecimal, and integers with a U suffix are allowed to
1590 // be an unsigned int.
1591 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
1592
1593 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner55258cf2008-05-09 05:59:00 +00001594 unsigned Width = 0;
Chris Lattner7b939cf2007-08-23 21:58:08 +00001595 if (!Literal.isLong && !Literal.isLongLong) {
1596 // Are int/unsigned possibilities?
Chris Lattner55258cf2008-05-09 05:59:00 +00001597 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00001598
Chris Lattner67ca9252007-05-21 01:08:44 +00001599 // Does it fit in a unsigned int?
1600 if (ResultVal.isIntN(IntSize)) {
1601 // Does it fit in a signed int?
1602 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001603 Ty = Context.IntTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00001604 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001605 Ty = Context.UnsignedIntTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00001606 Width = IntSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00001607 }
Chris Lattner67ca9252007-05-21 01:08:44 +00001608 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00001609
Chris Lattner67ca9252007-05-21 01:08:44 +00001610 // Are long/unsigned long possibilities?
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001611 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner55258cf2008-05-09 05:59:00 +00001612 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00001613
Chris Lattner67ca9252007-05-21 01:08:44 +00001614 // Does it fit in a unsigned long?
1615 if (ResultVal.isIntN(LongSize)) {
1616 // Does it fit in a signed long?
1617 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001618 Ty = Context.LongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00001619 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001620 Ty = Context.UnsignedLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00001621 Width = LongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00001622 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00001623 }
1624
Chris Lattner67ca9252007-05-21 01:08:44 +00001625 // Finally, check long long if needed.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001626 if (Ty.isNull()) {
Chris Lattner55258cf2008-05-09 05:59:00 +00001627 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00001628
Chris Lattner67ca9252007-05-21 01:08:44 +00001629 // Does it fit in a unsigned long long?
1630 if (ResultVal.isIntN(LongLongSize)) {
1631 // Does it fit in a signed long long?
1632 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001633 Ty = Context.LongLongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00001634 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001635 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00001636 Width = LongLongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00001637 }
1638 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00001639
Chris Lattner67ca9252007-05-21 01:08:44 +00001640 // If we still couldn't decide a type, we probably have something that
1641 // does not fit in a signed long long, but has no U suffix.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001642 if (Ty.isNull()) {
Chris Lattner67ca9252007-05-21 01:08:44 +00001643 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001644 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00001645 Width = Context.Target.getLongLongWidth();
Chris Lattner67ca9252007-05-21 01:08:44 +00001646 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00001647
Chris Lattner55258cf2008-05-09 05:59:00 +00001648 if (ResultVal.getBitWidth() != Width)
1649 ResultVal.trunc(Width);
Steve Naroff09ef4742007-03-09 23:16:33 +00001650 }
Sebastian Redl20614a72009-01-20 22:23:13 +00001651 Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Steve Naroff09ef4742007-03-09 23:16:33 +00001652 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00001653
Chris Lattner1c20a172007-08-26 03:42:43 +00001654 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
1655 if (Literal.isImaginary)
Mike Stump11289f42009-09-09 15:08:12 +00001656 Res = new (Context) ImaginaryLiteral(Res,
Steve Narofff6009ed2009-01-21 00:14:39 +00001657 Context.getComplexType(Res->getType()));
Sebastian Redlffbcf962009-01-18 18:53:16 +00001658
1659 return Owned(Res);
Chris Lattnere168f762006-11-10 05:29:30 +00001660}
1661
Sebastian Redlffbcf962009-01-18 18:53:16 +00001662Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1663 SourceLocation R, ExprArg Val) {
Anders Carlssonb781bcd2009-05-01 19:49:17 +00001664 Expr *E = Val.takeAs<Expr>();
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001665 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Narofff6009ed2009-01-21 00:14:39 +00001666 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattnere168f762006-11-10 05:29:30 +00001667}
1668
Steve Naroff71b59a92007-06-04 22:22:31 +00001669/// The UsualUnaryConversions() function is *not* called by this routine.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00001670/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001671bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Sebastian Redl6f282892008-11-11 17:56:53 +00001672 SourceLocation OpLoc,
1673 const SourceRange &ExprRange,
1674 bool isSizeof) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001675 if (exprType->isDependentType())
1676 return false;
1677
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001678 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
1679 // the result is the size of the referenced type."
1680 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
1681 // result shall be the alignment of the referenced type."
1682 if (const ReferenceType *Ref = exprType->getAs<ReferenceType>())
1683 exprType = Ref->getPointeeType();
1684
Steve Naroff043d45d2007-05-15 02:32:35 +00001685 // C99 6.5.3.4p1:
John McCall4c98fd82009-11-04 07:28:41 +00001686 if (exprType->isFunctionType()) {
Chris Lattner62975a72009-04-24 00:30:45 +00001687 // alignof(function) is allowed as an extension.
Chris Lattnerb1355b12009-01-24 19:46:37 +00001688 if (isSizeof)
1689 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
1690 return false;
1691 }
Mike Stump11289f42009-09-09 15:08:12 +00001692
Chris Lattner62975a72009-04-24 00:30:45 +00001693 // Allow sizeof(void)/alignof(void) as an extension.
Chris Lattnerb1355b12009-01-24 19:46:37 +00001694 if (exprType->isVoidType()) {
Chris Lattner3b054132008-11-19 05:08:23 +00001695 Diag(OpLoc, diag::ext_sizeof_void_type)
1696 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattnerb1355b12009-01-24 19:46:37 +00001697 return false;
1698 }
Mike Stump11289f42009-09-09 15:08:12 +00001699
Chris Lattner62975a72009-04-24 00:30:45 +00001700 if (RequireCompleteType(OpLoc, exprType,
Douglas Gregor906db8a2009-12-15 16:44:32 +00001701 PDiag(diag::err_sizeof_alignof_incomplete_type)
1702 << int(!isSizeof) << ExprRange))
Chris Lattner62975a72009-04-24 00:30:45 +00001703 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001704
Chris Lattner62975a72009-04-24 00:30:45 +00001705 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
Fariborz Jahanian1dcb3222009-04-24 17:34:33 +00001706 if (LangOpts.ObjCNonFragileABI && exprType->isObjCInterfaceType()) {
Chris Lattner62975a72009-04-24 00:30:45 +00001707 Diag(OpLoc, diag::err_sizeof_nonfragile_interface)
Chris Lattnercd2a8c52009-04-24 22:30:50 +00001708 << exprType << isSizeof << ExprRange;
1709 return true;
Chris Lattner37920f52009-04-21 19:55:16 +00001710 }
Mike Stump11289f42009-09-09 15:08:12 +00001711
Chris Lattner62975a72009-04-24 00:30:45 +00001712 return false;
Steve Naroff043d45d2007-05-15 02:32:35 +00001713}
1714
Chris Lattner8dff0172009-01-24 20:17:12 +00001715bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
1716 const SourceRange &ExprRange) {
1717 E = E->IgnoreParens();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001718
Mike Stump11289f42009-09-09 15:08:12 +00001719 // alignof decl is always ok.
Chris Lattner8dff0172009-01-24 20:17:12 +00001720 if (isa<DeclRefExpr>(E))
1721 return false;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001722
1723 // Cannot know anything else if the expression is dependent.
1724 if (E->isTypeDependent())
1725 return false;
1726
Douglas Gregor71235ec2009-05-02 02:18:30 +00001727 if (E->getBitField()) {
1728 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
1729 return true;
Chris Lattner8dff0172009-01-24 20:17:12 +00001730 }
Douglas Gregor71235ec2009-05-02 02:18:30 +00001731
1732 // Alignment of a field access is always okay, so long as it isn't a
1733 // bit-field.
1734 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump212005c2009-07-22 18:58:19 +00001735 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor71235ec2009-05-02 02:18:30 +00001736 return false;
1737
Chris Lattner8dff0172009-01-24 20:17:12 +00001738 return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
1739}
1740
Douglas Gregor0950e412009-03-13 21:01:28 +00001741/// \brief Build a sizeof or alignof expression given a type operand.
Mike Stump11289f42009-09-09 15:08:12 +00001742Action::OwningExprResult
John McCallbcd03502009-12-07 02:54:59 +00001743Sema::CreateSizeOfAlignOfExpr(TypeSourceInfo *TInfo,
John McCall4c98fd82009-11-04 07:28:41 +00001744 SourceLocation OpLoc,
Douglas Gregor0950e412009-03-13 21:01:28 +00001745 bool isSizeOf, SourceRange R) {
John McCallbcd03502009-12-07 02:54:59 +00001746 if (!TInfo)
Douglas Gregor0950e412009-03-13 21:01:28 +00001747 return ExprError();
1748
John McCallbcd03502009-12-07 02:54:59 +00001749 QualType T = TInfo->getType();
John McCall4c98fd82009-11-04 07:28:41 +00001750
Douglas Gregor0950e412009-03-13 21:01:28 +00001751 if (!T->isDependentType() &&
1752 CheckSizeOfAlignOfOperand(T, OpLoc, R, isSizeOf))
1753 return ExprError();
1754
1755 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
John McCallbcd03502009-12-07 02:54:59 +00001756 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, TInfo,
Douglas Gregor0950e412009-03-13 21:01:28 +00001757 Context.getSizeType(), OpLoc,
1758 R.getEnd()));
1759}
1760
1761/// \brief Build a sizeof or alignof expression given an expression
1762/// operand.
Mike Stump11289f42009-09-09 15:08:12 +00001763Action::OwningExprResult
1764Sema::CreateSizeOfAlignOfExpr(Expr *E, SourceLocation OpLoc,
Douglas Gregor0950e412009-03-13 21:01:28 +00001765 bool isSizeOf, SourceRange R) {
1766 // Verify that the operand is valid.
1767 bool isInvalid = false;
1768 if (E->isTypeDependent()) {
1769 // Delay type-checking for type-dependent expressions.
1770 } else if (!isSizeOf) {
1771 isInvalid = CheckAlignOfExpr(E, OpLoc, R);
Douglas Gregor71235ec2009-05-02 02:18:30 +00001772 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Douglas Gregor0950e412009-03-13 21:01:28 +00001773 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
1774 isInvalid = true;
1775 } else {
1776 isInvalid = CheckSizeOfAlignOfOperand(E->getType(), OpLoc, R, true);
1777 }
1778
1779 if (isInvalid)
1780 return ExprError();
1781
1782 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1783 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, E,
1784 Context.getSizeType(), OpLoc,
1785 R.getEnd()));
1786}
1787
Sebastian Redl6f282892008-11-11 17:56:53 +00001788/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1789/// the same for @c alignof and @c __alignof
1790/// Note that the ArgRange is invalid if isType is false.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001791Action::OwningExprResult
Sebastian Redl6f282892008-11-11 17:56:53 +00001792Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1793 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner0d8b1a12006-11-20 04:34:45 +00001794 // If error parsing type, ignore.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001795 if (TyOrEx == 0) return ExprError();
Steve Naroff043d45d2007-05-15 02:32:35 +00001796
Sebastian Redl6f282892008-11-11 17:56:53 +00001797 if (isType) {
John McCallbcd03502009-12-07 02:54:59 +00001798 TypeSourceInfo *TInfo;
1799 (void) GetTypeFromParser(TyOrEx, &TInfo);
1800 return CreateSizeOfAlignOfExpr(TInfo, OpLoc, isSizeof, ArgRange);
Mike Stump11289f42009-09-09 15:08:12 +00001801 }
Sebastian Redl6f282892008-11-11 17:56:53 +00001802
Douglas Gregor0950e412009-03-13 21:01:28 +00001803 Expr *ArgEx = (Expr *)TyOrEx;
1804 Action::OwningExprResult Result
1805 = CreateSizeOfAlignOfExpr(ArgEx, OpLoc, isSizeof, ArgEx->getSourceRange());
1806
1807 if (Result.isInvalid())
1808 DeleteExpr(ArgEx);
1809
1810 return move(Result);
Chris Lattnere168f762006-11-10 05:29:30 +00001811}
1812
Chris Lattner709322b2009-02-17 08:12:06 +00001813QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc, bool isReal) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001814 if (V->isTypeDependent())
1815 return Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00001816
Chris Lattnere267f5d2007-08-26 05:39:26 +00001817 // These operators return the element type of a complex type.
John McCall9dd450b2009-09-21 23:43:11 +00001818 if (const ComplexType *CT = V->getType()->getAs<ComplexType>())
Chris Lattner30b5dd02007-08-24 21:16:53 +00001819 return CT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00001820
Chris Lattnere267f5d2007-08-26 05:39:26 +00001821 // Otherwise they pass through real integer and floating point types here.
1822 if (V->getType()->isArithmeticType())
1823 return V->getType();
Mike Stump11289f42009-09-09 15:08:12 +00001824
Chris Lattnere267f5d2007-08-26 05:39:26 +00001825 // Reject anything else.
Chris Lattner709322b2009-02-17 08:12:06 +00001826 Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
1827 << (isReal ? "__real" : "__imag");
Chris Lattnere267f5d2007-08-26 05:39:26 +00001828 return QualType();
Chris Lattner30b5dd02007-08-24 21:16:53 +00001829}
1830
1831
Chris Lattnere168f762006-11-10 05:29:30 +00001832
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001833Action::OwningExprResult
1834Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
1835 tok::TokenKind Kind, ExprArg Input) {
Chris Lattnere168f762006-11-10 05:29:30 +00001836 UnaryOperator::Opcode Opc;
1837 switch (Kind) {
1838 default: assert(0 && "Unknown unary op!");
1839 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
1840 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1841 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001842
Eli Friedmancfdd40c2009-11-18 03:38:04 +00001843 return BuildUnaryOp(S, OpLoc, Opc, move(Input));
Chris Lattnere168f762006-11-10 05:29:30 +00001844}
1845
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001846Action::OwningExprResult
1847Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
1848 ExprArg Idx, SourceLocation RLoc) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00001849 // Since this might be a postfix expression, get rid of ParenListExprs.
1850 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
1851
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001852 Expr *LHSExp = static_cast<Expr*>(Base.get()),
1853 *RHSExp = static_cast<Expr*>(Idx.get());
Mike Stump11289f42009-09-09 15:08:12 +00001854
Douglas Gregor40412ac2008-11-19 17:17:41 +00001855 if (getLangOptions().CPlusPlus &&
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00001856 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
1857 Base.release();
1858 Idx.release();
1859 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
1860 Context.DependentTy, RLoc));
1861 }
1862
Mike Stump11289f42009-09-09 15:08:12 +00001863 if (getLangOptions().CPlusPlus &&
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001864 (LHSExp->getType()->isRecordType() ||
Eli Friedman254a1a22008-12-15 22:34:21 +00001865 LHSExp->getType()->isEnumeralType() ||
1866 RHSExp->getType()->isRecordType() ||
1867 RHSExp->getType()->isEnumeralType())) {
Sebastian Redladba46e2009-10-29 20:17:01 +00001868 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, move(Base),move(Idx));
Douglas Gregor40412ac2008-11-19 17:17:41 +00001869 }
1870
Sebastian Redladba46e2009-10-29 20:17:01 +00001871 return CreateBuiltinArraySubscriptExpr(move(Base), LLoc, move(Idx), RLoc);
1872}
1873
1874
1875Action::OwningExprResult
1876Sema::CreateBuiltinArraySubscriptExpr(ExprArg Base, SourceLocation LLoc,
1877 ExprArg Idx, SourceLocation RLoc) {
1878 Expr *LHSExp = static_cast<Expr*>(Base.get());
1879 Expr *RHSExp = static_cast<Expr*>(Idx.get());
1880
Chris Lattner36d572b2007-07-16 00:14:47 +00001881 // Perform default conversions.
1882 DefaultFunctionArrayConversion(LHSExp);
1883 DefaultFunctionArrayConversion(RHSExp);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001884
Chris Lattner36d572b2007-07-16 00:14:47 +00001885 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
Steve Narofff1e53692007-03-23 22:27:02 +00001886
Steve Naroffc1aadb12007-03-28 21:49:40 +00001887 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattnerf17bd422007-08-30 17:45:32 +00001888 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stump4e1f26a2009-02-19 03:04:26 +00001889 // in the subscript position. As a result, we need to derive the array base
Steve Narofff1e53692007-03-23 22:27:02 +00001890 // and index from the expression types.
Chris Lattner36d572b2007-07-16 00:14:47 +00001891 Expr *BaseExpr, *IndexExpr;
1892 QualType ResultType;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001893 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
1894 BaseExpr = LHSExp;
1895 IndexExpr = RHSExp;
1896 ResultType = Context.DependentTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001897 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner36d572b2007-07-16 00:14:47 +00001898 BaseExpr = LHSExp;
1899 IndexExpr = RHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00001900 ResultType = PTy->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001901 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattneraee0cfd2007-07-16 00:23:25 +00001902 // Handle the uncommon case of "123[Ptr]".
Chris Lattner36d572b2007-07-16 00:14:47 +00001903 BaseExpr = RHSExp;
1904 IndexExpr = LHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00001905 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00001906 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00001907 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001908 BaseExpr = LHSExp;
1909 IndexExpr = RHSExp;
1910 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00001911 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00001912 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001913 // Handle the uncommon case of "123[Ptr]".
1914 BaseExpr = RHSExp;
1915 IndexExpr = LHSExp;
1916 ResultType = PTy->getPointeeType();
John McCall9dd450b2009-09-21 23:43:11 +00001917 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattner41977962007-07-31 19:29:30 +00001918 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner36d572b2007-07-16 00:14:47 +00001919 IndexExpr = RHSExp;
Nate Begemanc1bf0612009-01-18 00:45:31 +00001920
Chris Lattner36d572b2007-07-16 00:14:47 +00001921 // FIXME: need to deal with const...
1922 ResultType = VTy->getElementType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00001923 } else if (LHSTy->isArrayType()) {
1924 // If we see an array that wasn't promoted by
1925 // DefaultFunctionArrayConversion, it must be an array that
1926 // wasn't promoted because of the C90 rule that doesn't
1927 // allow promoting non-lvalue arrays. Warn, then
1928 // force the promotion here.
1929 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
1930 LHSExp->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00001931 ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
1932 CastExpr::CK_ArrayToPointerDecay);
Eli Friedmanab2784f2009-04-25 23:46:54 +00001933 LHSTy = LHSExp->getType();
1934
1935 BaseExpr = LHSExp;
1936 IndexExpr = RHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001937 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00001938 } else if (RHSTy->isArrayType()) {
1939 // Same as previous, except for 123[f().a] case
1940 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
1941 RHSExp->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00001942 ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
1943 CastExpr::CK_ArrayToPointerDecay);
Eli Friedmanab2784f2009-04-25 23:46:54 +00001944 RHSTy = RHSExp->getType();
1945
1946 BaseExpr = RHSExp;
1947 IndexExpr = LHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001948 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroffb3096442007-06-09 03:47:53 +00001949 } else {
Chris Lattner003af242009-04-25 22:50:55 +00001950 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
1951 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001952 }
Steve Naroffc1aadb12007-03-28 21:49:40 +00001953 // C99 6.5.2.1p1
Nate Begeman5ec4b312009-08-10 23:49:36 +00001954 if (!(IndexExpr->getType()->isIntegerType() &&
1955 IndexExpr->getType()->isScalarType()) && !IndexExpr->isTypeDependent())
Chris Lattner003af242009-04-25 22:50:55 +00001956 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
1957 << IndexExpr->getSourceRange());
Steve Naroffb29cdd52007-07-10 18:23:31 +00001958
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00001959 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinigb7608d72009-09-14 20:14:57 +00001960 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
1961 && !IndexExpr->isTypeDependent())
Sam Weinig914244e2009-09-14 01:58:58 +00001962 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
1963
Douglas Gregorac1fb652009-03-24 19:52:54 +00001964 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump11289f42009-09-09 15:08:12 +00001965 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
1966 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregorac1fb652009-03-24 19:52:54 +00001967 // incomplete types are not object types.
1968 if (ResultType->isFunctionType()) {
1969 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
1970 << ResultType << BaseExpr->getSourceRange();
1971 return ExprError();
1972 }
Mike Stump11289f42009-09-09 15:08:12 +00001973
Douglas Gregorac1fb652009-03-24 19:52:54 +00001974 if (!ResultType->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00001975 RequireCompleteType(LLoc, ResultType,
Anders Carlssond624e162009-08-26 23:45:07 +00001976 PDiag(diag::err_subscript_incomplete_type)
1977 << BaseExpr->getSourceRange()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00001978 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001979
Chris Lattner62975a72009-04-24 00:30:45 +00001980 // Diagnose bad cases where we step over interface counts.
1981 if (ResultType->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
1982 Diag(LLoc, diag::err_subscript_nonfragile_interface)
1983 << ResultType << BaseExpr->getSourceRange();
1984 return ExprError();
1985 }
Mike Stump11289f42009-09-09 15:08:12 +00001986
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001987 Base.release();
1988 Idx.release();
Mike Stump4e1f26a2009-02-19 03:04:26 +00001989 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
Steve Narofff6009ed2009-01-21 00:14:39 +00001990 ResultType, RLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00001991}
1992
Steve Narofff8fd09e2007-07-27 22:15:19 +00001993QualType Sema::
Nate Begemance4d7fc2008-04-18 23:10:10 +00001994CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001995 const IdentifierInfo *CompName,
Anders Carlssonf571c112009-08-26 18:25:21 +00001996 SourceLocation CompLoc) {
Daniel Dunbarc0429402009-10-18 02:09:38 +00001997 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
1998 // see FIXME there.
1999 //
2000 // FIXME: This logic can be greatly simplified by splitting it along
2001 // halving/not halving and reworking the component checking.
John McCall9dd450b2009-09-21 23:43:11 +00002002 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
Nate Begemanf322eab2008-05-09 06:41:27 +00002003
Steve Narofff8fd09e2007-07-27 22:15:19 +00002004 // The vector accessor can't exceed the number of elements.
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002005 const char *compStr = CompName->getNameStart();
Nate Begemanbb70bf62009-01-18 01:47:54 +00002006
Mike Stump4e1f26a2009-02-19 03:04:26 +00002007 // This flag determines whether or not the component is one of the four
Nate Begemanbb70bf62009-01-18 01:47:54 +00002008 // special names that indicate a subset of exactly half the elements are
2009 // to be selected.
2010 bool HalvingSwizzle = false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00002011
Nate Begemanbb70bf62009-01-18 01:47:54 +00002012 // This flag determines whether or not CompName has an 's' char prefix,
2013 // indicating that it is a string of hex values to be used as vector indices.
Nate Begeman0359e122009-06-25 21:06:09 +00002014 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
Nate Begemanf322eab2008-05-09 06:41:27 +00002015
2016 // Check that we've found one of the special components, or that the component
2017 // names must come from the same set.
Mike Stump4e1f26a2009-02-19 03:04:26 +00002018 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begemanbb70bf62009-01-18 01:47:54 +00002019 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
2020 HalvingSwizzle = true;
Nate Begemanf322eab2008-05-09 06:41:27 +00002021 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner7e152db2007-08-02 22:33:49 +00002022 do
2023 compStr++;
2024 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
Nate Begemanbb70bf62009-01-18 01:47:54 +00002025 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
Chris Lattner7e152db2007-08-02 22:33:49 +00002026 do
2027 compStr++;
Nate Begemanbb70bf62009-01-18 01:47:54 +00002028 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
Chris Lattner7e152db2007-08-02 22:33:49 +00002029 }
Nate Begemanbb70bf62009-01-18 01:47:54 +00002030
Mike Stump4e1f26a2009-02-19 03:04:26 +00002031 if (!HalvingSwizzle && *compStr) {
Steve Narofff8fd09e2007-07-27 22:15:19 +00002032 // We didn't get to the end of the string. This means the component names
2033 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattner3b054132008-11-19 05:08:23 +00002034 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
2035 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Narofff8fd09e2007-07-27 22:15:19 +00002036 return QualType();
2037 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00002038
Nate Begemanbb70bf62009-01-18 01:47:54 +00002039 // Ensure no component accessor exceeds the width of the vector type it
2040 // operates on.
2041 if (!HalvingSwizzle) {
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002042 compStr = CompName->getNameStart();
Nate Begemanbb70bf62009-01-18 01:47:54 +00002043
2044 if (HexSwizzle)
Steve Narofff8fd09e2007-07-27 22:15:19 +00002045 compStr++;
Nate Begemanbb70bf62009-01-18 01:47:54 +00002046
2047 while (*compStr) {
2048 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
2049 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
2050 << baseType << SourceRange(CompLoc);
2051 return QualType();
2052 }
2053 }
Steve Narofff8fd09e2007-07-27 22:15:19 +00002054 }
Nate Begemanf322eab2008-05-09 06:41:27 +00002055
Nate Begemanbb70bf62009-01-18 01:47:54 +00002056 // If this is a halving swizzle, verify that the base type has an even
2057 // number of elements.
2058 if (HalvingSwizzle && (vecType->getNumElements() & 1U)) {
Chris Lattner3b054132008-11-19 05:08:23 +00002059 Diag(OpLoc, diag::err_ext_vector_component_requires_even)
Chris Lattner1e5665e2008-11-24 06:25:27 +00002060 << baseType << SourceRange(CompLoc);
Nate Begemanf322eab2008-05-09 06:41:27 +00002061 return QualType();
2062 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00002063
Steve Narofff8fd09e2007-07-27 22:15:19 +00002064 // The component accessor looks fine - now we need to compute the actual type.
Mike Stump4e1f26a2009-02-19 03:04:26 +00002065 // The vector type is implied by the component accessor. For example,
Steve Narofff8fd09e2007-07-27 22:15:19 +00002066 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begemanbb70bf62009-01-18 01:47:54 +00002067 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begemanf322eab2008-05-09 06:41:27 +00002068 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begemanbb70bf62009-01-18 01:47:54 +00002069 unsigned CompSize = HalvingSwizzle ? vecType->getNumElements() / 2
Anders Carlssonf571c112009-08-26 18:25:21 +00002070 : CompName->getLength();
Nate Begemanbb70bf62009-01-18 01:47:54 +00002071 if (HexSwizzle)
2072 CompSize--;
2073
Steve Narofff8fd09e2007-07-27 22:15:19 +00002074 if (CompSize == 1)
2075 return vecType->getElementType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00002076
Nate Begemance4d7fc2008-04-18 23:10:10 +00002077 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stump4e1f26a2009-02-19 03:04:26 +00002078 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemance4d7fc2008-04-18 23:10:10 +00002079 // diagostics look bad. We want extended vector types to appear built-in.
2080 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
2081 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
2082 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroffddf5a1d2007-07-29 16:33:31 +00002083 }
2084 return VT; // should never get here (a typedef type should always be found).
Steve Narofff8fd09e2007-07-27 22:15:19 +00002085}
2086
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002087static Decl *FindGetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
Anders Carlssonf571c112009-08-26 18:25:21 +00002088 IdentifierInfo *Member,
Douglas Gregorbcced4e2009-04-09 21:40:53 +00002089 const Selector &Sel,
2090 ASTContext &Context) {
Mike Stump11289f42009-09-09 15:08:12 +00002091
Anders Carlssonf571c112009-08-26 18:25:21 +00002092 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002093 return PD;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002094 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002095 return OMD;
Mike Stump11289f42009-09-09 15:08:12 +00002096
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002097 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
2098 E = PDecl->protocol_end(); I != E; ++I) {
Mike Stump11289f42009-09-09 15:08:12 +00002099 if (Decl *D = FindGetterNameDeclFromProtocolList(*I, Member, Sel,
Douglas Gregorbcced4e2009-04-09 21:40:53 +00002100 Context))
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002101 return D;
2102 }
2103 return 0;
2104}
2105
Steve Narofffb4330f2009-06-17 22:40:22 +00002106static Decl *FindGetterNameDecl(const ObjCObjectPointerType *QIdTy,
Anders Carlssonf571c112009-08-26 18:25:21 +00002107 IdentifierInfo *Member,
Douglas Gregorbcced4e2009-04-09 21:40:53 +00002108 const Selector &Sel,
2109 ASTContext &Context) {
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002110 // Check protocols on qualified interfaces.
2111 Decl *GDecl = 0;
Steve Narofffb4330f2009-06-17 22:40:22 +00002112 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002113 E = QIdTy->qual_end(); I != E; ++I) {
Anders Carlssonf571c112009-08-26 18:25:21 +00002114 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002115 GDecl = PD;
2116 break;
2117 }
2118 // Also must look for a getter name which uses property syntax.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002119 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002120 GDecl = OMD;
2121 break;
2122 }
2123 }
2124 if (!GDecl) {
Steve Narofffb4330f2009-06-17 22:40:22 +00002125 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002126 E = QIdTy->qual_end(); I != E; ++I) {
2127 // Search in the protocol-qualifier list of current protocol.
Douglas Gregorbcced4e2009-04-09 21:40:53 +00002128 GDecl = FindGetterNameDeclFromProtocolList(*I, Member, Sel, Context);
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002129 if (GDecl)
2130 return GDecl;
2131 }
2132 }
2133 return GDecl;
2134}
Chris Lattner4bf74fd2009-02-15 22:43:40 +00002135
John McCall10eae182009-11-30 22:42:35 +00002136Sema::OwningExprResult
John McCall2d74de92009-12-01 22:10:20 +00002137Sema::ActOnDependentMemberExpr(ExprArg Base, QualType BaseType,
2138 bool IsArrow, SourceLocation OpLoc,
John McCall10eae182009-11-30 22:42:35 +00002139 const CXXScopeSpec &SS,
2140 NamedDecl *FirstQualifierInScope,
2141 DeclarationName Name, SourceLocation NameLoc,
2142 const TemplateArgumentListInfo *TemplateArgs) {
2143 Expr *BaseExpr = Base.takeAs<Expr>();
2144
2145 // Even in dependent contexts, try to diagnose base expressions with
2146 // obviously wrong types, e.g.:
2147 //
2148 // T* t;
2149 // t.f;
2150 //
2151 // In Obj-C++, however, the above expression is valid, since it could be
2152 // accessing the 'f' property if T is an Obj-C interface. The extra check
2153 // allows this, while still reporting an error if T is a struct pointer.
2154 if (!IsArrow) {
John McCall2d74de92009-12-01 22:10:20 +00002155 const PointerType *PT = BaseType->getAs<PointerType>();
John McCall10eae182009-11-30 22:42:35 +00002156 if (PT && (!getLangOptions().ObjC1 ||
2157 PT->getPointeeType()->isRecordType())) {
John McCall2d74de92009-12-01 22:10:20 +00002158 assert(BaseExpr && "cannot happen with implicit member accesses");
John McCall10eae182009-11-30 22:42:35 +00002159 Diag(NameLoc, diag::err_typecheck_member_reference_struct_union)
John McCall2d74de92009-12-01 22:10:20 +00002160 << BaseType << BaseExpr->getSourceRange();
John McCall10eae182009-11-30 22:42:35 +00002161 return ExprError();
2162 }
2163 }
2164
John McCall2d74de92009-12-01 22:10:20 +00002165 assert(BaseType->isDependentType());
John McCall10eae182009-11-30 22:42:35 +00002166
2167 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
2168 // must have pointer type, and the accessed type is the pointee.
John McCall2d74de92009-12-01 22:10:20 +00002169 return Owned(CXXDependentScopeMemberExpr::Create(Context, BaseExpr, BaseType,
John McCall10eae182009-11-30 22:42:35 +00002170 IsArrow, OpLoc,
2171 static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
2172 SS.getRange(),
2173 FirstQualifierInScope,
2174 Name, NameLoc,
2175 TemplateArgs));
2176}
2177
2178/// We know that the given qualified member reference points only to
2179/// declarations which do not belong to the static type of the base
2180/// expression. Diagnose the problem.
2181static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
2182 Expr *BaseExpr,
2183 QualType BaseType,
John McCallcd4b4772009-12-02 03:53:29 +00002184 const CXXScopeSpec &SS,
John McCall10eae182009-11-30 22:42:35 +00002185 const LookupResult &R) {
John McCallcd4b4772009-12-02 03:53:29 +00002186 // If this is an implicit member access, use a different set of
2187 // diagnostics.
2188 if (!BaseExpr)
2189 return DiagnoseInstanceReference(SemaRef, SS, R);
John McCall10eae182009-11-30 22:42:35 +00002190
2191 // FIXME: this is an exceedingly lame diagnostic for some of the more
2192 // complicated cases here.
John McCallcd4b4772009-12-02 03:53:29 +00002193 DeclContext *DC = R.getRepresentativeDecl()->getDeclContext();
John McCall10eae182009-11-30 22:42:35 +00002194 SemaRef.Diag(R.getNameLoc(), diag::err_not_direct_base_or_virtual)
John McCallcd4b4772009-12-02 03:53:29 +00002195 << SS.getRange() << DC << BaseType;
John McCall10eae182009-11-30 22:42:35 +00002196}
2197
2198// Check whether the declarations we found through a nested-name
2199// specifier in a member expression are actually members of the base
2200// type. The restriction here is:
2201//
2202// C++ [expr.ref]p2:
2203// ... In these cases, the id-expression shall name a
2204// member of the class or of one of its base classes.
2205//
2206// So it's perfectly legitimate for the nested-name specifier to name
2207// an unrelated class, and for us to find an overload set including
2208// decls from classes which are not superclasses, as long as the decl
2209// we actually pick through overload resolution is from a superclass.
2210bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
2211 QualType BaseType,
John McCallcd4b4772009-12-02 03:53:29 +00002212 const CXXScopeSpec &SS,
John McCall10eae182009-11-30 22:42:35 +00002213 const LookupResult &R) {
John McCall2d74de92009-12-01 22:10:20 +00002214 const RecordType *BaseRT = BaseType->getAs<RecordType>();
2215 if (!BaseRT) {
2216 // We can't check this yet because the base type is still
2217 // dependent.
2218 assert(BaseType->isDependentType());
2219 return false;
2220 }
2221 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall10eae182009-11-30 22:42:35 +00002222
2223 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
John McCall2d74de92009-12-01 22:10:20 +00002224 // If this is an implicit member reference and we find a
2225 // non-instance member, it's not an error.
2226 if (!BaseExpr && !IsInstanceMember((*I)->getUnderlyingDecl()))
2227 return false;
John McCall10eae182009-11-30 22:42:35 +00002228
John McCall2d74de92009-12-01 22:10:20 +00002229 // Note that we use the DC of the decl, not the underlying decl.
2230 CXXRecordDecl *RecordD = cast<CXXRecordDecl>((*I)->getDeclContext());
2231 while (RecordD->isAnonymousStructOrUnion())
2232 RecordD = cast<CXXRecordDecl>(RecordD->getParent());
2233
2234 llvm::SmallPtrSet<CXXRecordDecl*,4> MemberRecord;
2235 MemberRecord.insert(RecordD->getCanonicalDecl());
2236
2237 if (!IsProvablyNotDerivedFrom(*this, BaseRecord, MemberRecord))
2238 return false;
2239 }
2240
John McCallcd4b4772009-12-02 03:53:29 +00002241 DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS, R);
John McCall2d74de92009-12-01 22:10:20 +00002242 return true;
2243}
2244
2245static bool
2246LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
2247 SourceRange BaseRange, const RecordType *RTy,
2248 SourceLocation OpLoc, const CXXScopeSpec &SS) {
2249 RecordDecl *RDecl = RTy->getDecl();
2250 if (SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
2251 PDiag(diag::err_typecheck_incomplete_tag)
2252 << BaseRange))
2253 return true;
2254
2255 DeclContext *DC = RDecl;
2256 if (SS.isSet()) {
2257 // If the member name was a qualified-id, look into the
2258 // nested-name-specifier.
2259 DC = SemaRef.computeDeclContext(SS, false);
2260
John McCallcd4b4772009-12-02 03:53:29 +00002261 if (SemaRef.RequireCompleteDeclContext(SS)) {
2262 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
2263 << SS.getRange() << DC;
2264 return true;
2265 }
2266
John McCall2d74de92009-12-01 22:10:20 +00002267 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
2268
2269 if (!isa<TypeDecl>(DC)) {
2270 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
2271 << DC << SS.getRange();
2272 return true;
John McCall10eae182009-11-30 22:42:35 +00002273 }
2274 }
2275
John McCall2d74de92009-12-01 22:10:20 +00002276 // The record definition is complete, now look up the member.
2277 SemaRef.LookupQualifiedName(R, DC);
John McCall10eae182009-11-30 22:42:35 +00002278
2279 return false;
2280}
2281
2282Sema::OwningExprResult
John McCall2d74de92009-12-01 22:10:20 +00002283Sema::BuildMemberReferenceExpr(ExprArg BaseArg, QualType BaseType,
John McCall10eae182009-11-30 22:42:35 +00002284 SourceLocation OpLoc, bool IsArrow,
2285 const CXXScopeSpec &SS,
2286 NamedDecl *FirstQualifierInScope,
2287 DeclarationName Name, SourceLocation NameLoc,
2288 const TemplateArgumentListInfo *TemplateArgs) {
2289 Expr *Base = BaseArg.takeAs<Expr>();
2290
John McCallcd4b4772009-12-02 03:53:29 +00002291 if (BaseType->isDependentType() ||
2292 (SS.isSet() && isDependentScopeSpecifier(SS)))
John McCall2d74de92009-12-01 22:10:20 +00002293 return ActOnDependentMemberExpr(ExprArg(*this, Base), BaseType,
John McCall10eae182009-11-30 22:42:35 +00002294 IsArrow, OpLoc,
2295 SS, FirstQualifierInScope,
2296 Name, NameLoc,
2297 TemplateArgs);
2298
2299 LookupResult R(*this, Name, NameLoc, LookupMemberName);
John McCall10eae182009-11-30 22:42:35 +00002300
John McCall2d74de92009-12-01 22:10:20 +00002301 // Implicit member accesses.
2302 if (!Base) {
2303 QualType RecordTy = BaseType;
2304 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
2305 if (LookupMemberExprInRecord(*this, R, SourceRange(),
2306 RecordTy->getAs<RecordType>(),
2307 OpLoc, SS))
2308 return ExprError();
2309
2310 // Explicit member accesses.
2311 } else {
2312 OwningExprResult Result =
2313 LookupMemberExpr(R, Base, IsArrow, OpLoc,
2314 SS, FirstQualifierInScope,
2315 /*ObjCImpDecl*/ DeclPtrTy());
2316
2317 if (Result.isInvalid()) {
2318 Owned(Base);
2319 return ExprError();
2320 }
2321
2322 if (Result.get())
2323 return move(Result);
John McCall10eae182009-11-30 22:42:35 +00002324 }
2325
John McCall2d74de92009-12-01 22:10:20 +00002326 return BuildMemberReferenceExpr(ExprArg(*this, Base), BaseType,
2327 OpLoc, IsArrow, SS, R, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00002328}
2329
2330Sema::OwningExprResult
John McCall2d74de92009-12-01 22:10:20 +00002331Sema::BuildMemberReferenceExpr(ExprArg Base, QualType BaseExprType,
2332 SourceLocation OpLoc, bool IsArrow,
2333 const CXXScopeSpec &SS,
John McCall10eae182009-11-30 22:42:35 +00002334 LookupResult &R,
2335 const TemplateArgumentListInfo *TemplateArgs) {
2336 Expr *BaseExpr = Base.takeAs<Expr>();
John McCall2d74de92009-12-01 22:10:20 +00002337 QualType BaseType = BaseExprType;
John McCall10eae182009-11-30 22:42:35 +00002338 if (IsArrow) {
2339 assert(BaseType->isPointerType());
2340 BaseType = BaseType->getAs<PointerType>()->getPointeeType();
2341 }
2342
2343 NestedNameSpecifier *Qualifier =
2344 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
2345 DeclarationName MemberName = R.getLookupName();
2346 SourceLocation MemberLoc = R.getNameLoc();
2347
2348 if (R.isAmbiguous())
Douglas Gregord8061562009-08-06 03:17:00 +00002349 return ExprError();
2350
John McCall10eae182009-11-30 22:42:35 +00002351 if (R.empty()) {
2352 // Rederive where we looked up.
2353 DeclContext *DC = (SS.isSet()
2354 ? computeDeclContext(SS, false)
2355 : BaseType->getAs<RecordType>()->getDecl());
Nate Begeman5ec4b312009-08-10 23:49:36 +00002356
John McCall10eae182009-11-30 22:42:35 +00002357 Diag(R.getNameLoc(), diag::err_no_member)
John McCall2d74de92009-12-01 22:10:20 +00002358 << MemberName << DC
2359 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
John McCall10eae182009-11-30 22:42:35 +00002360 return ExprError();
2361 }
2362
John McCallcd4b4772009-12-02 03:53:29 +00002363 // Diagnose qualified lookups that find only declarations from a
2364 // non-base type. Note that it's okay for lookup to find
2365 // declarations from a non-base type as long as those aren't the
2366 // ones picked by overload resolution.
2367 if (SS.isSet() && CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
John McCall10eae182009-11-30 22:42:35 +00002368 return ExprError();
2369
2370 // Construct an unresolved result if we in fact got an unresolved
2371 // result.
2372 if (R.isOverloadedResult() || R.isUnresolvableResult()) {
John McCall2d74de92009-12-01 22:10:20 +00002373 bool Dependent =
2374 R.isUnresolvableResult() ||
2375 UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(), TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00002376
2377 UnresolvedMemberExpr *MemExpr
2378 = UnresolvedMemberExpr::Create(Context, Dependent,
2379 R.isUnresolvableResult(),
John McCall2d74de92009-12-01 22:10:20 +00002380 BaseExpr, BaseExprType,
2381 IsArrow, OpLoc,
John McCall10eae182009-11-30 22:42:35 +00002382 Qualifier, SS.getRange(),
2383 MemberName, MemberLoc,
2384 TemplateArgs);
2385 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
2386 MemExpr->addDecl(*I);
2387
2388 return Owned(MemExpr);
2389 }
2390
2391 assert(R.isSingleResult());
2392 NamedDecl *MemberDecl = R.getFoundDecl();
2393
2394 // FIXME: diagnose the presence of template arguments now.
2395
2396 // If the decl being referenced had an error, return an error for this
2397 // sub-expr without emitting another error, in order to avoid cascading
2398 // error cases.
2399 if (MemberDecl->isInvalidDecl())
2400 return ExprError();
2401
John McCall2d74de92009-12-01 22:10:20 +00002402 // Handle the implicit-member-access case.
2403 if (!BaseExpr) {
2404 // If this is not an instance member, convert to a non-member access.
2405 if (!IsInstanceMember(MemberDecl))
2406 return BuildDeclarationNameExpr(SS, R.getNameLoc(), MemberDecl);
2407
2408 BaseExpr = new (Context) CXXThisExpr(SourceLocation(), BaseExprType);
2409 }
2410
John McCall10eae182009-11-30 22:42:35 +00002411 bool ShouldCheckUse = true;
2412 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
2413 // Don't diagnose the use of a virtual member function unless it's
2414 // explicitly qualified.
2415 if (MD->isVirtual() && !SS.isSet())
2416 ShouldCheckUse = false;
2417 }
2418
2419 // Check the use of this member.
2420 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc)) {
2421 Owned(BaseExpr);
2422 return ExprError();
2423 }
2424
2425 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
2426 // We may have found a field within an anonymous union or struct
2427 // (C++ [class.union]).
Eli Friedman78cde142009-12-04 07:18:51 +00002428 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion() &&
2429 !BaseType->getAs<RecordType>()->getDecl()->isAnonymousStructOrUnion())
John McCall10eae182009-11-30 22:42:35 +00002430 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
2431 BaseExpr, OpLoc);
2432
2433 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
2434 QualType MemberType = FD->getType();
2435 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>())
2436 MemberType = Ref->getPointeeType();
2437 else {
2438 Qualifiers BaseQuals = BaseType.getQualifiers();
2439 BaseQuals.removeObjCGCAttr();
2440 if (FD->isMutable()) BaseQuals.removeConst();
2441
2442 Qualifiers MemberQuals
2443 = Context.getCanonicalType(MemberType).getQualifiers();
2444
2445 Qualifiers Combined = BaseQuals + MemberQuals;
2446 if (Combined != MemberQuals)
2447 MemberType = Context.getQualifiedType(MemberType, Combined);
2448 }
2449
2450 MarkDeclarationReferenced(MemberLoc, FD);
2451 if (PerformObjectMemberConversion(BaseExpr, FD))
2452 return ExprError();
2453 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
2454 FD, MemberLoc, MemberType));
2455 }
2456
2457 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
2458 MarkDeclarationReferenced(MemberLoc, Var);
2459 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
2460 Var, MemberLoc,
2461 Var->getType().getNonReferenceType()));
2462 }
2463
2464 if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl)) {
2465 MarkDeclarationReferenced(MemberLoc, MemberDecl);
2466 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
2467 MemberFn, MemberLoc,
2468 MemberFn->getType()));
2469 }
2470
2471 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
2472 MarkDeclarationReferenced(MemberLoc, MemberDecl);
2473 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
2474 Enum, MemberLoc, Enum->getType()));
2475 }
2476
2477 Owned(BaseExpr);
2478
2479 if (isa<TypeDecl>(MemberDecl))
2480 return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
2481 << MemberName << int(IsArrow));
2482
2483 // We found a declaration kind that we didn't expect. This is a
2484 // generic error message that tells the user that she can't refer
2485 // to this member with '.' or '->'.
2486 return ExprError(Diag(MemberLoc,
2487 diag::err_typecheck_member_reference_unknown)
2488 << MemberName << int(IsArrow));
2489}
2490
2491/// Look up the given member of the given non-type-dependent
2492/// expression. This can return in one of two ways:
2493/// * If it returns a sentinel null-but-valid result, the caller will
2494/// assume that lookup was performed and the results written into
2495/// the provided structure. It will take over from there.
2496/// * Otherwise, the returned expression will be produced in place of
2497/// an ordinary member expression.
2498///
2499/// The ObjCImpDecl bit is a gross hack that will need to be properly
2500/// fixed for ObjC++.
2501Sema::OwningExprResult
2502Sema::LookupMemberExpr(LookupResult &R, Expr *&BaseExpr,
John McCalla928c652009-12-07 22:46:59 +00002503 bool &IsArrow, SourceLocation OpLoc,
John McCall10eae182009-11-30 22:42:35 +00002504 const CXXScopeSpec &SS,
2505 NamedDecl *FirstQualifierInScope,
2506 DeclPtrTy ObjCImpDecl) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00002507 assert(BaseExpr && "no base expression");
Mike Stump11289f42009-09-09 15:08:12 +00002508
Steve Naroffeaaae462007-12-16 21:42:28 +00002509 // Perform default conversions.
2510 DefaultFunctionArrayConversion(BaseExpr);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002511
Steve Naroff185616f2007-07-26 03:11:44 +00002512 QualType BaseType = BaseExpr->getType();
John McCall10eae182009-11-30 22:42:35 +00002513 assert(!BaseType->isDependentType());
2514
2515 DeclarationName MemberName = R.getLookupName();
2516 SourceLocation MemberLoc = R.getNameLoc();
Douglas Gregord82ae382009-11-06 06:30:47 +00002517
2518 // If the user is trying to apply -> or . to a function pointer
John McCall10eae182009-11-30 22:42:35 +00002519 // type, it's probably because they forgot parentheses to call that
Douglas Gregord82ae382009-11-06 06:30:47 +00002520 // function. Suggest the addition of those parentheses, build the
2521 // call, and continue on.
2522 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
2523 if (const FunctionProtoType *Fun
2524 = Ptr->getPointeeType()->getAs<FunctionProtoType>()) {
2525 QualType ResultTy = Fun->getResultType();
2526 if (Fun->getNumArgs() == 0 &&
John McCall10eae182009-11-30 22:42:35 +00002527 ((!IsArrow && ResultTy->isRecordType()) ||
2528 (IsArrow && ResultTy->isPointerType() &&
Douglas Gregord82ae382009-11-06 06:30:47 +00002529 ResultTy->getAs<PointerType>()->getPointeeType()
2530 ->isRecordType()))) {
2531 SourceLocation Loc = PP.getLocForEndOfToken(BaseExpr->getLocEnd());
2532 Diag(Loc, diag::err_member_reference_needs_call)
2533 << QualType(Fun, 0)
2534 << CodeModificationHint::CreateInsertion(Loc, "()");
2535
2536 OwningExprResult NewBase
John McCall10eae182009-11-30 22:42:35 +00002537 = ActOnCallExpr(0, ExprArg(*this, BaseExpr), Loc,
Douglas Gregord82ae382009-11-06 06:30:47 +00002538 MultiExprArg(*this, 0, 0), 0, Loc);
2539 if (NewBase.isInvalid())
John McCall10eae182009-11-30 22:42:35 +00002540 return ExprError();
Douglas Gregord82ae382009-11-06 06:30:47 +00002541
2542 BaseExpr = NewBase.takeAs<Expr>();
2543 DefaultFunctionArrayConversion(BaseExpr);
2544 BaseType = BaseExpr->getType();
2545 }
2546 }
2547 }
2548
David Chisnall9f57c292009-08-17 16:35:33 +00002549 // If this is an Objective-C pseudo-builtin and a definition is provided then
2550 // use that.
2551 if (BaseType->isObjCIdType()) {
Fariborz Jahanianc2949f92009-12-07 20:09:25 +00002552 if (IsArrow) {
2553 // Handle the following exceptional case PObj->isa.
2554 if (const ObjCObjectPointerType *OPT =
2555 BaseType->getAs<ObjCObjectPointerType>()) {
2556 if (OPT->getPointeeType()->isSpecificBuiltinType(BuiltinType::ObjCId) &&
2557 MemberName.getAsIdentifierInfo()->isStr("isa"))
Fariborz Jahaniana5fee262009-12-09 19:05:56 +00002558 return Owned(new (Context) ObjCIsaExpr(BaseExpr, true, MemberLoc,
2559 Context.getObjCClassType()));
Fariborz Jahanianc2949f92009-12-07 20:09:25 +00002560 }
2561 }
David Chisnall9f57c292009-08-17 16:35:33 +00002562 // We have an 'id' type. Rather than fall through, we check if this
2563 // is a reference to 'isa'.
2564 if (BaseType != Context.ObjCIdRedefinitionType) {
2565 BaseType = Context.ObjCIdRedefinitionType;
Eli Friedman06ed2a52009-10-20 08:27:19 +00002566 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
David Chisnall9f57c292009-08-17 16:35:33 +00002567 }
David Chisnall9f57c292009-08-17 16:35:33 +00002568 }
John McCall10eae182009-11-30 22:42:35 +00002569
Fariborz Jahanian04b258c2009-11-25 23:07:42 +00002570 // If this is an Objective-C pseudo-builtin and a definition is provided then
2571 // use that.
2572 if (Context.isObjCSelType(BaseType)) {
2573 // We have an 'SEL' type. Rather than fall through, we check if this
2574 // is a reference to 'sel_id'.
2575 if (BaseType != Context.ObjCSelRedefinitionType) {
2576 BaseType = Context.ObjCSelRedefinitionType;
2577 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
2578 }
2579 }
John McCall10eae182009-11-30 22:42:35 +00002580
Steve Naroff185616f2007-07-26 03:11:44 +00002581 assert(!BaseType.isNull() && "no type for member expression");
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002582
Fariborz Jahaniane983d172009-09-22 16:48:37 +00002583 // Handle properties on ObjC 'Class' types.
John McCall10eae182009-11-30 22:42:35 +00002584 if (!IsArrow && BaseType->isObjCClassType()) {
Fariborz Jahaniane983d172009-09-22 16:48:37 +00002585 // Also must look for a getter name which uses property syntax.
2586 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
2587 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
2588 if (ObjCMethodDecl *MD = getCurMethodDecl()) {
2589 ObjCInterfaceDecl *IFace = MD->getClassInterface();
2590 ObjCMethodDecl *Getter;
2591 // FIXME: need to also look locally in the implementation.
2592 if ((Getter = IFace->lookupClassMethod(Sel))) {
2593 // Check the use of this method.
2594 if (DiagnoseUseOfDecl(Getter, MemberLoc))
2595 return ExprError();
2596 }
2597 // If we found a getter then this may be a valid dot-reference, we
2598 // will look for the matching setter, in case it is needed.
2599 Selector SetterSel =
2600 SelectorTable::constructSetterName(PP.getIdentifierTable(),
2601 PP.getSelectorTable(), Member);
2602 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
2603 if (!Setter) {
2604 // If this reference is in an @implementation, also check for 'private'
2605 // methods.
Steve Naroffbb69c942009-10-01 23:46:04 +00002606 Setter = IFace->lookupPrivateInstanceMethod(SetterSel);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00002607 }
2608 // Look through local category implementations associated with the class.
2609 if (!Setter)
2610 Setter = IFace->getCategoryClassMethod(SetterSel);
2611
2612 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2613 return ExprError();
2614
2615 if (Getter || Setter) {
2616 QualType PType;
2617
2618 if (Getter)
2619 PType = Getter->getResultType();
2620 else
2621 // Get the expression type from Setter's incoming parameter.
2622 PType = (*(Setter->param_end() -1))->getType();
2623 // FIXME: we must check that the setter has property type.
2624 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter,
2625 PType,
2626 Setter, MemberLoc, BaseExpr));
2627 }
2628 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
2629 << MemberName << BaseType);
2630 }
2631 }
2632
2633 if (BaseType->isObjCClassType() &&
2634 BaseType != Context.ObjCClassRedefinitionType) {
2635 BaseType = Context.ObjCClassRedefinitionType;
Eli Friedman06ed2a52009-10-20 08:27:19 +00002636 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00002637 }
Mike Stump11289f42009-09-09 15:08:12 +00002638
John McCall10eae182009-11-30 22:42:35 +00002639 if (IsArrow) {
2640 if (const PointerType *PT = BaseType->getAs<PointerType>())
Steve Naroff185616f2007-07-26 03:11:44 +00002641 BaseType = PT->getPointeeType();
Steve Naroff7cae42b2009-07-10 23:34:53 +00002642 else if (BaseType->isObjCObjectPointerType())
2643 ;
John McCalla928c652009-12-07 22:46:59 +00002644 else if (BaseType->isRecordType()) {
2645 // Recover from arrow accesses to records, e.g.:
2646 // struct MyRecord foo;
2647 // foo->bar
2648 // This is actually well-formed in C++ if MyRecord has an
2649 // overloaded operator->, but that should have been dealt with
2650 // by now.
2651 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
2652 << BaseType << int(IsArrow) << BaseExpr->getSourceRange()
2653 << CodeModificationHint::CreateReplacement(OpLoc, ".");
2654 IsArrow = false;
2655 } else {
John McCall10eae182009-11-30 22:42:35 +00002656 Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
2657 << BaseType << BaseExpr->getSourceRange();
2658 return ExprError();
Anders Carlsson524d5a42009-05-16 20:31:20 +00002659 }
John McCalla928c652009-12-07 22:46:59 +00002660 } else {
2661 // Recover from dot accesses to pointers, e.g.:
2662 // type *foo;
2663 // foo.bar
2664 // This is actually well-formed in two cases:
2665 // - 'type' is an Objective C type
2666 // - 'bar' is a pseudo-destructor name which happens to refer to
2667 // the appropriate pointer type
2668 if (MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
2669 const PointerType *PT = BaseType->getAs<PointerType>();
2670 if (PT && PT->getPointeeType()->isRecordType()) {
2671 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
2672 << BaseType << int(IsArrow) << BaseExpr->getSourceRange()
2673 << CodeModificationHint::CreateReplacement(OpLoc, "->");
2674 BaseType = PT->getPointeeType();
2675 IsArrow = true;
2676 }
2677 }
John McCall10eae182009-11-30 22:42:35 +00002678 }
John McCalla928c652009-12-07 22:46:59 +00002679
John McCall10eae182009-11-30 22:42:35 +00002680 // Handle field access to simple records. This also handles access
2681 // to fields of the ObjC 'id' struct.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002682 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
John McCall2d74de92009-12-01 22:10:20 +00002683 if (LookupMemberExprInRecord(*this, R, BaseExpr->getSourceRange(),
2684 RTy, OpLoc, SS))
Douglas Gregordd430f72009-01-19 19:26:10 +00002685 return ExprError();
John McCall10eae182009-11-30 22:42:35 +00002686 return Owned((Expr*) 0);
Chris Lattnerb63a7452008-07-21 04:28:12 +00002687 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002688
Douglas Gregorad8a3362009-09-04 17:36:40 +00002689 // Handle pseudo-destructors (C++ [expr.pseudo]). Since anything referring
2690 // into a record type was handled above, any destructor we see here is a
2691 // pseudo-destructor.
2692 if (MemberName.getNameKind() == DeclarationName::CXXDestructorName) {
2693 // C++ [expr.pseudo]p2:
Mike Stump11289f42009-09-09 15:08:12 +00002694 // The left hand side of the dot operator shall be of scalar type. The
2695 // left hand side of the arrow operator shall be of pointer to scalar
Douglas Gregorad8a3362009-09-04 17:36:40 +00002696 // type.
2697 if (!BaseType->isScalarType())
2698 return Owned(Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
2699 << BaseType << BaseExpr->getSourceRange());
Mike Stump11289f42009-09-09 15:08:12 +00002700
Douglas Gregorad8a3362009-09-04 17:36:40 +00002701 // [...] The type designated by the pseudo-destructor-name shall be the
2702 // same as the object type.
2703 if (!MemberName.getCXXNameType()->isDependentType() &&
2704 !Context.hasSameUnqualifiedType(BaseType, MemberName.getCXXNameType()))
2705 return Owned(Diag(OpLoc, diag::err_pseudo_dtor_type_mismatch)
2706 << BaseType << MemberName.getCXXNameType()
2707 << BaseExpr->getSourceRange() << SourceRange(MemberLoc));
Mike Stump11289f42009-09-09 15:08:12 +00002708
2709 // [...] Furthermore, the two type-names in a pseudo-destructor-name of
Douglas Gregorad8a3362009-09-04 17:36:40 +00002710 // the form
2711 //
Mike Stump11289f42009-09-09 15:08:12 +00002712 // ::[opt] nested-name-specifier[opt] type-name :: ̃ type-name
2713 //
Douglas Gregorad8a3362009-09-04 17:36:40 +00002714 // shall designate the same scalar type.
2715 //
2716 // FIXME: DPG can't see any way to trigger this particular clause, so it
2717 // isn't checked here.
Mike Stump11289f42009-09-09 15:08:12 +00002718
Douglas Gregorad8a3362009-09-04 17:36:40 +00002719 // FIXME: We've lost the precise spelling of the type by going through
2720 // DeclarationName. Can we do better?
2721 return Owned(new (Context) CXXPseudoDestructorExpr(Context, BaseExpr,
John McCall10eae182009-11-30 22:42:35 +00002722 IsArrow, OpLoc,
2723 (NestedNameSpecifier *) SS.getScopeRep(),
2724 SS.getRange(),
Douglas Gregorad8a3362009-09-04 17:36:40 +00002725 MemberName.getCXXNameType(),
2726 MemberLoc));
2727 }
Mike Stump11289f42009-09-09 15:08:12 +00002728
Chris Lattnerdc420f42008-07-21 04:59:05 +00002729 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
2730 // (*Obj).ivar.
John McCall10eae182009-11-30 22:42:35 +00002731 if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
2732 (!IsArrow && BaseType->isObjCInterfaceType())) {
John McCall9dd450b2009-09-21 23:43:11 +00002733 const ObjCObjectPointerType *OPT = BaseType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00002734 const ObjCInterfaceType *IFaceT =
John McCall9dd450b2009-09-21 23:43:11 +00002735 OPT ? OPT->getInterfaceType() : BaseType->getAs<ObjCInterfaceType>();
Steve Naroffa057ba92009-07-16 00:25:06 +00002736 if (IFaceT) {
Anders Carlssonf571c112009-08-26 18:25:21 +00002737 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
2738
Steve Naroffa057ba92009-07-16 00:25:06 +00002739 ObjCInterfaceDecl *IDecl = IFaceT->getDecl();
2740 ObjCInterfaceDecl *ClassDeclared;
Anders Carlssonf571c112009-08-26 18:25:21 +00002741 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
Mike Stump11289f42009-09-09 15:08:12 +00002742
Steve Naroffa057ba92009-07-16 00:25:06 +00002743 if (IV) {
2744 // If the decl being referenced had an error, return an error for this
2745 // sub-expr without emitting another error, in order to avoid cascading
2746 // error cases.
2747 if (IV->isInvalidDecl())
2748 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00002749
Steve Naroffa057ba92009-07-16 00:25:06 +00002750 // Check whether we can reference this field.
2751 if (DiagnoseUseOfDecl(IV, MemberLoc))
2752 return ExprError();
2753 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
2754 IV->getAccessControl() != ObjCIvarDecl::Package) {
2755 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
2756 if (ObjCMethodDecl *MD = getCurMethodDecl())
2757 ClassOfMethodDecl = MD->getClassInterface();
2758 else if (ObjCImpDecl && getCurFunctionDecl()) {
2759 // Case of a c-function declared inside an objc implementation.
2760 // FIXME: For a c-style function nested inside an objc implementation
2761 // class, there is no implementation context available, so we pass
2762 // down the context as argument to this routine. Ideally, this context
2763 // need be passed down in the AST node and somehow calculated from the
2764 // AST for a function decl.
2765 Decl *ImplDecl = ObjCImpDecl.getAs<Decl>();
Mike Stump11289f42009-09-09 15:08:12 +00002766 if (ObjCImplementationDecl *IMPD =
Steve Naroffa057ba92009-07-16 00:25:06 +00002767 dyn_cast<ObjCImplementationDecl>(ImplDecl))
2768 ClassOfMethodDecl = IMPD->getClassInterface();
2769 else if (ObjCCategoryImplDecl* CatImplClass =
2770 dyn_cast<ObjCCategoryImplDecl>(ImplDecl))
2771 ClassOfMethodDecl = CatImplClass->getClassInterface();
2772 }
Mike Stump11289f42009-09-09 15:08:12 +00002773
2774 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
2775 if (ClassDeclared != IDecl ||
Steve Naroffa057ba92009-07-16 00:25:06 +00002776 ClassOfMethodDecl != ClassDeclared)
Mike Stump11289f42009-09-09 15:08:12 +00002777 Diag(MemberLoc, diag::error_private_ivar_access)
Steve Naroffa057ba92009-07-16 00:25:06 +00002778 << IV->getDeclName();
Mike Stump12b8ce12009-08-04 21:02:39 +00002779 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
2780 // @protected
Mike Stump11289f42009-09-09 15:08:12 +00002781 Diag(MemberLoc, diag::error_protected_ivar_access)
Steve Naroffa057ba92009-07-16 00:25:06 +00002782 << IV->getDeclName();
Steve Naroffd1b64be2009-03-04 18:34:24 +00002783 }
Steve Naroffa057ba92009-07-16 00:25:06 +00002784
2785 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
2786 MemberLoc, BaseExpr,
John McCall10eae182009-11-30 22:42:35 +00002787 IsArrow));
Fariborz Jahaniana458c4f2009-03-03 01:21:12 +00002788 }
Steve Naroffa057ba92009-07-16 00:25:06 +00002789 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
Anders Carlssonf571c112009-08-26 18:25:21 +00002790 << IDecl->getDeclName() << MemberName
Steve Naroffa057ba92009-07-16 00:25:06 +00002791 << BaseExpr->getSourceRange());
Fariborz Jahanianb1378f92008-12-13 22:20:28 +00002792 }
Chris Lattnerb63a7452008-07-21 04:28:12 +00002793 }
Steve Naroff1329fa02009-07-15 18:40:39 +00002794 // Handle properties on 'id' and qualified "id".
John McCall10eae182009-11-30 22:42:35 +00002795 if (!IsArrow && (BaseType->isObjCIdType() ||
2796 BaseType->isObjCQualifiedIdType())) {
John McCall9dd450b2009-09-21 23:43:11 +00002797 const ObjCObjectPointerType *QIdTy = BaseType->getAs<ObjCObjectPointerType>();
Anders Carlssonf571c112009-08-26 18:25:21 +00002798 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Mike Stump11289f42009-09-09 15:08:12 +00002799
Steve Naroff7cae42b2009-07-10 23:34:53 +00002800 // Check protocols on qualified interfaces.
Anders Carlssonf571c112009-08-26 18:25:21 +00002801 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002802 if (Decl *PMDecl = FindGetterNameDecl(QIdTy, Member, Sel, Context)) {
2803 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
2804 // Check the use of this declaration
2805 if (DiagnoseUseOfDecl(PD, MemberLoc))
2806 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00002807
Steve Naroff7cae42b2009-07-10 23:34:53 +00002808 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
2809 MemberLoc, BaseExpr));
2810 }
2811 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
2812 // Check the use of this method.
2813 if (DiagnoseUseOfDecl(OMD, MemberLoc))
2814 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00002815
Steve Naroff7cae42b2009-07-10 23:34:53 +00002816 return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel,
Mike Stump11289f42009-09-09 15:08:12 +00002817 OMD->getResultType(),
2818 OMD, OpLoc, MemberLoc,
Steve Naroff7cae42b2009-07-10 23:34:53 +00002819 NULL, 0));
2820 }
2821 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002822
Steve Naroff7cae42b2009-07-10 23:34:53 +00002823 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlssonf571c112009-08-26 18:25:21 +00002824 << MemberName << BaseType);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002825 }
Chris Lattnerdc420f42008-07-21 04:59:05 +00002826 // Handle Objective-C property access, which is "Obj.property" where Obj is a
2827 // pointer to a (potentially qualified) interface type.
Steve Naroff7cae42b2009-07-10 23:34:53 +00002828 const ObjCObjectPointerType *OPT;
John McCall10eae182009-11-30 22:42:35 +00002829 if (!IsArrow && (OPT = BaseType->getAsObjCInterfacePointerType())) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002830 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
2831 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
Anders Carlssonf571c112009-08-26 18:25:21 +00002832 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Mike Stump11289f42009-09-09 15:08:12 +00002833
Daniel Dunbaref89086c2008-09-03 01:05:41 +00002834 // Search for a declared property first.
Anders Carlssonf571c112009-08-26 18:25:21 +00002835 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00002836 // Check whether we can reference this property.
2837 if (DiagnoseUseOfDecl(PD, MemberLoc))
2838 return ExprError();
Fariborz Jahanianb2ab73d2009-05-08 19:36:34 +00002839 QualType ResTy = PD->getType();
Anders Carlssonf571c112009-08-26 18:25:21 +00002840 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002841 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Fariborz Jahanianfe9e3942009-05-08 20:20:55 +00002842 if (DiagnosePropertyAccessorMismatch(PD, Getter, MemberLoc))
2843 ResTy = Getter->getResultType();
Fariborz Jahanianb2ab73d2009-05-08 19:36:34 +00002844 return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
Chris Lattner43df5562009-02-16 18:35:08 +00002845 MemberLoc, BaseExpr));
2846 }
Daniel Dunbaref89086c2008-09-03 01:05:41 +00002847 // Check protocols on qualified interfaces.
Steve Naroffaccc4882009-07-20 17:56:53 +00002848 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
2849 E = OPT->qual_end(); I != E; ++I)
Anders Carlssonf571c112009-08-26 18:25:21 +00002850 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00002851 // Check whether we can reference this property.
2852 if (DiagnoseUseOfDecl(PD, MemberLoc))
2853 return ExprError();
Chris Lattner43df5562009-02-16 18:35:08 +00002854
Steve Narofff6009ed2009-01-21 00:14:39 +00002855 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner43df5562009-02-16 18:35:08 +00002856 MemberLoc, BaseExpr));
2857 }
Daniel Dunbaref89086c2008-09-03 01:05:41 +00002858 // If that failed, look for an "implicit" property by seeing if the nullary
2859 // selector is implemented.
2860
2861 // FIXME: The logic for looking up nullary and unary selectors should be
2862 // shared with the code in ActOnInstanceMessage.
2863
Anders Carlssonf571c112009-08-26 18:25:21 +00002864 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002865 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002866
Daniel Dunbaref89086c2008-09-03 01:05:41 +00002867 // If this reference is in an @implementation, check for 'private' methods.
2868 if (!Getter)
Steve Naroffbb69c942009-10-01 23:46:04 +00002869 Getter = IFace->lookupPrivateInstanceMethod(Sel);
Daniel Dunbaref89086c2008-09-03 01:05:41 +00002870
Steve Naroff1df62692008-10-22 19:16:27 +00002871 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1559d67b2009-07-21 00:06:20 +00002872 if (!Getter)
2873 Getter = IFace->getCategoryInstanceMethod(Sel);
Daniel Dunbaref89086c2008-09-03 01:05:41 +00002874 if (Getter) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00002875 // Check if we can reference this property.
2876 if (DiagnoseUseOfDecl(Getter, MemberLoc))
2877 return ExprError();
Steve Naroff1d984fe2009-03-11 13:48:17 +00002878 }
2879 // If we found a getter then this may be a valid dot-reference, we
2880 // will look for the matching setter, in case it is needed.
Mike Stump11289f42009-09-09 15:08:12 +00002881 Selector SetterSel =
2882 SelectorTable::constructSetterName(PP.getIdentifierTable(),
Anders Carlssonf571c112009-08-26 18:25:21 +00002883 PP.getSelectorTable(), Member);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002884 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
Steve Naroff1d984fe2009-03-11 13:48:17 +00002885 if (!Setter) {
2886 // If this reference is in an @implementation, also check for 'private'
2887 // methods.
Steve Naroffbb69c942009-10-01 23:46:04 +00002888 Setter = IFace->lookupPrivateInstanceMethod(SetterSel);
Steve Naroff1d984fe2009-03-11 13:48:17 +00002889 }
2890 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1559d67b2009-07-21 00:06:20 +00002891 if (!Setter)
2892 Setter = IFace->getCategoryInstanceMethod(SetterSel);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002893
Steve Naroff1d984fe2009-03-11 13:48:17 +00002894 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2895 return ExprError();
2896
2897 if (Getter || Setter) {
2898 QualType PType;
2899
2900 if (Getter)
2901 PType = Getter->getResultType();
Fariborz Jahanian88cc2342009-08-18 20:50:23 +00002902 else
2903 // Get the expression type from Setter's incoming parameter.
2904 PType = (*(Setter->param_end() -1))->getType();
Steve Naroff1d984fe2009-03-11 13:48:17 +00002905 // FIXME: we must check that the setter has property type.
Fariborz Jahanian9a846652009-08-20 17:02:02 +00002906 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter, PType,
Steve Naroff1d984fe2009-03-11 13:48:17 +00002907 Setter, MemberLoc, BaseExpr));
2908 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002909 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlssonf571c112009-08-26 18:25:21 +00002910 << MemberName << BaseType);
Fariborz Jahanian21f54ee2007-11-12 22:29:28 +00002911 }
Mike Stump11289f42009-09-09 15:08:12 +00002912
Steve Naroffe87026a2009-07-24 17:54:45 +00002913 // Handle the following exceptional case (*Obj).isa.
John McCall10eae182009-11-30 22:42:35 +00002914 if (!IsArrow &&
Steve Naroffe87026a2009-07-24 17:54:45 +00002915 BaseType->isSpecificBuiltinType(BuiltinType::ObjCId) &&
Anders Carlssonf571c112009-08-26 18:25:21 +00002916 MemberName.getAsIdentifierInfo()->isStr("isa"))
Steve Naroffe87026a2009-07-24 17:54:45 +00002917 return Owned(new (Context) ObjCIsaExpr(BaseExpr, false, MemberLoc,
Fariborz Jahaniana5fee262009-12-09 19:05:56 +00002918 Context.getObjCClassType()));
Steve Naroffe87026a2009-07-24 17:54:45 +00002919
Chris Lattnerb63a7452008-07-21 04:28:12 +00002920 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner6c7ce102009-02-16 21:11:58 +00002921 if (BaseType->isExtVectorType()) {
Anders Carlssonf571c112009-08-26 18:25:21 +00002922 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Chris Lattnerb63a7452008-07-21 04:28:12 +00002923 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
2924 if (ret.isNull())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002925 return ExprError();
Anders Carlssonf571c112009-08-26 18:25:21 +00002926 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, *Member,
Steve Narofff6009ed2009-01-21 00:14:39 +00002927 MemberLoc));
Chris Lattnerb63a7452008-07-21 04:28:12 +00002928 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002929
Douglas Gregor0b08ba42009-03-27 06:00:30 +00002930 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
2931 << BaseType << BaseExpr->getSourceRange();
2932
Douglas Gregor0b08ba42009-03-27 06:00:30 +00002933 return ExprError();
Chris Lattnere168f762006-11-10 05:29:30 +00002934}
2935
John McCall10eae182009-11-30 22:42:35 +00002936static Sema::OwningExprResult DiagnoseDtorReference(Sema &SemaRef,
2937 SourceLocation NameLoc,
2938 Sema::ExprArg MemExpr) {
2939 Expr *E = (Expr *) MemExpr.get();
2940 SourceLocation ExpectedLParenLoc = SemaRef.PP.getLocForEndOfToken(NameLoc);
2941 SemaRef.Diag(E->getLocStart(), diag::err_dtor_expr_without_call)
Douglas Gregor30d60cb2009-11-03 19:44:04 +00002942 << isa<CXXPseudoDestructorExpr>(E)
2943 << CodeModificationHint::CreateInsertion(ExpectedLParenLoc, "()");
2944
John McCall10eae182009-11-30 22:42:35 +00002945 return SemaRef.ActOnCallExpr(/*Scope*/ 0,
2946 move(MemExpr),
2947 /*LPLoc*/ ExpectedLParenLoc,
2948 Sema::MultiExprArg(SemaRef, 0, 0),
2949 /*CommaLocs*/ 0,
2950 /*RPLoc*/ ExpectedLParenLoc);
2951}
2952
2953/// The main callback when the parser finds something like
2954/// expression . [nested-name-specifier] identifier
2955/// expression -> [nested-name-specifier] identifier
2956/// where 'identifier' encompasses a fairly broad spectrum of
2957/// possibilities, including destructor and operator references.
2958///
2959/// \param OpKind either tok::arrow or tok::period
2960/// \param HasTrailingLParen whether the next token is '(', which
2961/// is used to diagnose mis-uses of special members that can
2962/// only be called
2963/// \param ObjCImpDecl the current ObjC @implementation decl;
2964/// this is an ugly hack around the fact that ObjC @implementations
2965/// aren't properly put in the context chain
2966Sema::OwningExprResult Sema::ActOnMemberAccessExpr(Scope *S, ExprArg BaseArg,
2967 SourceLocation OpLoc,
2968 tok::TokenKind OpKind,
2969 const CXXScopeSpec &SS,
2970 UnqualifiedId &Id,
2971 DeclPtrTy ObjCImpDecl,
2972 bool HasTrailingLParen) {
2973 if (SS.isSet() && SS.isInvalid())
2974 return ExprError();
2975
2976 TemplateArgumentListInfo TemplateArgsBuffer;
2977
2978 // Decompose the name into its component parts.
2979 DeclarationName Name;
2980 SourceLocation NameLoc;
2981 const TemplateArgumentListInfo *TemplateArgs;
2982 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer,
2983 Name, NameLoc, TemplateArgs);
2984
2985 bool IsArrow = (OpKind == tok::arrow);
2986
2987 NamedDecl *FirstQualifierInScope
2988 = (!SS.isSet() ? 0 : FindFirstQualifierInScope(S,
2989 static_cast<NestedNameSpecifier*>(SS.getScopeRep())));
2990
2991 // This is a postfix expression, so get rid of ParenListExprs.
2992 BaseArg = MaybeConvertParenListExprToParenExpr(S, move(BaseArg));
2993
2994 Expr *Base = BaseArg.takeAs<Expr>();
2995 OwningExprResult Result(*this);
2996 if (Base->getType()->isDependentType()) {
John McCall2d74de92009-12-01 22:10:20 +00002997 Result = ActOnDependentMemberExpr(ExprArg(*this, Base), Base->getType(),
John McCall10eae182009-11-30 22:42:35 +00002998 IsArrow, OpLoc,
2999 SS, FirstQualifierInScope,
3000 Name, NameLoc,
3001 TemplateArgs);
3002 } else {
3003 LookupResult R(*this, Name, NameLoc, LookupMemberName);
3004 if (TemplateArgs) {
3005 // Re-use the lookup done for the template name.
3006 DecomposeTemplateName(R, Id);
3007 } else {
3008 Result = LookupMemberExpr(R, Base, IsArrow, OpLoc,
3009 SS, FirstQualifierInScope,
3010 ObjCImpDecl);
3011
3012 if (Result.isInvalid()) {
3013 Owned(Base);
3014 return ExprError();
3015 }
3016
3017 if (Result.get()) {
3018 // The only way a reference to a destructor can be used is to
3019 // immediately call it, which falls into this case. If the
3020 // next token is not a '(', produce a diagnostic and build the
3021 // call now.
3022 if (!HasTrailingLParen &&
3023 Id.getKind() == UnqualifiedId::IK_DestructorName)
3024 return DiagnoseDtorReference(*this, NameLoc, move(Result));
3025
3026 return move(Result);
3027 }
3028 }
3029
John McCall2d74de92009-12-01 22:10:20 +00003030 Result = BuildMemberReferenceExpr(ExprArg(*this, Base), Base->getType(),
3031 OpLoc, IsArrow, SS, R, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00003032 }
3033
3034 return move(Result);
Anders Carlssonf571c112009-08-26 18:25:21 +00003035}
3036
Anders Carlsson355933d2009-08-25 03:49:14 +00003037Sema::OwningExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
3038 FunctionDecl *FD,
3039 ParmVarDecl *Param) {
3040 if (Param->hasUnparsedDefaultArg()) {
3041 Diag (CallLoc,
3042 diag::err_use_of_default_argument_to_function_declared_later) <<
3043 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00003044 Diag(UnparsedDefaultArgLocs[Param],
Anders Carlsson355933d2009-08-25 03:49:14 +00003045 diag::note_default_argument_declared_here);
3046 } else {
3047 if (Param->hasUninstantiatedDefaultArg()) {
3048 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
3049
3050 // Instantiate the expression.
Douglas Gregor01afeef2009-08-28 20:31:08 +00003051 MultiLevelTemplateArgumentList ArgList = getTemplateInstantiationArgs(FD);
Anders Carlsson657bad42009-09-05 05:14:19 +00003052
Mike Stump11289f42009-09-09 15:08:12 +00003053 InstantiatingTemplate Inst(*this, CallLoc, Param,
3054 ArgList.getInnermost().getFlatArgumentList(),
Douglas Gregor01afeef2009-08-28 20:31:08 +00003055 ArgList.getInnermost().flat_size());
Anders Carlsson355933d2009-08-25 03:49:14 +00003056
John McCall76d824f2009-08-25 22:02:44 +00003057 OwningExprResult Result = SubstExpr(UninstExpr, ArgList);
Mike Stump11289f42009-09-09 15:08:12 +00003058 if (Result.isInvalid())
Anders Carlsson355933d2009-08-25 03:49:14 +00003059 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003060
3061 if (SetParamDefaultArgument(Param, move(Result),
Anders Carlsson355933d2009-08-25 03:49:14 +00003062 /*FIXME:EqualLoc*/
3063 UninstExpr->getSourceRange().getBegin()))
3064 return ExprError();
3065 }
Mike Stump11289f42009-09-09 15:08:12 +00003066
Anders Carlsson355933d2009-08-25 03:49:14 +00003067 Expr *DefaultExpr = Param->getDefaultArg();
Mike Stump11289f42009-09-09 15:08:12 +00003068
Anders Carlsson355933d2009-08-25 03:49:14 +00003069 // If the default expression creates temporaries, we need to
3070 // push them to the current stack of expression temporaries so they'll
3071 // be properly destroyed.
Mike Stump11289f42009-09-09 15:08:12 +00003072 if (CXXExprWithTemporaries *E
Anders Carlsson355933d2009-08-25 03:49:14 +00003073 = dyn_cast_or_null<CXXExprWithTemporaries>(DefaultExpr)) {
Mike Stump11289f42009-09-09 15:08:12 +00003074 assert(!E->shouldDestroyTemporaries() &&
Anders Carlsson355933d2009-08-25 03:49:14 +00003075 "Can't destroy temporaries in a default argument expr!");
3076 for (unsigned I = 0, N = E->getNumTemporaries(); I != N; ++I)
3077 ExprTemporaries.push_back(E->getTemporary(I));
3078 }
3079 }
3080
3081 // We already type-checked the argument, so we know it works.
3082 return Owned(CXXDefaultArgExpr::Create(Context, Param));
3083}
3084
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003085/// ConvertArgumentsForCall - Converts the arguments specified in
3086/// Args/NumArgs to the parameter types of the function FDecl with
3087/// function prototype Proto. Call is the call expression itself, and
3088/// Fn is the function expression. For a C++ member function, this
3089/// routine does not attempt to convert the object argument. Returns
3090/// true if the call is ill-formed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003091bool
3092Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003093 FunctionDecl *FDecl,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003094 const FunctionProtoType *Proto,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003095 Expr **Args, unsigned NumArgs,
3096 SourceLocation RParenLoc) {
Mike Stump4e1f26a2009-02-19 03:04:26 +00003097 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003098 // assignment, to the types of the corresponding parameter, ...
3099 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregorb6b99612009-01-23 21:30:56 +00003100 bool Invalid = false;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003101
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003102 // If too few arguments are available (and we don't have default
3103 // arguments for the remaining parameters), don't make the call.
3104 if (NumArgs < NumArgsInProto) {
3105 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
3106 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
3107 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
Ted Kremenek5a201952009-02-07 01:47:29 +00003108 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003109 }
3110
3111 // If too many are passed and not variadic, error on the extras and drop
3112 // them.
3113 if (NumArgs > NumArgsInProto) {
3114 if (!Proto->isVariadic()) {
3115 Diag(Args[NumArgsInProto]->getLocStart(),
3116 diag::err_typecheck_call_too_many_args)
3117 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
3118 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3119 Args[NumArgs-1]->getLocEnd());
3120 // This deletes the extra arguments.
Ted Kremenek5a201952009-02-07 01:47:29 +00003121 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003122 return true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003123 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003124 }
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003125 llvm::SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003126 VariadicCallType CallType =
3127 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
3128 if (Fn->getType()->isBlockPointerType())
3129 CallType = VariadicBlock; // Block
3130 else if (isa<MemberExpr>(Fn))
3131 CallType = VariadicMethod;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003132 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00003133 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003134 if (Invalid)
3135 return true;
3136 unsigned TotalNumArgs = AllArgs.size();
3137 for (unsigned i = 0; i < TotalNumArgs; ++i)
3138 Call->setArg(i, AllArgs[i]);
3139
3140 return false;
3141}
Mike Stump4e1f26a2009-02-19 03:04:26 +00003142
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003143bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
3144 FunctionDecl *FDecl,
3145 const FunctionProtoType *Proto,
3146 unsigned FirstProtoArg,
3147 Expr **Args, unsigned NumArgs,
3148 llvm::SmallVector<Expr *, 8> &AllArgs,
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003149 VariadicCallType CallType) {
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003150 unsigned NumArgsInProto = Proto->getNumArgs();
3151 unsigned NumArgsToCheck = NumArgs;
3152 bool Invalid = false;
3153 if (NumArgs != NumArgsInProto)
3154 // Use default arguments for missing arguments
3155 NumArgsToCheck = NumArgsInProto;
3156 unsigned ArgIx = 0;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003157 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003158 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003159 QualType ProtoArgType = Proto->getArgType(i);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003160
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003161 Expr *Arg;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003162 if (ArgIx < NumArgs) {
3163 Arg = Args[ArgIx++];
3164
Eli Friedman3164fb12009-03-22 22:00:50 +00003165 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3166 ProtoArgType,
Anders Carlssond624e162009-08-26 23:45:07 +00003167 PDiag(diag::err_call_incomplete_argument)
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003168 << Arg->getSourceRange()))
Eli Friedman3164fb12009-03-22 22:00:50 +00003169 return true;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003170
Douglas Gregor58354032008-12-24 00:01:03 +00003171 // Pass the argument.
3172 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
3173 return true;
Anders Carlsson78cfaa92009-11-13 04:34:45 +00003174
Anders Carlsson97df0b42009-11-13 17:04:35 +00003175 if (!ProtoArgType->isReferenceType())
3176 Arg = MaybeBindToTemporary(Arg).takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00003177 } else {
Anders Carlssonc80a1272009-08-25 02:29:20 +00003178 ParmVarDecl *Param = FDecl->getParamDecl(i);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003179
Mike Stump11289f42009-09-09 15:08:12 +00003180 OwningExprResult ArgExpr =
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003181 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson355933d2009-08-25 03:49:14 +00003182 if (ArgExpr.isInvalid())
3183 return true;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003184
Anders Carlsson355933d2009-08-25 03:49:14 +00003185 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00003186 }
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003187 AllArgs.push_back(Arg);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003188 }
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003189
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003190 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003191 if (CallType != VariadicDoesNotApply) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003192 // Promote the arguments (C99 6.5.2.2p7).
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003193 for (unsigned i = ArgIx; i < NumArgs; i++) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003194 Expr *Arg = Args[i];
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00003195 Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003196 AllArgs.push_back(Arg);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003197 }
3198 }
Douglas Gregorb6b99612009-01-23 21:30:56 +00003199 return Invalid;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003200}
3201
Douglas Gregorcabea402009-09-22 15:41:20 +00003202/// \brief "Deconstruct" the function argument of a call expression to find
3203/// the underlying declaration (if any), the name of the called function,
3204/// whether argument-dependent lookup is available, whether it has explicit
3205/// template arguments, etc.
3206void Sema::DeconstructCallFunction(Expr *FnExpr,
John McCalld14a8642009-11-21 08:51:07 +00003207 llvm::SmallVectorImpl<NamedDecl*> &Fns,
Douglas Gregorcabea402009-09-22 15:41:20 +00003208 DeclarationName &Name,
3209 NestedNameSpecifier *&Qualifier,
3210 SourceRange &QualifierRange,
3211 bool &ArgumentDependentLookup,
John McCall283b9012009-11-22 00:44:51 +00003212 bool &Overloaded,
Douglas Gregorcabea402009-09-22 15:41:20 +00003213 bool &HasExplicitTemplateArguments,
John McCall6b51f282009-11-23 01:53:49 +00003214 TemplateArgumentListInfo &ExplicitTemplateArgs) {
Douglas Gregorcabea402009-09-22 15:41:20 +00003215 // Set defaults for all of the output parameters.
Douglas Gregorcabea402009-09-22 15:41:20 +00003216 Name = DeclarationName();
3217 Qualifier = 0;
3218 QualifierRange = SourceRange();
John McCalle66edc12009-11-24 19:00:30 +00003219 ArgumentDependentLookup = false;
John McCall283b9012009-11-22 00:44:51 +00003220 Overloaded = false;
Douglas Gregorcabea402009-09-22 15:41:20 +00003221 HasExplicitTemplateArguments = false;
John McCall283b9012009-11-22 00:44:51 +00003222
Douglas Gregorcabea402009-09-22 15:41:20 +00003223 // If we're directly calling a function, get the appropriate declaration.
3224 // Also, in C++, keep track of whether we should perform argument-dependent
3225 // lookup and whether there were any explicitly-specified template arguments.
3226 while (true) {
3227 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(FnExpr))
3228 FnExpr = IcExpr->getSubExpr();
3229 else if (ParenExpr *PExpr = dyn_cast<ParenExpr>(FnExpr)) {
Douglas Gregorcabea402009-09-22 15:41:20 +00003230 FnExpr = PExpr->getSubExpr();
3231 } else if (isa<UnaryOperator>(FnExpr) &&
3232 cast<UnaryOperator>(FnExpr)->getOpcode()
3233 == UnaryOperator::AddrOf) {
3234 FnExpr = cast<UnaryOperator>(FnExpr)->getSubExpr();
Douglas Gregorcabea402009-09-22 15:41:20 +00003235 } else if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(FnExpr)) {
John McCalld14a8642009-11-21 08:51:07 +00003236 Fns.push_back(cast<NamedDecl>(DRExpr->getDecl()));
3237 ArgumentDependentLookup = false;
3238 if ((Qualifier = DRExpr->getQualifier()))
Douglas Gregor4bd90e52009-10-23 18:54:35 +00003239 QualifierRange = DRExpr->getQualifierRange();
Douglas Gregorcabea402009-09-22 15:41:20 +00003240 break;
John McCalld14a8642009-11-21 08:51:07 +00003241 } else if (UnresolvedLookupExpr *UnresLookup
3242 = dyn_cast<UnresolvedLookupExpr>(FnExpr)) {
3243 Name = UnresLookup->getName();
3244 Fns.append(UnresLookup->decls_begin(), UnresLookup->decls_end());
3245 ArgumentDependentLookup = UnresLookup->requiresADL();
John McCall283b9012009-11-22 00:44:51 +00003246 Overloaded = UnresLookup->isOverloaded();
John McCalld14a8642009-11-21 08:51:07 +00003247 if ((Qualifier = UnresLookup->getQualifier()))
3248 QualifierRange = UnresLookup->getQualifierRange();
John McCalle66edc12009-11-24 19:00:30 +00003249 if (UnresLookup->hasExplicitTemplateArgs()) {
3250 HasExplicitTemplateArguments = true;
3251 UnresLookup->copyTemplateArgumentsInto(ExplicitTemplateArgs);
Douglas Gregorcabea402009-09-22 15:41:20 +00003252 }
3253 break;
3254 } else {
Douglas Gregorcabea402009-09-22 15:41:20 +00003255 break;
3256 }
3257 }
3258}
3259
Steve Naroff83895f72007-09-16 03:34:24 +00003260/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattnere168f762006-11-10 05:29:30 +00003261/// This provides the location of the left/right parens and a list of comma
3262/// locations.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003263Action::OwningExprResult
3264Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
3265 MultiExprArg args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003266 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003267 unsigned NumArgs = args.size();
Nate Begeman5ec4b312009-08-10 23:49:36 +00003268
3269 // Since this might be a postfix expression, get rid of ParenListExprs.
3270 fn = MaybeConvertParenListExprToParenExpr(S, move(fn));
Mike Stump11289f42009-09-09 15:08:12 +00003271
Anders Carlsson3cbc8592009-05-01 19:30:39 +00003272 Expr *Fn = fn.takeAs<Expr>();
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003273 Expr **Args = reinterpret_cast<Expr**>(args.release());
Chris Lattner38dbdb22007-07-21 03:03:59 +00003274 assert(Fn && "no function call expression");
Mike Stump11289f42009-09-09 15:08:12 +00003275
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003276 if (getLangOptions().CPlusPlus) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00003277 // If this is a pseudo-destructor expression, build the call immediately.
3278 if (isa<CXXPseudoDestructorExpr>(Fn)) {
3279 if (NumArgs > 0) {
3280 // Pseudo-destructor calls should not have any arguments.
3281 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
3282 << CodeModificationHint::CreateRemoval(
3283 SourceRange(Args[0]->getLocStart(),
3284 Args[NumArgs-1]->getLocEnd()));
Mike Stump11289f42009-09-09 15:08:12 +00003285
Douglas Gregorad8a3362009-09-04 17:36:40 +00003286 for (unsigned I = 0; I != NumArgs; ++I)
3287 Args[I]->Destroy(Context);
Mike Stump11289f42009-09-09 15:08:12 +00003288
Douglas Gregorad8a3362009-09-04 17:36:40 +00003289 NumArgs = 0;
3290 }
Mike Stump11289f42009-09-09 15:08:12 +00003291
Douglas Gregorad8a3362009-09-04 17:36:40 +00003292 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
3293 RParenLoc));
3294 }
Mike Stump11289f42009-09-09 15:08:12 +00003295
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003296 // Determine whether this is a dependent call inside a C++ template,
Mike Stump4e1f26a2009-02-19 03:04:26 +00003297 // in which case we won't do any semantic analysis now.
Mike Stump87c57ac2009-05-16 07:39:55 +00003298 // FIXME: Will need to cache the results of name lookup (including ADL) in
3299 // Fn.
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003300 bool Dependent = false;
3301 if (Fn->isTypeDependent())
3302 Dependent = true;
3303 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
3304 Dependent = true;
3305
3306 if (Dependent)
Ted Kremenekd7b4f402009-02-09 20:51:47 +00003307 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003308 Context.DependentTy, RParenLoc));
3309
3310 // Determine whether this is a call to an object (C++ [over.call.object]).
3311 if (Fn->getType()->isRecordType())
3312 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
3313 CommaLocs, RParenLoc));
3314
John McCall10eae182009-11-30 22:42:35 +00003315 Expr *NakedFn = Fn->IgnoreParens();
3316
3317 // Determine whether this is a call to an unresolved member function.
3318 if (UnresolvedMemberExpr *MemE = dyn_cast<UnresolvedMemberExpr>(NakedFn)) {
3319 // If lookup was unresolved but not dependent (i.e. didn't find
3320 // an unresolved using declaration), it has to be an overloaded
3321 // function set, which means it must contain either multiple
3322 // declarations (all methods or method templates) or a single
3323 // method template.
3324 assert((MemE->getNumDecls() > 1) ||
3325 isa<FunctionTemplateDecl>(*MemE->decls_begin()));
Douglas Gregor8f184a32009-12-01 03:34:29 +00003326 (void)MemE;
John McCall10eae182009-11-30 22:42:35 +00003327
John McCall2d74de92009-12-01 22:10:20 +00003328 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
3329 CommaLocs, RParenLoc);
John McCall10eae182009-11-30 22:42:35 +00003330 }
3331
Douglas Gregore254f902009-02-04 00:32:51 +00003332 // Determine whether this is a call to a member function.
John McCall10eae182009-11-30 22:42:35 +00003333 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(NakedFn)) {
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003334 NamedDecl *MemDecl = MemExpr->getMemberDecl();
John McCall10eae182009-11-30 22:42:35 +00003335 if (isa<CXXMethodDecl>(MemDecl))
John McCall2d74de92009-12-01 22:10:20 +00003336 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
3337 CommaLocs, RParenLoc);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003338 }
Anders Carlsson61914b52009-10-03 17:40:22 +00003339
3340 // Determine whether this is a call to a pointer-to-member function.
John McCall10eae182009-11-30 22:42:35 +00003341 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(NakedFn)) {
Anders Carlsson61914b52009-10-03 17:40:22 +00003342 if (BO->getOpcode() == BinaryOperator::PtrMemD ||
3343 BO->getOpcode() == BinaryOperator::PtrMemI) {
Fariborz Jahanian42f66632009-10-28 16:49:46 +00003344 if (const FunctionProtoType *FPT =
3345 dyn_cast<FunctionProtoType>(BO->getType())) {
3346 QualType ResultTy = FPT->getResultType().getNonReferenceType();
Anders Carlsson61914b52009-10-03 17:40:22 +00003347
Fariborz Jahanian42f66632009-10-28 16:49:46 +00003348 ExprOwningPtr<CXXMemberCallExpr>
3349 TheCall(this, new (Context) CXXMemberCallExpr(Context, BO, Args,
3350 NumArgs, ResultTy,
3351 RParenLoc));
Anders Carlsson61914b52009-10-03 17:40:22 +00003352
Fariborz Jahanian42f66632009-10-28 16:49:46 +00003353 if (CheckCallReturnType(FPT->getResultType(),
3354 BO->getRHS()->getSourceRange().getBegin(),
3355 TheCall.get(), 0))
3356 return ExprError();
Anders Carlsson63dce022009-10-15 00:41:48 +00003357
Fariborz Jahanian42f66632009-10-28 16:49:46 +00003358 if (ConvertArgumentsForCall(&*TheCall, BO, 0, FPT, Args, NumArgs,
3359 RParenLoc))
3360 return ExprError();
Anders Carlsson61914b52009-10-03 17:40:22 +00003361
Fariborz Jahanian42f66632009-10-28 16:49:46 +00003362 return Owned(MaybeBindToTemporary(TheCall.release()).release());
3363 }
3364 return ExprError(Diag(Fn->getLocStart(),
3365 diag::err_typecheck_call_not_function)
3366 << Fn->getType() << Fn->getSourceRange());
Anders Carlsson61914b52009-10-03 17:40:22 +00003367 }
3368 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003369 }
3370
Douglas Gregore254f902009-02-04 00:32:51 +00003371 // If we're directly calling a function, get the appropriate declaration.
Mike Stump11289f42009-09-09 15:08:12 +00003372 // Also, in C++, keep track of whether we should perform argument-dependent
Douglas Gregor89026b52009-06-30 23:57:56 +00003373 // lookup and whether there were any explicitly-specified template arguments.
John McCalld14a8642009-11-21 08:51:07 +00003374 llvm::SmallVector<NamedDecl*,8> Fns;
3375 DeclarationName UnqualifiedName;
John McCall283b9012009-11-22 00:44:51 +00003376 bool Overloaded;
3377 bool ADL;
Douglas Gregor89026b52009-06-30 23:57:56 +00003378 bool HasExplicitTemplateArgs = 0;
John McCall6b51f282009-11-23 01:53:49 +00003379 TemplateArgumentListInfo ExplicitTemplateArgs;
Douglas Gregorcabea402009-09-22 15:41:20 +00003380 NestedNameSpecifier *Qualifier = 0;
3381 SourceRange QualifierRange;
John McCalld14a8642009-11-21 08:51:07 +00003382 DeconstructCallFunction(Fn, Fns, UnqualifiedName, Qualifier, QualifierRange,
John McCall283b9012009-11-22 00:44:51 +00003383 ADL, Overloaded, HasExplicitTemplateArgs,
John McCall6b51f282009-11-23 01:53:49 +00003384 ExplicitTemplateArgs);
Mike Stump4e1f26a2009-02-19 03:04:26 +00003385
John McCall283b9012009-11-22 00:44:51 +00003386 NamedDecl *NDecl; // the specific declaration we're calling, if applicable
3387 FunctionDecl *FDecl; // same, if it's known to be a function
John McCalld14a8642009-11-21 08:51:07 +00003388
John McCall283b9012009-11-22 00:44:51 +00003389 if (Overloaded || ADL) {
3390#ifndef NDEBUG
3391 if (ADL) {
3392 // To do ADL, we must have found an unqualified name.
3393 assert(UnqualifiedName && "found no unqualified name for ADL");
3394
3395 // We don't perform ADL for implicit declarations of builtins.
3396 // Verify that this was correctly set up.
3397 if (Fns.size() == 1 && (FDecl = dyn_cast<FunctionDecl>(Fns[0])) &&
3398 FDecl->getBuiltinID() && FDecl->isImplicit())
3399 assert(0 && "performing ADL for builtin");
3400
3401 // We don't perform ADL in C.
3402 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
3403 }
3404
3405 if (Overloaded) {
3406 // To be overloaded, we must either have multiple functions or
3407 // at least one function template (which is effectively an
3408 // infinite set of functions).
3409 assert((Fns.size() > 1 ||
3410 (Fns.size() == 1 &&
3411 isa<FunctionTemplateDecl>(Fns[0]->getUnderlyingDecl())))
3412 && "unrecognized overload situation");
3413 }
3414#endif
3415
3416 FDecl = ResolveOverloadedCallFn(Fn, Fns, UnqualifiedName,
John McCall6b51f282009-11-23 01:53:49 +00003417 (HasExplicitTemplateArgs ? &ExplicitTemplateArgs : 0),
John McCall283b9012009-11-22 00:44:51 +00003418 LParenLoc, Args, NumArgs, CommaLocs,
3419 RParenLoc, ADL);
3420 if (!FDecl)
3421 return ExprError();
3422
3423 Fn = FixOverloadedFunctionReference(Fn, FDecl);
3424
3425 NDecl = FDecl;
3426 } else {
3427 assert(Fns.size() <= 1 && "overloaded without Overloaded flag");
3428 if (Fns.empty())
John McCall2d74de92009-12-01 22:10:20 +00003429 NDecl = 0;
John McCall283b9012009-11-22 00:44:51 +00003430 else {
3431 NDecl = Fns[0];
Douglas Gregore254f902009-02-04 00:32:51 +00003432 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003433 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00003434
John McCall2d74de92009-12-01 22:10:20 +00003435 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc);
3436}
3437
3438/// BuildCallExpr - Build a call to a resolved expression, i.e. an
3439/// expression not of \p OverloadTy. The expression should
3440/// unary-convert to an expression of function-pointer or
3441/// block-pointer type.
3442///
3443/// \param NDecl the declaration being called, if available
3444Sema::OwningExprResult
3445Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
3446 SourceLocation LParenLoc,
3447 Expr **Args, unsigned NumArgs,
3448 SourceLocation RParenLoc) {
3449 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
3450
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00003451 // Promote the function operand.
3452 UsualUnaryConversions(Fn);
3453
Chris Lattner08464942007-12-28 05:29:59 +00003454 // Make the call expr early, before semantic checks. This guarantees cleanup
3455 // of arguments and function on error.
Ted Kremenekd7b4f402009-02-09 20:51:47 +00003456 ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
3457 Args, NumArgs,
3458 Context.BoolTy,
3459 RParenLoc));
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003460
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003461 const FunctionType *FuncT;
3462 if (!Fn->getType()->isBlockPointerType()) {
3463 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
3464 // have type pointer to function".
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003465 const PointerType *PT = Fn->getType()->getAs<PointerType>();
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003466 if (PT == 0)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003467 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3468 << Fn->getType() << Fn->getSourceRange());
John McCall9dd450b2009-09-21 23:43:11 +00003469 FuncT = PT->getPointeeType()->getAs<FunctionType>();
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003470 } else { // This is a block call.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003471 FuncT = Fn->getType()->getAs<BlockPointerType>()->getPointeeType()->
John McCall9dd450b2009-09-21 23:43:11 +00003472 getAs<FunctionType>();
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003473 }
Chris Lattner08464942007-12-28 05:29:59 +00003474 if (FuncT == 0)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003475 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3476 << Fn->getType() << Fn->getSourceRange());
3477
Eli Friedman3164fb12009-03-22 22:00:50 +00003478 // Check for a valid return type
Anders Carlsson7f84ed92009-10-09 23:51:55 +00003479 if (CheckCallReturnType(FuncT->getResultType(),
3480 Fn->getSourceRange().getBegin(), TheCall.get(),
3481 FDecl))
Eli Friedman3164fb12009-03-22 22:00:50 +00003482 return ExprError();
3483
Chris Lattner08464942007-12-28 05:29:59 +00003484 // We know the result type of the call, set it.
Douglas Gregor786ab212008-10-29 02:00:59 +00003485 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003486
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003487 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
Mike Stump4e1f26a2009-02-19 03:04:26 +00003488 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003489 RParenLoc))
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003490 return ExprError();
Chris Lattner08464942007-12-28 05:29:59 +00003491 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003492 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003493
Douglas Gregord8e97de2009-04-02 15:37:10 +00003494 if (FDecl) {
3495 // Check if we have too few/too many template arguments, based
3496 // on our knowledge of the function definition.
3497 const FunctionDecl *Def = 0;
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00003498 if (FDecl->getBody(Def) && NumArgs != Def->param_size()) {
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00003499 const FunctionProtoType *Proto =
John McCall9dd450b2009-09-21 23:43:11 +00003500 Def->getType()->getAs<FunctionProtoType>();
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00003501 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size())) {
3502 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
3503 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
3504 }
3505 }
Douglas Gregord8e97de2009-04-02 15:37:10 +00003506 }
3507
Steve Naroff0b661582007-08-28 23:30:39 +00003508 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner08464942007-12-28 05:29:59 +00003509 for (unsigned i = 0; i != NumArgs; i++) {
3510 Expr *Arg = Args[i];
3511 DefaultArgumentPromotion(Arg);
Eli Friedman3164fb12009-03-22 22:00:50 +00003512 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3513 Arg->getType(),
Anders Carlssond624e162009-08-26 23:45:07 +00003514 PDiag(diag::err_call_incomplete_argument)
3515 << Arg->getSourceRange()))
Eli Friedman3164fb12009-03-22 22:00:50 +00003516 return ExprError();
Chris Lattner08464942007-12-28 05:29:59 +00003517 TheCall->setArg(i, Arg);
Steve Naroff0b661582007-08-28 23:30:39 +00003518 }
Steve Naroffae4143e2007-04-26 20:39:23 +00003519 }
Chris Lattner08464942007-12-28 05:29:59 +00003520
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003521 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3522 if (!Method->isStatic())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003523 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
3524 << Fn->getSourceRange());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003525
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +00003526 // Check for sentinels
3527 if (NDecl)
3528 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump11289f42009-09-09 15:08:12 +00003529
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003530 // Do special checking on direct calls to functions.
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003531 if (FDecl) {
3532 if (CheckFunctionCall(FDecl, TheCall.get()))
3533 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003534
Douglas Gregor15fc9562009-09-12 00:22:50 +00003535 if (unsigned BuiltinID = FDecl->getBuiltinID())
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003536 return CheckBuiltinFunctionCall(BuiltinID, TheCall.take());
3537 } else if (NDecl) {
3538 if (CheckBlockCall(NDecl, TheCall.get()))
3539 return ExprError();
3540 }
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003541
Anders Carlssonf8984012009-08-16 03:06:32 +00003542 return MaybeBindToTemporary(TheCall.take());
Chris Lattnere168f762006-11-10 05:29:30 +00003543}
3544
Sebastian Redlb5d49352009-01-19 22:31:54 +00003545Action::OwningExprResult
3546Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
3547 SourceLocation RParenLoc, ExprArg InitExpr) {
Steve Naroff83895f72007-09-16 03:34:24 +00003548 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00003549 //FIXME: Preserve type source info.
3550 QualType literalType = GetTypeFromParser(Ty);
Steve Naroff57eb2c52007-07-19 21:32:11 +00003551 // FIXME: put back this assert when initializers are worked out.
Steve Naroff83895f72007-09-16 03:34:24 +00003552 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Sebastian Redlb5d49352009-01-19 22:31:54 +00003553 Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
Anders Carlsson2c1ec6d2007-12-05 07:24:19 +00003554
Eli Friedman37a186d2008-05-20 05:22:08 +00003555 if (literalType->isArrayType()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00003556 if (literalType->isVariableArrayType())
Sebastian Redlb5d49352009-01-19 22:31:54 +00003557 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
3558 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor1c37d9e2009-05-21 23:48:18 +00003559 } else if (!literalType->isDependentType() &&
3560 RequireCompleteType(LParenLoc, literalType,
Anders Carlssond624e162009-08-26 23:45:07 +00003561 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump11289f42009-09-09 15:08:12 +00003562 << SourceRange(LParenLoc,
Anders Carlssond624e162009-08-26 23:45:07 +00003563 literalExpr->getSourceRange().getEnd())))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003564 return ExprError();
Eli Friedman37a186d2008-05-20 05:22:08 +00003565
Sebastian Redlb5d49352009-01-19 22:31:54 +00003566 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003567 DeclarationName(), /*FIXME:DirectInit=*/false))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003568 return ExprError();
Steve Naroffd32419d2008-01-14 18:19:28 +00003569
Chris Lattner79413952008-12-04 23:50:19 +00003570 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffd32419d2008-01-14 18:19:28 +00003571 if (isFileScope) { // 6.5.2.5p3
Steve Naroff98f72032008-01-10 22:15:12 +00003572 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003573 return ExprError();
Steve Naroff98f72032008-01-10 22:15:12 +00003574 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00003575 InitExpr.release();
Mike Stump4e1f26a2009-02-19 03:04:26 +00003576 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType,
Steve Narofff6009ed2009-01-21 00:14:39 +00003577 literalExpr, isFileScope));
Steve Narofffbd09832007-07-19 01:06:55 +00003578}
3579
Sebastian Redlb5d49352009-01-19 22:31:54 +00003580Action::OwningExprResult
3581Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redlb5d49352009-01-19 22:31:54 +00003582 SourceLocation RBraceLoc) {
3583 unsigned NumInit = initlist.size();
3584 Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
Anders Carlsson4692db02007-08-31 04:56:16 +00003585
Steve Naroff30d242c2007-09-15 18:49:24 +00003586 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump4e1f26a2009-02-19 03:04:26 +00003587 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb5d49352009-01-19 22:31:54 +00003588
Mike Stump4e1f26a2009-02-19 03:04:26 +00003589 InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00003590 RBraceLoc);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003591 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb5d49352009-01-19 22:31:54 +00003592 return Owned(E);
Steve Narofffbd09832007-07-19 01:06:55 +00003593}
3594
Anders Carlsson094c4592009-10-18 18:12:03 +00003595static CastExpr::CastKind getScalarCastKind(ASTContext &Context,
3596 QualType SrcTy, QualType DestTy) {
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003597 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
Anders Carlsson094c4592009-10-18 18:12:03 +00003598 return CastExpr::CK_NoOp;
3599
3600 if (SrcTy->hasPointerRepresentation()) {
3601 if (DestTy->hasPointerRepresentation())
3602 return CastExpr::CK_BitCast;
3603 if (DestTy->isIntegerType())
3604 return CastExpr::CK_PointerToIntegral;
3605 }
3606
3607 if (SrcTy->isIntegerType()) {
3608 if (DestTy->isIntegerType())
3609 return CastExpr::CK_IntegralCast;
3610 if (DestTy->hasPointerRepresentation())
3611 return CastExpr::CK_IntegralToPointer;
3612 if (DestTy->isRealFloatingType())
3613 return CastExpr::CK_IntegralToFloating;
3614 }
3615
3616 if (SrcTy->isRealFloatingType()) {
3617 if (DestTy->isRealFloatingType())
3618 return CastExpr::CK_FloatingCast;
3619 if (DestTy->isIntegerType())
3620 return CastExpr::CK_FloatingToIntegral;
3621 }
3622
3623 // FIXME: Assert here.
3624 // assert(false && "Unhandled cast combination!");
3625 return CastExpr::CK_Unknown;
3626}
3627
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003628/// CheckCastTypes - Check type constraints for casting between types.
Sebastian Redl955a0672009-07-29 13:50:23 +00003629bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr,
Mike Stump11289f42009-09-09 15:08:12 +00003630 CastExpr::CastKind& Kind,
Fariborz Jahanian1cec0c42009-08-26 18:55:36 +00003631 CXXMethodDecl *& ConversionDecl,
3632 bool FunctionalStyle) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00003633 if (getLangOptions().CPlusPlus)
Fariborz Jahanian1cec0c42009-08-26 18:55:36 +00003634 return CXXCheckCStyleCast(TyR, castType, castExpr, Kind, FunctionalStyle,
3635 ConversionDecl);
Sebastian Redl9f831db2009-07-25 15:41:38 +00003636
Eli Friedmanda8d4de2009-08-15 19:02:19 +00003637 DefaultFunctionArrayConversion(castExpr);
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003638
3639 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
3640 // type needs to be scalar.
3641 if (castType->isVoidType()) {
3642 // Cast to void allows any expr type.
Anders Carlssonef918ac2009-10-16 02:35:04 +00003643 Kind = CastExpr::CK_ToVoid;
3644 return false;
3645 }
3646
3647 if (!castType->isScalarType() && !castType->isVectorType()) {
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003648 if (Context.hasSameUnqualifiedType(castType, castExpr->getType()) &&
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003649 (castType->isStructureType() || castType->isUnionType())) {
3650 // GCC struct/union extension: allow cast to self.
Eli Friedmanba961a92009-03-23 00:24:07 +00003651 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003652 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
3653 << castType << castExpr->getSourceRange();
Anders Carlssonec143772009-08-07 23:22:37 +00003654 Kind = CastExpr::CK_NoOp;
Anders Carlsson525b76b2009-10-16 02:48:28 +00003655 return false;
3656 }
3657
3658 if (castType->isUnionType()) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003659 // GCC cast to union extension
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003660 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003661 RecordDecl::field_iterator Field, FieldEnd;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003662 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003663 Field != FieldEnd; ++Field) {
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003664 if (Context.hasSameUnqualifiedType(Field->getType(),
3665 castExpr->getType())) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003666 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
3667 << castExpr->getSourceRange();
3668 break;
3669 }
3670 }
3671 if (Field == FieldEnd)
3672 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
3673 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlssonec143772009-08-07 23:22:37 +00003674 Kind = CastExpr::CK_ToUnion;
Anders Carlsson525b76b2009-10-16 02:48:28 +00003675 return false;
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003676 }
Anders Carlsson525b76b2009-10-16 02:48:28 +00003677
3678 // Reject any other conversions to non-scalar types.
3679 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
3680 << castType << castExpr->getSourceRange();
3681 }
3682
3683 if (!castExpr->getType()->isScalarType() &&
3684 !castExpr->getType()->isVectorType()) {
Chris Lattner3b054132008-11-19 05:08:23 +00003685 return Diag(castExpr->getLocStart(),
3686 diag::err_typecheck_expect_scalar_operand)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003687 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlsson525b76b2009-10-16 02:48:28 +00003688 }
3689
Anders Carlsson43d70f82009-10-16 05:23:41 +00003690 if (castType->isExtVectorType())
3691 return CheckExtVectorCast(TyR, castType, castExpr, Kind);
3692
Anders Carlsson525b76b2009-10-16 02:48:28 +00003693 if (castType->isVectorType())
3694 return CheckVectorCast(TyR, castType, castExpr->getType(), Kind);
3695 if (castExpr->getType()->isVectorType())
3696 return CheckVectorCast(TyR, castExpr->getType(), castType, Kind);
3697
3698 if (getLangOptions().ObjC1 && isa<ObjCSuperExpr>(castExpr))
Steve Naroffb47acdb2009-04-08 23:52:26 +00003699 return Diag(castExpr->getLocStart(), diag::err_illegal_super_cast) << TyR;
Anders Carlsson525b76b2009-10-16 02:48:28 +00003700
Anders Carlsson43d70f82009-10-16 05:23:41 +00003701 if (isa<ObjCSelectorExpr>(castExpr))
3702 return Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
3703
Anders Carlsson525b76b2009-10-16 02:48:28 +00003704 if (!castType->isArithmeticType()) {
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00003705 QualType castExprType = castExpr->getType();
3706 if (!castExprType->isIntegralType() && castExprType->isArithmeticType())
3707 return Diag(castExpr->getLocStart(),
3708 diag::err_cast_pointer_from_non_pointer_int)
3709 << castExprType << castExpr->getSourceRange();
3710 } else if (!castExpr->getType()->isArithmeticType()) {
3711 if (!castType->isIntegralType() && castType->isArithmeticType())
3712 return Diag(castExpr->getLocStart(),
3713 diag::err_cast_pointer_to_non_pointer_int)
3714 << castType << castExpr->getSourceRange();
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003715 }
Anders Carlsson094c4592009-10-18 18:12:03 +00003716
3717 Kind = getScalarCastKind(Context, castExpr->getType(), castType);
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003718 return false;
3719}
3720
Anders Carlsson525b76b2009-10-16 02:48:28 +00003721bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
3722 CastExpr::CastKind &Kind) {
Anders Carlssonde71adf2007-11-27 05:51:55 +00003723 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00003724
Anders Carlssonde71adf2007-11-27 05:51:55 +00003725 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner37e05872008-03-05 18:54:05 +00003726 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonde71adf2007-11-27 05:51:55 +00003727 return Diag(R.getBegin(),
Mike Stump4e1f26a2009-02-19 03:04:26 +00003728 Ty->isVectorType() ?
Anders Carlssonde71adf2007-11-27 05:51:55 +00003729 diag::err_invalid_conversion_between_vectors :
Chris Lattner3b054132008-11-19 05:08:23 +00003730 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003731 << VectorTy << Ty << R;
Anders Carlssonde71adf2007-11-27 05:51:55 +00003732 } else
3733 return Diag(R.getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00003734 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003735 << VectorTy << Ty << R;
Mike Stump4e1f26a2009-02-19 03:04:26 +00003736
Anders Carlsson525b76b2009-10-16 02:48:28 +00003737 Kind = CastExpr::CK_BitCast;
Anders Carlssonde71adf2007-11-27 05:51:55 +00003738 return false;
3739}
3740
Anders Carlsson43d70f82009-10-16 05:23:41 +00003741bool Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *&CastExpr,
3742 CastExpr::CastKind &Kind) {
Nate Begemanc69b7402009-06-26 00:50:28 +00003743 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Anders Carlsson43d70f82009-10-16 05:23:41 +00003744
3745 QualType SrcTy = CastExpr->getType();
3746
Nate Begemanc8961a42009-06-27 22:05:55 +00003747 // If SrcTy is a VectorType, the total size must match to explicitly cast to
3748 // an ExtVectorType.
Nate Begemanc69b7402009-06-26 00:50:28 +00003749 if (SrcTy->isVectorType()) {
3750 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
3751 return Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
3752 << DestTy << SrcTy << R;
Anders Carlsson43d70f82009-10-16 05:23:41 +00003753 Kind = CastExpr::CK_BitCast;
Nate Begemanc69b7402009-06-26 00:50:28 +00003754 return false;
3755 }
3756
Nate Begemanbd956c42009-06-28 02:36:38 +00003757 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begemanc69b7402009-06-26 00:50:28 +00003758 // conversion will take place first from scalar to elt type, and then
3759 // splat from elt type to vector.
Nate Begemanbd956c42009-06-28 02:36:38 +00003760 if (SrcTy->isPointerType())
3761 return Diag(R.getBegin(),
3762 diag::err_invalid_conversion_between_vector_and_scalar)
3763 << DestTy << SrcTy << R;
Eli Friedman06ed2a52009-10-20 08:27:19 +00003764
3765 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
3766 ImpCastExprToType(CastExpr, DestElemTy,
3767 getScalarCastKind(Context, SrcTy, DestElemTy));
Anders Carlsson43d70f82009-10-16 05:23:41 +00003768
3769 Kind = CastExpr::CK_VectorSplat;
Nate Begemanc69b7402009-06-26 00:50:28 +00003770 return false;
3771}
3772
Sebastian Redlb5d49352009-01-19 22:31:54 +00003773Action::OwningExprResult
Nate Begeman5ec4b312009-08-10 23:49:36 +00003774Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, TypeTy *Ty,
Sebastian Redlb5d49352009-01-19 22:31:54 +00003775 SourceLocation RParenLoc, ExprArg Op) {
Anders Carlssonf10e4142009-08-07 22:21:05 +00003776 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Mike Stump11289f42009-09-09 15:08:12 +00003777
Sebastian Redlb5d49352009-01-19 22:31:54 +00003778 assert((Ty != 0) && (Op.get() != 0) &&
3779 "ActOnCastExpr(): missing type or expr");
Steve Naroff1a2cf6b2007-07-16 23:25:18 +00003780
Nate Begeman5ec4b312009-08-10 23:49:36 +00003781 Expr *castExpr = (Expr *)Op.get();
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00003782 //FIXME: Preserve type source info.
3783 QualType castType = GetTypeFromParser(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00003784
Nate Begeman5ec4b312009-08-10 23:49:36 +00003785 // If the Expr being casted is a ParenListExpr, handle it specially.
3786 if (isa<ParenListExpr>(castExpr))
3787 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, move(Op),castType);
Anders Carlssone9766d52009-09-09 21:33:21 +00003788 CXXMethodDecl *Method = 0;
Mike Stump11289f42009-09-09 15:08:12 +00003789 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr,
Anders Carlssone9766d52009-09-09 21:33:21 +00003790 Kind, Method))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003791 return ExprError();
Anders Carlssone9766d52009-09-09 21:33:21 +00003792
3793 if (Method) {
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00003794 OwningExprResult CastArg = BuildCXXCastArgument(LParenLoc, castType, Kind,
Anders Carlssone9766d52009-09-09 21:33:21 +00003795 Method, move(Op));
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00003796
Anders Carlssone9766d52009-09-09 21:33:21 +00003797 if (CastArg.isInvalid())
3798 return ExprError();
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00003799
Anders Carlssone9766d52009-09-09 21:33:21 +00003800 castExpr = CastArg.takeAs<Expr>();
3801 } else {
3802 Op.release();
Fariborz Jahanian3df87672009-08-29 19:15:16 +00003803 }
Mike Stump11289f42009-09-09 15:08:12 +00003804
Sebastian Redl9f831db2009-07-25 15:41:38 +00003805 return Owned(new (Context) CStyleCastExpr(castType.getNonReferenceType(),
Mike Stump11289f42009-09-09 15:08:12 +00003806 Kind, castExpr, castType,
Anders Carlssonf10e4142009-08-07 22:21:05 +00003807 LParenLoc, RParenLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00003808}
3809
Nate Begeman5ec4b312009-08-10 23:49:36 +00003810/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
3811/// of comma binary operators.
3812Action::OwningExprResult
3813Sema::MaybeConvertParenListExprToParenExpr(Scope *S, ExprArg EA) {
3814 Expr *expr = EA.takeAs<Expr>();
3815 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
3816 if (!E)
3817 return Owned(expr);
Mike Stump11289f42009-09-09 15:08:12 +00003818
Nate Begeman5ec4b312009-08-10 23:49:36 +00003819 OwningExprResult Result(*this, E->getExpr(0));
Mike Stump11289f42009-09-09 15:08:12 +00003820
Nate Begeman5ec4b312009-08-10 23:49:36 +00003821 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
3822 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, move(Result),
3823 Owned(E->getExpr(i)));
Mike Stump11289f42009-09-09 15:08:12 +00003824
Nate Begeman5ec4b312009-08-10 23:49:36 +00003825 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), move(Result));
3826}
3827
3828Action::OwningExprResult
3829Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
3830 SourceLocation RParenLoc, ExprArg Op,
3831 QualType Ty) {
3832 ParenListExpr *PE = (ParenListExpr *)Op.get();
Mike Stump11289f42009-09-09 15:08:12 +00003833
3834 // If this is an altivec initializer, '(' type ')' '(' init, ..., init ')'
Nate Begeman5ec4b312009-08-10 23:49:36 +00003835 // then handle it as such.
3836 if (getLangOptions().AltiVec && Ty->isVectorType()) {
3837 if (PE->getNumExprs() == 0) {
3838 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
3839 return ExprError();
3840 }
3841
3842 llvm::SmallVector<Expr *, 8> initExprs;
3843 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
3844 initExprs.push_back(PE->getExpr(i));
3845
3846 // FIXME: This means that pretty-printing the final AST will produce curly
3847 // braces instead of the original commas.
3848 Op.release();
Mike Stump11289f42009-09-09 15:08:12 +00003849 InitListExpr *E = new (Context) InitListExpr(LParenLoc, &initExprs[0],
Nate Begeman5ec4b312009-08-10 23:49:36 +00003850 initExprs.size(), RParenLoc);
3851 E->setType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00003852 return ActOnCompoundLiteral(LParenLoc, Ty.getAsOpaquePtr(), RParenLoc,
Nate Begeman5ec4b312009-08-10 23:49:36 +00003853 Owned(E));
3854 } else {
Mike Stump11289f42009-09-09 15:08:12 +00003855 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
Nate Begeman5ec4b312009-08-10 23:49:36 +00003856 // sequence of BinOp comma operators.
3857 Op = MaybeConvertParenListExprToParenExpr(S, move(Op));
3858 return ActOnCastExpr(S, LParenLoc, Ty.getAsOpaquePtr(), RParenLoc,move(Op));
3859 }
3860}
3861
Fariborz Jahanian906d8712009-11-25 01:26:41 +00003862Action::OwningExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
Nate Begeman5ec4b312009-08-10 23:49:36 +00003863 SourceLocation R,
Fariborz Jahanian906d8712009-11-25 01:26:41 +00003864 MultiExprArg Val,
3865 TypeTy *TypeOfCast) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00003866 unsigned nexprs = Val.size();
3867 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanian906d8712009-11-25 01:26:41 +00003868 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
3869 Expr *expr;
3870 if (nexprs == 1 && TypeOfCast && !TypeIsVectorType(TypeOfCast))
3871 expr = new (Context) ParenExpr(L, R, exprs[0]);
3872 else
3873 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
Nate Begeman5ec4b312009-08-10 23:49:36 +00003874 return Owned(expr);
3875}
3876
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003877/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
3878/// In that case, lhs = cond.
Chris Lattner2c486602009-02-18 04:38:20 +00003879/// C99 6.5.15
3880QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
3881 SourceLocation QuestionLoc) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00003882 // C++ is sufficiently different to merit its own checker.
3883 if (getLangOptions().CPlusPlus)
3884 return CXXCheckConditionalOperands(Cond, LHS, RHS, QuestionLoc);
3885
John McCall1fa36b72009-11-05 09:23:39 +00003886 CheckSignCompare(LHS, RHS, QuestionLoc, diag::warn_mixed_sign_conditional);
3887
Chris Lattner432cff52009-02-18 04:28:32 +00003888 UsualUnaryConversions(Cond);
3889 UsualUnaryConversions(LHS);
3890 UsualUnaryConversions(RHS);
3891 QualType CondTy = Cond->getType();
3892 QualType LHSTy = LHS->getType();
3893 QualType RHSTy = RHS->getType();
Steve Naroff31090012007-07-16 21:54:35 +00003894
Steve Naroffa78fe7e2007-05-16 19:47:19 +00003895 // first, check the condition.
Sebastian Redl1a99f442009-04-16 17:51:27 +00003896 if (!CondTy->isScalarType()) { // C99 6.5.15p2
3897 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
3898 << CondTy;
3899 return QualType();
Steve Naroffa78fe7e2007-05-16 19:47:19 +00003900 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00003901
Chris Lattnere2949f42008-01-06 22:42:25 +00003902 // Now check the two expressions.
Nate Begeman5ec4b312009-08-10 23:49:36 +00003903 if (LHSTy->isVectorType() || RHSTy->isVectorType())
3904 return CheckVectorOperands(QuestionLoc, LHS, RHS);
Douglas Gregor4619e432008-12-05 23:32:09 +00003905
Chris Lattnere2949f42008-01-06 22:42:25 +00003906 // If both operands have arithmetic type, do the usual arithmetic conversions
3907 // to find a common type: C99 6.5.15p3,5.
Chris Lattner432cff52009-02-18 04:28:32 +00003908 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
3909 UsualArithmeticConversions(LHS, RHS);
3910 return LHS->getType();
Steve Naroffdbd9e892007-07-17 00:58:39 +00003911 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00003912
Chris Lattnere2949f42008-01-06 22:42:25 +00003913 // If both operands are the same structure or union type, the result is that
3914 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003915 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
3916 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattner2ab40a62007-11-26 01:40:58 +00003917 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump4e1f26a2009-02-19 03:04:26 +00003918 // "If both the operands have structure or union type, the result has
Chris Lattnere2949f42008-01-06 22:42:25 +00003919 // that type." This implies that CV qualifiers are dropped.
Chris Lattner432cff52009-02-18 04:28:32 +00003920 return LHSTy.getUnqualifiedType();
Eli Friedmanba961a92009-03-23 00:24:07 +00003921 // FIXME: Type of conditional expression must be complete in C mode.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00003922 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00003923
Chris Lattnere2949f42008-01-06 22:42:25 +00003924 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffbf1516c2008-05-12 21:44:38 +00003925 // The following || allows only one side to be void (a GCC-ism).
Chris Lattner432cff52009-02-18 04:28:32 +00003926 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
3927 if (!LHSTy->isVoidType())
3928 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
3929 << RHS->getSourceRange();
3930 if (!RHSTy->isVoidType())
3931 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
3932 << LHS->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00003933 ImpCastExprToType(LHS, Context.VoidTy, CastExpr::CK_ToVoid);
3934 ImpCastExprToType(RHS, Context.VoidTy, CastExpr::CK_ToVoid);
Eli Friedman3e1852f2008-06-04 19:47:51 +00003935 return Context.VoidTy;
Steve Naroffbf1516c2008-05-12 21:44:38 +00003936 }
Steve Naroff039ad3c2008-01-08 01:11:38 +00003937 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
3938 // the type of the other operand."
Steve Naroff6b712a72009-07-14 18:25:06 +00003939 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
Douglas Gregor56751b52009-09-25 04:25:58 +00003940 RHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00003941 // promote the null to a pointer.
3942 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_Unknown);
Chris Lattner432cff52009-02-18 04:28:32 +00003943 return LHSTy;
Steve Naroff039ad3c2008-01-08 01:11:38 +00003944 }
Steve Naroff6b712a72009-07-14 18:25:06 +00003945 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
Douglas Gregor56751b52009-09-25 04:25:58 +00003946 LHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00003947 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_Unknown);
Chris Lattner432cff52009-02-18 04:28:32 +00003948 return RHSTy;
Steve Naroff039ad3c2008-01-08 01:11:38 +00003949 }
Fariborz Jahaniana430f712009-12-10 19:47:41 +00003950
3951 // All objective-c pointer type analysis is done here.
3952 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
3953 QuestionLoc);
3954 if (!compositeType.isNull())
3955 return compositeType;
3956
3957
Steve Naroff05efa972009-07-01 14:36:47 +00003958 // Handle block pointer types.
3959 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
3960 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
3961 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
3962 QualType destType = Context.getPointerType(Context.VoidTy);
Eli Friedman06ed2a52009-10-20 08:27:19 +00003963 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
3964 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00003965 return destType;
3966 }
3967 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Fariborz Jahaniana430f712009-12-10 19:47:41 +00003968 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Steve Naroff05efa972009-07-01 14:36:47 +00003969 return QualType();
Mike Stump1b821b42009-05-07 03:14:14 +00003970 }
Steve Naroff05efa972009-07-01 14:36:47 +00003971 // We have 2 block pointer types.
3972 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3973 // Two identical block pointer types are always compatible.
Mike Stump1b821b42009-05-07 03:14:14 +00003974 return LHSTy;
3975 }
Steve Naroff05efa972009-07-01 14:36:47 +00003976 // The block pointer types aren't identical, continue checking.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003977 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
3978 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00003979
Steve Naroff05efa972009-07-01 14:36:47 +00003980 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
3981 rhptee.getUnqualifiedType())) {
Mike Stump1b821b42009-05-07 03:14:14 +00003982 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
Fariborz Jahaniana430f712009-12-10 19:47:41 +00003983 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stump1b821b42009-05-07 03:14:14 +00003984 // In this situation, we assume void* type. No especially good
3985 // reason, but this is what gcc does, and we do have to pick
3986 // to get a consistent AST.
3987 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Eli Friedman06ed2a52009-10-20 08:27:19 +00003988 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
3989 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
Mike Stump1b821b42009-05-07 03:14:14 +00003990 return incompatTy;
Steve Naroffa78fe7e2007-05-16 19:47:19 +00003991 }
Steve Naroff05efa972009-07-01 14:36:47 +00003992 // The block pointer types are compatible.
Eli Friedman06ed2a52009-10-20 08:27:19 +00003993 ImpCastExprToType(LHS, LHSTy, CastExpr::CK_BitCast);
3994 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
Steve Naroffea4c7802009-04-08 17:05:15 +00003995 return LHSTy;
3996 }
Fariborz Jahaniana430f712009-12-10 19:47:41 +00003997
Steve Naroff05efa972009-07-01 14:36:47 +00003998 // Check constraints for C object pointers types (C99 6.5.15p3,6).
3999 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
4000 // get the "pointed to" types
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004001 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4002 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff05efa972009-07-01 14:36:47 +00004003
4004 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
4005 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
4006 // Figure out necessary qualifiers (C99 6.5.15p6)
John McCall8ccfcb52009-09-24 19:53:00 +00004007 QualType destPointee
4008 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
Steve Naroff05efa972009-07-01 14:36:47 +00004009 QualType destType = Context.getPointerType(destPointee);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004010 // Add qualifiers if necessary.
4011 ImpCastExprToType(LHS, destType, CastExpr::CK_NoOp);
4012 // Promote to void*.
4013 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004014 return destType;
4015 }
4016 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00004017 QualType destPointee
4018 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
Steve Naroff05efa972009-07-01 14:36:47 +00004019 QualType destType = Context.getPointerType(destPointee);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004020 // Add qualifiers if necessary.
Eli Friedmanb0bc5592009-11-17 01:22:05 +00004021 ImpCastExprToType(RHS, destType, CastExpr::CK_NoOp);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004022 // Promote to void*.
Eli Friedmanb0bc5592009-11-17 01:22:05 +00004023 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004024 return destType;
4025 }
4026
4027 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4028 // Two identical pointer types are always compatible.
4029 return LHSTy;
4030 }
4031 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
4032 rhptee.getUnqualifiedType())) {
4033 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
4034 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
4035 // In this situation, we assume void* type. No especially good
4036 // reason, but this is what gcc does, and we do have to pick
4037 // to get a consistent AST.
4038 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004039 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
4040 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004041 return incompatTy;
4042 }
4043 // The pointer types are compatible.
4044 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
4045 // differently qualified versions of compatible types, the result type is
4046 // a pointer to an appropriately qualified version of the *composite*
4047 // type.
4048 // FIXME: Need to calculate the composite type.
4049 // FIXME: Need to add qualifiers
Eli Friedman06ed2a52009-10-20 08:27:19 +00004050 ImpCastExprToType(LHS, LHSTy, CastExpr::CK_BitCast);
4051 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004052 return LHSTy;
4053 }
Mike Stump11289f42009-09-09 15:08:12 +00004054
Steve Naroff05efa972009-07-01 14:36:47 +00004055 // GCC compatibility: soften pointer/integer mismatch.
4056 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
4057 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4058 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00004059 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_IntegralToPointer);
Steve Naroff05efa972009-07-01 14:36:47 +00004060 return RHSTy;
4061 }
4062 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
4063 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4064 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00004065 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_IntegralToPointer);
Steve Naroff05efa972009-07-01 14:36:47 +00004066 return LHSTy;
4067 }
Daniel Dunbar484603b2008-09-11 23:12:46 +00004068
Chris Lattnere2949f42008-01-06 22:42:25 +00004069 // Otherwise, the operands are not compatible.
Chris Lattner432cff52009-02-18 04:28:32 +00004070 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
4071 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004072 return QualType();
Steve Narofff8a28c52007-05-15 20:29:32 +00004073}
4074
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004075/// FindCompositeObjCPointerType - Helper method to find composite type of
4076/// two objective-c pointer types of the two input expressions.
4077QualType Sema::FindCompositeObjCPointerType(Expr *&LHS, Expr *&RHS,
4078 SourceLocation QuestionLoc) {
4079 QualType LHSTy = LHS->getType();
4080 QualType RHSTy = RHS->getType();
4081
4082 // Handle things like Class and struct objc_class*. Here we case the result
4083 // to the pseudo-builtin, because that will be implicitly cast back to the
4084 // redefinition type if an attempt is made to access its fields.
4085 if (LHSTy->isObjCClassType() &&
4086 (RHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
4087 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
4088 return LHSTy;
4089 }
4090 if (RHSTy->isObjCClassType() &&
4091 (LHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
4092 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
4093 return RHSTy;
4094 }
4095 // And the same for struct objc_object* / id
4096 if (LHSTy->isObjCIdType() &&
4097 (RHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
4098 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
4099 return LHSTy;
4100 }
4101 if (RHSTy->isObjCIdType() &&
4102 (LHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
4103 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
4104 return RHSTy;
4105 }
4106 // And the same for struct objc_selector* / SEL
4107 if (Context.isObjCSelType(LHSTy) &&
4108 (RHSTy.getDesugaredType() == Context.ObjCSelRedefinitionType)) {
4109 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
4110 return LHSTy;
4111 }
4112 if (Context.isObjCSelType(RHSTy) &&
4113 (LHSTy.getDesugaredType() == Context.ObjCSelRedefinitionType)) {
4114 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
4115 return RHSTy;
4116 }
4117 // Check constraints for Objective-C object pointers types.
4118 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
4119
4120 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4121 // Two identical object pointer types are always compatible.
4122 return LHSTy;
4123 }
4124 const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>();
4125 const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>();
4126 QualType compositeType = LHSTy;
4127
4128 // If both operands are interfaces and either operand can be
4129 // assigned to the other, use that type as the composite
4130 // type. This allows
4131 // xxx ? (A*) a : (B*) b
4132 // where B is a subclass of A.
4133 //
4134 // Additionally, as for assignment, if either type is 'id'
4135 // allow silent coercion. Finally, if the types are
4136 // incompatible then make sure to use 'id' as the composite
4137 // type so the result is acceptable for sending messages to.
4138
4139 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
4140 // It could return the composite type.
4141 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
4142 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
4143 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
4144 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
4145 } else if ((LHSTy->isObjCQualifiedIdType() ||
4146 RHSTy->isObjCQualifiedIdType()) &&
4147 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
4148 // Need to handle "id<xx>" explicitly.
4149 // GCC allows qualified id and any Objective-C type to devolve to
4150 // id. Currently localizing to here until clear this should be
4151 // part of ObjCQualifiedIdTypesAreCompatible.
4152 compositeType = Context.getObjCIdType();
4153 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
4154 compositeType = Context.getObjCIdType();
4155 } else if (!(compositeType =
4156 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
4157 ;
4158 else {
4159 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
4160 << LHSTy << RHSTy
4161 << LHS->getSourceRange() << RHS->getSourceRange();
4162 QualType incompatTy = Context.getObjCIdType();
4163 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
4164 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
4165 return incompatTy;
4166 }
4167 // The object pointer types are compatible.
4168 ImpCastExprToType(LHS, compositeType, CastExpr::CK_BitCast);
4169 ImpCastExprToType(RHS, compositeType, CastExpr::CK_BitCast);
4170 return compositeType;
4171 }
4172 // Check Objective-C object pointer types and 'void *'
4173 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
4174 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4175 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4176 QualType destPointee
4177 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4178 QualType destType = Context.getPointerType(destPointee);
4179 // Add qualifiers if necessary.
4180 ImpCastExprToType(LHS, destType, CastExpr::CK_NoOp);
4181 // Promote to void*.
4182 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
4183 return destType;
4184 }
4185 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
4186 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4187 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4188 QualType destPointee
4189 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4190 QualType destType = Context.getPointerType(destPointee);
4191 // Add qualifiers if necessary.
4192 ImpCastExprToType(RHS, destType, CastExpr::CK_NoOp);
4193 // Promote to void*.
4194 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
4195 return destType;
4196 }
4197 return QualType();
4198}
4199
Steve Naroff83895f72007-09-16 03:34:24 +00004200/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattnere168f762006-11-10 05:29:30 +00004201/// in the case of a the GNU conditional expr extension.
Sebastian Redlb5d49352009-01-19 22:31:54 +00004202Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
4203 SourceLocation ColonLoc,
4204 ExprArg Cond, ExprArg LHS,
4205 ExprArg RHS) {
4206 Expr *CondExpr = (Expr *) Cond.get();
4207 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
Chris Lattner2ab40a62007-11-26 01:40:58 +00004208
4209 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
4210 // was the condition.
4211 bool isLHSNull = LHSExpr == 0;
4212 if (isLHSNull)
4213 LHSExpr = CondExpr;
Sebastian Redlb5d49352009-01-19 22:31:54 +00004214
4215 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
Chris Lattnerdaaa9f22007-07-16 21:39:03 +00004216 RHSExpr, QuestionLoc);
Steve Narofff8a28c52007-05-15 20:29:32 +00004217 if (result.isNull())
Sebastian Redlb5d49352009-01-19 22:31:54 +00004218 return ExprError();
4219
4220 Cond.release();
4221 LHS.release();
4222 RHS.release();
Douglas Gregor7e112b02009-08-26 14:37:04 +00004223 return Owned(new (Context) ConditionalOperator(CondExpr, QuestionLoc,
Steve Narofff6009ed2009-01-21 00:14:39 +00004224 isLHSNull ? 0 : LHSExpr,
Douglas Gregor7e112b02009-08-26 14:37:04 +00004225 ColonLoc, RHSExpr, result));
Chris Lattnere168f762006-11-10 05:29:30 +00004226}
4227
Steve Naroff3f597292007-05-11 22:18:03 +00004228// CheckPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump4e1f26a2009-02-19 03:04:26 +00004229// being closely modeled after the C99 spec:-). The odd characteristic of this
Steve Naroff3f597292007-05-11 22:18:03 +00004230// routine is it effectively iqnores the qualifiers on the top level pointee.
4231// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
4232// FIXME: add a couple examples in this comment.
Mike Stump4e1f26a2009-02-19 03:04:26 +00004233Sema::AssignConvertType
Steve Naroff98cf3e92007-06-06 18:38:38 +00004234Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
Steve Naroff3f597292007-05-11 22:18:03 +00004235 QualType lhptee, rhptee;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004236
David Chisnall9f57c292009-08-17 16:35:33 +00004237 if ((lhsType->isObjCClassType() &&
4238 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
4239 (rhsType->isObjCClassType() &&
4240 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
4241 return Compatible;
4242 }
4243
Steve Naroff1f4d7272007-05-11 04:00:31 +00004244 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004245 lhptee = lhsType->getAs<PointerType>()->getPointeeType();
4246 rhptee = rhsType->getAs<PointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004247
Steve Naroff1f4d7272007-05-11 04:00:31 +00004248 // make sure we operate on the canonical type
Chris Lattner574dee62008-07-26 22:17:49 +00004249 lhptee = Context.getCanonicalType(lhptee);
4250 rhptee = Context.getCanonicalType(rhptee);
Steve Naroff1f4d7272007-05-11 04:00:31 +00004251
Chris Lattner9bad62c2008-01-04 18:04:52 +00004252 AssignConvertType ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004253
4254 // C99 6.5.16.1p1: This following citation is common to constraints
4255 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
4256 // qualifiers of the type *pointed to* by the right;
Fariborz Jahanianece85822009-02-17 18:27:45 +00004257 // FIXME: Handle ExtQualType
Douglas Gregor9a657932008-10-21 23:43:52 +00004258 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner9bad62c2008-01-04 18:04:52 +00004259 ConvTy = CompatiblePointerDiscardsQualifiers;
Steve Naroff3f597292007-05-11 22:18:03 +00004260
Mike Stump4e1f26a2009-02-19 03:04:26 +00004261 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
4262 // incomplete type and the other is a pointer to a qualified or unqualified
Steve Naroff3f597292007-05-11 22:18:03 +00004263 // version of void...
Chris Lattner0a788432008-01-03 22:56:36 +00004264 if (lhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00004265 if (rhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00004266 return ConvTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004267
Chris Lattner0a788432008-01-03 22:56:36 +00004268 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00004269 assert(rhptee->isFunctionType());
4270 return FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00004271 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004272
Chris Lattner0a788432008-01-03 22:56:36 +00004273 if (rhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00004274 if (lhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00004275 return ConvTy;
Chris Lattner0a788432008-01-03 22:56:36 +00004276
4277 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00004278 assert(lhptee->isFunctionType());
4279 return FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00004280 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004281 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Steve Naroff3f597292007-05-11 22:18:03 +00004282 // unqualified versions of compatible types, ...
Eli Friedman80160bd2009-03-22 23:59:44 +00004283 lhptee = lhptee.getUnqualifiedType();
4284 rhptee = rhptee.getUnqualifiedType();
4285 if (!Context.typesAreCompatible(lhptee, rhptee)) {
4286 // Check if the pointee types are compatible ignoring the sign.
4287 // We explicitly check for char so that we catch "char" vs
4288 // "unsigned char" on systems where "char" is unsigned.
Chris Lattnerec3a1562009-10-17 20:33:28 +00004289 if (lhptee->isCharType())
Eli Friedman80160bd2009-03-22 23:59:44 +00004290 lhptee = Context.UnsignedCharTy;
Chris Lattnerec3a1562009-10-17 20:33:28 +00004291 else if (lhptee->isSignedIntegerType())
Eli Friedman80160bd2009-03-22 23:59:44 +00004292 lhptee = Context.getCorrespondingUnsignedType(lhptee);
Chris Lattnerec3a1562009-10-17 20:33:28 +00004293
4294 if (rhptee->isCharType())
Eli Friedman80160bd2009-03-22 23:59:44 +00004295 rhptee = Context.UnsignedCharTy;
Chris Lattnerec3a1562009-10-17 20:33:28 +00004296 else if (rhptee->isSignedIntegerType())
Eli Friedman80160bd2009-03-22 23:59:44 +00004297 rhptee = Context.getCorrespondingUnsignedType(rhptee);
Chris Lattnerec3a1562009-10-17 20:33:28 +00004298
Eli Friedman80160bd2009-03-22 23:59:44 +00004299 if (lhptee == rhptee) {
4300 // Types are compatible ignoring the sign. Qualifier incompatibility
4301 // takes priority over sign incompatibility because the sign
4302 // warning can be disabled.
4303 if (ConvTy != Compatible)
4304 return ConvTy;
4305 return IncompatiblePointerSign;
4306 }
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00004307
4308 // If we are a multi-level pointer, it's possible that our issue is simply
4309 // one of qualification - e.g. char ** -> const char ** is not allowed. If
4310 // the eventual target type is the same and the pointers have the same
4311 // level of indirection, this must be the issue.
4312 if (lhptee->isPointerType() && rhptee->isPointerType()) {
4313 do {
4314 lhptee = lhptee->getAs<PointerType>()->getPointeeType();
4315 rhptee = rhptee->getAs<PointerType>()->getPointeeType();
4316
4317 lhptee = Context.getCanonicalType(lhptee);
4318 rhptee = Context.getCanonicalType(rhptee);
4319 } while (lhptee->isPointerType() && rhptee->isPointerType());
4320
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004321 if (Context.hasSameUnqualifiedType(lhptee, rhptee))
Alexis Hunt6f3de502009-11-08 07:46:34 +00004322 return IncompatibleNestedPointerQualifiers;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00004323 }
4324
Eli Friedman80160bd2009-03-22 23:59:44 +00004325 // General pointer incompatibility takes priority over qualifiers.
Mike Stump11289f42009-09-09 15:08:12 +00004326 return IncompatiblePointer;
Eli Friedman80160bd2009-03-22 23:59:44 +00004327 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00004328 return ConvTy;
Steve Naroff1f4d7272007-05-11 04:00:31 +00004329}
4330
Steve Naroff081c7422008-09-04 15:10:53 +00004331/// CheckBlockPointerTypesForAssignment - This routine determines whether two
4332/// block pointer types are compatible or whether a block and normal pointer
4333/// are compatible. It is more restrict than comparing two function pointer
4334// types.
Mike Stump4e1f26a2009-02-19 03:04:26 +00004335Sema::AssignConvertType
4336Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
Steve Naroff081c7422008-09-04 15:10:53 +00004337 QualType rhsType) {
4338 QualType lhptee, rhptee;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004339
Steve Naroff081c7422008-09-04 15:10:53 +00004340 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004341 lhptee = lhsType->getAs<BlockPointerType>()->getPointeeType();
4342 rhptee = rhsType->getAs<BlockPointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004343
Steve Naroff081c7422008-09-04 15:10:53 +00004344 // make sure we operate on the canonical type
4345 lhptee = Context.getCanonicalType(lhptee);
4346 rhptee = Context.getCanonicalType(rhptee);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004347
Steve Naroff081c7422008-09-04 15:10:53 +00004348 AssignConvertType ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004349
Steve Naroff081c7422008-09-04 15:10:53 +00004350 // For blocks we enforce that qualifiers are identical.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004351 if (lhptee.getLocalCVRQualifiers() != rhptee.getLocalCVRQualifiers())
Steve Naroff081c7422008-09-04 15:10:53 +00004352 ConvTy = CompatiblePointerDiscardsQualifiers;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004353
Eli Friedmana6638ca2009-06-08 05:08:54 +00004354 if (!Context.typesAreCompatible(lhptee, rhptee))
Mike Stump4e1f26a2009-02-19 03:04:26 +00004355 return IncompatibleBlockPointer;
Steve Naroff081c7422008-09-04 15:10:53 +00004356 return ConvTy;
4357}
4358
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00004359/// CheckObjCPointerTypesForAssignment - Compares two objective-c pointer types
4360/// for assignment compatibility.
4361Sema::AssignConvertType
4362Sema::CheckObjCPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
4363 if (lhsType->isObjCBuiltinType() || rhsType->isObjCBuiltinType())
4364 return Compatible;
4365 QualType lhptee =
4366 lhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
4367 QualType rhptee =
4368 rhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
4369 // make sure we operate on the canonical type
4370 lhptee = Context.getCanonicalType(lhptee);
4371 rhptee = Context.getCanonicalType(rhptee);
4372 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
4373 return CompatiblePointerDiscardsQualifiers;
4374
4375 if (Context.typesAreCompatible(lhsType, rhsType))
4376 return Compatible;
4377 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
4378 return IncompatibleObjCQualifiedId;
4379 return IncompatiblePointer;
4380}
4381
Mike Stump4e1f26a2009-02-19 03:04:26 +00004382/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
4383/// has code to accommodate several GCC extensions when type checking
Steve Naroff17f76e02007-05-03 21:03:48 +00004384/// pointers. Here are some objectionable examples that GCC considers warnings:
4385///
4386/// int a, *pint;
4387/// short *pshort;
4388/// struct foo *pfoo;
4389///
4390/// pint = pshort; // warning: assignment from incompatible pointer type
4391/// a = pint; // warning: assignment makes integer from pointer without a cast
4392/// pint = a; // warning: assignment makes pointer from integer without a cast
4393/// pint = pfoo; // warning: assignment from incompatible pointer type
4394///
4395/// As a result, the code for dealing with pointers is more complex than the
Mike Stump4e1f26a2009-02-19 03:04:26 +00004396/// C99 spec dictates.
Steve Naroff17f76e02007-05-03 21:03:48 +00004397///
Chris Lattner9bad62c2008-01-04 18:04:52 +00004398Sema::AssignConvertType
Steve Naroff98cf3e92007-06-06 18:38:38 +00004399Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattnera52c2f22008-01-04 23:18:45 +00004400 // Get canonical types. We're not formatting these types, just comparing
4401 // them.
Chris Lattner574dee62008-07-26 22:17:49 +00004402 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
4403 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman3360d892008-05-30 18:07:22 +00004404
4405 if (lhsType == rhsType)
Chris Lattnerf5c973d2008-01-07 17:51:46 +00004406 return Compatible; // Common case: fast path an exact match.
Steve Naroff44fd8ff2007-07-24 21:46:40 +00004407
David Chisnall9f57c292009-08-17 16:35:33 +00004408 if ((lhsType->isObjCClassType() &&
4409 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
4410 (rhsType->isObjCClassType() &&
4411 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
4412 return Compatible;
4413 }
4414
Douglas Gregor6b754842008-10-28 00:22:11 +00004415 // If the left-hand side is a reference type, then we are in a
4416 // (rare!) case where we've allowed the use of references in C,
4417 // e.g., as a parameter type in a built-in function. In this case,
4418 // just make sure that the type referenced is compatible with the
4419 // right-hand side type. The caller is responsible for adjusting
4420 // lhsType so that the resulting expression does not have reference
4421 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004422 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
Douglas Gregor6b754842008-10-28 00:22:11 +00004423 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlsson24ebce62007-10-12 23:56:29 +00004424 return Compatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00004425 return Incompatible;
Fariborz Jahaniana1e34202007-12-19 17:45:58 +00004426 }
Nate Begemanbd956c42009-06-28 02:36:38 +00004427 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
4428 // to the same ExtVector type.
4429 if (lhsType->isExtVectorType()) {
4430 if (rhsType->isExtVectorType())
4431 return lhsType == rhsType ? Compatible : Incompatible;
4432 if (!rhsType->isVectorType() && rhsType->isArithmeticType())
4433 return Compatible;
4434 }
Mike Stump11289f42009-09-09 15:08:12 +00004435
Nate Begeman191a6b12008-07-14 18:02:46 +00004436 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begeman191a6b12008-07-14 18:02:46 +00004437 // If we are allowing lax vector conversions, and LHS and RHS are both
Mike Stump4e1f26a2009-02-19 03:04:26 +00004438 // vectors, the total size only needs to be the same. This is a bitcast;
Nate Begeman191a6b12008-07-14 18:02:46 +00004439 // no bits are changed but the result type is different.
Chris Lattner881a2122008-01-04 23:32:24 +00004440 if (getLangOptions().LaxVectorConversions &&
4441 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begeman191a6b12008-07-14 18:02:46 +00004442 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
Anders Carlssondb5a9b62009-01-30 23:17:46 +00004443 return IncompatibleVectors;
Chris Lattner881a2122008-01-04 23:32:24 +00004444 }
4445 return Incompatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004446 }
Eli Friedman3360d892008-05-30 18:07:22 +00004447
Chris Lattner881a2122008-01-04 23:32:24 +00004448 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Steve Naroff98cf3e92007-06-06 18:38:38 +00004449 return Compatible;
Eli Friedman3360d892008-05-30 18:07:22 +00004450
Chris Lattnerec646832008-04-07 06:49:41 +00004451 if (isa<PointerType>(lhsType)) {
Steve Naroff98cf3e92007-06-06 18:38:38 +00004452 if (rhsType->isIntegerType())
Chris Lattner940cfeb2008-01-04 18:22:42 +00004453 return IntToPointer;
Eli Friedman3360d892008-05-30 18:07:22 +00004454
Chris Lattnerec646832008-04-07 06:49:41 +00004455 if (isa<PointerType>(rhsType))
Steve Naroff98cf3e92007-06-06 18:38:38 +00004456 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004457
Steve Naroffaccc4882009-07-20 17:56:53 +00004458 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004459 if (isa<ObjCObjectPointerType>(rhsType)) {
Steve Naroffaccc4882009-07-20 17:56:53 +00004460 if (lhsType->isVoidPointerType()) // an exception to the rule.
4461 return Compatible;
4462 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004463 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004464 if (rhsType->getAs<BlockPointerType>()) {
4465 if (lhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregore7dd1452008-11-27 00:44:28 +00004466 return Compatible;
Steve Naroff32d072c2008-09-29 18:10:17 +00004467
4468 // Treat block pointers as objects.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004469 if (getLangOptions().ObjC1 && lhsType->isObjCIdType())
Steve Naroff32d072c2008-09-29 18:10:17 +00004470 return Compatible;
4471 }
Steve Naroff081c7422008-09-04 15:10:53 +00004472 return Incompatible;
4473 }
4474
4475 if (isa<BlockPointerType>(lhsType)) {
4476 if (rhsType->isIntegerType())
Eli Friedman8163b7a2009-02-25 04:20:42 +00004477 return IntToBlockPointer;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004478
Steve Naroff32d072c2008-09-29 18:10:17 +00004479 // Treat block pointers as objects.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004480 if (getLangOptions().ObjC1 && rhsType->isObjCIdType())
Steve Naroff32d072c2008-09-29 18:10:17 +00004481 return Compatible;
4482
Steve Naroff081c7422008-09-04 15:10:53 +00004483 if (rhsType->isBlockPointerType())
4484 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004485
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004486 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff081c7422008-09-04 15:10:53 +00004487 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregore7dd1452008-11-27 00:44:28 +00004488 return Compatible;
Steve Naroff081c7422008-09-04 15:10:53 +00004489 }
Chris Lattnera52c2f22008-01-04 23:18:45 +00004490 return Incompatible;
4491 }
4492
Steve Naroff7cae42b2009-07-10 23:34:53 +00004493 if (isa<ObjCObjectPointerType>(lhsType)) {
4494 if (rhsType->isIntegerType())
4495 return IntToPointer;
Mike Stump11289f42009-09-09 15:08:12 +00004496
Steve Naroffaccc4882009-07-20 17:56:53 +00004497 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004498 if (isa<PointerType>(rhsType)) {
Steve Naroffaccc4882009-07-20 17:56:53 +00004499 if (rhsType->isVoidPointerType()) // an exception to the rule.
4500 return Compatible;
4501 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004502 }
4503 if (rhsType->isObjCObjectPointerType()) {
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00004504 return CheckObjCPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff7cae42b2009-07-10 23:34:53 +00004505 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004506 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004507 if (RHSPT->getPointeeType()->isVoidType())
4508 return Compatible;
4509 }
4510 // Treat block pointers as objects.
4511 if (rhsType->isBlockPointerType())
4512 return Compatible;
4513 return Incompatible;
4514 }
Chris Lattnerec646832008-04-07 06:49:41 +00004515 if (isa<PointerType>(rhsType)) {
Steve Naroff98cf3e92007-06-06 18:38:38 +00004516 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedman3360d892008-05-30 18:07:22 +00004517 if (lhsType == Context.BoolTy)
4518 return Compatible;
4519
4520 if (lhsType->isIntegerType())
Chris Lattner940cfeb2008-01-04 18:22:42 +00004521 return PointerToInt;
Steve Naroff98cf3e92007-06-06 18:38:38 +00004522
Mike Stump4e1f26a2009-02-19 03:04:26 +00004523 if (isa<PointerType>(lhsType))
Steve Naroff98cf3e92007-06-06 18:38:38 +00004524 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004525
4526 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004527 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregore7dd1452008-11-27 00:44:28 +00004528 return Compatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00004529 return Incompatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00004530 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00004531 if (isa<ObjCObjectPointerType>(rhsType)) {
4532 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
4533 if (lhsType == Context.BoolTy)
4534 return Compatible;
4535
4536 if (lhsType->isIntegerType())
4537 return PointerToInt;
4538
Steve Naroffaccc4882009-07-20 17:56:53 +00004539 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004540 if (isa<PointerType>(lhsType)) {
Steve Naroffaccc4882009-07-20 17:56:53 +00004541 if (lhsType->isVoidPointerType()) // an exception to the rule.
4542 return Compatible;
4543 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004544 }
4545 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004546 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00004547 return Compatible;
4548 return Incompatible;
4549 }
Eli Friedman3360d892008-05-30 18:07:22 +00004550
Chris Lattnera52c2f22008-01-04 23:18:45 +00004551 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattnerec646832008-04-07 06:49:41 +00004552 if (Context.typesAreCompatible(lhsType, rhsType))
Steve Naroff98cf3e92007-06-06 18:38:38 +00004553 return Compatible;
Bill Wendling216423b2007-05-30 06:30:29 +00004554 }
Steve Naroff98cf3e92007-06-06 18:38:38 +00004555 return Incompatible;
Steve Naroff9eb24652007-05-02 21:58:15 +00004556}
4557
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004558/// \brief Constructs a transparent union from an expression that is
4559/// used to initialize the transparent union.
Mike Stump11289f42009-09-09 15:08:12 +00004560static void ConstructTransparentUnion(ASTContext &C, Expr *&E,
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004561 QualType UnionType, FieldDecl *Field) {
4562 // Build an initializer list that designates the appropriate member
4563 // of the transparent union.
4564 InitListExpr *Initializer = new (C) InitListExpr(SourceLocation(),
4565 &E, 1,
4566 SourceLocation());
4567 Initializer->setType(UnionType);
4568 Initializer->setInitializedFieldInUnion(Field);
4569
4570 // Build a compound literal constructing a value of the transparent
4571 // union type from this initializer list.
4572 E = new (C) CompoundLiteralExpr(SourceLocation(), UnionType, Initializer,
4573 false);
4574}
4575
4576Sema::AssignConvertType
4577Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) {
4578 QualType FromType = rExpr->getType();
4579
Mike Stump11289f42009-09-09 15:08:12 +00004580 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004581 // transparent_union GCC extension.
4582 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004583 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004584 return Incompatible;
4585
4586 // The field to initialize within the transparent union.
4587 RecordDecl *UD = UT->getDecl();
4588 FieldDecl *InitField = 0;
4589 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004590 for (RecordDecl::field_iterator it = UD->field_begin(),
4591 itend = UD->field_end();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004592 it != itend; ++it) {
4593 if (it->getType()->isPointerType()) {
4594 // If the transparent union contains a pointer type, we allow:
4595 // 1) void pointer
4596 // 2) null pointer constant
4597 if (FromType->isPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004598 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004599 ImpCastExprToType(rExpr, it->getType(), CastExpr::CK_BitCast);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004600 InitField = *it;
4601 break;
4602 }
Mike Stump11289f42009-09-09 15:08:12 +00004603
Douglas Gregor56751b52009-09-25 04:25:58 +00004604 if (rExpr->isNullPointerConstant(Context,
4605 Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004606 ImpCastExprToType(rExpr, it->getType(), CastExpr::CK_IntegralToPointer);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004607 InitField = *it;
4608 break;
4609 }
4610 }
4611
4612 if (CheckAssignmentConstraints(it->getType(), rExpr->getType())
4613 == Compatible) {
4614 InitField = *it;
4615 break;
4616 }
4617 }
4618
4619 if (!InitField)
4620 return Incompatible;
4621
4622 ConstructTransparentUnion(Context, rExpr, ArgType, InitField);
4623 return Compatible;
4624}
4625
Chris Lattner9bad62c2008-01-04 18:04:52 +00004626Sema::AssignConvertType
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00004627Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor9a657932008-10-21 23:43:52 +00004628 if (getLangOptions().CPlusPlus) {
4629 if (!lhsType->isRecordType()) {
4630 // C++ 5.17p3: If the left operand is not of class type, the
4631 // expression is implicitly converted (C++ 4) to the
4632 // cv-unqualified type of the left operand.
Douglas Gregor47d3f272008-12-19 17:40:08 +00004633 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
4634 "assigning"))
Douglas Gregor9a657932008-10-21 23:43:52 +00004635 return Incompatible;
Chris Lattner0d5640c2009-04-12 09:02:39 +00004636 return Compatible;
Douglas Gregor9a657932008-10-21 23:43:52 +00004637 }
4638
4639 // FIXME: Currently, we fall through and treat C++ classes like C
4640 // structures.
4641 }
4642
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00004643 // C99 6.5.16.1p1: the left operand is a pointer and the right is
4644 // a null pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00004645 if ((lhsType->isPointerType() ||
4646 lhsType->isObjCObjectPointerType() ||
Mike Stump4e1f26a2009-02-19 03:04:26 +00004647 lhsType->isBlockPointerType())
Douglas Gregor56751b52009-09-25 04:25:58 +00004648 && rExpr->isNullPointerConstant(Context,
4649 Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004650 ImpCastExprToType(rExpr, lhsType, CastExpr::CK_Unknown);
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00004651 return Compatible;
4652 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004653
Chris Lattnere6dcd502007-10-16 02:55:40 +00004654 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00004655 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregora121b752009-11-03 16:56:39 +00004656 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00004657 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattnere6dcd502007-10-16 02:55:40 +00004658 //
Mike Stump4e1f26a2009-02-19 03:04:26 +00004659 // Suppress this for references: C++ 8.5.3p5.
Chris Lattnere6dcd502007-10-16 02:55:40 +00004660 if (!lhsType->isReferenceType())
4661 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00004662
Chris Lattner9bad62c2008-01-04 18:04:52 +00004663 Sema::AssignConvertType result =
4664 CheckAssignmentConstraints(lhsType, rExpr->getType());
Mike Stump4e1f26a2009-02-19 03:04:26 +00004665
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00004666 // C99 6.5.16.1p2: The value of the right operand is converted to the
4667 // type of the assignment expression.
Douglas Gregor6b754842008-10-28 00:22:11 +00004668 // CheckAssignmentConstraints allows the left-hand side to be a reference,
4669 // so that we can use references in built-in functions even in C.
4670 // The getNonReferenceType() call makes sure that the resulting expression
4671 // does not have reference type.
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004672 if (result != Incompatible && rExpr->getType() != lhsType)
Eli Friedman06ed2a52009-10-20 08:27:19 +00004673 ImpCastExprToType(rExpr, lhsType.getNonReferenceType(),
4674 CastExpr::CK_Unknown);
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00004675 return result;
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00004676}
4677
Chris Lattner326f7572008-11-18 01:30:42 +00004678QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattner377d1f82008-11-18 22:52:51 +00004679 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattner6a2ed6f2008-11-23 09:13:29 +00004680 << lex->getType() << rex->getType()
Chris Lattner377d1f82008-11-18 22:52:51 +00004681 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner5c11c412007-12-12 05:47:28 +00004682 return QualType();
Steve Naroff6f49f5d2007-05-29 14:23:36 +00004683}
4684
Mike Stump4e1f26a2009-02-19 03:04:26 +00004685inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Steve Naroff7a5af782007-07-13 16:58:59 +00004686 Expr *&rex) {
Mike Stump4e1f26a2009-02-19 03:04:26 +00004687 // For conversion purposes, we ignore any qualifiers.
Nate Begeman002e4bd2008-04-04 01:30:25 +00004688 // For example, "const float" and "float" are equivalent.
Chris Lattner574dee62008-07-26 22:17:49 +00004689 QualType lhsType =
4690 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
4691 QualType rhsType =
4692 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004693
Nate Begeman191a6b12008-07-14 18:02:46 +00004694 // If the vector types are identical, return.
Nate Begeman002e4bd2008-04-04 01:30:25 +00004695 if (lhsType == rhsType)
Steve Naroff84ff4b42007-07-09 21:31:10 +00004696 return lhsType;
Nate Begeman330aaa72007-12-30 02:59:45 +00004697
Nate Begeman191a6b12008-07-14 18:02:46 +00004698 // Handle the case of a vector & extvector type of the same size and element
4699 // type. It would be nice if we only had one vector type someday.
Anders Carlssondb5a9b62009-01-30 23:17:46 +00004700 if (getLangOptions().LaxVectorConversions) {
4701 // FIXME: Should we warn here?
John McCall9dd450b2009-09-21 23:43:11 +00004702 if (const VectorType *LV = lhsType->getAs<VectorType>()) {
4703 if (const VectorType *RV = rhsType->getAs<VectorType>())
Nate Begeman191a6b12008-07-14 18:02:46 +00004704 if (LV->getElementType() == RV->getElementType() &&
Anders Carlssondb5a9b62009-01-30 23:17:46 +00004705 LV->getNumElements() == RV->getNumElements()) {
Nate Begeman191a6b12008-07-14 18:02:46 +00004706 return lhsType->isExtVectorType() ? lhsType : rhsType;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00004707 }
4708 }
4709 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004710
Nate Begemanbd956c42009-06-28 02:36:38 +00004711 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
4712 // swap back (so that we don't reverse the inputs to a subtract, for instance.
4713 bool swapped = false;
4714 if (rhsType->isExtVectorType()) {
4715 swapped = true;
4716 std::swap(rex, lex);
4717 std::swap(rhsType, lhsType);
4718 }
Mike Stump11289f42009-09-09 15:08:12 +00004719
Nate Begeman886448d2009-06-28 19:12:57 +00004720 // Handle the case of an ext vector and scalar.
John McCall9dd450b2009-09-21 23:43:11 +00004721 if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) {
Nate Begemanbd956c42009-06-28 02:36:38 +00004722 QualType EltTy = LV->getElementType();
4723 if (EltTy->isIntegralType() && rhsType->isIntegralType()) {
4724 if (Context.getIntegerTypeOrder(EltTy, rhsType) >= 0) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004725 ImpCastExprToType(rex, lhsType, CastExpr::CK_IntegralCast);
Nate Begemanbd956c42009-06-28 02:36:38 +00004726 if (swapped) std::swap(rex, lex);
4727 return lhsType;
4728 }
4729 }
4730 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
4731 rhsType->isRealFloatingType()) {
4732 if (Context.getFloatingTypeOrder(EltTy, rhsType) >= 0) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004733 ImpCastExprToType(rex, lhsType, CastExpr::CK_FloatingCast);
Nate Begemanbd956c42009-06-28 02:36:38 +00004734 if (swapped) std::swap(rex, lex);
4735 return lhsType;
4736 }
Nate Begeman330aaa72007-12-30 02:59:45 +00004737 }
4738 }
Mike Stump11289f42009-09-09 15:08:12 +00004739
Nate Begeman886448d2009-06-28 19:12:57 +00004740 // Vectors of different size or scalar and non-ext-vector are errors.
Chris Lattner377d1f82008-11-18 22:52:51 +00004741 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004742 << lex->getType() << rex->getType()
Chris Lattner377d1f82008-11-18 22:52:51 +00004743 << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff84ff4b42007-07-09 21:31:10 +00004744 return QualType();
Sebastian Redl112a97662009-02-07 00:15:38 +00004745}
4746
Steve Naroff218bc2b2007-05-04 21:54:46 +00004747inline QualType Sema::CheckMultiplyDivideOperands(
Mike Stump11289f42009-09-09 15:08:12 +00004748 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Daniel Dunbar060d5e22009-01-05 22:42:10 +00004749 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner326f7572008-11-18 01:30:42 +00004750 return CheckVectorOperands(Loc, lex, rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004751
Steve Naroffbe4c4d12007-08-24 19:07:16 +00004752 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004753
Steve Naroffdbd9e892007-07-17 00:58:39 +00004754 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroffbe4c4d12007-08-24 19:07:16 +00004755 return compType;
Chris Lattner326f7572008-11-18 01:30:42 +00004756 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00004757}
4758
Steve Naroff218bc2b2007-05-04 21:54:46 +00004759inline QualType Sema::CheckRemainderOperands(
Mike Stump11289f42009-09-09 15:08:12 +00004760 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Daniel Dunbar0d2bfec2009-01-05 22:55:36 +00004761 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4762 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
4763 return CheckVectorOperands(Loc, lex, rex);
4764 return InvalidOperands(Loc, lex, rex);
4765 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00004766
Steve Naroffbe4c4d12007-08-24 19:07:16 +00004767 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004768
Steve Naroffdbd9e892007-07-17 00:58:39 +00004769 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroffbe4c4d12007-08-24 19:07:16 +00004770 return compType;
Chris Lattner326f7572008-11-18 01:30:42 +00004771 return InvalidOperands(Loc, lex, rex);
Steve Naroff218bc2b2007-05-04 21:54:46 +00004772}
4773
4774inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Mike Stump11289f42009-09-09 15:08:12 +00004775 Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004776 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4777 QualType compType = CheckVectorOperands(Loc, lex, rex);
4778 if (CompLHSTy) *CompLHSTy = compType;
4779 return compType;
4780 }
Steve Naroff7a5af782007-07-13 16:58:59 +00004781
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004782 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Eli Friedman8e122982008-05-18 18:08:51 +00004783
Steve Naroffe4718892007-04-27 18:30:00 +00004784 // handle the common case first (both operands are arithmetic).
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004785 if (lex->getType()->isArithmeticType() &&
4786 rex->getType()->isArithmeticType()) {
4787 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00004788 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004789 }
Steve Naroff218bc2b2007-05-04 21:54:46 +00004790
Eli Friedman8e122982008-05-18 18:08:51 +00004791 // Put any potential pointer into PExp
4792 Expr* PExp = lex, *IExp = rex;
Steve Naroff6b712a72009-07-14 18:25:06 +00004793 if (IExp->getType()->isAnyPointerType())
Eli Friedman8e122982008-05-18 18:08:51 +00004794 std::swap(PExp, IExp);
4795
Steve Naroff6b712a72009-07-14 18:25:06 +00004796 if (PExp->getType()->isAnyPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00004797
Eli Friedman8e122982008-05-18 18:08:51 +00004798 if (IExp->getType()->isIntegerType()) {
Steve Naroffaacd4cc2009-07-13 21:20:41 +00004799 QualType PointeeTy = PExp->getType()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00004800
Chris Lattner12bdebb2009-04-24 23:50:08 +00004801 // Check for arithmetic on pointers to incomplete types.
4802 if (PointeeTy->isVoidType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00004803 if (getLangOptions().CPlusPlus) {
4804 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
Chris Lattner3b054132008-11-19 05:08:23 +00004805 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregordd430f72009-01-19 19:26:10 +00004806 return QualType();
Eli Friedman8e122982008-05-18 18:08:51 +00004807 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00004808
4809 // GNU extension: arithmetic on pointer to void
4810 Diag(Loc, diag::ext_gnu_void_ptr)
4811 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner12bdebb2009-04-24 23:50:08 +00004812 } else if (PointeeTy->isFunctionType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00004813 if (getLangOptions().CPlusPlus) {
4814 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
4815 << lex->getType() << lex->getSourceRange();
4816 return QualType();
4817 }
4818
4819 // GNU extension: arithmetic on pointer to function
4820 Diag(Loc, diag::ext_gnu_ptr_func_arith)
4821 << lex->getType() << lex->getSourceRange();
Steve Naroffa63372d2009-07-13 21:32:29 +00004822 } else {
Steve Naroffaacd4cc2009-07-13 21:20:41 +00004823 // Check if we require a complete type.
Mike Stump11289f42009-09-09 15:08:12 +00004824 if (((PExp->getType()->isPointerType() &&
Steve Naroffa63372d2009-07-13 21:32:29 +00004825 !PExp->getType()->isDependentType()) ||
Steve Naroffaacd4cc2009-07-13 21:20:41 +00004826 PExp->getType()->isObjCObjectPointerType()) &&
4827 RequireCompleteType(Loc, PointeeTy,
Mike Stump11289f42009-09-09 15:08:12 +00004828 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
4829 << PExp->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00004830 << PExp->getType()))
Steve Naroffaacd4cc2009-07-13 21:20:41 +00004831 return QualType();
4832 }
Chris Lattner12bdebb2009-04-24 23:50:08 +00004833 // Diagnose bad cases where we step over interface counts.
4834 if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4835 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
4836 << PointeeTy << PExp->getSourceRange();
4837 return QualType();
4838 }
Mike Stump11289f42009-09-09 15:08:12 +00004839
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004840 if (CompLHSTy) {
Eli Friedman629ffb92009-08-20 04:21:42 +00004841 QualType LHSTy = Context.isPromotableBitField(lex);
4842 if (LHSTy.isNull()) {
4843 LHSTy = lex->getType();
4844 if (LHSTy->isPromotableIntegerType())
4845 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregord2c2d172009-05-02 00:36:19 +00004846 }
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004847 *CompLHSTy = LHSTy;
4848 }
Eli Friedman8e122982008-05-18 18:08:51 +00004849 return PExp->getType();
4850 }
4851 }
4852
Chris Lattner326f7572008-11-18 01:30:42 +00004853 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00004854}
4855
Chris Lattner2a3569b2008-04-07 05:30:13 +00004856// C99 6.5.6
4857QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004858 SourceLocation Loc, QualType* CompLHSTy) {
4859 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4860 QualType compType = CheckVectorOperands(Loc, lex, rex);
4861 if (CompLHSTy) *CompLHSTy = compType;
4862 return compType;
4863 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004864
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004865 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004866
Chris Lattner4d62f422007-12-09 21:53:25 +00004867 // Enforce type constraints: C99 6.5.6p3.
Mike Stump4e1f26a2009-02-19 03:04:26 +00004868
Chris Lattner4d62f422007-12-09 21:53:25 +00004869 // Handle the common case first (both operands are arithmetic).
Mike Stumpf70bcf72009-05-07 18:43:07 +00004870 if (lex->getType()->isArithmeticType()
4871 && rex->getType()->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004872 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00004873 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004874 }
Mike Stump11289f42009-09-09 15:08:12 +00004875
Chris Lattner4d62f422007-12-09 21:53:25 +00004876 // Either ptr - int or ptr - ptr.
Steve Naroff6b712a72009-07-14 18:25:06 +00004877 if (lex->getType()->isAnyPointerType()) {
Steve Naroff4eed7a12009-07-13 17:19:15 +00004878 QualType lpointee = lex->getType()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004879
Douglas Gregorac1fb652009-03-24 19:52:54 +00004880 // The LHS must be an completely-defined object type.
Douglas Gregorf6cd9282009-01-23 00:36:41 +00004881
Douglas Gregorac1fb652009-03-24 19:52:54 +00004882 bool ComplainAboutVoid = false;
4883 Expr *ComplainAboutFunc = 0;
4884 if (lpointee->isVoidType()) {
4885 if (getLangOptions().CPlusPlus) {
4886 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
4887 << lex->getSourceRange() << rex->getSourceRange();
4888 return QualType();
4889 }
4890
4891 // GNU C extension: arithmetic on pointer to void
4892 ComplainAboutVoid = true;
4893 } else if (lpointee->isFunctionType()) {
4894 if (getLangOptions().CPlusPlus) {
4895 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004896 << lex->getType() << lex->getSourceRange();
Chris Lattner4d62f422007-12-09 21:53:25 +00004897 return QualType();
4898 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00004899
4900 // GNU C extension: arithmetic on pointer to function
4901 ComplainAboutFunc = lex;
4902 } else if (!lpointee->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00004903 RequireCompleteType(Loc, lpointee,
Anders Carlsson029fc692009-08-26 22:59:12 +00004904 PDiag(diag::err_typecheck_sub_ptr_object)
Mike Stump11289f42009-09-09 15:08:12 +00004905 << lex->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00004906 << lex->getType()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00004907 return QualType();
Chris Lattner4d62f422007-12-09 21:53:25 +00004908
Chris Lattner12bdebb2009-04-24 23:50:08 +00004909 // Diagnose bad cases where we step over interface counts.
4910 if (lpointee->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4911 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
4912 << lpointee << lex->getSourceRange();
4913 return QualType();
4914 }
Mike Stump11289f42009-09-09 15:08:12 +00004915
Chris Lattner4d62f422007-12-09 21:53:25 +00004916 // The result type of a pointer-int computation is the pointer type.
Douglas Gregorac1fb652009-03-24 19:52:54 +00004917 if (rex->getType()->isIntegerType()) {
4918 if (ComplainAboutVoid)
4919 Diag(Loc, diag::ext_gnu_void_ptr)
4920 << lex->getSourceRange() << rex->getSourceRange();
4921 if (ComplainAboutFunc)
4922 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump11289f42009-09-09 15:08:12 +00004923 << ComplainAboutFunc->getType()
Douglas Gregorac1fb652009-03-24 19:52:54 +00004924 << ComplainAboutFunc->getSourceRange();
4925
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004926 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00004927 return lex->getType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00004928 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004929
Chris Lattner4d62f422007-12-09 21:53:25 +00004930 // Handle pointer-pointer subtractions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004931 if (const PointerType *RHSPTy = rex->getType()->getAs<PointerType>()) {
Eli Friedman1974e532008-02-08 01:19:44 +00004932 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004933
Douglas Gregorac1fb652009-03-24 19:52:54 +00004934 // RHS must be a completely-type object type.
4935 // Handle the GNU void* extension.
4936 if (rpointee->isVoidType()) {
4937 if (getLangOptions().CPlusPlus) {
4938 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
4939 << lex->getSourceRange() << rex->getSourceRange();
4940 return QualType();
4941 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004942
Douglas Gregorac1fb652009-03-24 19:52:54 +00004943 ComplainAboutVoid = true;
4944 } else if (rpointee->isFunctionType()) {
4945 if (getLangOptions().CPlusPlus) {
4946 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004947 << rex->getType() << rex->getSourceRange();
Chris Lattner4d62f422007-12-09 21:53:25 +00004948 return QualType();
4949 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00004950
4951 // GNU extension: arithmetic on pointer to function
4952 if (!ComplainAboutFunc)
4953 ComplainAboutFunc = rex;
4954 } else if (!rpointee->isDependentType() &&
4955 RequireCompleteType(Loc, rpointee,
Anders Carlsson029fc692009-08-26 22:59:12 +00004956 PDiag(diag::err_typecheck_sub_ptr_object)
4957 << rex->getSourceRange()
4958 << rex->getType()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00004959 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004960
Eli Friedman168fe152009-05-16 13:54:38 +00004961 if (getLangOptions().CPlusPlus) {
4962 // Pointee types must be the same: C++ [expr.add]
4963 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
4964 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
4965 << lex->getType() << rex->getType()
4966 << lex->getSourceRange() << rex->getSourceRange();
4967 return QualType();
4968 }
4969 } else {
4970 // Pointee types must be compatible C99 6.5.6p3
4971 if (!Context.typesAreCompatible(
4972 Context.getCanonicalType(lpointee).getUnqualifiedType(),
4973 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
4974 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
4975 << lex->getType() << rex->getType()
4976 << lex->getSourceRange() << rex->getSourceRange();
4977 return QualType();
4978 }
Chris Lattner4d62f422007-12-09 21:53:25 +00004979 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004980
Douglas Gregorac1fb652009-03-24 19:52:54 +00004981 if (ComplainAboutVoid)
4982 Diag(Loc, diag::ext_gnu_void_ptr)
4983 << lex->getSourceRange() << rex->getSourceRange();
4984 if (ComplainAboutFunc)
4985 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump11289f42009-09-09 15:08:12 +00004986 << ComplainAboutFunc->getType()
Douglas Gregorac1fb652009-03-24 19:52:54 +00004987 << ComplainAboutFunc->getSourceRange();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004988
4989 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00004990 return Context.getPointerDiffType();
4991 }
4992 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004993
Chris Lattner326f7572008-11-18 01:30:42 +00004994 return InvalidOperands(Loc, lex, rex);
Steve Naroff218bc2b2007-05-04 21:54:46 +00004995}
4996
Chris Lattner2a3569b2008-04-07 05:30:13 +00004997// C99 6.5.7
Chris Lattner326f7572008-11-18 01:30:42 +00004998QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattner2a3569b2008-04-07 05:30:13 +00004999 bool isCompAssign) {
Chris Lattner5c11c412007-12-12 05:47:28 +00005000 // C99 6.5.7p2: Each of the operands shall have integer type.
5001 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner326f7572008-11-18 01:30:42 +00005002 return InvalidOperands(Loc, lex, rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005003
Nate Begemane46ee9a2009-10-25 02:26:48 +00005004 // Vector shifts promote their scalar inputs to vector type.
5005 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
5006 return CheckVectorOperands(Loc, lex, rex);
5007
Chris Lattner5c11c412007-12-12 05:47:28 +00005008 // Shifts don't perform usual arithmetic conversions, they just do integer
5009 // promotions on each operand. C99 6.5.7p3
Eli Friedman629ffb92009-08-20 04:21:42 +00005010 QualType LHSTy = Context.isPromotableBitField(lex);
5011 if (LHSTy.isNull()) {
5012 LHSTy = lex->getType();
5013 if (LHSTy->isPromotableIntegerType())
5014 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregord2c2d172009-05-02 00:36:19 +00005015 }
Chris Lattner3c133402007-12-13 07:28:16 +00005016 if (!isCompAssign)
Eli Friedman06ed2a52009-10-20 08:27:19 +00005017 ImpCastExprToType(lex, LHSTy, CastExpr::CK_IntegralCast);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005018
Chris Lattner5c11c412007-12-12 05:47:28 +00005019 UsualUnaryConversions(rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005020
Ryan Flynnf53fab82009-08-07 16:20:20 +00005021 // Sanity-check shift operands
5022 llvm::APSInt Right;
5023 // Check right/shifter operand
Daniel Dunbar687fa862009-09-17 06:31:27 +00005024 if (!rex->isValueDependent() &&
5025 rex->isIntegerConstantExpr(Right, Context)) {
Ryan Flynn2f085712009-08-08 19:18:23 +00005026 if (Right.isNegative())
Ryan Flynnf53fab82009-08-07 16:20:20 +00005027 Diag(Loc, diag::warn_shift_negative) << rex->getSourceRange();
5028 else {
5029 llvm::APInt LeftBits(Right.getBitWidth(),
5030 Context.getTypeSize(lex->getType()));
5031 if (Right.uge(LeftBits))
5032 Diag(Loc, diag::warn_shift_gt_typewidth) << rex->getSourceRange();
5033 }
5034 }
5035
Chris Lattner5c11c412007-12-12 05:47:28 +00005036 // "The type of the result is that of the promoted left operand."
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005037 return LHSTy;
Steve Naroff26c8ea52007-03-21 21:08:52 +00005038}
5039
John McCall99ce6bf2009-11-06 08:49:08 +00005040/// \brief Implements -Wsign-compare.
5041///
5042/// \param lex the left-hand expression
5043/// \param rex the right-hand expression
5044/// \param OpLoc the location of the joining operator
John McCalle46fd852009-11-06 08:53:51 +00005045/// \param Equality whether this is an "equality-like" join, which
5046/// suppresses the warning in some cases
John McCall1fa36b72009-11-05 09:23:39 +00005047void Sema::CheckSignCompare(Expr *lex, Expr *rex, SourceLocation OpLoc,
John McCall99ce6bf2009-11-06 08:49:08 +00005048 const PartialDiagnostic &PD, bool Equality) {
John McCalle2c91e62009-11-06 18:16:06 +00005049 // Don't warn if we're in an unevaluated context.
Douglas Gregorff790f12009-11-26 00:44:06 +00005050 if (ExprEvalContexts.back().Context == Unevaluated)
John McCalle2c91e62009-11-06 18:16:06 +00005051 return;
5052
John McCall644a4182009-11-05 00:40:04 +00005053 QualType lt = lex->getType(), rt = rex->getType();
5054
5055 // Only warn if both operands are integral.
5056 if (!lt->isIntegerType() || !rt->isIntegerType())
5057 return;
5058
Sebastian Redl0b7c85f2009-11-05 21:09:23 +00005059 // If either expression is value-dependent, don't warn. We'll get another
5060 // chance at instantiation time.
5061 if (lex->isValueDependent() || rex->isValueDependent())
5062 return;
5063
John McCall644a4182009-11-05 00:40:04 +00005064 // The rule is that the signed operand becomes unsigned, so isolate the
5065 // signed operand.
John McCall99ce6bf2009-11-06 08:49:08 +00005066 Expr *signedOperand, *unsignedOperand;
John McCall644a4182009-11-05 00:40:04 +00005067 if (lt->isSignedIntegerType()) {
5068 if (rt->isSignedIntegerType()) return;
5069 signedOperand = lex;
John McCall99ce6bf2009-11-06 08:49:08 +00005070 unsignedOperand = rex;
John McCall644a4182009-11-05 00:40:04 +00005071 } else {
5072 if (!rt->isSignedIntegerType()) return;
5073 signedOperand = rex;
John McCall99ce6bf2009-11-06 08:49:08 +00005074 unsignedOperand = lex;
John McCall644a4182009-11-05 00:40:04 +00005075 }
5076
John McCall99ce6bf2009-11-06 08:49:08 +00005077 // If the unsigned type is strictly smaller than the signed type,
John McCalle46fd852009-11-06 08:53:51 +00005078 // then (1) the result type will be signed and (2) the unsigned
5079 // value will fit fully within the signed type, and thus the result
John McCall99ce6bf2009-11-06 08:49:08 +00005080 // of the comparison will be exact.
5081 if (Context.getIntWidth(signedOperand->getType()) >
5082 Context.getIntWidth(unsignedOperand->getType()))
5083 return;
5084
John McCall644a4182009-11-05 00:40:04 +00005085 // If the value is a non-negative integer constant, then the
5086 // signed->unsigned conversion won't change it.
5087 llvm::APSInt value;
John McCall1fa36b72009-11-05 09:23:39 +00005088 if (signedOperand->isIntegerConstantExpr(value, Context)) {
John McCall644a4182009-11-05 00:40:04 +00005089 assert(value.isSigned() && "result of signed expression not signed");
5090
5091 if (value.isNonNegative())
5092 return;
5093 }
5094
John McCall99ce6bf2009-11-06 08:49:08 +00005095 if (Equality) {
5096 // For (in)equality comparisons, if the unsigned operand is a
John McCalle46fd852009-11-06 08:53:51 +00005097 // constant which cannot collide with a overflowed signed operand,
5098 // then reinterpreting the signed operand as unsigned will not
5099 // change the result of the comparison.
John McCall99ce6bf2009-11-06 08:49:08 +00005100 if (unsignedOperand->isIntegerConstantExpr(value, Context)) {
5101 assert(!value.isSigned() && "result of unsigned expression is signed");
5102
5103 // 2's complement: test the top bit.
5104 if (value.isNonNegative())
5105 return;
5106 }
5107 }
5108
John McCall1fa36b72009-11-05 09:23:39 +00005109 Diag(OpLoc, PD)
John McCall644a4182009-11-05 00:40:04 +00005110 << lex->getType() << rex->getType()
5111 << lex->getSourceRange() << rex->getSourceRange();
5112}
5113
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00005114// C99 6.5.8, C++ [expr.rel]
Chris Lattner326f7572008-11-18 01:30:42 +00005115QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Douglas Gregor7a5bc762009-04-06 18:45:53 +00005116 unsigned OpaqueOpc, bool isRelational) {
5117 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)OpaqueOpc;
5118
Chris Lattner9a152e22009-12-05 05:40:13 +00005119 // Handle vector comparisons separately.
Nate Begeman191a6b12008-07-14 18:02:46 +00005120 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner326f7572008-11-18 01:30:42 +00005121 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005122
John McCall99ce6bf2009-11-06 08:49:08 +00005123 CheckSignCompare(lex, rex, Loc, diag::warn_mixed_sign_comparison,
5124 (Opc == BinaryOperator::EQ || Opc == BinaryOperator::NE));
John McCall644a4182009-11-05 00:40:04 +00005125
Chris Lattnerb620c342007-08-26 01:18:55 +00005126 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroff47fea352007-08-10 18:26:40 +00005127 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
5128 UsualArithmeticConversions(lex, rex);
5129 else {
5130 UsualUnaryConversions(lex);
5131 UsualUnaryConversions(rex);
5132 }
Steve Naroff31090012007-07-16 21:54:35 +00005133 QualType lType = lex->getType();
5134 QualType rType = rex->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005135
Mike Stumpf70bcf72009-05-07 18:43:07 +00005136 if (!lType->isFloatingType()
5137 && !(lType->isBlockPointerType() && isRelational)) {
Chris Lattner222b8bd2009-03-08 19:39:53 +00005138 // For non-floating point types, check for self-comparisons of the form
5139 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
5140 // often indicate logic errors in the program.
Mike Stump11289f42009-09-09 15:08:12 +00005141 // NOTE: Don't warn about comparisons of enum constants. These can arise
Ted Kremenekde9e9682009-03-20 19:57:37 +00005142 // from macro expansions, and are usually quite deliberate.
Chris Lattner222b8bd2009-03-08 19:39:53 +00005143 Expr *LHSStripped = lex->IgnoreParens();
5144 Expr *RHSStripped = rex->IgnoreParens();
5145 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped))
5146 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped))
Ted Kremenek9ffbe412009-03-20 18:35:45 +00005147 if (DRL->getDecl() == DRR->getDecl() &&
5148 !isa<EnumConstantDecl>(DRL->getDecl()))
Mike Stump4e1f26a2009-02-19 03:04:26 +00005149 Diag(Loc, diag::warn_selfcomparison);
Mike Stump11289f42009-09-09 15:08:12 +00005150
Chris Lattner222b8bd2009-03-08 19:39:53 +00005151 if (isa<CastExpr>(LHSStripped))
5152 LHSStripped = LHSStripped->IgnoreParenCasts();
5153 if (isa<CastExpr>(RHSStripped))
5154 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00005155
Chris Lattner222b8bd2009-03-08 19:39:53 +00005156 // Warn about comparisons against a string constant (unless the other
5157 // operand is null), the user probably wants strcmp.
Douglas Gregor7a5bc762009-04-06 18:45:53 +00005158 Expr *literalString = 0;
5159 Expr *literalStringStripped = 0;
Chris Lattner222b8bd2009-03-08 19:39:53 +00005160 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Douglas Gregor56751b52009-09-25 04:25:58 +00005161 !RHSStripped->isNullPointerConstant(Context,
5162 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregor7a5bc762009-04-06 18:45:53 +00005163 literalString = lex;
5164 literalStringStripped = LHSStripped;
Mike Stump12b8ce12009-08-04 21:02:39 +00005165 } else if ((isa<StringLiteral>(RHSStripped) ||
5166 isa<ObjCEncodeExpr>(RHSStripped)) &&
Douglas Gregor56751b52009-09-25 04:25:58 +00005167 !LHSStripped->isNullPointerConstant(Context,
5168 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregor7a5bc762009-04-06 18:45:53 +00005169 literalString = rex;
5170 literalStringStripped = RHSStripped;
5171 }
5172
5173 if (literalString) {
5174 std::string resultComparison;
5175 switch (Opc) {
5176 case BinaryOperator::LT: resultComparison = ") < 0"; break;
5177 case BinaryOperator::GT: resultComparison = ") > 0"; break;
5178 case BinaryOperator::LE: resultComparison = ") <= 0"; break;
5179 case BinaryOperator::GE: resultComparison = ") >= 0"; break;
5180 case BinaryOperator::EQ: resultComparison = ") == 0"; break;
5181 case BinaryOperator::NE: resultComparison = ") != 0"; break;
5182 default: assert(false && "Invalid comparison operator");
5183 }
5184 Diag(Loc, diag::warn_stringcompare)
5185 << isa<ObjCEncodeExpr>(literalStringStripped)
5186 << literalString->getSourceRange()
Douglas Gregor170512f2009-04-01 23:51:29 +00005187 << CodeModificationHint::CreateReplacement(SourceRange(Loc), ", ")
5188 << CodeModificationHint::CreateInsertion(lex->getLocStart(),
5189 "strcmp(")
5190 << CodeModificationHint::CreateInsertion(
5191 PP.getLocForEndOfToken(rex->getLocEnd()),
Douglas Gregor7a5bc762009-04-06 18:45:53 +00005192 resultComparison);
5193 }
Ted Kremeneke451eae2007-10-29 16:58:49 +00005194 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005195
Douglas Gregorca63811b2008-11-19 03:25:36 +00005196 // The result of comparisons is 'bool' in C++, 'int' in C.
Chris Lattner9a152e22009-12-05 05:40:13 +00005197 QualType ResultTy = getLangOptions().CPlusPlus ? Context.BoolTy:Context.IntTy;
Douglas Gregorca63811b2008-11-19 03:25:36 +00005198
Chris Lattnerb620c342007-08-26 01:18:55 +00005199 if (isRelational) {
5200 if (lType->isRealType() && rType->isRealType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00005201 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00005202 } else {
Ted Kremeneke2763b02007-10-29 17:13:39 +00005203 // Check for comparisons of floating point operands using != and ==.
Chris Lattner9a152e22009-12-05 05:40:13 +00005204 if (lType->isFloatingType() && rType->isFloatingType())
Chris Lattner326f7572008-11-18 01:30:42 +00005205 CheckFloatComparison(Loc,lex,rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005206
Chris Lattnerb620c342007-08-26 01:18:55 +00005207 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00005208 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00005209 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005210
Douglas Gregor56751b52009-09-25 04:25:58 +00005211 bool LHSIsNull = lex->isNullPointerConstant(Context,
5212 Expr::NPC_ValueDependentIsNull);
5213 bool RHSIsNull = rex->isNullPointerConstant(Context,
5214 Expr::NPC_ValueDependentIsNull);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005215
Chris Lattnerb620c342007-08-26 01:18:55 +00005216 // All of the following pointer related warnings are GCC extensions, except
5217 // when handling null pointer constants. One day, we can consider making them
5218 // errors (when -pedantic-errors is enabled).
Steve Naroff808eb8f2007-08-27 04:08:11 +00005219 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner3a0702e2008-04-03 05:07:25 +00005220 QualType LCanPointeeTy =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005221 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattner3a0702e2008-04-03 05:07:25 +00005222 QualType RCanPointeeTy =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005223 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stump4e1f26a2009-02-19 03:04:26 +00005224
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00005225 if (getLangOptions().CPlusPlus) {
Eli Friedman16c209612009-08-23 00:27:47 +00005226 if (LCanPointeeTy == RCanPointeeTy)
5227 return ResultTy;
5228
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00005229 // C++ [expr.rel]p2:
5230 // [...] Pointer conversions (4.10) and qualification
5231 // conversions (4.4) are performed on pointer operands (or on
5232 // a pointer operand and a null pointer constant) to bring
5233 // them to their composite pointer type. [...]
5234 //
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005235 // C++ [expr.eq]p1 uses the same notion for (in)equality
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00005236 // comparisons of pointers.
Douglas Gregorb8420462009-05-05 04:50:50 +00005237 QualType T = FindCompositePointerType(lex, rex);
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00005238 if (T.isNull()) {
5239 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
5240 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5241 return QualType();
5242 }
5243
Eli Friedman06ed2a52009-10-20 08:27:19 +00005244 ImpCastExprToType(lex, T, CastExpr::CK_BitCast);
5245 ImpCastExprToType(rex, T, CastExpr::CK_BitCast);
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00005246 return ResultTy;
5247 }
Eli Friedman16c209612009-08-23 00:27:47 +00005248 // C99 6.5.9p2 and C99 6.5.8p2
5249 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
5250 RCanPointeeTy.getUnqualifiedType())) {
5251 // Valid unless a relational comparison of function pointers
5252 if (isRelational && LCanPointeeTy->isFunctionType()) {
5253 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
5254 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5255 }
5256 } else if (!isRelational &&
5257 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
5258 // Valid unless comparison between non-null pointer and function pointer
5259 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
5260 && !LHSIsNull && !RHSIsNull) {
5261 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
5262 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5263 }
5264 } else {
5265 // Invalid
Chris Lattner377d1f82008-11-18 22:52:51 +00005266 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005267 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff75c17232007-06-13 21:41:08 +00005268 }
Eli Friedman16c209612009-08-23 00:27:47 +00005269 if (LCanPointeeTy != RCanPointeeTy)
Eli Friedman06ed2a52009-10-20 08:27:19 +00005270 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005271 return ResultTy;
Steve Naroffcdee44c2007-08-16 21:48:38 +00005272 }
Mike Stump11289f42009-09-09 15:08:12 +00005273
Sebastian Redl576fd422009-05-10 18:38:11 +00005274 if (getLangOptions().CPlusPlus) {
Mike Stump11289f42009-09-09 15:08:12 +00005275 // Comparison of pointers with null pointer constants and equality
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005276 // comparisons of member pointers to null pointer constants.
Mike Stump11289f42009-09-09 15:08:12 +00005277 if (RHSIsNull &&
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005278 (lType->isPointerType() ||
5279 (!isRelational && lType->isMemberPointerType()))) {
Anders Carlsson83133d92009-08-24 18:03:14 +00005280 ImpCastExprToType(rex, lType, CastExpr::CK_NullToMemberPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00005281 return ResultTy;
5282 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005283 if (LHSIsNull &&
5284 (rType->isPointerType() ||
5285 (!isRelational && rType->isMemberPointerType()))) {
Anders Carlsson83133d92009-08-24 18:03:14 +00005286 ImpCastExprToType(lex, rType, CastExpr::CK_NullToMemberPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00005287 return ResultTy;
5288 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005289
5290 // Comparison of member pointers.
Mike Stump11289f42009-09-09 15:08:12 +00005291 if (!isRelational &&
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005292 lType->isMemberPointerType() && rType->isMemberPointerType()) {
5293 // C++ [expr.eq]p2:
Mike Stump11289f42009-09-09 15:08:12 +00005294 // In addition, pointers to members can be compared, or a pointer to
5295 // member and a null pointer constant. Pointer to member conversions
5296 // (4.11) and qualification conversions (4.4) are performed to bring
5297 // them to a common type. If one operand is a null pointer constant,
5298 // the common type is the type of the other operand. Otherwise, the
5299 // common type is a pointer to member type similar (4.4) to the type
5300 // of one of the operands, with a cv-qualification signature (4.4)
5301 // that is the union of the cv-qualification signatures of the operand
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005302 // types.
5303 QualType T = FindCompositePointerType(lex, rex);
5304 if (T.isNull()) {
5305 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
5306 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5307 return QualType();
5308 }
Mike Stump11289f42009-09-09 15:08:12 +00005309
Eli Friedman06ed2a52009-10-20 08:27:19 +00005310 ImpCastExprToType(lex, T, CastExpr::CK_BitCast);
5311 ImpCastExprToType(rex, T, CastExpr::CK_BitCast);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005312 return ResultTy;
5313 }
Mike Stump11289f42009-09-09 15:08:12 +00005314
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005315 // Comparison of nullptr_t with itself.
Sebastian Redl576fd422009-05-10 18:38:11 +00005316 if (lType->isNullPtrType() && rType->isNullPtrType())
5317 return ResultTy;
5318 }
Mike Stump11289f42009-09-09 15:08:12 +00005319
Steve Naroff081c7422008-09-04 15:10:53 +00005320 // Handle block pointer types.
Mike Stump1b821b42009-05-07 03:14:14 +00005321 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005322 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
5323 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005324
Steve Naroff081c7422008-09-04 15:10:53 +00005325 if (!LHSIsNull && !RHSIsNull &&
Eli Friedmana6638ca2009-06-08 05:08:54 +00005326 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00005327 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005328 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff081c7422008-09-04 15:10:53 +00005329 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00005330 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005331 return ResultTy;
Steve Naroff081c7422008-09-04 15:10:53 +00005332 }
Steve Naroffe18f94c2008-09-28 01:11:11 +00005333 // Allow block pointers to be compared with null pointer constants.
Mike Stump1b821b42009-05-07 03:14:14 +00005334 if (!isRelational
5335 && ((lType->isBlockPointerType() && rType->isPointerType())
5336 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Naroffe18f94c2008-09-28 01:11:11 +00005337 if (!LHSIsNull && !RHSIsNull) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005338 if (!((rType->isPointerType() && rType->getAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00005339 ->getPointeeType()->isVoidType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005340 || (lType->isPointerType() && lType->getAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00005341 ->getPointeeType()->isVoidType())))
5342 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
5343 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroffe18f94c2008-09-28 01:11:11 +00005344 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00005345 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005346 return ResultTy;
Steve Naroffe18f94c2008-09-28 01:11:11 +00005347 }
Steve Naroff081c7422008-09-04 15:10:53 +00005348
Steve Naroff7cae42b2009-07-10 23:34:53 +00005349 if ((lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType())) {
Steve Naroff1d4a9a32008-10-27 10:33:19 +00005350 if (lType->isPointerType() || rType->isPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005351 const PointerType *LPT = lType->getAs<PointerType>();
5352 const PointerType *RPT = rType->getAs<PointerType>();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005353 bool LPtrToVoid = LPT ?
Steve Naroff753567f2008-11-17 19:49:16 +00005354 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005355 bool RPtrToVoid = RPT ?
Steve Naroff753567f2008-11-17 19:49:16 +00005356 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005357
Steve Naroff753567f2008-11-17 19:49:16 +00005358 if (!LPtrToVoid && !RPtrToVoid &&
5359 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00005360 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005361 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff1d4a9a32008-10-27 10:33:19 +00005362 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00005363 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005364 return ResultTy;
Steve Naroffea54d9e2008-10-20 18:19:10 +00005365 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00005366 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00005367 if (!Context.areComparableObjCPointerTypes(lType, rType))
Steve Naroff7cae42b2009-07-10 23:34:53 +00005368 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
5369 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00005370 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005371 return ResultTy;
Steve Naroffb788d9b2008-06-03 14:04:54 +00005372 }
Fariborz Jahanian134cbef2007-12-20 01:06:58 +00005373 }
Steve Naroff6b712a72009-07-14 18:25:06 +00005374 if (lType->isAnyPointerType() && rType->isIntegerType()) {
Chris Lattnerd99bd522009-08-23 00:03:44 +00005375 unsigned DiagID = 0;
5376 if (RHSIsNull) {
5377 if (isRelational)
5378 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
5379 } else if (isRelational)
5380 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
5381 else
5382 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump11289f42009-09-09 15:08:12 +00005383
Chris Lattnerd99bd522009-08-23 00:03:44 +00005384 if (DiagID) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00005385 Diag(Loc, DiagID)
Chris Lattnerd466ea12009-06-30 06:24:05 +00005386 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf8344db2009-08-22 18:58:31 +00005387 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00005388 ImpCastExprToType(rex, lType, CastExpr::CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005389 return ResultTy;
Steve Naroffcdee44c2007-08-16 21:48:38 +00005390 }
Steve Naroff6b712a72009-07-14 18:25:06 +00005391 if (lType->isIntegerType() && rType->isAnyPointerType()) {
Chris Lattnerd99bd522009-08-23 00:03:44 +00005392 unsigned DiagID = 0;
5393 if (LHSIsNull) {
5394 if (isRelational)
5395 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
5396 } else if (isRelational)
5397 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
5398 else
5399 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump11289f42009-09-09 15:08:12 +00005400
Chris Lattnerd99bd522009-08-23 00:03:44 +00005401 if (DiagID) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00005402 Diag(Loc, DiagID)
Chris Lattnerd466ea12009-06-30 06:24:05 +00005403 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf8344db2009-08-22 18:58:31 +00005404 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00005405 ImpCastExprToType(lex, rType, CastExpr::CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005406 return ResultTy;
Steve Naroff043d45d2007-05-15 02:32:35 +00005407 }
Steve Naroff4b191572008-09-04 16:56:14 +00005408 // Handle block pointers.
Mike Stumpf70bcf72009-05-07 18:43:07 +00005409 if (!isRelational && RHSIsNull
5410 && lType->isBlockPointerType() && rType->isIntegerType()) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00005411 ImpCastExprToType(rex, lType, CastExpr::CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005412 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00005413 }
Mike Stumpf70bcf72009-05-07 18:43:07 +00005414 if (!isRelational && LHSIsNull
5415 && lType->isIntegerType() && rType->isBlockPointerType()) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00005416 ImpCastExprToType(lex, rType, CastExpr::CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005417 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00005418 }
Chris Lattner326f7572008-11-18 01:30:42 +00005419 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00005420}
5421
Nate Begeman191a6b12008-07-14 18:02:46 +00005422/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump4e1f26a2009-02-19 03:04:26 +00005423/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begeman191a6b12008-07-14 18:02:46 +00005424/// like a scalar comparison, a vector comparison produces a vector of integer
5425/// types.
5426QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner326f7572008-11-18 01:30:42 +00005427 SourceLocation Loc,
Nate Begeman191a6b12008-07-14 18:02:46 +00005428 bool isRelational) {
5429 // Check to make sure we're operating on vectors of the same type and width,
5430 // Allowing one side to be a scalar of element type.
Chris Lattner326f7572008-11-18 01:30:42 +00005431 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begeman191a6b12008-07-14 18:02:46 +00005432 if (vType.isNull())
5433 return vType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005434
Nate Begeman191a6b12008-07-14 18:02:46 +00005435 QualType lType = lex->getType();
5436 QualType rType = rex->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005437
Nate Begeman191a6b12008-07-14 18:02:46 +00005438 // For non-floating point types, check for self-comparisons of the form
5439 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
5440 // often indicate logic errors in the program.
5441 if (!lType->isFloatingType()) {
5442 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
5443 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
5444 if (DRL->getDecl() == DRR->getDecl())
Mike Stump4e1f26a2009-02-19 03:04:26 +00005445 Diag(Loc, diag::warn_selfcomparison);
Nate Begeman191a6b12008-07-14 18:02:46 +00005446 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005447
Nate Begeman191a6b12008-07-14 18:02:46 +00005448 // Check for comparisons of floating point operands using != and ==.
5449 if (!isRelational && lType->isFloatingType()) {
5450 assert (rType->isFloatingType());
Chris Lattner326f7572008-11-18 01:30:42 +00005451 CheckFloatComparison(Loc,lex,rex);
Nate Begeman191a6b12008-07-14 18:02:46 +00005452 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005453
Nate Begeman191a6b12008-07-14 18:02:46 +00005454 // Return the type for the comparison, which is the same as vector type for
5455 // integer vectors, or an integer type of identical size and number of
5456 // elements for floating point vectors.
5457 if (lType->isIntegerType())
5458 return lType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005459
John McCall9dd450b2009-09-21 23:43:11 +00005460 const VectorType *VTy = lType->getAs<VectorType>();
Nate Begeman191a6b12008-07-14 18:02:46 +00005461 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005462 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begeman191a6b12008-07-14 18:02:46 +00005463 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattner5d688962009-03-31 07:46:52 +00005464 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005465 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
5466
Mike Stump4e1f26a2009-02-19 03:04:26 +00005467 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005468 "Unhandled vector element size in vector compare");
Nate Begeman191a6b12008-07-14 18:02:46 +00005469 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
5470}
5471
Steve Naroff218bc2b2007-05-04 21:54:46 +00005472inline QualType Sema::CheckBitwiseOperands(
Mike Stump11289f42009-09-09 15:08:12 +00005473 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Steve Naroff94a5aca2007-07-16 22:23:01 +00005474 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner326f7572008-11-18 01:30:42 +00005475 return CheckVectorOperands(Loc, lex, rex);
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005476
Steve Naroffbe4c4d12007-08-24 19:07:16 +00005477 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005478
Steve Naroffdbd9e892007-07-17 00:58:39 +00005479 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroffbe4c4d12007-08-24 19:07:16 +00005480 return compType;
Chris Lattner326f7572008-11-18 01:30:42 +00005481 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00005482}
5483
Steve Naroff218bc2b2007-05-04 21:54:46 +00005484inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Mike Stump11289f42009-09-09 15:08:12 +00005485 Expr *&lex, Expr *&rex, SourceLocation Loc) {
Anders Carlsson2e7bc112009-11-23 21:47:44 +00005486 if (!Context.getLangOptions().CPlusPlus) {
5487 UsualUnaryConversions(lex);
5488 UsualUnaryConversions(rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005489
Anders Carlsson2e7bc112009-11-23 21:47:44 +00005490 if (!lex->getType()->isScalarType() || !rex->getType()->isScalarType())
5491 return InvalidOperands(Loc, lex, rex);
Anders Carlsson35a99d92009-10-16 01:44:21 +00005492
Anders Carlsson2e7bc112009-11-23 21:47:44 +00005493 return Context.IntTy;
Anders Carlsson35a99d92009-10-16 01:44:21 +00005494 }
Anders Carlsson2e7bc112009-11-23 21:47:44 +00005495
5496 // C++ [expr.log.and]p1
5497 // C++ [expr.log.or]p1
5498 // The operands are both implicitly converted to type bool (clause 4).
5499 StandardConversionSequence LHS;
5500 if (!IsStandardConversion(lex, Context.BoolTy,
5501 /*InOverloadResolution=*/false, LHS))
5502 return InvalidOperands(Loc, lex, rex);
Anders Carlsson35a99d92009-10-16 01:44:21 +00005503
Anders Carlsson2e7bc112009-11-23 21:47:44 +00005504 if (PerformImplicitConversion(lex, Context.BoolTy, LHS,
5505 "passing", /*IgnoreBaseAccess=*/false))
5506 return InvalidOperands(Loc, lex, rex);
5507
5508 StandardConversionSequence RHS;
5509 if (!IsStandardConversion(rex, Context.BoolTy,
5510 /*InOverloadResolution=*/false, RHS))
5511 return InvalidOperands(Loc, lex, rex);
5512
5513 if (PerformImplicitConversion(rex, Context.BoolTy, RHS,
5514 "passing", /*IgnoreBaseAccess=*/false))
5515 return InvalidOperands(Loc, lex, rex);
5516
5517 // C++ [expr.log.and]p2
5518 // C++ [expr.log.or]p2
5519 // The result is a bool.
5520 return Context.BoolTy;
Steve Naroffae4143e2007-04-26 20:39:23 +00005521}
5522
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00005523/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
5524/// is a read-only property; return true if so. A readonly property expression
5525/// depends on various declarations and thus must be treated specially.
5526///
Mike Stump11289f42009-09-09 15:08:12 +00005527static bool IsReadonlyProperty(Expr *E, Sema &S) {
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00005528 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
5529 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
5530 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
5531 QualType BaseType = PropExpr->getBase()->getType();
Mike Stump11289f42009-09-09 15:08:12 +00005532 if (const ObjCObjectPointerType *OPT =
Steve Naroff7cae42b2009-07-10 23:34:53 +00005533 BaseType->getAsObjCInterfacePointerType())
5534 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
5535 if (S.isPropertyReadonly(PDecl, IFace))
5536 return true;
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00005537 }
5538 }
5539 return false;
5540}
5541
Chris Lattner30bd3272008-11-18 01:22:49 +00005542/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
5543/// emit an error and return true. If so, return false.
5544static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00005545 SourceLocation OrigLoc = Loc;
Mike Stump11289f42009-09-09 15:08:12 +00005546 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00005547 &Loc);
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00005548 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
5549 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattner30bd3272008-11-18 01:22:49 +00005550 if (IsLV == Expr::MLV_Valid)
5551 return false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005552
Chris Lattner30bd3272008-11-18 01:22:49 +00005553 unsigned Diag = 0;
5554 bool NeedType = false;
5555 switch (IsLV) { // C99 6.5.16p2
5556 default: assert(0 && "Unknown result from isModifiableLvalue!");
5557 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005558 case Expr::MLV_ArrayType:
Chris Lattner30bd3272008-11-18 01:22:49 +00005559 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
5560 NeedType = true;
5561 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005562 case Expr::MLV_NotObjectType:
Chris Lattner30bd3272008-11-18 01:22:49 +00005563 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
5564 NeedType = true;
5565 break;
Chris Lattner9b3bbe92008-11-17 19:51:54 +00005566 case Expr::MLV_LValueCast:
Chris Lattner30bd3272008-11-18 01:22:49 +00005567 Diag = diag::err_typecheck_lvalue_casts_not_supported;
5568 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00005569 case Expr::MLV_InvalidExpression:
Chris Lattner30bd3272008-11-18 01:22:49 +00005570 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
5571 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00005572 case Expr::MLV_IncompleteType:
5573 case Expr::MLV_IncompleteVoidType:
Douglas Gregored0cfbd2009-03-09 16:13:40 +00005574 return S.RequireCompleteType(Loc, E->getType(),
Anders Carlssond624e162009-08-26 23:45:07 +00005575 PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
5576 << E->getSourceRange());
Chris Lattner9bad62c2008-01-04 18:04:52 +00005577 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner30bd3272008-11-18 01:22:49 +00005578 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
5579 break;
Steve Naroffba756cb2008-09-26 14:41:28 +00005580 case Expr::MLV_NotBlockQualified:
Chris Lattner30bd3272008-11-18 01:22:49 +00005581 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
5582 break;
Fariborz Jahanian8a1810f2008-11-22 18:39:36 +00005583 case Expr::MLV_ReadonlyProperty:
5584 Diag = diag::error_readonly_property_assignment;
5585 break;
Fariborz Jahanian5118c412008-11-22 20:25:50 +00005586 case Expr::MLV_NoSetterProperty:
5587 Diag = diag::error_nosetter_property_assignment;
5588 break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00005589 }
Steve Naroffad373bd2007-07-31 12:34:36 +00005590
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00005591 SourceRange Assign;
5592 if (Loc != OrigLoc)
5593 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattner30bd3272008-11-18 01:22:49 +00005594 if (NeedType)
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00005595 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00005596 else
Mike Stump11289f42009-09-09 15:08:12 +00005597 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00005598 return true;
5599}
5600
5601
5602
5603// C99 6.5.16.1
Chris Lattner326f7572008-11-18 01:30:42 +00005604QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
5605 SourceLocation Loc,
5606 QualType CompoundType) {
5607 // Verify that LHS is a modifiable lvalue, and emit error if not.
5608 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner30bd3272008-11-18 01:22:49 +00005609 return QualType();
Chris Lattner326f7572008-11-18 01:30:42 +00005610
5611 QualType LHSType = LHS->getType();
5612 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005613
Chris Lattner9bad62c2008-01-04 18:04:52 +00005614 AssignConvertType ConvTy;
Chris Lattner326f7572008-11-18 01:30:42 +00005615 if (CompoundType.isNull()) {
Chris Lattnerea714382008-08-21 18:04:13 +00005616 // Simple assignment "x = y".
Chris Lattner326f7572008-11-18 01:30:42 +00005617 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Fariborz Jahanian255c0952009-01-13 23:34:40 +00005618 // Special case of NSObject attributes on c-style pointer types.
5619 if (ConvTy == IncompatiblePointer &&
5620 ((Context.isObjCNSObjectType(LHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00005621 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanian255c0952009-01-13 23:34:40 +00005622 (Context.isObjCNSObjectType(RHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00005623 LHSType->isObjCObjectPointerType())))
Fariborz Jahanian255c0952009-01-13 23:34:40 +00005624 ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005625
Chris Lattnerea714382008-08-21 18:04:13 +00005626 // If the RHS is a unary plus or minus, check to see if they = and + are
5627 // right next to each other. If so, the user may have typo'd "x =+ 4"
5628 // instead of "x += 4".
Chris Lattner326f7572008-11-18 01:30:42 +00005629 Expr *RHSCheck = RHS;
Chris Lattnerea714382008-08-21 18:04:13 +00005630 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
5631 RHSCheck = ICE->getSubExpr();
5632 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
5633 if ((UO->getOpcode() == UnaryOperator::Plus ||
5634 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner326f7572008-11-18 01:30:42 +00005635 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattnerea714382008-08-21 18:04:13 +00005636 // Only if the two operators are exactly adjacent.
Chris Lattner36c39c92009-03-08 06:51:10 +00005637 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
5638 // And there is a space or other character before the subexpr of the
5639 // unary +/-. We don't want to warn on "x=-1".
Chris Lattnered9f14c2009-03-09 07:11:10 +00005640 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
5641 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattner29e812b2008-11-20 06:06:08 +00005642 Diag(Loc, diag::warn_not_compound_assign)
5643 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
5644 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner36c39c92009-03-08 06:51:10 +00005645 }
Chris Lattnerea714382008-08-21 18:04:13 +00005646 }
5647 } else {
5648 // Compound assignment "x += y"
Eli Friedmanb05c41e2009-05-16 05:56:02 +00005649 ConvTy = CheckAssignmentConstraints(LHSType, RHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00005650 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00005651
Chris Lattner326f7572008-11-18 01:30:42 +00005652 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
5653 RHS, "assigning"))
Chris Lattner9bad62c2008-01-04 18:04:52 +00005654 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005655
Steve Naroff98cf3e92007-06-06 18:38:38 +00005656 // C99 6.5.16p3: The type of an assignment expression is the type of the
5657 // left operand unless the left operand has qualified type, in which case
Mike Stump4e1f26a2009-02-19 03:04:26 +00005658 // it is the unqualified version of the type of the left operand.
Steve Naroff98cf3e92007-06-06 18:38:38 +00005659 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
5660 // is converted to the type of the assignment expression (above).
Chris Lattnerf17bd422007-08-30 17:45:32 +00005661 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregord2c2d172009-05-02 00:36:19 +00005662 // operand.
Chris Lattner326f7572008-11-18 01:30:42 +00005663 return LHSType.getUnqualifiedType();
Steve Naroffae4143e2007-04-26 20:39:23 +00005664}
5665
Chris Lattner326f7572008-11-18 01:30:42 +00005666// C99 6.5.17
5667QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
Chris Lattnerf6e1e302008-07-25 20:54:07 +00005668 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner326f7572008-11-18 01:30:42 +00005669 DefaultFunctionArrayConversion(RHS);
Eli Friedmanba961a92009-03-23 00:24:07 +00005670
5671 // FIXME: Check that RHS type is complete in C mode (it's legal for it to be
5672 // incomplete in C++).
5673
Chris Lattner326f7572008-11-18 01:30:42 +00005674 return RHS->getType();
Steve Naroff95af0132007-03-30 23:47:58 +00005675}
5676
Steve Naroff7a5af782007-07-13 16:58:59 +00005677/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
5678/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redle10c2c32008-12-20 09:35:34 +00005679QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
5680 bool isInc) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005681 if (Op->isTypeDependent())
5682 return Context.DependentTy;
5683
Chris Lattner6b0cf142008-11-21 07:05:48 +00005684 QualType ResType = Op->getType();
5685 assert(!ResType.isNull() && "no type for increment/decrement expression");
Steve Naroffd50c88e2007-04-05 21:15:20 +00005686
Sebastian Redle10c2c32008-12-20 09:35:34 +00005687 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
5688 // Decrement of bool is not allowed.
5689 if (!isInc) {
5690 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
5691 return QualType();
5692 }
5693 // Increment of bool sets it to true, but is deprecated.
5694 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
5695 } else if (ResType->isRealType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00005696 // OK!
Steve Naroff6b712a72009-07-14 18:25:06 +00005697 } else if (ResType->isAnyPointerType()) {
5698 QualType PointeeTy = ResType->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00005699
Chris Lattner6b0cf142008-11-21 07:05:48 +00005700 // C99 6.5.2.4p2, 6.5.6p2
Steve Naroff7cae42b2009-07-10 23:34:53 +00005701 if (PointeeTy->isVoidType()) {
Douglas Gregorf6cd9282009-01-23 00:36:41 +00005702 if (getLangOptions().CPlusPlus) {
5703 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
5704 << Op->getSourceRange();
5705 return QualType();
5706 }
5707
5708 // Pointer to void is a GNU extension in C.
Chris Lattner6b0cf142008-11-21 07:05:48 +00005709 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005710 } else if (PointeeTy->isFunctionType()) {
Douglas Gregorf6cd9282009-01-23 00:36:41 +00005711 if (getLangOptions().CPlusPlus) {
5712 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
5713 << Op->getType() << Op->getSourceRange();
5714 return QualType();
5715 }
5716
5717 Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005718 << ResType << Op->getSourceRange();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005719 } else if (RequireCompleteType(OpLoc, PointeeTy,
Anders Carlsson029fc692009-08-26 22:59:12 +00005720 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
Mike Stump11289f42009-09-09 15:08:12 +00005721 << Op->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00005722 << ResType))
Douglas Gregordd430f72009-01-19 19:26:10 +00005723 return QualType();
Fariborz Jahanianca75db72009-07-16 17:59:14 +00005724 // Diagnose bad cases where we step over interface counts.
5725 else if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
5726 Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
5727 << PointeeTy << Op->getSourceRange();
5728 return QualType();
5729 }
Chris Lattner6b0cf142008-11-21 07:05:48 +00005730 } else if (ResType->isComplexType()) {
5731 // C99 does not support ++/-- on complex types, we allow as an extension.
5732 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005733 << ResType << Op->getSourceRange();
Chris Lattner6b0cf142008-11-21 07:05:48 +00005734 } else {
5735 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Douglas Gregor906db8a2009-12-15 16:44:32 +00005736 << ResType << int(isInc) << Op->getSourceRange();
Chris Lattner6b0cf142008-11-21 07:05:48 +00005737 return QualType();
Steve Naroff46ba1eb2007-04-03 23:13:13 +00005738 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005739 // At this point, we know we have a real, complex or pointer type.
Steve Naroff9e1e5512007-08-23 21:37:33 +00005740 // Now make sure the operand is a modifiable lvalue.
Chris Lattner6b0cf142008-11-21 07:05:48 +00005741 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Steve Naroff35d85152007-05-07 00:24:15 +00005742 return QualType();
Chris Lattner6b0cf142008-11-21 07:05:48 +00005743 return ResType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00005744}
5745
Anders Carlsson806700f2008-02-01 07:15:58 +00005746/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Steve Naroff47500512007-04-19 23:00:49 +00005747/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb692ef42008-08-04 20:02:37 +00005748/// where the declaration is needed for type checking. We only need to
5749/// handle cases when the expression references a function designator
5750/// or is an lvalue. Here are some examples:
5751/// - &(x) => x
5752/// - &*****f => f for f a function designator.
5753/// - &s.xx => s
5754/// - &s.zz[1].yy -> s, if zz is an array
5755/// - *(x + 1) -> x, if x is an array
5756/// - &"123"[2] -> 0
5757/// - & __real__ x -> x
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005758static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00005759 switch (E->getStmtClass()) {
Steve Naroff47500512007-04-19 23:00:49 +00005760 case Stmt::DeclRefExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00005761 return cast<DeclRefExpr>(E)->getDecl();
Steve Naroff47500512007-04-19 23:00:49 +00005762 case Stmt::MemberExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00005763 // If this is an arrow operator, the address is an offset from
5764 // the base's value, so the object the base refers to is
5765 // irrelevant.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00005766 if (cast<MemberExpr>(E)->isArrow())
Chris Lattner48d52842007-11-16 17:46:48 +00005767 return 0;
Eli Friedman3a1e6922009-04-20 08:23:18 +00005768 // Otherwise, the expression refers to a part of the base
Chris Lattner24d5bfe2008-04-02 04:24:33 +00005769 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson806700f2008-02-01 07:15:58 +00005770 case Stmt::ArraySubscriptExprClass: {
Mike Stump87c57ac2009-05-16 07:39:55 +00005771 // FIXME: This code shouldn't be necessary! We should catch the implicit
5772 // promotion of register arrays earlier.
Eli Friedman3a1e6922009-04-20 08:23:18 +00005773 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
5774 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
5775 if (ICE->getSubExpr()->getType()->isArrayType())
5776 return getPrimaryDecl(ICE->getSubExpr());
5777 }
5778 return 0;
Anders Carlsson806700f2008-02-01 07:15:58 +00005779 }
Daniel Dunbarb692ef42008-08-04 20:02:37 +00005780 case Stmt::UnaryOperatorClass: {
5781 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005782
Daniel Dunbarb692ef42008-08-04 20:02:37 +00005783 switch(UO->getOpcode()) {
Daniel Dunbarb692ef42008-08-04 20:02:37 +00005784 case UnaryOperator::Real:
5785 case UnaryOperator::Imag:
5786 case UnaryOperator::Extension:
5787 return getPrimaryDecl(UO->getSubExpr());
5788 default:
5789 return 0;
5790 }
5791 }
Steve Naroff47500512007-04-19 23:00:49 +00005792 case Stmt::ParenExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00005793 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattner48d52842007-11-16 17:46:48 +00005794 case Stmt::ImplicitCastExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00005795 // If the result of an implicit cast is an l-value, we care about
5796 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00005797 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Steve Naroff47500512007-04-19 23:00:49 +00005798 default:
5799 return 0;
5800 }
5801}
5802
5803/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump4e1f26a2009-02-19 03:04:26 +00005804/// designator or an lvalue designating an object. If it is an lvalue, the
Steve Naroff47500512007-04-19 23:00:49 +00005805/// object cannot be declared with storage class register or be a bit field.
Mike Stump4e1f26a2009-02-19 03:04:26 +00005806/// Note: The usual conversions are *not* applied to the operand of the &
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005807/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump4e1f26a2009-02-19 03:04:26 +00005808/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregorcd695e52008-11-10 20:40:00 +00005809/// we allow the '&' but retain the overloaded-function type.
Steve Naroff35d85152007-05-07 00:24:15 +00005810QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Eli Friedman3a1e6922009-04-20 08:23:18 +00005811 // Make sure to ignore parentheses in subsequent checks
5812 op = op->IgnoreParens();
5813
Douglas Gregor19b8c4f2008-12-17 22:52:20 +00005814 if (op->isTypeDependent())
5815 return Context.DependentTy;
5816
Steve Naroff826e91a2008-01-13 17:10:08 +00005817 if (getLangOptions().C99) {
5818 // Implement C99-only parts of addressof rules.
5819 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
5820 if (uOp->getOpcode() == UnaryOperator::Deref)
5821 // Per C99 6.5.3.2, the address of a deref always returns a valid result
5822 // (assuming the deref expression is valid).
5823 return uOp->getSubExpr()->getType();
5824 }
5825 // Technically, there should be a check for array subscript
5826 // expressions here, but the result of one is always an lvalue anyway.
5827 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005828 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner67315442008-07-26 21:30:36 +00005829 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes17f345f2008-12-16 22:59:47 +00005830
Eli Friedmance7f9002009-05-16 23:27:50 +00005831 if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
5832 // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00005833 // The operand must be either an l-value or a function designator
Eli Friedmance7f9002009-05-16 23:27:50 +00005834 if (!op->getType()->isFunctionType()) {
Chris Lattner48d52842007-11-16 17:46:48 +00005835 // FIXME: emit more specific diag...
Chris Lattnerf490e152008-11-19 05:27:50 +00005836 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
5837 << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00005838 return QualType();
5839 }
Douglas Gregor71235ec2009-05-02 02:18:30 +00005840 } else if (op->getBitField()) { // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00005841 // The operand cannot be a bit-field
5842 Diag(OpLoc, diag::err_typecheck_address_of)
5843 << "bit-field" << op->getSourceRange();
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00005844 return QualType();
Nate Begemana6b47a42009-02-15 22:45:20 +00005845 } else if (isa<ExtVectorElementExpr>(op) || (isa<ArraySubscriptExpr>(op) &&
5846 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType())){
Eli Friedman3a1e6922009-04-20 08:23:18 +00005847 // The operand cannot be an element of a vector
Chris Lattner29e812b2008-11-20 06:06:08 +00005848 Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemana6b47a42009-02-15 22:45:20 +00005849 << "vector element" << op->getSourceRange();
Steve Naroffb96e4ab62008-02-29 23:30:25 +00005850 return QualType();
Fariborz Jahanian385db802009-07-07 18:50:52 +00005851 } else if (isa<ObjCPropertyRefExpr>(op)) {
5852 // cannot take address of a property expression.
5853 Diag(OpLoc, diag::err_typecheck_address_of)
5854 << "property expression" << op->getSourceRange();
5855 return QualType();
Anders Carlsson3fa58d12009-09-14 23:15:26 +00005856 } else if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(op)) {
5857 // FIXME: Can LHS ever be null here?
Anders Carlsson01ccf992009-09-15 16:03:44 +00005858 if (!CheckAddressOfOperand(CO->getTrueExpr(), OpLoc).isNull())
5859 return CheckAddressOfOperand(CO->getFalseExpr(), OpLoc);
John McCalld14a8642009-11-21 08:51:07 +00005860 } else if (isa<UnresolvedLookupExpr>(op)) {
5861 return Context.OverloadTy;
Steve Naroffb96e4ab62008-02-29 23:30:25 +00005862 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump4e1f26a2009-02-19 03:04:26 +00005863 // We have an lvalue with a decl. Make sure the decl is not declared
Steve Naroff47500512007-04-19 23:00:49 +00005864 // with the register storage-class specifier.
5865 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Steve Naroff35d85152007-05-07 00:24:15 +00005866 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattner29e812b2008-11-20 06:06:08 +00005867 Diag(OpLoc, diag::err_typecheck_address_of)
5868 << "register variable" << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00005869 return QualType();
5870 }
John McCalld14a8642009-11-21 08:51:07 +00005871 } else if (isa<FunctionTemplateDecl>(dcl)) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00005872 return Context.OverloadTy;
Anders Carlsson0b675f52009-07-08 21:45:58 +00005873 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(dcl)) {
Douglas Gregor9aa8b552008-12-10 21:26:49 +00005874 // Okay: we can take the address of a field.
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00005875 // Could be a pointer to member, though, if there is an explicit
5876 // scope qualifier for the class.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00005877 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00005878 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlsson0b675f52009-07-08 21:45:58 +00005879 if (Ctx && Ctx->isRecord()) {
5880 if (FD->getType()->isReferenceType()) {
Mike Stump11289f42009-09-09 15:08:12 +00005881 Diag(OpLoc,
Anders Carlsson0b675f52009-07-08 21:45:58 +00005882 diag::err_cannot_form_pointer_to_member_of_reference_type)
5883 << FD->getDeclName() << FD->getType();
5884 return QualType();
5885 }
Mike Stump11289f42009-09-09 15:08:12 +00005886
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00005887 return Context.getMemberPointerType(op->getType(),
5888 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlsson0b675f52009-07-08 21:45:58 +00005889 }
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00005890 }
Anders Carlsson5b535762009-05-16 21:43:42 +00005891 } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(dcl)) {
Nuno Lopes5773a1b2008-12-16 22:58:26 +00005892 // Okay: we can take the address of a function.
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005893 // As above.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00005894 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier() &&
5895 MD->isInstance())
Anders Carlsson5b535762009-05-16 21:43:42 +00005896 return Context.getMemberPointerType(op->getType(),
5897 Context.getTypeDeclType(MD->getParent()).getTypePtr());
5898 } else if (!isa<FunctionDecl>(dcl))
Steve Narofff633d092007-04-25 19:01:39 +00005899 assert(0 && "Unknown/unexpected decl type");
Steve Naroff47500512007-04-19 23:00:49 +00005900 }
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005901
Eli Friedmance7f9002009-05-16 23:27:50 +00005902 if (lval == Expr::LV_IncompleteVoidType) {
5903 // Taking the address of a void variable is technically illegal, but we
5904 // allow it in cases which are otherwise valid.
5905 // Example: "extern void x; void* y = &x;".
5906 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
5907 }
5908
Steve Naroff47500512007-04-19 23:00:49 +00005909 // If the operand has type "type", the result has type "pointer to type".
Steve Naroff35d85152007-05-07 00:24:15 +00005910 return Context.getPointerType(op->getType());
Steve Naroff47500512007-04-19 23:00:49 +00005911}
5912
Chris Lattner6a2ed6f2008-11-23 09:13:29 +00005913QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005914 if (Op->isTypeDependent())
5915 return Context.DependentTy;
5916
Chris Lattner6a2ed6f2008-11-23 09:13:29 +00005917 UsualUnaryConversions(Op);
5918 QualType Ty = Op->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005919
Chris Lattner6a2ed6f2008-11-23 09:13:29 +00005920 // Note that per both C89 and C99, this is always legal, even if ptype is an
5921 // incomplete type or void. It would be possible to warn about dereferencing
5922 // a void pointer, but it's completely well-defined, and such a warning is
5923 // unlikely to catch any mistakes.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005924 if (const PointerType *PT = Ty->getAs<PointerType>())
Steve Naroff826e91a2008-01-13 17:10:08 +00005925 return PT->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005926
John McCall9dd450b2009-09-21 23:43:11 +00005927 if (const ObjCObjectPointerType *OPT = Ty->getAs<ObjCObjectPointerType>())
Fariborz Jahanianf15d4b62009-09-03 00:43:07 +00005928 return OPT->getPointeeType();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005929
Chris Lattner29e812b2008-11-20 06:06:08 +00005930 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner6a2ed6f2008-11-23 09:13:29 +00005931 << Ty << Op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00005932 return QualType();
Steve Naroff1926c832007-04-24 00:23:05 +00005933}
Steve Naroff218bc2b2007-05-04 21:54:46 +00005934
5935static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
5936 tok::TokenKind Kind) {
5937 BinaryOperator::Opcode Opc;
5938 switch (Kind) {
5939 default: assert(0 && "Unknown binop!");
Sebastian Redl112a97662009-02-07 00:15:38 +00005940 case tok::periodstar: Opc = BinaryOperator::PtrMemD; break;
5941 case tok::arrowstar: Opc = BinaryOperator::PtrMemI; break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00005942 case tok::star: Opc = BinaryOperator::Mul; break;
5943 case tok::slash: Opc = BinaryOperator::Div; break;
5944 case tok::percent: Opc = BinaryOperator::Rem; break;
5945 case tok::plus: Opc = BinaryOperator::Add; break;
5946 case tok::minus: Opc = BinaryOperator::Sub; break;
5947 case tok::lessless: Opc = BinaryOperator::Shl; break;
5948 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
5949 case tok::lessequal: Opc = BinaryOperator::LE; break;
5950 case tok::less: Opc = BinaryOperator::LT; break;
5951 case tok::greaterequal: Opc = BinaryOperator::GE; break;
5952 case tok::greater: Opc = BinaryOperator::GT; break;
5953 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
5954 case tok::equalequal: Opc = BinaryOperator::EQ; break;
5955 case tok::amp: Opc = BinaryOperator::And; break;
5956 case tok::caret: Opc = BinaryOperator::Xor; break;
5957 case tok::pipe: Opc = BinaryOperator::Or; break;
5958 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
5959 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
5960 case tok::equal: Opc = BinaryOperator::Assign; break;
5961 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
5962 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
5963 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
5964 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
5965 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
5966 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
5967 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
5968 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
5969 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
5970 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
5971 case tok::comma: Opc = BinaryOperator::Comma; break;
5972 }
5973 return Opc;
5974}
5975
Steve Naroff35d85152007-05-07 00:24:15 +00005976static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
5977 tok::TokenKind Kind) {
5978 UnaryOperator::Opcode Opc;
5979 switch (Kind) {
5980 default: assert(0 && "Unknown unary op!");
5981 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
5982 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
5983 case tok::amp: Opc = UnaryOperator::AddrOf; break;
5984 case tok::star: Opc = UnaryOperator::Deref; break;
5985 case tok::plus: Opc = UnaryOperator::Plus; break;
5986 case tok::minus: Opc = UnaryOperator::Minus; break;
5987 case tok::tilde: Opc = UnaryOperator::Not; break;
5988 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Steve Naroff35d85152007-05-07 00:24:15 +00005989 case tok::kw___real: Opc = UnaryOperator::Real; break;
5990 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
Chris Lattnerd0f76512007-06-08 22:16:53 +00005991 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
Steve Naroff35d85152007-05-07 00:24:15 +00005992 }
5993 return Opc;
5994}
5995
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00005996/// CreateBuiltinBinOp - Creates a new built-in binary operation with
5997/// operator @p Opc at location @c TokLoc. This routine only supports
5998/// built-in operations; ActOnBinOp handles overloaded operators.
Sebastian Redlb5d49352009-01-19 22:31:54 +00005999Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
6000 unsigned Op,
6001 Expr *lhs, Expr *rhs) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006002 QualType ResultTy; // Result type of the binary operator.
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006003 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006004 // The following two variables are used for compound assignment operators
6005 QualType CompLHSTy; // Type of LHS after promotions for computation
6006 QualType CompResultTy; // Type of computation result
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006007
6008 switch (Opc) {
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006009 case BinaryOperator::Assign:
6010 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
6011 break;
Sebastian Redl112a97662009-02-07 00:15:38 +00006012 case BinaryOperator::PtrMemD:
6013 case BinaryOperator::PtrMemI:
6014 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
6015 Opc == BinaryOperator::PtrMemI);
6016 break;
6017 case BinaryOperator::Mul:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006018 case BinaryOperator::Div:
6019 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
6020 break;
6021 case BinaryOperator::Rem:
6022 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
6023 break;
6024 case BinaryOperator::Add:
6025 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
6026 break;
6027 case BinaryOperator::Sub:
6028 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
6029 break;
Sebastian Redl112a97662009-02-07 00:15:38 +00006030 case BinaryOperator::Shl:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006031 case BinaryOperator::Shr:
6032 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
6033 break;
6034 case BinaryOperator::LE:
6035 case BinaryOperator::LT:
6036 case BinaryOperator::GE:
6037 case BinaryOperator::GT:
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006038 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006039 break;
6040 case BinaryOperator::EQ:
6041 case BinaryOperator::NE:
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006042 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006043 break;
6044 case BinaryOperator::And:
6045 case BinaryOperator::Xor:
6046 case BinaryOperator::Or:
6047 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
6048 break;
6049 case BinaryOperator::LAnd:
6050 case BinaryOperator::LOr:
6051 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
6052 break;
6053 case BinaryOperator::MulAssign:
6054 case BinaryOperator::DivAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006055 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
6056 CompLHSTy = CompResultTy;
6057 if (!CompResultTy.isNull())
6058 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006059 break;
6060 case BinaryOperator::RemAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006061 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
6062 CompLHSTy = CompResultTy;
6063 if (!CompResultTy.isNull())
6064 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006065 break;
6066 case BinaryOperator::AddAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006067 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
6068 if (!CompResultTy.isNull())
6069 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006070 break;
6071 case BinaryOperator::SubAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006072 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
6073 if (!CompResultTy.isNull())
6074 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006075 break;
6076 case BinaryOperator::ShlAssign:
6077 case BinaryOperator::ShrAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006078 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
6079 CompLHSTy = CompResultTy;
6080 if (!CompResultTy.isNull())
6081 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006082 break;
6083 case BinaryOperator::AndAssign:
6084 case BinaryOperator::XorAssign:
6085 case BinaryOperator::OrAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006086 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
6087 CompLHSTy = CompResultTy;
6088 if (!CompResultTy.isNull())
6089 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006090 break;
6091 case BinaryOperator::Comma:
6092 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
6093 break;
6094 }
6095 if (ResultTy.isNull())
Sebastian Redlb5d49352009-01-19 22:31:54 +00006096 return ExprError();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006097 if (CompResultTy.isNull())
Steve Narofff6009ed2009-01-21 00:14:39 +00006098 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
6099 else
6100 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006101 CompLHSTy, CompResultTy,
6102 OpLoc));
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006103}
6104
Sebastian Redl44615072009-10-27 12:10:02 +00006105/// SuggestParentheses - Emit a diagnostic together with a fixit hint that wraps
6106/// ParenRange in parentheses.
Sebastian Redl4afb7c582009-10-26 17:01:32 +00006107static void SuggestParentheses(Sema &Self, SourceLocation Loc,
6108 const PartialDiagnostic &PD,
6109 SourceRange ParenRange)
6110{
6111 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
6112 if (!ParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
6113 // We can't display the parentheses, so just dig the
6114 // warning/error and return.
6115 Self.Diag(Loc, PD);
6116 return;
6117 }
6118
6119 Self.Diag(Loc, PD)
6120 << CodeModificationHint::CreateInsertion(ParenRange.getBegin(), "(")
6121 << CodeModificationHint::CreateInsertion(EndLoc, ")");
6122}
6123
Sebastian Redl44615072009-10-27 12:10:02 +00006124/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
6125/// operators are mixed in a way that suggests that the programmer forgot that
6126/// comparison operators have higher precedence. The most typical example of
6127/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
Sebastian Redl43028242009-10-26 15:24:15 +00006128static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperator::Opcode Opc,
6129 SourceLocation OpLoc,Expr *lhs,Expr *rhs){
Sebastian Redl44615072009-10-27 12:10:02 +00006130 typedef BinaryOperator BinOp;
6131 BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1),
6132 rhsopc = static_cast<BinOp::Opcode>(-1);
6133 if (BinOp *BO = dyn_cast<BinOp>(lhs))
Sebastian Redl43028242009-10-26 15:24:15 +00006134 lhsopc = BO->getOpcode();
Sebastian Redl44615072009-10-27 12:10:02 +00006135 if (BinOp *BO = dyn_cast<BinOp>(rhs))
Sebastian Redl43028242009-10-26 15:24:15 +00006136 rhsopc = BO->getOpcode();
6137
6138 // Subs are not binary operators.
6139 if (lhsopc == -1 && rhsopc == -1)
6140 return;
6141
6142 // Bitwise operations are sometimes used as eager logical ops.
6143 // Don't diagnose this.
Sebastian Redl44615072009-10-27 12:10:02 +00006144 if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) &&
6145 (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc)))
Sebastian Redl43028242009-10-26 15:24:15 +00006146 return;
6147
Sebastian Redl44615072009-10-27 12:10:02 +00006148 if (BinOp::isComparisonOp(lhsopc))
Sebastian Redl4afb7c582009-10-26 17:01:32 +00006149 SuggestParentheses(Self, OpLoc,
6150 PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redl44615072009-10-27 12:10:02 +00006151 << SourceRange(lhs->getLocStart(), OpLoc)
6152 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(lhsopc),
6153 SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(), rhs->getLocEnd()));
6154 else if (BinOp::isComparisonOp(rhsopc))
Sebastian Redl4afb7c582009-10-26 17:01:32 +00006155 SuggestParentheses(Self, OpLoc,
6156 PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redl44615072009-10-27 12:10:02 +00006157 << SourceRange(OpLoc, rhs->getLocEnd())
6158 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(rhsopc),
6159 SourceRange(lhs->getLocEnd(), cast<BinOp>(rhs)->getLHS()->getLocStart()));
Sebastian Redl43028242009-10-26 15:24:15 +00006160}
6161
6162/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
6163/// precedence. This currently diagnoses only "arg1 'bitwise' arg2 'eq' arg3".
6164/// But it could also warn about arg1 && arg2 || arg3, as GCC 4.3+ does.
6165static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperator::Opcode Opc,
6166 SourceLocation OpLoc, Expr *lhs, Expr *rhs){
Sebastian Redl44615072009-10-27 12:10:02 +00006167 if (BinaryOperator::isBitwiseOp(Opc))
Sebastian Redl43028242009-10-26 15:24:15 +00006168 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs);
6169}
6170
Steve Naroff218bc2b2007-05-04 21:54:46 +00006171// Binary Operators. 'Tok' is the token for the operator.
Sebastian Redlb5d49352009-01-19 22:31:54 +00006172Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
6173 tok::TokenKind Kind,
6174 ExprArg LHS, ExprArg RHS) {
Steve Naroff218bc2b2007-05-04 21:54:46 +00006175 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
Anders Carlssonb781bcd2009-05-01 19:49:17 +00006176 Expr *lhs = LHS.takeAs<Expr>(), *rhs = RHS.takeAs<Expr>();
Steve Naroff218bc2b2007-05-04 21:54:46 +00006177
Steve Naroff83895f72007-09-16 03:34:24 +00006178 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
6179 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Steve Naroff218bc2b2007-05-04 21:54:46 +00006180
Sebastian Redl43028242009-10-26 15:24:15 +00006181 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
6182 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs);
6183
Douglas Gregor5287f092009-11-05 00:51:44 +00006184 return BuildBinOp(S, TokLoc, Opc, lhs, rhs);
6185}
6186
6187Action::OwningExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
6188 BinaryOperator::Opcode Opc,
6189 Expr *lhs, Expr *rhs) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006190 if (getLangOptions().CPlusPlus &&
Mike Stump11289f42009-09-09 15:08:12 +00006191 (lhs->getType()->isOverloadableType() ||
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006192 rhs->getType()->isOverloadableType())) {
6193 // Find all of the overloaded operators visible from this
6194 // point. We perform both an operator-name lookup from the local
6195 // scope and an argument-dependent lookup based on the types of
6196 // the arguments.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00006197 FunctionSet Functions;
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006198 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
6199 if (OverOp != OO_None) {
Douglas Gregor5287f092009-11-05 00:51:44 +00006200 if (S)
6201 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
6202 Functions);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006203 Expr *Args[2] = { lhs, rhs };
Mike Stump11289f42009-09-09 15:08:12 +00006204 DeclarationName OpName
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006205 = Context.DeclarationNames.getCXXOperatorName(OverOp);
Sebastian Redlc057f422009-10-23 19:23:15 +00006206 ArgumentDependentLookup(OpName, /*Operator*/true, Args, 2, Functions);
Douglas Gregora11693b2008-11-12 17:17:38 +00006207 }
Douglas Gregor5287f092009-11-05 00:51:44 +00006208
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006209 // Build the (potentially-overloaded, potentially-dependent)
6210 // binary operation.
Douglas Gregor5287f092009-11-05 00:51:44 +00006211 return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs);
Sebastian Redlb5d49352009-01-19 22:31:54 +00006212 }
Douglas Gregor5287f092009-11-05 00:51:44 +00006213
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006214 // Build a built-in binary operation.
Douglas Gregor5287f092009-11-05 00:51:44 +00006215 return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs);
Steve Naroff218bc2b2007-05-04 21:54:46 +00006216}
6217
Douglas Gregor084d8552009-03-13 23:49:33 +00006218Action::OwningExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00006219 unsigned OpcIn,
Douglas Gregor084d8552009-03-13 23:49:33 +00006220 ExprArg InputArg) {
6221 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregord08452f2008-11-19 15:42:04 +00006222
Mike Stump87c57ac2009-05-16 07:39:55 +00006223 // FIXME: Input is modified below, but InputArg is not updated appropriately.
Douglas Gregor084d8552009-03-13 23:49:33 +00006224 Expr *Input = (Expr *)InputArg.get();
Steve Naroff35d85152007-05-07 00:24:15 +00006225 QualType resultType;
6226 switch (Opc) {
Douglas Gregor084d8552009-03-13 23:49:33 +00006227 case UnaryOperator::OffsetOf:
6228 assert(false && "Invalid unary operator");
6229 break;
6230
Steve Naroff35d85152007-05-07 00:24:15 +00006231 case UnaryOperator::PreInc:
6232 case UnaryOperator::PreDec:
Eli Friedman6aea5752009-07-22 22:25:00 +00006233 case UnaryOperator::PostInc:
6234 case UnaryOperator::PostDec:
Sebastian Redle10c2c32008-12-20 09:35:34 +00006235 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
Eli Friedman6aea5752009-07-22 22:25:00 +00006236 Opc == UnaryOperator::PreInc ||
6237 Opc == UnaryOperator::PostInc);
Steve Naroff35d85152007-05-07 00:24:15 +00006238 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006239 case UnaryOperator::AddrOf:
Chris Lattner86554282007-06-08 22:32:33 +00006240 resultType = CheckAddressOfOperand(Input, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00006241 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006242 case UnaryOperator::Deref:
Steve Naroffb7235642007-12-18 04:06:57 +00006243 DefaultFunctionArrayConversion(Input);
Chris Lattner86554282007-06-08 22:32:33 +00006244 resultType = CheckIndirectionOperand(Input, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00006245 break;
6246 case UnaryOperator::Plus:
6247 case UnaryOperator::Minus:
Steve Naroff31090012007-07-16 21:54:35 +00006248 UsualUnaryConversions(Input);
6249 resultType = Input->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006250 if (resultType->isDependentType())
6251 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00006252 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
6253 break;
6254 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
6255 resultType->isEnumeralType())
6256 break;
6257 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
6258 Opc == UnaryOperator::Plus &&
6259 resultType->isPointerType())
6260 break;
6261
Sebastian Redlc215cfc2009-01-19 00:08:26 +00006262 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
6263 << resultType << Input->getSourceRange());
Steve Naroff35d85152007-05-07 00:24:15 +00006264 case UnaryOperator::Not: // bitwise complement
Steve Naroff31090012007-07-16 21:54:35 +00006265 UsualUnaryConversions(Input);
6266 resultType = Input->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006267 if (resultType->isDependentType())
6268 break;
Chris Lattner0d707612008-07-25 23:52:49 +00006269 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
6270 if (resultType->isComplexType() || resultType->isComplexIntegerType())
6271 // C99 does not support '~' for complex conjugation.
Chris Lattner29e812b2008-11-20 06:06:08 +00006272 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006273 << resultType << Input->getSourceRange();
Chris Lattner0d707612008-07-25 23:52:49 +00006274 else if (!resultType->isIntegerType())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00006275 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
6276 << resultType << Input->getSourceRange());
Steve Naroff35d85152007-05-07 00:24:15 +00006277 break;
6278 case UnaryOperator::LNot: // logical negation
Steve Naroff71b59a92007-06-04 22:22:31 +00006279 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Steve Naroff31090012007-07-16 21:54:35 +00006280 DefaultFunctionArrayConversion(Input);
6281 resultType = Input->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006282 if (resultType->isDependentType())
6283 break;
Steve Naroff35d85152007-05-07 00:24:15 +00006284 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redlc215cfc2009-01-19 00:08:26 +00006285 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
6286 << resultType << Input->getSourceRange());
Chris Lattnerbe31ed82007-06-02 19:11:33 +00006287 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00006288 // In C++, it's bool. C++ 5.3.1p8
6289 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Steve Naroff35d85152007-05-07 00:24:15 +00006290 break;
Chris Lattner30b5dd02007-08-24 21:16:53 +00006291 case UnaryOperator::Real:
Chris Lattner30b5dd02007-08-24 21:16:53 +00006292 case UnaryOperator::Imag:
Chris Lattner709322b2009-02-17 08:12:06 +00006293 resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real);
Chris Lattner30b5dd02007-08-24 21:16:53 +00006294 break;
Chris Lattner86554282007-06-08 22:32:33 +00006295 case UnaryOperator::Extension:
Chris Lattner86554282007-06-08 22:32:33 +00006296 resultType = Input->getType();
Steve Naroff043d45d2007-05-15 02:32:35 +00006297 break;
Steve Naroff35d85152007-05-07 00:24:15 +00006298 }
6299 if (resultType.isNull())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00006300 return ExprError();
Douglas Gregor084d8552009-03-13 23:49:33 +00006301
6302 InputArg.release();
Steve Narofff6009ed2009-01-21 00:14:39 +00006303 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
Steve Naroff35d85152007-05-07 00:24:15 +00006304}
Chris Lattnereefa10e2007-05-28 06:56:27 +00006305
Douglas Gregor5287f092009-11-05 00:51:44 +00006306Action::OwningExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
6307 UnaryOperator::Opcode Opc,
6308 ExprArg input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00006309 Expr *Input = (Expr*)input.get();
Anders Carlsson461a2c02009-11-14 21:26:41 +00006310 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
6311 Opc != UnaryOperator::Extension) {
Douglas Gregor084d8552009-03-13 23:49:33 +00006312 // Find all of the overloaded operators visible from this
6313 // point. We perform both an operator-name lookup from the local
6314 // scope and an argument-dependent lookup based on the types of
6315 // the arguments.
6316 FunctionSet Functions;
6317 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
6318 if (OverOp != OO_None) {
Douglas Gregor5287f092009-11-05 00:51:44 +00006319 if (S)
6320 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
6321 Functions);
Mike Stump11289f42009-09-09 15:08:12 +00006322 DeclarationName OpName
Douglas Gregor084d8552009-03-13 23:49:33 +00006323 = Context.DeclarationNames.getCXXOperatorName(OverOp);
Sebastian Redlc057f422009-10-23 19:23:15 +00006324 ArgumentDependentLookup(OpName, /*Operator*/true, &Input, 1, Functions);
Douglas Gregor084d8552009-03-13 23:49:33 +00006325 }
Douglas Gregor5287f092009-11-05 00:51:44 +00006326
Douglas Gregor084d8552009-03-13 23:49:33 +00006327 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, move(input));
6328 }
Douglas Gregor5287f092009-11-05 00:51:44 +00006329
Douglas Gregor084d8552009-03-13 23:49:33 +00006330 return CreateBuiltinUnaryOp(OpLoc, Opc, move(input));
6331}
6332
Douglas Gregor5287f092009-11-05 00:51:44 +00006333// Unary Operators. 'Tok' is the token for the operator.
6334Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
6335 tok::TokenKind Op, ExprArg input) {
6336 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), move(input));
6337}
6338
Steve Naroff66356bd2007-09-16 14:56:35 +00006339/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006340Sema::OwningExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
6341 SourceLocation LabLoc,
6342 IdentifierInfo *LabelII) {
Chris Lattnereefa10e2007-05-28 06:56:27 +00006343 // Look up the record for this label identifier.
Chris Lattner3318e862009-04-18 20:01:55 +00006344 LabelStmt *&LabelDecl = getLabelMap()[LabelII];
Mike Stump4e1f26a2009-02-19 03:04:26 +00006345
Daniel Dunbar88402ce2008-08-04 16:51:22 +00006346 // If we haven't seen this label yet, create a forward reference. It
6347 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Steve Naroff846b1ec2009-03-13 15:38:40 +00006348 if (LabelDecl == 0)
Steve Narofff6009ed2009-01-21 00:14:39 +00006349 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006350
Chris Lattnereefa10e2007-05-28 06:56:27 +00006351 // Create the AST node. The address of a label always has type 'void*'.
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006352 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
6353 Context.getPointerType(Context.VoidTy)));
Chris Lattnereefa10e2007-05-28 06:56:27 +00006354}
6355
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006356Sema::OwningExprResult
6357Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtArg substmt,
6358 SourceLocation RPLoc) { // "({..})"
6359 Stmt *SubStmt = static_cast<Stmt*>(substmt.get());
Chris Lattner366727f2007-07-24 16:58:17 +00006360 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
6361 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
6362
Eli Friedman52cc0162009-01-24 23:09:00 +00006363 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Chris Lattnera69b0762009-04-25 19:11:05 +00006364 if (isFileScope)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006365 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedman52cc0162009-01-24 23:09:00 +00006366
Chris Lattner366727f2007-07-24 16:58:17 +00006367 // FIXME: there are a variety of strange constraints to enforce here, for
6368 // example, it is not possible to goto into a stmt expression apparently.
6369 // More semantic analysis is needed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00006370
Chris Lattner366727f2007-07-24 16:58:17 +00006371 // If there are sub stmts in the compound stmt, take the type of the last one
6372 // as the type of the stmtexpr.
6373 QualType Ty = Context.VoidTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006374
Chris Lattner944d3062008-07-26 19:51:01 +00006375 if (!Compound->body_empty()) {
6376 Stmt *LastStmt = Compound->body_back();
6377 // If LastStmt is a label, skip down through into the body.
6378 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
6379 LastStmt = Label->getSubStmt();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006380
Chris Lattner944d3062008-07-26 19:51:01 +00006381 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattner366727f2007-07-24 16:58:17 +00006382 Ty = LastExpr->getType();
Chris Lattner944d3062008-07-26 19:51:01 +00006383 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006384
Eli Friedmanba961a92009-03-23 00:24:07 +00006385 // FIXME: Check that expression type is complete/non-abstract; statement
6386 // expressions are not lvalues.
6387
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006388 substmt.release();
6389 return Owned(new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc));
Chris Lattner366727f2007-07-24 16:58:17 +00006390}
Steve Naroff78864672007-08-01 22:05:33 +00006391
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006392Sema::OwningExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
6393 SourceLocation BuiltinLoc,
6394 SourceLocation TypeLoc,
6395 TypeTy *argty,
6396 OffsetOfComponent *CompPtr,
6397 unsigned NumComponents,
6398 SourceLocation RPLoc) {
6399 // FIXME: This function leaks all expressions in the offset components on
6400 // error.
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00006401 // FIXME: Preserve type source info.
6402 QualType ArgTy = GetTypeFromParser(argty);
Chris Lattnerf17bd422007-08-30 17:45:32 +00006403 assert(!ArgTy.isNull() && "Missing type argument!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00006404
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006405 bool Dependent = ArgTy->isDependentType();
6406
Chris Lattnerf17bd422007-08-30 17:45:32 +00006407 // We must have at least one component that refers to the type, and the first
6408 // one is known to be a field designator. Verify that the ArgTy represents
6409 // a struct/union/class.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006410 if (!Dependent && !ArgTy->isRecordType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006411 return ExprError(Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006412
Eli Friedmanba961a92009-03-23 00:24:07 +00006413 // FIXME: Type must be complete per C99 7.17p3 because a declaring a variable
6414 // with an incomplete type would be illegal.
Douglas Gregor26897462009-03-11 16:48:53 +00006415
Eli Friedman988a16b2009-02-27 06:44:11 +00006416 // Otherwise, create a null pointer as the base, and iteratively process
6417 // the offsetof designators.
6418 QualType ArgTyPtr = Context.getPointerType(ArgTy);
6419 Expr* Res = new (Context) ImplicitValueInitExpr(ArgTyPtr);
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006420 Res = new (Context) UnaryOperator(Res, UnaryOperator::Deref,
Eli Friedman988a16b2009-02-27 06:44:11 +00006421 ArgTy, SourceLocation());
Eli Friedman16c88df2009-01-26 01:33:06 +00006422
Chris Lattner78502cf2007-08-31 21:49:13 +00006423 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
6424 // GCC extension, diagnose them.
Eli Friedman988a16b2009-02-27 06:44:11 +00006425 // FIXME: This diagnostic isn't actually visible because the location is in
6426 // a system header!
Chris Lattner78502cf2007-08-31 21:49:13 +00006427 if (NumComponents != 1)
Chris Lattnerf490e152008-11-19 05:27:50 +00006428 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
6429 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006430
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006431 if (!Dependent) {
Eli Friedman8469bc72009-05-03 21:22:18 +00006432 bool DidWarnAboutNonPOD = false;
Mike Stump11289f42009-09-09 15:08:12 +00006433
John McCall9eff4e62009-11-04 03:03:43 +00006434 if (RequireCompleteType(TypeLoc, Res->getType(),
6435 diag::err_offsetof_incomplete_type))
6436 return ExprError();
6437
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006438 // FIXME: Dependent case loses a lot of information here. And probably
6439 // leaks like a sieve.
6440 for (unsigned i = 0; i != NumComponents; ++i) {
6441 const OffsetOfComponent &OC = CompPtr[i];
6442 if (OC.isBrackets) {
6443 // Offset of an array sub-field. TODO: Should we allow vector elements?
6444 const ArrayType *AT = Context.getAsArrayType(Res->getType());
6445 if (!AT) {
6446 Res->Destroy(Context);
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006447 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
6448 << Res->getType());
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006449 }
6450
6451 // FIXME: C++: Verify that operator[] isn't overloaded.
6452
Eli Friedman988a16b2009-02-27 06:44:11 +00006453 // Promote the array so it looks more like a normal array subscript
6454 // expression.
6455 DefaultFunctionArrayConversion(Res);
6456
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006457 // C99 6.5.2.1p1
6458 Expr *Idx = static_cast<Expr*>(OC.U.E);
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006459 // FIXME: Leaks Res
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006460 if (!Idx->isTypeDependent() && !Idx->getType()->isIntegerType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006461 return ExprError(Diag(Idx->getLocStart(),
Chris Lattner003af242009-04-25 22:50:55 +00006462 diag::err_typecheck_subscript_not_integer)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006463 << Idx->getSourceRange());
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006464
6465 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
6466 OC.LocEnd);
6467 continue;
Chris Lattnerf17bd422007-08-30 17:45:32 +00006468 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006469
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006470 const RecordType *RC = Res->getType()->getAs<RecordType>();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006471 if (!RC) {
6472 Res->Destroy(Context);
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006473 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
6474 << Res->getType());
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006475 }
Chris Lattner98dbf0a2007-08-30 17:59:59 +00006476
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006477 // Get the decl corresponding to this.
6478 RecordDecl *RD = RC->getDecl();
Anders Carlsson2bbb86b2009-05-01 23:20:30 +00006479 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
Anders Carlsson38ebcaa2009-05-02 18:36:10 +00006480 if (!CRD->isPOD() && !DidWarnAboutNonPOD) {
Douglas Gregor7ca84af2009-12-12 07:25:49 +00006481 switch (ExprEvalContexts.back().Context ) {
6482 case Unevaluated:
6483 // The argument will never be evaluated, so don't complain.
6484 break;
6485
6486 case PotentiallyEvaluated:
6487 ExprError(Diag(BuiltinLoc, diag::warn_offsetof_non_pod_type)
6488 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
6489 << Res->getType());
6490 DidWarnAboutNonPOD = true;
6491 break;
6492
6493 case PotentiallyPotentiallyEvaluated:
Douglas Gregorfab31f42009-12-12 07:57:52 +00006494 ExprEvalContexts.back().addDiagnostic(BuiltinLoc,
6495 PDiag(diag::warn_offsetof_non_pod_type)
6496 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
6497 << Res->getType());
Douglas Gregor7ca84af2009-12-12 07:25:49 +00006498 DidWarnAboutNonPOD = true;
6499 break;
6500 }
Anders Carlsson38ebcaa2009-05-02 18:36:10 +00006501 }
Anders Carlsson2bbb86b2009-05-01 23:20:30 +00006502 }
Mike Stump11289f42009-09-09 15:08:12 +00006503
John McCall27b18f82009-11-17 02:14:36 +00006504 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
6505 LookupQualifiedName(R, RD);
John McCall9f3059a2009-10-09 21:13:30 +00006506
John McCall67c00872009-12-02 08:25:40 +00006507 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006508 // FIXME: Leaks Res
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006509 if (!MemberDecl)
Douglas Gregore40876a2009-10-13 21:16:44 +00006510 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
6511 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, OC.LocEnd));
Mike Stump4e1f26a2009-02-19 03:04:26 +00006512
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006513 // FIXME: C++: Verify that MemberDecl isn't a static field.
6514 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman64fc3c62009-04-26 20:50:44 +00006515 if (cast<RecordDecl>(MemberDecl->getDeclContext())->isAnonymousStructOrUnion()) {
Anders Carlsson3cbc8592009-05-01 19:30:39 +00006516 Res = BuildAnonymousStructUnionMemberReference(
John McCall7e1d6d72009-11-11 03:23:23 +00006517 OC.LocEnd, MemberDecl, Res, OC.LocEnd).takeAs<Expr>();
Eli Friedman64fc3c62009-04-26 20:50:44 +00006518 } else {
Eli Friedman78cde142009-12-04 07:18:51 +00006519 PerformObjectMemberConversion(Res, MemberDecl);
Eli Friedman64fc3c62009-04-26 20:50:44 +00006520 // MemberDecl->getType() doesn't get the right qualifiers, but it
6521 // doesn't matter here.
6522 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
6523 MemberDecl->getType().getNonReferenceType());
6524 }
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006525 }
Chris Lattnerf17bd422007-08-30 17:45:32 +00006526 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006527
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006528 return Owned(new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
6529 Context.getSizeType(), BuiltinLoc));
Chris Lattnerf17bd422007-08-30 17:45:32 +00006530}
6531
6532
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006533Sema::OwningExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
6534 TypeTy *arg1,TypeTy *arg2,
6535 SourceLocation RPLoc) {
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00006536 // FIXME: Preserve type source info.
6537 QualType argT1 = GetTypeFromParser(arg1);
6538 QualType argT2 = GetTypeFromParser(arg2);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006539
Steve Naroff78864672007-08-01 22:05:33 +00006540 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
Mike Stump4e1f26a2009-02-19 03:04:26 +00006541
Douglas Gregorf907cbf2009-05-19 22:28:02 +00006542 if (getLangOptions().CPlusPlus) {
6543 Diag(BuiltinLoc, diag::err_types_compatible_p_in_cplusplus)
6544 << SourceRange(BuiltinLoc, RPLoc);
6545 return ExprError();
6546 }
6547
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006548 return Owned(new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc,
6549 argT1, argT2, RPLoc));
Steve Naroff78864672007-08-01 22:05:33 +00006550}
6551
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006552Sema::OwningExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
6553 ExprArg cond,
6554 ExprArg expr1, ExprArg expr2,
6555 SourceLocation RPLoc) {
6556 Expr *CondExpr = static_cast<Expr*>(cond.get());
6557 Expr *LHSExpr = static_cast<Expr*>(expr1.get());
6558 Expr *RHSExpr = static_cast<Expr*>(expr2.get());
Mike Stump4e1f26a2009-02-19 03:04:26 +00006559
Steve Naroff9efdabc2007-08-03 21:21:27 +00006560 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
6561
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006562 QualType resType;
Douglas Gregor56751b52009-09-25 04:25:58 +00006563 bool ValueDependent = false;
Douglas Gregor0df91122009-05-19 22:43:30 +00006564 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006565 resType = Context.DependentTy;
Douglas Gregor56751b52009-09-25 04:25:58 +00006566 ValueDependent = true;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006567 } else {
6568 // The conditional expression is required to be a constant expression.
6569 llvm::APSInt condEval(32);
6570 SourceLocation ExpLoc;
6571 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006572 return ExprError(Diag(ExpLoc,
6573 diag::err_typecheck_choose_expr_requires_constant)
6574 << CondExpr->getSourceRange());
Steve Naroff9efdabc2007-08-03 21:21:27 +00006575
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006576 // If the condition is > zero, then the AST type is the same as the LSHExpr.
6577 resType = condEval.getZExtValue() ? LHSExpr->getType() : RHSExpr->getType();
Douglas Gregor56751b52009-09-25 04:25:58 +00006578 ValueDependent = condEval.getZExtValue() ? LHSExpr->isValueDependent()
6579 : RHSExpr->isValueDependent();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006580 }
6581
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006582 cond.release(); expr1.release(); expr2.release();
6583 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
Douglas Gregor56751b52009-09-25 04:25:58 +00006584 resType, RPLoc,
6585 resType->isDependentType(),
6586 ValueDependent));
Steve Naroff9efdabc2007-08-03 21:21:27 +00006587}
6588
Steve Naroffc540d662008-09-03 18:15:37 +00006589//===----------------------------------------------------------------------===//
6590// Clang Extensions.
6591//===----------------------------------------------------------------------===//
6592
6593/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff1d95e5a2008-10-10 01:28:17 +00006594void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroffc540d662008-09-03 18:15:37 +00006595 // Analyze block parameters.
6596 BlockSemaInfo *BSI = new BlockSemaInfo();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006597
Steve Naroffc540d662008-09-03 18:15:37 +00006598 // Add BSI to CurBlock.
6599 BSI->PrevBlockInfo = CurBlock;
6600 CurBlock = BSI;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006601
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00006602 BSI->ReturnType = QualType();
Steve Naroffc540d662008-09-03 18:15:37 +00006603 BSI->TheScope = BlockScope;
Mike Stumpa6703322009-02-19 22:01:56 +00006604 BSI->hasBlockDeclRefExprs = false;
Daniel Dunbarb9a68612009-07-29 01:59:17 +00006605 BSI->hasPrototype = false;
Chris Lattner45542ea2009-04-19 05:28:12 +00006606 BSI->SavedFunctionNeedsScopeChecking = CurFunctionNeedsScopeChecking;
6607 CurFunctionNeedsScopeChecking = false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006608
Steve Naroff1d95e5a2008-10-10 01:28:17 +00006609 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Ted Kremenek54ad1ab2009-12-07 22:01:30 +00006610 CurContext->addDecl(BSI->TheDecl);
Douglas Gregor91f84212008-12-11 16:49:14 +00006611 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff1d95e5a2008-10-10 01:28:17 +00006612}
6613
Mike Stump82f071f2009-02-04 22:31:32 +00006614void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpf70bcf72009-05-07 18:43:07 +00006615 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
Mike Stump82f071f2009-02-04 22:31:32 +00006616
6617 if (ParamInfo.getNumTypeObjects() == 0
6618 || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) {
Douglas Gregor758a8692009-06-17 21:51:59 +00006619 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
Mike Stump82f071f2009-02-04 22:31:32 +00006620 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
6621
Mike Stumpd456c482009-04-28 01:10:27 +00006622 if (T->isArrayType()) {
6623 Diag(ParamInfo.getSourceRange().getBegin(),
6624 diag::err_block_returns_array);
6625 return;
6626 }
6627
Mike Stump82f071f2009-02-04 22:31:32 +00006628 // The parameter list is optional, if there was none, assume ().
6629 if (!T->isFunctionType())
6630 T = Context.getFunctionType(T, NULL, 0, 0, 0);
6631
6632 CurBlock->hasPrototype = true;
6633 CurBlock->isVariadic = false;
Fariborz Jahanian6607b212009-05-14 20:53:39 +00006634 // Check for a valid sentinel attribute on this block.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00006635 if (CurBlock->TheDecl->getAttr<SentinelAttr>()) {
Mike Stump11289f42009-09-09 15:08:12 +00006636 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian6802ed92009-05-15 21:18:04 +00006637 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian6607b212009-05-14 20:53:39 +00006638 // FIXME: remove the attribute.
6639 }
John McCall9dd450b2009-09-21 23:43:11 +00006640 QualType RetTy = T.getTypePtr()->getAs<FunctionType>()->getResultType();
Mike Stump11289f42009-09-09 15:08:12 +00006641
Chris Lattner6de05082009-04-11 19:27:54 +00006642 // Do not allow returning a objc interface by-value.
6643 if (RetTy->isObjCInterfaceType()) {
6644 Diag(ParamInfo.getSourceRange().getBegin(),
6645 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
6646 return;
6647 }
Mike Stump82f071f2009-02-04 22:31:32 +00006648 return;
6649 }
6650
Steve Naroffc540d662008-09-03 18:15:37 +00006651 // Analyze arguments to block.
6652 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
6653 "Not a function declarator!");
6654 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006655
Steve Naroff1d95e5a2008-10-10 01:28:17 +00006656 CurBlock->hasPrototype = FTI.hasPrototype;
6657 CurBlock->isVariadic = true;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006658
Steve Naroffc540d662008-09-03 18:15:37 +00006659 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
6660 // no arguments, not a function that takes a single void argument.
6661 if (FTI.hasPrototype &&
6662 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
Chris Lattner83f095c2009-03-28 19:18:32 +00006663 (!FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType().getCVRQualifiers()&&
6664 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType())) {
Steve Naroffc540d662008-09-03 18:15:37 +00006665 // empty arg list, don't push any params.
Steve Naroff1d95e5a2008-10-10 01:28:17 +00006666 CurBlock->isVariadic = false;
Steve Naroffc540d662008-09-03 18:15:37 +00006667 } else if (FTI.hasPrototype) {
6668 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Chris Lattner83f095c2009-03-28 19:18:32 +00006669 CurBlock->Params.push_back(FTI.ArgInfo[i].Param.getAs<ParmVarDecl>());
Steve Naroff1d95e5a2008-10-10 01:28:17 +00006670 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroffc540d662008-09-03 18:15:37 +00006671 }
Jay Foad7d0479f2009-05-21 09:52:38 +00006672 CurBlock->TheDecl->setParams(Context, CurBlock->Params.data(),
Chris Lattner6de05082009-04-11 19:27:54 +00006673 CurBlock->Params.size());
Fariborz Jahanian960910a2009-05-19 17:08:59 +00006674 CurBlock->TheDecl->setIsVariadic(CurBlock->isVariadic);
Douglas Gregor758a8692009-06-17 21:51:59 +00006675 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
Steve Naroff1d95e5a2008-10-10 01:28:17 +00006676 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
6677 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
6678 // If this has an identifier, add it to the scope stack.
6679 if ((*AI)->getIdentifier())
6680 PushOnScopeChains(*AI, CurBlock->TheScope);
Chris Lattner6de05082009-04-11 19:27:54 +00006681
Fariborz Jahanian6607b212009-05-14 20:53:39 +00006682 // Check for a valid sentinel attribute on this block.
Mike Stump11289f42009-09-09 15:08:12 +00006683 if (!CurBlock->isVariadic &&
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00006684 CurBlock->TheDecl->getAttr<SentinelAttr>()) {
Mike Stump11289f42009-09-09 15:08:12 +00006685 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian6802ed92009-05-15 21:18:04 +00006686 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian6607b212009-05-14 20:53:39 +00006687 // FIXME: remove the attribute.
6688 }
Mike Stump11289f42009-09-09 15:08:12 +00006689
Chris Lattner6de05082009-04-11 19:27:54 +00006690 // Analyze the return type.
6691 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
John McCall9dd450b2009-09-21 23:43:11 +00006692 QualType RetTy = T->getAs<FunctionType>()->getResultType();
Mike Stump11289f42009-09-09 15:08:12 +00006693
Chris Lattner6de05082009-04-11 19:27:54 +00006694 // Do not allow returning a objc interface by-value.
6695 if (RetTy->isObjCInterfaceType()) {
6696 Diag(ParamInfo.getSourceRange().getBegin(),
6697 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
6698 } else if (!RetTy->isDependentType())
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00006699 CurBlock->ReturnType = RetTy;
Steve Naroffc540d662008-09-03 18:15:37 +00006700}
6701
6702/// ActOnBlockError - If there is an error parsing a block, this callback
6703/// is invoked to pop the information about the block from the action impl.
6704void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
6705 // Ensure that CurBlock is deleted.
6706 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006707
Chris Lattner45542ea2009-04-19 05:28:12 +00006708 CurFunctionNeedsScopeChecking = CurBlock->SavedFunctionNeedsScopeChecking;
6709
Steve Naroffc540d662008-09-03 18:15:37 +00006710 // Pop off CurBlock, handle nested blocks.
Chris Lattner41b86942009-04-21 22:38:46 +00006711 PopDeclContext();
Steve Naroffc540d662008-09-03 18:15:37 +00006712 CurBlock = CurBlock->PrevBlockInfo;
Steve Naroffc540d662008-09-03 18:15:37 +00006713 // FIXME: Delete the ParmVarDecl objects as well???
Steve Naroffc540d662008-09-03 18:15:37 +00006714}
6715
6716/// ActOnBlockStmtExpr - This is called when the body of a block statement
6717/// literal was successfully completed. ^(int x){...}
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006718Sema::OwningExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
6719 StmtArg body, Scope *CurScope) {
Chris Lattner9eac9312009-03-27 04:18:06 +00006720 // If blocks are disabled, emit an error.
6721 if (!LangOpts.Blocks)
6722 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump11289f42009-09-09 15:08:12 +00006723
Steve Naroffc540d662008-09-03 18:15:37 +00006724 // Ensure that CurBlock is deleted.
6725 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
Steve Naroffc540d662008-09-03 18:15:37 +00006726
Steve Naroff1d95e5a2008-10-10 01:28:17 +00006727 PopDeclContext();
6728
Steve Naroffc540d662008-09-03 18:15:37 +00006729 // Pop off CurBlock, handle nested blocks.
6730 CurBlock = CurBlock->PrevBlockInfo;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006731
Steve Naroffc540d662008-09-03 18:15:37 +00006732 QualType RetTy = Context.VoidTy;
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00006733 if (!BSI->ReturnType.isNull())
6734 RetTy = BSI->ReturnType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006735
Steve Naroffc540d662008-09-03 18:15:37 +00006736 llvm::SmallVector<QualType, 8> ArgTypes;
6737 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
6738 ArgTypes.push_back(BSI->Params[i]->getType());
Mike Stump4e1f26a2009-02-19 03:04:26 +00006739
Mike Stump3bf1ab42009-07-28 22:04:01 +00006740 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroffc540d662008-09-03 18:15:37 +00006741 QualType BlockTy;
6742 if (!BSI->hasPrototype)
Mike Stump3bf1ab42009-07-28 22:04:01 +00006743 BlockTy = Context.getFunctionType(RetTy, 0, 0, false, 0, false, false, 0, 0,
6744 NoReturn);
Steve Naroffc540d662008-09-03 18:15:37 +00006745 else
Jay Foad7d0479f2009-05-21 09:52:38 +00006746 BlockTy = Context.getFunctionType(RetTy, ArgTypes.data(), ArgTypes.size(),
Mike Stump3bf1ab42009-07-28 22:04:01 +00006747 BSI->isVariadic, 0, false, false, 0, 0,
6748 NoReturn);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006749
Eli Friedmanba961a92009-03-23 00:24:07 +00006750 // FIXME: Check that return/parameter types are complete/non-abstract
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006751 DiagnoseUnusedParameters(BSI->Params.begin(), BSI->Params.end());
Steve Naroffc540d662008-09-03 18:15:37 +00006752 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006753
Chris Lattner45542ea2009-04-19 05:28:12 +00006754 // If needed, diagnose invalid gotos and switches in the block.
6755 if (CurFunctionNeedsScopeChecking)
6756 DiagnoseInvalidJumps(static_cast<CompoundStmt*>(body.get()));
6757 CurFunctionNeedsScopeChecking = BSI->SavedFunctionNeedsScopeChecking;
Mike Stump11289f42009-09-09 15:08:12 +00006758
Anders Carlssonb781bcd2009-05-01 19:49:17 +00006759 BSI->TheDecl->setBody(body.takeAs<CompoundStmt>());
Mike Stump3bf1ab42009-07-28 22:04:01 +00006760 CheckFallThroughForBlock(BlockTy, BSI->TheDecl->getBody());
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006761 return Owned(new (Context) BlockExpr(BSI->TheDecl, BlockTy,
6762 BSI->hasBlockDeclRefExprs));
Steve Naroffc540d662008-09-03 18:15:37 +00006763}
6764
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006765Sema::OwningExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
6766 ExprArg expr, TypeTy *type,
6767 SourceLocation RPLoc) {
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00006768 QualType T = GetTypeFromParser(type);
Chris Lattner56382aa2009-04-05 15:49:53 +00006769 Expr *E = static_cast<Expr*>(expr.get());
6770 Expr *OrigExpr = E;
Mike Stump11289f42009-09-09 15:08:12 +00006771
Anders Carlsson7e13ab82007-10-15 20:28:48 +00006772 InitBuiltinVaListType();
Eli Friedman121ba0c2008-08-09 23:32:40 +00006773
6774 // Get the va_list type
6775 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedmane2cad652009-05-16 12:46:54 +00006776 if (VaListType->isArrayType()) {
6777 // Deal with implicit array decay; for example, on x86-64,
6778 // va_list is an array, but it's supposed to decay to
6779 // a pointer for va_arg.
Eli Friedman121ba0c2008-08-09 23:32:40 +00006780 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedmane2cad652009-05-16 12:46:54 +00006781 // Make sure the input expression also decays appropriately.
6782 UsualUnaryConversions(E);
6783 } else {
6784 // Otherwise, the va_list argument must be an l-value because
6785 // it is modified by va_arg.
Mike Stump11289f42009-09-09 15:08:12 +00006786 if (!E->isTypeDependent() &&
Douglas Gregorad3150c2009-05-19 23:10:31 +00006787 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedmane2cad652009-05-16 12:46:54 +00006788 return ExprError();
6789 }
Eli Friedman121ba0c2008-08-09 23:32:40 +00006790
Douglas Gregorad3150c2009-05-19 23:10:31 +00006791 if (!E->isTypeDependent() &&
6792 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006793 return ExprError(Diag(E->getLocStart(),
6794 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner56382aa2009-04-05 15:49:53 +00006795 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner3f5cd772009-04-05 00:59:53 +00006796 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006797
Eli Friedmanba961a92009-03-23 00:24:07 +00006798 // FIXME: Check that type is complete/non-abstract
Anders Carlsson7e13ab82007-10-15 20:28:48 +00006799 // FIXME: Warn if a non-POD type is passed in.
Mike Stump4e1f26a2009-02-19 03:04:26 +00006800
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006801 expr.release();
6802 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(),
6803 RPLoc));
Anders Carlsson7e13ab82007-10-15 20:28:48 +00006804}
6805
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006806Sema::OwningExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor3be4b122008-11-29 04:51:27 +00006807 // The type of __null will be int or long, depending on the size of
6808 // pointers on the target.
6809 QualType Ty;
6810 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
6811 Ty = Context.IntTy;
6812 else
6813 Ty = Context.LongTy;
6814
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006815 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor3be4b122008-11-29 04:51:27 +00006816}
6817
Anders Carlssonace5d072009-11-10 04:46:30 +00006818static void
6819MakeObjCStringLiteralCodeModificationHint(Sema& SemaRef,
6820 QualType DstType,
6821 Expr *SrcExpr,
6822 CodeModificationHint &Hint) {
6823 if (!SemaRef.getLangOptions().ObjC1)
6824 return;
6825
6826 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
6827 if (!PT)
6828 return;
6829
6830 // Check if the destination is of type 'id'.
6831 if (!PT->isObjCIdType()) {
6832 // Check if the destination is the 'NSString' interface.
6833 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
6834 if (!ID || !ID->getIdentifier()->isStr("NSString"))
6835 return;
6836 }
6837
6838 // Strip off any parens and casts.
6839 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
6840 if (!SL || SL->isWide())
6841 return;
6842
6843 Hint = CodeModificationHint::CreateInsertion(SL->getLocStart(), "@");
6844}
6845
Chris Lattner9bad62c2008-01-04 18:04:52 +00006846bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
6847 SourceLocation Loc,
6848 QualType DstType, QualType SrcType,
6849 Expr *SrcExpr, const char *Flavor) {
6850 // Decode the result (notice that AST's are still created for extensions).
6851 bool isInvalid = false;
6852 unsigned DiagKind;
Anders Carlssonace5d072009-11-10 04:46:30 +00006853 CodeModificationHint Hint;
6854
Chris Lattner9bad62c2008-01-04 18:04:52 +00006855 switch (ConvTy) {
6856 default: assert(0 && "Unknown conversion type");
6857 case Compatible: return false;
Chris Lattner940cfeb2008-01-04 18:22:42 +00006858 case PointerToInt:
Chris Lattner9bad62c2008-01-04 18:04:52 +00006859 DiagKind = diag::ext_typecheck_convert_pointer_int;
6860 break;
Chris Lattner940cfeb2008-01-04 18:22:42 +00006861 case IntToPointer:
6862 DiagKind = diag::ext_typecheck_convert_int_pointer;
6863 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00006864 case IncompatiblePointer:
Anders Carlssonace5d072009-11-10 04:46:30 +00006865 MakeObjCStringLiteralCodeModificationHint(*this, DstType, SrcExpr, Hint);
Chris Lattner9bad62c2008-01-04 18:04:52 +00006866 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
6867 break;
Eli Friedman80160bd2009-03-22 23:59:44 +00006868 case IncompatiblePointerSign:
6869 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
6870 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00006871 case FunctionVoidPointer:
6872 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
6873 break;
6874 case CompatiblePointerDiscardsQualifiers:
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00006875 // If the qualifiers lost were because we were applying the
6876 // (deprecated) C++ conversion from a string literal to a char*
6877 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
6878 // Ideally, this check would be performed in
6879 // CheckPointerTypesForAssignment. However, that would require a
6880 // bit of refactoring (so that the second argument is an
6881 // expression, rather than a type), which should be done as part
6882 // of a larger effort to fix CheckPointerTypesForAssignment for
6883 // C++ semantics.
6884 if (getLangOptions().CPlusPlus &&
6885 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
6886 return false;
Chris Lattner9bad62c2008-01-04 18:04:52 +00006887 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
6888 break;
Alexis Hunt6f3de502009-11-08 07:46:34 +00006889 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanianb98dade2009-11-09 22:16:37 +00006890 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00006891 break;
Steve Naroff081c7422008-09-04 15:10:53 +00006892 case IntToBlockPointer:
6893 DiagKind = diag::err_int_to_block_pointer;
6894 break;
6895 case IncompatibleBlockPointer:
Mike Stumpd79b5a82009-04-21 22:51:42 +00006896 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff081c7422008-09-04 15:10:53 +00006897 break;
Steve Naroff8afa9892008-10-14 22:18:38 +00006898 case IncompatibleObjCQualifiedId:
Mike Stump4e1f26a2009-02-19 03:04:26 +00006899 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff8afa9892008-10-14 22:18:38 +00006900 // it can give a more specific diagnostic.
6901 DiagKind = diag::warn_incompatible_qualified_id;
6902 break;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00006903 case IncompatibleVectors:
6904 DiagKind = diag::warn_incompatible_vectors;
6905 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00006906 case Incompatible:
6907 DiagKind = diag::err_typecheck_convert_incompatible;
6908 isInvalid = true;
6909 break;
6910 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006911
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00006912 Diag(Loc, DiagKind) << DstType << SrcType << Flavor
Anders Carlssonace5d072009-11-10 04:46:30 +00006913 << SrcExpr->getSourceRange() << Hint;
Chris Lattner9bad62c2008-01-04 18:04:52 +00006914 return isInvalid;
6915}
Anders Carlssone54e8a12008-11-30 19:50:32 +00006916
Chris Lattnerc71d08b2009-04-25 21:59:05 +00006917bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedmanbb967cc2009-04-25 22:26:58 +00006918 llvm::APSInt ICEResult;
6919 if (E->isIntegerConstantExpr(ICEResult, Context)) {
6920 if (Result)
6921 *Result = ICEResult;
6922 return false;
6923 }
6924
Anders Carlssone54e8a12008-11-30 19:50:32 +00006925 Expr::EvalResult EvalResult;
6926
Mike Stump4e1f26a2009-02-19 03:04:26 +00006927 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone54e8a12008-11-30 19:50:32 +00006928 EvalResult.HasSideEffects) {
6929 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
6930
6931 if (EvalResult.Diag) {
6932 // We only show the note if it's not the usual "invalid subexpression"
6933 // or if it's actually in a subexpression.
6934 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
6935 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
6936 Diag(EvalResult.DiagLoc, EvalResult.Diag);
6937 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006938
Anders Carlssone54e8a12008-11-30 19:50:32 +00006939 return true;
6940 }
6941
Eli Friedmanbb967cc2009-04-25 22:26:58 +00006942 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
6943 E->getSourceRange();
Anders Carlssone54e8a12008-11-30 19:50:32 +00006944
Eli Friedmanbb967cc2009-04-25 22:26:58 +00006945 if (EvalResult.Diag &&
6946 Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
6947 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006948
Anders Carlssone54e8a12008-11-30 19:50:32 +00006949 if (Result)
6950 *Result = EvalResult.Val.getInt();
6951 return false;
6952}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006953
Douglas Gregorff790f12009-11-26 00:44:06 +00006954void
Mike Stump11289f42009-09-09 15:08:12 +00006955Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregorff790f12009-11-26 00:44:06 +00006956 ExprEvalContexts.push_back(
6957 ExpressionEvaluationContextRecord(NewContext, ExprTemporaries.size()));
Douglas Gregor0b6a6242009-06-22 20:57:11 +00006958}
6959
Mike Stump11289f42009-09-09 15:08:12 +00006960void
Douglas Gregorff790f12009-11-26 00:44:06 +00006961Sema::PopExpressionEvaluationContext() {
6962 // Pop the current expression evaluation context off the stack.
6963 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
6964 ExprEvalContexts.pop_back();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00006965
Douglas Gregorfab31f42009-12-12 07:57:52 +00006966 if (Rec.Context == PotentiallyPotentiallyEvaluated) {
6967 if (Rec.PotentiallyReferenced) {
6968 // Mark any remaining declarations in the current position of the stack
6969 // as "referenced". If they were not meant to be referenced, semantic
6970 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
6971 for (PotentiallyReferencedDecls::iterator
6972 I = Rec.PotentiallyReferenced->begin(),
6973 IEnd = Rec.PotentiallyReferenced->end();
6974 I != IEnd; ++I)
6975 MarkDeclarationReferenced(I->first, I->second);
6976 }
6977
6978 if (Rec.PotentiallyDiagnosed) {
6979 // Emit any pending diagnostics.
6980 for (PotentiallyEmittedDiagnostics::iterator
6981 I = Rec.PotentiallyDiagnosed->begin(),
6982 IEnd = Rec.PotentiallyDiagnosed->end();
6983 I != IEnd; ++I)
6984 Diag(I->first, I->second);
6985 }
Douglas Gregorff790f12009-11-26 00:44:06 +00006986 }
6987
6988 // When are coming out of an unevaluated context, clear out any
6989 // temporaries that we may have created as part of the evaluation of
6990 // the expression in that context: they aren't relevant because they
6991 // will never be constructed.
6992 if (Rec.Context == Unevaluated &&
6993 ExprTemporaries.size() > Rec.NumTemporaries)
6994 ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
6995 ExprTemporaries.end());
6996
6997 // Destroy the popped expression evaluation record.
6998 Rec.Destroy();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00006999}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007000
7001/// \brief Note that the given declaration was referenced in the source code.
7002///
7003/// This routine should be invoke whenever a given declaration is referenced
7004/// in the source code, and where that reference occurred. If this declaration
7005/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
7006/// C99 6.9p3), then the declaration will be marked as used.
7007///
7008/// \param Loc the location where the declaration was referenced.
7009///
7010/// \param D the declaration that has been referenced by the source code.
7011void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
7012 assert(D && "No declaration?");
Mike Stump11289f42009-09-09 15:08:12 +00007013
Douglas Gregor77b50e12009-06-22 23:06:13 +00007014 if (D->isUsed())
7015 return;
Mike Stump11289f42009-09-09 15:08:12 +00007016
Douglas Gregor3beaf9b2009-10-08 21:35:42 +00007017 // Mark a parameter or variable declaration "used", regardless of whether we're in a
7018 // template or not. The reason for this is that unevaluated expressions
7019 // (e.g. (void)sizeof()) constitute a use for warning purposes (-Wunused-variables and
7020 // -Wunused-parameters)
7021 if (isa<ParmVarDecl>(D) ||
7022 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod()))
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007023 D->setUsed(true);
Mike Stump11289f42009-09-09 15:08:12 +00007024
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007025 // Do not mark anything as "used" within a dependent context; wait for
7026 // an instantiation.
7027 if (CurContext->isDependentContext())
7028 return;
Mike Stump11289f42009-09-09 15:08:12 +00007029
Douglas Gregorff790f12009-11-26 00:44:06 +00007030 switch (ExprEvalContexts.back().Context) {
Douglas Gregor0b6a6242009-06-22 20:57:11 +00007031 case Unevaluated:
7032 // We are in an expression that is not potentially evaluated; do nothing.
7033 return;
Mike Stump11289f42009-09-09 15:08:12 +00007034
Douglas Gregor0b6a6242009-06-22 20:57:11 +00007035 case PotentiallyEvaluated:
7036 // We are in a potentially-evaluated expression, so this declaration is
7037 // "used"; handle this below.
7038 break;
Mike Stump11289f42009-09-09 15:08:12 +00007039
Douglas Gregor0b6a6242009-06-22 20:57:11 +00007040 case PotentiallyPotentiallyEvaluated:
7041 // We are in an expression that may be potentially evaluated; queue this
7042 // declaration reference until we know whether the expression is
7043 // potentially evaluated.
Douglas Gregorff790f12009-11-26 00:44:06 +00007044 ExprEvalContexts.back().addReferencedDecl(Loc, D);
Douglas Gregor0b6a6242009-06-22 20:57:11 +00007045 return;
7046 }
Mike Stump11289f42009-09-09 15:08:12 +00007047
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007048 // Note that this declaration has been used.
Fariborz Jahanian3a363432009-06-22 17:30:33 +00007049 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Fariborz Jahanian477d2422009-06-22 23:34:40 +00007050 unsigned TypeQuals;
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00007051 if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) {
7052 if (!Constructor->isUsed())
7053 DefineImplicitDefaultConstructor(Loc, Constructor);
Mike Stump11289f42009-09-09 15:08:12 +00007054 } else if (Constructor->isImplicit() &&
Mike Stump12b8ce12009-08-04 21:02:39 +00007055 Constructor->isCopyConstructor(Context, TypeQuals)) {
Fariborz Jahanian477d2422009-06-22 23:34:40 +00007056 if (!Constructor->isUsed())
7057 DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals);
7058 }
Anders Carlsson82fccd02009-12-07 08:24:59 +00007059
7060 MaybeMarkVirtualMembersReferenced(Loc, Constructor);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00007061 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
7062 if (Destructor->isImplicit() && !Destructor->isUsed())
7063 DefineImplicitDestructor(Loc, Destructor);
Mike Stump11289f42009-09-09 15:08:12 +00007064
Fariborz Jahanian41f79272009-06-25 21:45:19 +00007065 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
7066 if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
7067 MethodDecl->getOverloadedOperator() == OO_Equal) {
7068 if (!MethodDecl->isUsed())
7069 DefineImplicitOverloadedAssign(Loc, MethodDecl);
7070 }
7071 }
Fariborz Jahanian49796cc72009-06-24 22:09:44 +00007072 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Mike Stump11289f42009-09-09 15:08:12 +00007073 // Implicit instantiation of function templates and member functions of
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00007074 // class templates.
Douglas Gregorafca3b42009-10-27 20:53:28 +00007075 if (!Function->getBody() && Function->isImplicitlyInstantiable()) {
Douglas Gregor06db9f52009-10-12 20:18:28 +00007076 bool AlreadyInstantiated = false;
7077 if (FunctionTemplateSpecializationInfo *SpecInfo
7078 = Function->getTemplateSpecializationInfo()) {
7079 if (SpecInfo->getPointOfInstantiation().isInvalid())
7080 SpecInfo->setPointOfInstantiation(Loc);
Douglas Gregorafca3b42009-10-27 20:53:28 +00007081 else if (SpecInfo->getTemplateSpecializationKind()
7082 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +00007083 AlreadyInstantiated = true;
7084 } else if (MemberSpecializationInfo *MSInfo
7085 = Function->getMemberSpecializationInfo()) {
7086 if (MSInfo->getPointOfInstantiation().isInvalid())
7087 MSInfo->setPointOfInstantiation(Loc);
Douglas Gregorafca3b42009-10-27 20:53:28 +00007088 else if (MSInfo->getTemplateSpecializationKind()
7089 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +00007090 AlreadyInstantiated = true;
7091 }
7092
7093 if (!AlreadyInstantiated)
7094 PendingImplicitInstantiations.push_back(std::make_pair(Function, Loc));
7095 }
7096
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007097 // FIXME: keep track of references to static functions
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007098 Function->setUsed(true);
7099 return;
Douglas Gregor77b50e12009-06-22 23:06:13 +00007100 }
Mike Stump11289f42009-09-09 15:08:12 +00007101
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007102 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00007103 // Implicit instantiation of static data members of class templates.
Mike Stump11289f42009-09-09 15:08:12 +00007104 if (Var->isStaticDataMember() &&
Douglas Gregor06db9f52009-10-12 20:18:28 +00007105 Var->getInstantiatedFromStaticDataMember()) {
7106 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
7107 assert(MSInfo && "Missing member specialization information?");
7108 if (MSInfo->getPointOfInstantiation().isInvalid() &&
7109 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
7110 MSInfo->setPointOfInstantiation(Loc);
7111 PendingImplicitInstantiations.push_back(std::make_pair(Var, Loc));
7112 }
7113 }
Mike Stump11289f42009-09-09 15:08:12 +00007114
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007115 // FIXME: keep track of references to static data?
Douglas Gregora6ef8f02009-07-24 20:34:43 +00007116
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007117 D->setUsed(true);
Douglas Gregora6ef8f02009-07-24 20:34:43 +00007118 return;
Sam Weinigbae69142009-09-11 03:29:30 +00007119 }
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007120}
Anders Carlsson7f84ed92009-10-09 23:51:55 +00007121
7122bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
7123 CallExpr *CE, FunctionDecl *FD) {
7124 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
7125 return false;
7126
7127 PartialDiagnostic Note =
7128 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
7129 << FD->getDeclName() : PDiag();
7130 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
7131
7132 if (RequireCompleteType(Loc, ReturnType,
7133 FD ?
7134 PDiag(diag::err_call_function_incomplete_return)
7135 << CE->getSourceRange() << FD->getDeclName() :
7136 PDiag(diag::err_call_incomplete_return)
7137 << CE->getSourceRange(),
7138 std::make_pair(NoteLoc, Note)))
7139 return true;
7140
7141 return false;
7142}
7143
John McCalld5707ab2009-10-12 21:59:07 +00007144// Diagnose the common s/=/==/ typo. Note that adding parentheses
7145// will prevent this condition from triggering, which is what we want.
7146void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
7147 SourceLocation Loc;
7148
John McCall0506e4a2009-11-11 02:41:58 +00007149 unsigned diagnostic = diag::warn_condition_is_assignment;
7150
John McCalld5707ab2009-10-12 21:59:07 +00007151 if (isa<BinaryOperator>(E)) {
7152 BinaryOperator *Op = cast<BinaryOperator>(E);
7153 if (Op->getOpcode() != BinaryOperator::Assign)
7154 return;
7155
John McCallb0e419e2009-11-12 00:06:05 +00007156 // Greylist some idioms by putting them into a warning subcategory.
7157 if (ObjCMessageExpr *ME
7158 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
7159 Selector Sel = ME->getSelector();
7160
John McCallb0e419e2009-11-12 00:06:05 +00007161 // self = [<foo> init...]
7162 if (isSelfExpr(Op->getLHS())
7163 && Sel.getIdentifierInfoForSlot(0)->getName().startswith("init"))
7164 diagnostic = diag::warn_condition_is_idiomatic_assignment;
7165
7166 // <foo> = [<bar> nextObject]
7167 else if (Sel.isUnarySelector() &&
7168 Sel.getIdentifierInfoForSlot(0)->getName() == "nextObject")
7169 diagnostic = diag::warn_condition_is_idiomatic_assignment;
7170 }
John McCall0506e4a2009-11-11 02:41:58 +00007171
John McCalld5707ab2009-10-12 21:59:07 +00007172 Loc = Op->getOperatorLoc();
7173 } else if (isa<CXXOperatorCallExpr>(E)) {
7174 CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(E);
7175 if (Op->getOperator() != OO_Equal)
7176 return;
7177
7178 Loc = Op->getOperatorLoc();
7179 } else {
7180 // Not an assignment.
7181 return;
7182 }
7183
John McCalld5707ab2009-10-12 21:59:07 +00007184 SourceLocation Open = E->getSourceRange().getBegin();
John McCalle724ae92009-10-12 22:25:59 +00007185 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
John McCalld5707ab2009-10-12 21:59:07 +00007186
John McCall0506e4a2009-11-11 02:41:58 +00007187 Diag(Loc, diagnostic)
John McCalld5707ab2009-10-12 21:59:07 +00007188 << E->getSourceRange()
7189 << CodeModificationHint::CreateInsertion(Open, "(")
7190 << CodeModificationHint::CreateInsertion(Close, ")");
7191}
7192
7193bool Sema::CheckBooleanCondition(Expr *&E, SourceLocation Loc) {
7194 DiagnoseAssignmentAsCondition(E);
7195
7196 if (!E->isTypeDependent()) {
7197 DefaultFunctionArrayConversion(E);
7198
7199 QualType T = E->getType();
7200
7201 if (getLangOptions().CPlusPlus) {
7202 if (CheckCXXBooleanCondition(E)) // C++ 6.4p4
7203 return true;
7204 } else if (!T->isScalarType()) { // C99 6.8.4.1p1
7205 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
7206 << T << E->getSourceRange();
7207 return true;
7208 }
7209 }
7210
7211 return false;
7212}