blob: 4f08ffe9db947b4eacd6478a4bc8c176e546d58b [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
John McCall7d384dd2009-11-18 07:57:50 +000015#include "Lookup.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000016#include "clang/AST/ASTContext.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000017#include "clang/AST/DeclObjC.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000018#include "clang/AST/DeclTemplate.h"
Chris Lattner04421082008-04-08 04:40:51 +000019#include "clang/AST/ExprCXX.h"
Steve Narofff494b572008-05-29 21:12:08 +000020#include "clang/AST/ExprObjC.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000021#include "clang/Basic/PartialDiagnostic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000022#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000023#include "clang/Basic/TargetInfo.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000024#include "clang/Lex/LiteralSupport.h"
25#include "clang/Lex/Preprocessor.h"
Steve Naroff4eb206b2008-09-03 18:15:37 +000026#include "clang/Parse/DeclSpec.h"
Chris Lattner418f6c72008-10-26 23:43:26 +000027#include "clang/Parse/Designator.h"
Steve Naroff4eb206b2008-09-03 18:15:37 +000028#include "clang/Parse/Scope.h"
Douglas Gregor314b97f2009-11-10 19:49:08 +000029#include "clang/Parse/Template.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000030using namespace clang;
31
David Chisnall0f436562009-08-17 16:35:33 +000032
Douglas Gregor48f3bb92009-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 Lattner52338262009-10-25 22:31:57 +000042/// If IgnoreDeprecated is set to true, this should not want about deprecated
43/// decls.
44///
Douglas Gregor48f3bb92009-02-18 21:56:37 +000045/// \returns true if there was an error (this declaration cannot be
46/// referenced), false otherwise.
Chris Lattner52338262009-10-25 22:31:57 +000047///
John McCall54abf7d2009-11-04 02:18:39 +000048bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc) {
Chris Lattner76a642f2009-02-15 22:43:40 +000049 // See if the decl is deprecated.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +000050 if (D->getAttr<DeprecatedAttr>()) {
John McCall54abf7d2009-11-04 02:18:39 +000051 EmitDeprecationWarning(D, Loc);
Chris Lattner76a642f2009-02-15 22:43:40 +000052 }
53
Chris Lattnerffb93682009-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 Gregor48f3bb92009-02-18 21:56:37 +000060 // See if this is a deleted function.
Douglas Gregor25d944a2009-02-24 04:26:15 +000061 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor48f3bb92009-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 Gregor25d944a2009-02-24 04:26:15 +000067 }
Douglas Gregor48f3bb92009-02-18 21:56:37 +000068
Douglas Gregor48f3bb92009-02-18 21:56:37 +000069 return false;
Chris Lattner76a642f2009-02-15 22:43:40 +000070}
71
Fariborz Jahanian5b530052009-05-13 18:09:35 +000072/// DiagnoseSentinelCalls - This routine checks on method dispatch calls
Mike Stump1eb44332009-09-09 15:08:12 +000073/// (and other functions in future), which have been declared with sentinel
Fariborz Jahanian5b530052009-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 Stump1eb44332009-09-09 15:08:12 +000077 Expr **Args, unsigned NumArgs) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +000078 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Mike Stump1eb44332009-09-09 15:08:12 +000079 if (!attr)
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +000080 return;
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +000081 int sentinelPos = attr->getSentinel();
82 int nullPos = attr->getNullPos();
Mike Stump1eb44332009-09-09 15:08:12 +000083
Mike Stump390b4cc2009-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 Jahanian88f1ba02009-05-13 23:20:50 +000086 unsigned int i = 0;
Fariborz Jahanian236673e2009-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 Stumpac5fc7c2009-08-04 21:02:39 +0000100 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Fariborz Jahanian236673e2009-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 Stumpac5fc7c2009-08-04 21:02:39 +0000110 } else if (VarDecl *V = dyn_cast<VarDecl>(D)) {
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000111 // block or function pointer call.
112 QualType Ty = V->getType();
113 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000114 const FunctionType *FT = Ty->isFunctionPointerType()
John McCall183700f2009-09-21 23:43:11 +0000115 ? Ty->getAs<PointerType>()->getPointeeType()->getAs<FunctionType>()
116 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
Fariborz Jahaniandaf04152009-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 Stumpac5fc7c2009-08-04 21:02:39 +0000130 } else
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000131 return;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000132 } else
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000133 return;
134
135 if (warnNotEnoughArgs) {
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000136 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000137 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian88f1ba02009-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 Jahanian236673e2009-05-14 18:00:00 +0000147 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000148 return;
149 }
150 while (i < NumArgs-1) {
151 ++i;
152 ++sentinel;
153 }
154 Expr *sentinelExpr = Args[sentinel];
155 if (sentinelExpr && (!sentinelExpr->getType()->isPointerType() ||
Douglas Gregorce940492009-09-25 04:25:58 +0000156 !sentinelExpr->isNullPointerConstant(Context,
157 Expr::NPC_ValueDependentIsNull))) {
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000158 Diag(Loc, diag::warn_missing_sentinel) << isMethod;
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000159 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000160 }
161 return;
Fariborz Jahanian5b530052009-05-13 18:09:35 +0000162}
163
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000164SourceRange Sema::getExprRange(ExprTy *E) const {
165 Expr *Ex = (Expr *)E;
166 return Ex? Ex->getSourceRange() : SourceRange();
167}
168
Chris Lattnere7a2e912008-07-25 21:10:04 +0000169//===----------------------------------------------------------------------===//
170// Standard Promotions and Conversions
171//===----------------------------------------------------------------------===//
172
Chris Lattnere7a2e912008-07-25 21:10:04 +0000173/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
174void Sema::DefaultFunctionArrayConversion(Expr *&E) {
175 QualType Ty = E->getType();
176 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
177
Chris Lattnere7a2e912008-07-25 21:10:04 +0000178 if (Ty->isFunctionType())
Mike Stump1eb44332009-09-09 15:08:12 +0000179 ImpCastExprToType(E, Context.getPointerType(Ty),
Anders Carlssonb633c4e2009-09-01 20:37:18 +0000180 CastExpr::CK_FunctionToPointerDecay);
Chris Lattner67d33d82008-07-25 21:33:13 +0000181 else if (Ty->isArrayType()) {
182 // In C90 mode, arrays only promote to pointers if the array expression is
183 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
184 // type 'array of type' is converted to an expression that has type 'pointer
185 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
186 // that has type 'array of type' ...". The relevant change is "an lvalue"
187 // (C90) to "an expression" (C99).
Argyrios Kyrtzidisc39a3d72008-09-11 04:25:59 +0000188 //
189 // C++ 4.2p1:
190 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
191 // T" can be converted to an rvalue of type "pointer to T".
192 //
193 if (getLangOptions().C99 || getLangOptions().CPlusPlus ||
194 E->isLvalue(Context) == Expr::LV_Valid)
Anders Carlsson112a0a82009-08-07 23:48:20 +0000195 ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
196 CastExpr::CK_ArrayToPointerDecay);
Chris Lattner67d33d82008-07-25 21:33:13 +0000197 }
Chris Lattnere7a2e912008-07-25 21:10:04 +0000198}
199
200/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump1eb44332009-09-09 15:08:12 +0000201/// operators (C99 6.3). The conversions of array and function types are
Chris Lattnere7a2e912008-07-25 21:10:04 +0000202/// sometimes surpressed. For example, the array->pointer conversion doesn't
203/// apply if the array is an argument to the sizeof or address (&) operators.
204/// In these instances, this routine should *not* be called.
205Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
206 QualType Ty = Expr->getType();
207 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
Mike Stump1eb44332009-09-09 15:08:12 +0000208
Douglas Gregorfc24e442009-05-01 20:41:21 +0000209 // C99 6.3.1.1p2:
210 //
211 // The following may be used in an expression wherever an int or
212 // unsigned int may be used:
213 // - an object or expression with an integer type whose integer
214 // conversion rank is less than or equal to the rank of int
215 // and unsigned int.
216 // - A bit-field of type _Bool, int, signed int, or unsigned int.
217 //
218 // If an int can represent all values of the original type, the
219 // value is converted to an int; otherwise, it is converted to an
220 // unsigned int. These are called the integer promotions. All
221 // other types are unchanged by the integer promotions.
Eli Friedman04e83572009-08-20 04:21:42 +0000222 QualType PTy = Context.isPromotableBitField(Expr);
223 if (!PTy.isNull()) {
Eli Friedman73c39ab2009-10-20 08:27:19 +0000224 ImpCastExprToType(Expr, PTy, CastExpr::CK_IntegralCast);
Eli Friedman04e83572009-08-20 04:21:42 +0000225 return Expr;
226 }
Douglas Gregorfc24e442009-05-01 20:41:21 +0000227 if (Ty->isPromotableIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +0000228 QualType PT = Context.getPromotedIntegerType(Ty);
Eli Friedman73c39ab2009-10-20 08:27:19 +0000229 ImpCastExprToType(Expr, PT, CastExpr::CK_IntegralCast);
Douglas Gregorfc24e442009-05-01 20:41:21 +0000230 return Expr;
Eli Friedman04e83572009-08-20 04:21:42 +0000231 }
232
Douglas Gregorfc24e442009-05-01 20:41:21 +0000233 DefaultFunctionArrayConversion(Expr);
Chris Lattnere7a2e912008-07-25 21:10:04 +0000234 return Expr;
235}
236
Chris Lattner05faf172008-07-25 22:25:12 +0000237/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Mike Stump1eb44332009-09-09 15:08:12 +0000238/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner05faf172008-07-25 22:25:12 +0000239/// double. All other argument types are converted by UsualUnaryConversions().
240void Sema::DefaultArgumentPromotion(Expr *&Expr) {
241 QualType Ty = Expr->getType();
242 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump1eb44332009-09-09 15:08:12 +0000243
Chris Lattner05faf172008-07-25 22:25:12 +0000244 // If this is a 'float' (CVR qualified or typedef) promote to double.
John McCall183700f2009-09-21 23:43:11 +0000245 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
Chris Lattner05faf172008-07-25 22:25:12 +0000246 if (BT->getKind() == BuiltinType::Float)
Eli Friedman73c39ab2009-10-20 08:27:19 +0000247 return ImpCastExprToType(Expr, Context.DoubleTy,
248 CastExpr::CK_FloatingCast);
Mike Stump1eb44332009-09-09 15:08:12 +0000249
Chris Lattner05faf172008-07-25 22:25:12 +0000250 UsualUnaryConversions(Expr);
251}
252
Chris Lattner312531a2009-04-12 08:11:20 +0000253/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
254/// will warn if the resulting type is not a POD type, and rejects ObjC
255/// interfaces passed by value. This returns true if the argument type is
256/// completely illegal.
257bool Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT) {
Anders Carlssondce5e2c2009-01-16 16:48:51 +0000258 DefaultArgumentPromotion(Expr);
Mike Stump1eb44332009-09-09 15:08:12 +0000259
Chris Lattner312531a2009-04-12 08:11:20 +0000260 if (Expr->getType()->isObjCInterfaceType()) {
261 Diag(Expr->getLocStart(),
262 diag::err_cannot_pass_objc_interface_to_vararg)
263 << Expr->getType() << CT;
264 return true;
Anders Carlssondce5e2c2009-01-16 16:48:51 +0000265 }
Mike Stump1eb44332009-09-09 15:08:12 +0000266
Chris Lattner312531a2009-04-12 08:11:20 +0000267 if (!Expr->getType()->isPODType())
268 Diag(Expr->getLocStart(), diag::warn_cannot_pass_non_pod_arg_to_vararg)
269 << Expr->getType() << CT;
270
271 return false;
Anders Carlssondce5e2c2009-01-16 16:48:51 +0000272}
273
274
Chris Lattnere7a2e912008-07-25 21:10:04 +0000275/// UsualArithmeticConversions - Performs various conversions that are common to
276/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump1eb44332009-09-09 15:08:12 +0000277/// routine returns the first non-arithmetic type found. The client is
Chris Lattnere7a2e912008-07-25 21:10:04 +0000278/// responsible for emitting appropriate error diagnostics.
279/// FIXME: verify the conversion rules for "complex int" are consistent with
280/// GCC.
281QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
282 bool isCompAssign) {
Eli Friedmanab3a8522009-03-28 01:22:36 +0000283 if (!isCompAssign)
Chris Lattnere7a2e912008-07-25 21:10:04 +0000284 UsualUnaryConversions(lhsExpr);
Eli Friedmanab3a8522009-03-28 01:22:36 +0000285
286 UsualUnaryConversions(rhsExpr);
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000287
Mike Stump1eb44332009-09-09 15:08:12 +0000288 // For conversion purposes, we ignore any qualifiers.
Chris Lattnere7a2e912008-07-25 21:10:04 +0000289 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +0000290 QualType lhs =
291 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +0000292 QualType rhs =
Chris Lattnerb77792e2008-07-26 22:17:49 +0000293 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000294
295 // If both types are identical, no conversion is needed.
296 if (lhs == rhs)
297 return lhs;
298
299 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
300 // The caller can deal with this (e.g. pointer + int).
301 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
302 return lhs;
303
Douglas Gregor2d833e32009-05-02 00:36:19 +0000304 // Perform bitfield promotions.
Eli Friedman04e83572009-08-20 04:21:42 +0000305 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr);
Douglas Gregor2d833e32009-05-02 00:36:19 +0000306 if (!LHSBitfieldPromoteTy.isNull())
307 lhs = LHSBitfieldPromoteTy;
Eli Friedman04e83572009-08-20 04:21:42 +0000308 QualType RHSBitfieldPromoteTy = Context.isPromotableBitField(rhsExpr);
Douglas Gregor2d833e32009-05-02 00:36:19 +0000309 if (!RHSBitfieldPromoteTy.isNull())
310 rhs = RHSBitfieldPromoteTy;
311
Eli Friedmana95d7572009-08-19 07:44:53 +0000312 QualType destType = Context.UsualArithmeticConversionsType(lhs, rhs);
Eli Friedmanab3a8522009-03-28 01:22:36 +0000313 if (!isCompAssign)
Eli Friedman73c39ab2009-10-20 08:27:19 +0000314 ImpCastExprToType(lhsExpr, destType, CastExpr::CK_Unknown);
315 ImpCastExprToType(rhsExpr, destType, CastExpr::CK_Unknown);
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000316 return destType;
317}
318
Chris Lattnere7a2e912008-07-25 21:10:04 +0000319//===----------------------------------------------------------------------===//
320// Semantic Analysis for various Expression Types
321//===----------------------------------------------------------------------===//
322
323
Steve Narofff69936d2007-09-16 03:34:24 +0000324/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Reid Spencer5f016e22007-07-11 17:01:13 +0000325/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
326/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
327/// multiple tokens. However, the common case is that StringToks points to one
328/// string.
Sebastian Redlcd965b92009-01-18 18:53:16 +0000329///
330Action::OwningExprResult
Steve Narofff69936d2007-09-16 03:34:24 +0000331Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000332 assert(NumStringToks && "Must have at least one string!");
333
Chris Lattnerbbee00b2009-01-16 18:51:42 +0000334 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Reid Spencer5f016e22007-07-11 17:01:13 +0000335 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +0000336 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +0000337
338 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
339 for (unsigned i = 0; i != NumStringToks; ++i)
340 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000341
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000342 QualType StrTy = Context.CharTy;
Argyrios Kyrtzidis55f4b022008-08-09 17:20:01 +0000343 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000344 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregor77a52232008-09-12 00:47:35 +0000345
346 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
347 if (getLangOptions().CPlusPlus)
348 StrTy.addConst();
Sebastian Redlcd965b92009-01-18 18:53:16 +0000349
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000350 // Get an array type for the string, according to C99 6.4.5. This includes
351 // the nul terminator character as well as the string length for pascal
352 // strings.
353 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerdbb1ecc2009-02-26 23:01:51 +0000354 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000355 ArrayType::Normal, 0);
Mike Stump1eb44332009-09-09 15:08:12 +0000356
Reid Spencer5f016e22007-07-11 17:01:13 +0000357 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Mike Stump1eb44332009-09-09 15:08:12 +0000358 return Owned(StringLiteral::Create(Context, Literal.GetString(),
Chris Lattner2085fd62009-02-18 06:40:38 +0000359 Literal.GetStringLength(),
360 Literal.AnyWide, StrTy,
361 &StringTokLocs[0],
362 StringTokLocs.size()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000363}
364
Chris Lattner639e2d32008-10-20 05:16:36 +0000365/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
366/// CurBlock to VD should cause it to be snapshotted (as we do for auto
367/// variables defined outside the block) or false if this is not needed (e.g.
368/// for values inside the block or for globals).
369///
Chris Lattner17f3a6d2009-04-21 22:26:47 +0000370/// This also keeps the 'hasBlockDeclRefExprs' in the BlockSemaInfo records
371/// up-to-date.
372///
Chris Lattner639e2d32008-10-20 05:16:36 +0000373static bool ShouldSnapshotBlockValueReference(BlockSemaInfo *CurBlock,
374 ValueDecl *VD) {
375 // If the value is defined inside the block, we couldn't snapshot it even if
376 // we wanted to.
377 if (CurBlock->TheDecl == VD->getDeclContext())
378 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000379
Chris Lattner639e2d32008-10-20 05:16:36 +0000380 // If this is an enum constant or function, it is constant, don't snapshot.
381 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
382 return false;
383
384 // If this is a reference to an extern, static, or global variable, no need to
385 // snapshot it.
386 // FIXME: What about 'const' variables in C++?
387 if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
Chris Lattner17f3a6d2009-04-21 22:26:47 +0000388 if (!Var->hasLocalStorage())
389 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000390
Chris Lattner17f3a6d2009-04-21 22:26:47 +0000391 // Blocks that have these can't be constant.
392 CurBlock->hasBlockDeclRefExprs = true;
393
394 // If we have nested blocks, the decl may be declared in an outer block (in
395 // which case that outer block doesn't get "hasBlockDeclRefExprs") or it may
396 // be defined outside all of the current blocks (in which case the blocks do
397 // all get the bit). Walk the nesting chain.
398 for (BlockSemaInfo *NextBlock = CurBlock->PrevBlockInfo; NextBlock;
399 NextBlock = NextBlock->PrevBlockInfo) {
400 // If we found the defining block for the variable, don't mark the block as
401 // having a reference outside it.
402 if (NextBlock->TheDecl == VD->getDeclContext())
403 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000404
Chris Lattner17f3a6d2009-04-21 22:26:47 +0000405 // Otherwise, the DeclRef from the inner block causes the outer one to need
406 // a snapshot as well.
407 NextBlock->hasBlockDeclRefExprs = true;
408 }
Mike Stump1eb44332009-09-09 15:08:12 +0000409
Chris Lattner639e2d32008-10-20 05:16:36 +0000410 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000411}
412
Chris Lattner639e2d32008-10-20 05:16:36 +0000413
414
Douglas Gregora2813ce2009-10-23 18:54:35 +0000415/// BuildDeclRefExpr - Build a DeclRefExpr.
Anders Carlssone41590d2009-06-24 00:10:43 +0000416Sema::OwningExprResult
Sebastian Redlebc07d52009-02-03 20:19:35 +0000417Sema::BuildDeclRefExpr(NamedDecl *D, QualType Ty, SourceLocation Loc,
418 bool TypeDependent, bool ValueDependent,
419 const CXXScopeSpec *SS) {
Anders Carlssone2bb2242009-06-26 19:16:07 +0000420 if (Context.getCanonicalType(Ty) == Context.UndeducedAutoTy) {
421 Diag(Loc,
Mike Stump1eb44332009-09-09 15:08:12 +0000422 diag::err_auto_variable_cannot_appear_in_own_initializer)
Anders Carlssone2bb2242009-06-26 19:16:07 +0000423 << D->getDeclName();
424 return ExprError();
425 }
Mike Stump1eb44332009-09-09 15:08:12 +0000426
Anders Carlssone41590d2009-06-24 00:10:43 +0000427 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
428 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
429 if (const FunctionDecl *FD = MD->getParent()->isLocalClass()) {
430 if (VD->hasLocalStorage() && VD->getDeclContext() != CurContext) {
Mike Stump1eb44332009-09-09 15:08:12 +0000431 Diag(Loc, diag::err_reference_to_local_var_in_enclosing_function)
Anders Carlssone41590d2009-06-24 00:10:43 +0000432 << D->getIdentifier() << FD->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +0000433 Diag(D->getLocation(), diag::note_local_variable_declared_here)
Anders Carlssone41590d2009-06-24 00:10:43 +0000434 << D->getIdentifier();
435 return ExprError();
436 }
437 }
438 }
439 }
Mike Stump1eb44332009-09-09 15:08:12 +0000440
Douglas Gregore0762c92009-06-19 23:52:42 +0000441 MarkDeclarationReferenced(Loc, D);
Mike Stump1eb44332009-09-09 15:08:12 +0000442
Douglas Gregora2813ce2009-10-23 18:54:35 +0000443 return Owned(DeclRefExpr::Create(Context,
444 SS? (NestedNameSpecifier *)SS->getScopeRep() : 0,
445 SS? SS->getRange() : SourceRange(),
446 D, Loc,
447 Ty, TypeDependent, ValueDependent));
Douglas Gregor1a49af92009-01-06 05:10:23 +0000448}
449
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000450/// getObjectForAnonymousRecordDecl - Retrieve the (unnamed) field or
451/// variable corresponding to the anonymous union or struct whose type
452/// is Record.
Douglas Gregor6ab35242009-04-09 21:40:53 +0000453static Decl *getObjectForAnonymousRecordDecl(ASTContext &Context,
454 RecordDecl *Record) {
Mike Stump1eb44332009-09-09 15:08:12 +0000455 assert(Record->isAnonymousStructOrUnion() &&
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000456 "Record must be an anonymous struct or union!");
Mike Stump1eb44332009-09-09 15:08:12 +0000457
Mike Stump390b4cc2009-05-16 07:39:55 +0000458 // FIXME: Once Decls are directly linked together, this will be an O(1)
459 // operation rather than a slow walk through DeclContext's vector (which
460 // itself will be eliminated). DeclGroups might make this even better.
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000461 DeclContext *Ctx = Record->getDeclContext();
Mike Stump1eb44332009-09-09 15:08:12 +0000462 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000463 DEnd = Ctx->decls_end();
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000464 D != DEnd; ++D) {
465 if (*D == Record) {
466 // The object for the anonymous struct/union directly
467 // follows its type in the list of declarations.
468 ++D;
469 assert(D != DEnd && "Missing object for anonymous record");
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000470 assert(!cast<NamedDecl>(*D)->getDeclName() && "Decl should be unnamed");
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000471 return *D;
472 }
473 }
474
475 assert(false && "Missing object for anonymous record");
476 return 0;
477}
478
Douglas Gregorffb4b6e2009-04-15 06:41:24 +0000479/// \brief Given a field that represents a member of an anonymous
480/// struct/union, build the path from that field's context to the
481/// actual member.
482///
483/// Construct the sequence of field member references we'll have to
484/// perform to get to the field in the anonymous union/struct. The
485/// list of members is built from the field outward, so traverse it
486/// backwards to go from an object in the current context to the field
487/// we found.
488///
489/// \returns The variable from which the field access should begin,
490/// for an anonymous struct/union that is not a member of another
491/// class. Otherwise, returns NULL.
492VarDecl *Sema::BuildAnonymousStructUnionMemberPath(FieldDecl *Field,
493 llvm::SmallVectorImpl<FieldDecl *> &Path) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000494 assert(Field->getDeclContext()->isRecord() &&
495 cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion()
496 && "Field must be stored inside an anonymous struct or union");
497
Douglas Gregorffb4b6e2009-04-15 06:41:24 +0000498 Path.push_back(Field);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000499 VarDecl *BaseObject = 0;
500 DeclContext *Ctx = Field->getDeclContext();
501 do {
502 RecordDecl *Record = cast<RecordDecl>(Ctx);
Douglas Gregor6ab35242009-04-09 21:40:53 +0000503 Decl *AnonObject = getObjectForAnonymousRecordDecl(Context, Record);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000504 if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject))
Douglas Gregorffb4b6e2009-04-15 06:41:24 +0000505 Path.push_back(AnonField);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000506 else {
507 BaseObject = cast<VarDecl>(AnonObject);
508 break;
509 }
510 Ctx = Ctx->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +0000511 } while (Ctx->isRecord() &&
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000512 cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion());
Douglas Gregorffb4b6e2009-04-15 06:41:24 +0000513
514 return BaseObject;
515}
516
517Sema::OwningExprResult
518Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
519 FieldDecl *Field,
520 Expr *BaseObjectExpr,
521 SourceLocation OpLoc) {
522 llvm::SmallVector<FieldDecl *, 4> AnonFields;
Mike Stump1eb44332009-09-09 15:08:12 +0000523 VarDecl *BaseObject = BuildAnonymousStructUnionMemberPath(Field,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +0000524 AnonFields);
525
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000526 // Build the expression that refers to the base object, from
527 // which we will build a sequence of member references to each
528 // of the anonymous union objects and, eventually, the field we
529 // found via name lookup.
530 bool BaseObjectIsPointer = false;
John McCall0953e762009-09-24 19:53:00 +0000531 Qualifiers BaseQuals;
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000532 if (BaseObject) {
533 // BaseObject is an anonymous struct/union variable (and is,
534 // therefore, not part of another non-anonymous record).
Ted Kremenek8189cde2009-02-07 01:47:29 +0000535 if (BaseObjectExpr) BaseObjectExpr->Destroy(Context);
Douglas Gregore0762c92009-06-19 23:52:42 +0000536 MarkDeclarationReferenced(Loc, BaseObject);
Steve Naroff6ece14c2009-01-21 00:14:39 +0000537 BaseObjectExpr = new (Context) DeclRefExpr(BaseObject,BaseObject->getType(),
Mike Stumpeed9cac2009-02-19 03:04:26 +0000538 SourceLocation());
John McCall0953e762009-09-24 19:53:00 +0000539 BaseQuals
540 = Context.getCanonicalType(BaseObject->getType()).getQualifiers();
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000541 } else if (BaseObjectExpr) {
542 // The caller provided the base object expression. Determine
543 // whether its a pointer and whether it adds any qualifiers to the
544 // anonymous struct/union fields we're looking into.
545 QualType ObjectType = BaseObjectExpr->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000546 if (const PointerType *ObjectPtr = ObjectType->getAs<PointerType>()) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000547 BaseObjectIsPointer = true;
548 ObjectType = ObjectPtr->getPointeeType();
549 }
John McCall0953e762009-09-24 19:53:00 +0000550 BaseQuals
551 = Context.getCanonicalType(ObjectType).getQualifiers();
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000552 } else {
553 // We've found a member of an anonymous struct/union that is
554 // inside a non-anonymous struct/union, so in a well-formed
555 // program our base object expression is "this".
556 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
557 if (!MD->isStatic()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000558 QualType AnonFieldType
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000559 = Context.getTagDeclType(
560 cast<RecordDecl>(AnonFields.back()->getDeclContext()));
561 QualType ThisType = Context.getTagDeclType(MD->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +0000562 if ((Context.getCanonicalType(AnonFieldType)
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000563 == Context.getCanonicalType(ThisType)) ||
564 IsDerivedFrom(ThisType, AnonFieldType)) {
565 // Our base object expression is "this".
Steve Naroff6ece14c2009-01-21 00:14:39 +0000566 BaseObjectExpr = new (Context) CXXThisExpr(SourceLocation(),
Mike Stumpeed9cac2009-02-19 03:04:26 +0000567 MD->getThisType(Context));
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000568 BaseObjectIsPointer = true;
569 }
570 } else {
Sebastian Redlcd965b92009-01-18 18:53:16 +0000571 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
572 << Field->getDeclName());
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000573 }
John McCall0953e762009-09-24 19:53:00 +0000574 BaseQuals = Qualifiers::fromCVRMask(MD->getTypeQualifiers());
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000575 }
576
Mike Stump1eb44332009-09-09 15:08:12 +0000577 if (!BaseObjectExpr)
Sebastian Redlcd965b92009-01-18 18:53:16 +0000578 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
579 << Field->getDeclName());
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000580 }
581
582 // Build the implicit member references to the field of the
583 // anonymous struct/union.
584 Expr *Result = BaseObjectExpr;
John McCall0953e762009-09-24 19:53:00 +0000585 Qualifiers ResultQuals = BaseQuals;
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000586 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
587 FI = AnonFields.rbegin(), FIEnd = AnonFields.rend();
588 FI != FIEnd; ++FI) {
589 QualType MemberType = (*FI)->getType();
John McCall0953e762009-09-24 19:53:00 +0000590 Qualifiers MemberTypeQuals =
591 Context.getCanonicalType(MemberType).getQualifiers();
592
593 // CVR attributes from the base are picked up by members,
594 // except that 'mutable' members don't pick up 'const'.
595 if ((*FI)->isMutable())
596 ResultQuals.removeConst();
597
598 // GC attributes are never picked up by members.
599 ResultQuals.removeObjCGCAttr();
600
601 // TR 18037 does not allow fields to be declared with address spaces.
602 assert(!MemberTypeQuals.hasAddressSpace());
603
604 Qualifiers NewQuals = ResultQuals + MemberTypeQuals;
605 if (NewQuals != MemberTypeQuals)
606 MemberType = Context.getQualifiedType(MemberType, NewQuals);
607
Douglas Gregore0762c92009-06-19 23:52:42 +0000608 MarkDeclarationReferenced(Loc, *FI);
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +0000609 // FIXME: Might this end up being a qualified name?
Steve Naroff6ece14c2009-01-21 00:14:39 +0000610 Result = new (Context) MemberExpr(Result, BaseObjectIsPointer, *FI,
611 OpLoc, MemberType);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000612 BaseObjectIsPointer = false;
John McCall0953e762009-09-24 19:53:00 +0000613 ResultQuals = NewQuals;
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000614 }
615
Sebastian Redlcd965b92009-01-18 18:53:16 +0000616 return Owned(Result);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000617}
618
Douglas Gregor02a24ee2009-11-03 16:56:39 +0000619Sema::OwningExprResult Sema::ActOnIdExpression(Scope *S,
620 const CXXScopeSpec &SS,
621 UnqualifiedId &Name,
622 bool HasTrailingLParen,
623 bool IsAddressOfOperand) {
624 if (Name.getKind() == UnqualifiedId::IK_TemplateId) {
625 ASTTemplateArgsPtr TemplateArgsPtr(*this,
626 Name.TemplateId->getTemplateArgs(),
Douglas Gregor02a24ee2009-11-03 16:56:39 +0000627 Name.TemplateId->NumArgs);
628 return ActOnTemplateIdExpr(SS,
629 TemplateTy::make(Name.TemplateId->Template),
630 Name.TemplateId->TemplateNameLoc,
631 Name.TemplateId->LAngleLoc,
632 TemplateArgsPtr,
Douglas Gregor02a24ee2009-11-03 16:56:39 +0000633 Name.TemplateId->RAngleLoc);
634 }
635
636 // FIXME: We lose a bunch of source information by doing this. Later,
637 // we'll want to merge ActOnDeclarationNameExpr's logic into
638 // ActOnIdExpression.
639 return ActOnDeclarationNameExpr(S,
640 Name.StartLocation,
641 GetNameFromUnqualifiedId(Name),
642 HasTrailingLParen,
643 &SS,
644 IsAddressOfOperand);
645}
646
Douglas Gregor10c42622008-11-18 15:03:34 +0000647/// ActOnDeclarationNameExpr - The parser has read some kind of name
648/// (e.g., a C++ id-expression (C++ [expr.prim]p1)). This routine
649/// performs lookup on that name and returns an expression that refers
650/// to that name. This routine isn't directly called from the parser,
651/// because the parser doesn't know about DeclarationName. Rather,
Douglas Gregor02a24ee2009-11-03 16:56:39 +0000652/// this routine is called by ActOnIdExpression, which contains a
653/// parsed UnqualifiedId.
Douglas Gregor10c42622008-11-18 15:03:34 +0000654///
655/// HasTrailingLParen indicates whether this identifier is used in a
656/// function call context. LookupCtx is only used for a C++
657/// qualified-id (foo::bar) to indicate the class or namespace that
658/// the identifier must be a member of.
Douglas Gregor5c37de72008-12-06 00:22:45 +0000659///
Sebastian Redlebc07d52009-02-03 20:19:35 +0000660/// isAddressOfOperand means that this expression is the direct operand
661/// of an address-of operator. This matters because this is the only
662/// situation where a qualified name referencing a non-static member may
663/// appear outside a member function of this class.
Sebastian Redlcd965b92009-01-18 18:53:16 +0000664Sema::OwningExprResult
665Sema::ActOnDeclarationNameExpr(Scope *S, SourceLocation Loc,
666 DeclarationName Name, bool HasTrailingLParen,
Mike Stump1eb44332009-09-09 15:08:12 +0000667 const CXXScopeSpec *SS,
Sebastian Redlebc07d52009-02-03 20:19:35 +0000668 bool isAddressOfOperand) {
Chris Lattner8a934232008-03-31 00:36:02 +0000669 // Could be enum-constant, value decl, instance variable, etc.
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000670 if (SS && SS->isInvalid())
671 return ExprError();
Douglas Gregor5953d8b2009-03-19 17:26:29 +0000672
673 // C++ [temp.dep.expr]p3:
674 // An id-expression is type-dependent if it contains:
675 // -- a nested-name-specifier that contains a class-name that
676 // names a dependent type.
Douglas Gregor00c44862009-05-29 14:49:33 +0000677 // FIXME: Member of the current instantiation.
Douglas Gregor5953d8b2009-03-19 17:26:29 +0000678 if (SS && isDependentScopeSpecifier(*SS)) {
Douglas Gregorab452ba2009-03-26 23:50:42 +0000679 return Owned(new (Context) UnresolvedDeclRefExpr(Name, Context.DependentTy,
Mike Stump1eb44332009-09-09 15:08:12 +0000680 Loc, SS->getRange(),
Anders Carlsson9b31df42009-07-09 00:05:08 +0000681 static_cast<NestedNameSpecifier *>(SS->getScopeRep()),
682 isAddressOfOperand));
Douglas Gregor5953d8b2009-03-19 17:26:29 +0000683 }
684
John McCalla24dc2e2009-11-17 02:14:36 +0000685 LookupResult Lookup(*this, Name, Loc, LookupOrdinaryName);
686 LookupParsedName(Lookup, S, SS, true);
Douglas Gregor7176fff2009-01-15 00:26:24 +0000687
John McCalla24dc2e2009-11-17 02:14:36 +0000688 if (Lookup.isAmbiguous())
Sebastian Redlcd965b92009-01-18 18:53:16 +0000689 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000690
John McCallf36e02d2009-10-09 21:13:30 +0000691 NamedDecl *D = Lookup.getAsSingleDecl(Context);
Douglas Gregor5c37de72008-12-06 00:22:45 +0000692
Chris Lattner8a934232008-03-31 00:36:02 +0000693 // If this reference is in an Objective-C method, then ivar lookup happens as
694 // well.
Douglas Gregor10c42622008-11-18 15:03:34 +0000695 IdentifierInfo *II = Name.getAsIdentifierInfo();
696 if (II && getCurMethodDecl()) {
Chris Lattner8a934232008-03-31 00:36:02 +0000697 // There are two cases to handle here. 1) scoped lookup could have failed,
698 // in which case we should look for an ivar. 2) scoped lookup could have
Mike Stump1eb44332009-09-09 15:08:12 +0000699 // found a decl, but that decl is outside the current instance method (i.e.
700 // a global variable). In these two cases, we do a lookup for an ivar with
Fariborz Jahanian077c1e72009-03-02 21:55:29 +0000701 // this name, if the lookup sucedes, we replace it our current decl.
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000702 if (D == 0 || D->isDefinedOutsideFunctionOrMethod()) {
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000703 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Fariborz Jahanian935fd762009-03-03 01:21:12 +0000704 ObjCInterfaceDecl *ClassDeclared;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000705 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
Chris Lattner553905d2009-02-16 17:19:12 +0000706 // Check if referencing a field with __attribute__((deprecated)).
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000707 if (DiagnoseUseOfDecl(IV, Loc))
708 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000709
Chris Lattner5cb10d32009-04-24 22:30:50 +0000710 // If we're referencing an invalid decl, just return this as a silent
711 // error node. The error diagnostic was already emitted on the decl.
712 if (IV->isInvalidDecl())
713 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000714
Fariborz Jahanian077c1e72009-03-02 21:55:29 +0000715 bool IsClsMethod = getCurMethodDecl()->isClassMethod();
716 // If a class method attemps to use a free standing ivar, this is
717 // an error.
718 if (IsClsMethod && D && !D->isDefinedOutsideFunctionOrMethod())
719 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
720 << IV->getDeclName());
721 // If a class method uses a global variable, even if an ivar with
722 // same name exists, use the global.
723 if (!IsClsMethod) {
Fariborz Jahanian935fd762009-03-03 01:21:12 +0000724 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
725 ClassDeclared != IFace)
726 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
Mike Stump390b4cc2009-05-16 07:39:55 +0000727 // FIXME: This should use a new expr for a direct reference, don't
728 // turn this into Self->ivar, just return a BareIVarExpr or something.
Fariborz Jahanian077c1e72009-03-02 21:55:29 +0000729 IdentifierInfo &II = Context.Idents.get("self");
Douglas Gregor02a24ee2009-11-03 16:56:39 +0000730 UnqualifiedId SelfName;
731 SelfName.setIdentifier(&II, SourceLocation());
732 CXXScopeSpec SelfScopeSpec;
733 OwningExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
734 SelfName, false, false);
Douglas Gregore0762c92009-06-19 23:52:42 +0000735 MarkDeclarationReferenced(Loc, IV);
Mike Stump1eb44332009-09-09 15:08:12 +0000736 return Owned(new (Context)
737 ObjCIvarRefExpr(IV, IV->getType(), Loc,
Anders Carlssone9146f22009-05-01 19:49:17 +0000738 SelfExpr.takeAs<Expr>(), true, true));
Fariborz Jahanian077c1e72009-03-02 21:55:29 +0000739 }
Chris Lattner8a934232008-03-31 00:36:02 +0000740 }
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000741 } else if (getCurMethodDecl()->isInstanceMethod()) {
Fariborz Jahanian077c1e72009-03-02 21:55:29 +0000742 // We should warn if a local variable hides an ivar.
743 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Fariborz Jahanian935fd762009-03-03 01:21:12 +0000744 ObjCInterfaceDecl *ClassDeclared;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000745 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
Fariborz Jahanian935fd762009-03-03 01:21:12 +0000746 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
747 IFace == ClassDeclared)
Chris Lattner5cb10d32009-04-24 22:30:50 +0000748 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
Fariborz Jahanian935fd762009-03-03 01:21:12 +0000749 }
Fariborz Jahanian077c1e72009-03-02 21:55:29 +0000750 }
Steve Naroff76de9d72008-08-10 19:10:41 +0000751 // Needed to implement property "super.method" notation.
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000752 if (D == 0 && II->isStr("super")) {
Steve Naroffdd53eb52009-03-05 20:12:00 +0000753 QualType T;
Mike Stump1eb44332009-09-09 15:08:12 +0000754
Steve Naroffdd53eb52009-03-05 20:12:00 +0000755 if (getCurMethodDecl()->isInstanceMethod())
Steve Naroff14108da2009-07-10 23:34:53 +0000756 T = Context.getObjCObjectPointerType(Context.getObjCInterfaceType(
757 getCurMethodDecl()->getClassInterface()));
Steve Naroffdd53eb52009-03-05 20:12:00 +0000758 else
759 T = Context.getObjCClassType();
Steve Naroff6ece14c2009-01-21 00:14:39 +0000760 return Owned(new (Context) ObjCSuperExpr(Loc, T));
Steve Naroffe3e9add2008-06-02 23:03:37 +0000761 }
Chris Lattner8a934232008-03-31 00:36:02 +0000762 }
Douglas Gregorc71e28c2009-02-16 19:28:42 +0000763
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000764 // Determine whether this name might be a candidate for
765 // argument-dependent lookup.
Mike Stump1eb44332009-09-09 15:08:12 +0000766 bool ADL = getLangOptions().CPlusPlus && (!SS || !SS->isSet()) &&
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000767 HasTrailingLParen;
768
769 if (ADL && D == 0) {
Douglas Gregorc71e28c2009-02-16 19:28:42 +0000770 // We've seen something of the form
771 //
772 // identifier(
773 //
774 // and we did not find any entity by the name
775 // "identifier". However, this identifier is still subject to
776 // argument-dependent lookup, so keep track of the name.
777 return Owned(new (Context) UnresolvedFunctionNameExpr(Name,
778 Context.OverloadTy,
779 Loc));
780 }
781
Reid Spencer5f016e22007-07-11 17:01:13 +0000782 if (D == 0) {
783 // Otherwise, this could be an implicitly declared function reference (legal
784 // in C90, extension in C99).
Douglas Gregor10c42622008-11-18 15:03:34 +0000785 if (HasTrailingLParen && II &&
Chris Lattner8a934232008-03-31 00:36:02 +0000786 !getLangOptions().CPlusPlus) // Not in C++.
Douglas Gregor10c42622008-11-18 15:03:34 +0000787 D = ImplicitlyDefineFunction(Loc, *II, S);
Reid Spencer5f016e22007-07-11 17:01:13 +0000788 else {
789 // If this name wasn't predeclared and if this is not a function call,
790 // diagnose the problem.
Douglas Gregor3f093272009-10-13 21:16:44 +0000791 if (SS && !SS->isEmpty())
792 return ExprError(Diag(Loc, diag::err_no_member)
793 << Name << computeDeclContext(*SS, false)
794 << SS->getRange());
795 else if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
Douglas Gregor10c42622008-11-18 15:03:34 +0000796 Name.getNameKind() == DeclarationName::CXXConversionFunctionName)
Sebastian Redlcd965b92009-01-18 18:53:16 +0000797 return ExprError(Diag(Loc, diag::err_undeclared_use)
798 << Name.getAsString());
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000799 else
Sebastian Redlcd965b92009-01-18 18:53:16 +0000800 return ExprError(Diag(Loc, diag::err_undeclared_var_use) << Name);
Reid Spencer5f016e22007-07-11 17:01:13 +0000801 }
802 }
Mike Stump1eb44332009-09-09 15:08:12 +0000803
Douglas Gregor751f9a42009-06-30 15:47:41 +0000804 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
805 // Warn about constructs like:
806 // if (void *X = foo()) { ... } else { X }.
807 // In the else block, the pointer is always false.
Mike Stump1eb44332009-09-09 15:08:12 +0000808
Douglas Gregor751f9a42009-06-30 15:47:41 +0000809 // FIXME: In a template instantiation, we don't have scope
810 // information to check this property.
811 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
812 Scope *CheckS = S;
Douglas Gregor9c4b8382009-11-05 17:49:26 +0000813 while (CheckS && CheckS->getControlParent()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000814 if (CheckS->isWithinElse() &&
Douglas Gregor751f9a42009-06-30 15:47:41 +0000815 CheckS->getControlParent()->isDeclScope(DeclPtrTy::make(Var))) {
Douglas Gregor9c4b8382009-11-05 17:49:26 +0000816 ExprError(Diag(Loc, diag::warn_value_always_zero)
817 << Var->getDeclName()
818 << (Var->getType()->isPointerType()? 2 :
819 Var->getType()->isBooleanType()? 1 : 0));
Douglas Gregor751f9a42009-06-30 15:47:41 +0000820 break;
821 }
Mike Stump1eb44332009-09-09 15:08:12 +0000822
Douglas Gregor9c4b8382009-11-05 17:49:26 +0000823 // Move to the parent of this scope.
824 CheckS = CheckS->getParent();
Douglas Gregor751f9a42009-06-30 15:47:41 +0000825 }
826 }
827 } else if (FunctionDecl *Func = dyn_cast<FunctionDecl>(D)) {
828 if (!getLangOptions().CPlusPlus && !Func->hasPrototype()) {
829 // C99 DR 316 says that, if a function type comes from a
830 // function definition (without a prototype), that type is only
831 // used for checking compatibility. Therefore, when referencing
832 // the function, we pretend that we don't have the full function
833 // type.
834 if (DiagnoseUseOfDecl(Func, Loc))
835 return ExprError();
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000836
Douglas Gregor751f9a42009-06-30 15:47:41 +0000837 QualType T = Func->getType();
838 QualType NoProtoType = T;
John McCall183700f2009-09-21 23:43:11 +0000839 if (const FunctionProtoType *Proto = T->getAs<FunctionProtoType>())
Douglas Gregor751f9a42009-06-30 15:47:41 +0000840 NoProtoType = Context.getFunctionNoProtoType(Proto->getResultType());
841 return BuildDeclRefExpr(Func, NoProtoType, Loc, false, false, SS);
842 }
843 }
Mike Stump1eb44332009-09-09 15:08:12 +0000844
Douglas Gregor751f9a42009-06-30 15:47:41 +0000845 return BuildDeclarationNameExpr(Loc, D, HasTrailingLParen, SS, isAddressOfOperand);
846}
Fariborz Jahanian98a541e2009-07-29 18:40:24 +0000847/// \brief Cast member's object to its own class if necessary.
Fariborz Jahanianf3e53d32009-07-29 19:40:11 +0000848bool
Fariborz Jahanian98a541e2009-07-29 18:40:24 +0000849Sema::PerformObjectMemberConversion(Expr *&From, NamedDecl *Member) {
850 if (FieldDecl *FD = dyn_cast<FieldDecl>(Member))
Mike Stump1eb44332009-09-09 15:08:12 +0000851 if (CXXRecordDecl *RD =
Fariborz Jahanian98a541e2009-07-29 18:40:24 +0000852 dyn_cast<CXXRecordDecl>(FD->getDeclContext())) {
Mike Stump1eb44332009-09-09 15:08:12 +0000853 QualType DestType =
Fariborz Jahanian98a541e2009-07-29 18:40:24 +0000854 Context.getCanonicalType(Context.getTypeDeclType(RD));
Fariborz Jahanian96e2fa92009-07-29 20:41:46 +0000855 if (DestType->isDependentType() || From->getType()->isDependentType())
856 return false;
857 QualType FromRecordType = From->getType();
858 QualType DestRecordType = DestType;
Ted Kremenek6217b802009-07-29 21:53:49 +0000859 if (FromRecordType->getAs<PointerType>()) {
Fariborz Jahanian96e2fa92009-07-29 20:41:46 +0000860 DestType = Context.getPointerType(DestType);
861 FromRecordType = FromRecordType->getPointeeType();
Fariborz Jahanian98a541e2009-07-29 18:40:24 +0000862 }
Fariborz Jahanian96e2fa92009-07-29 20:41:46 +0000863 if (!Context.hasSameUnqualifiedType(FromRecordType, DestRecordType) &&
864 CheckDerivedToBaseConversion(FromRecordType,
865 DestRecordType,
866 From->getSourceRange().getBegin(),
867 From->getSourceRange()))
868 return true;
Anders Carlsson3503d042009-07-31 01:23:52 +0000869 ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
870 /*isLvalue=*/true);
Fariborz Jahanian98a541e2009-07-29 18:40:24 +0000871 }
Fariborz Jahanianf3e53d32009-07-29 19:40:11 +0000872 return false;
Fariborz Jahanian98a541e2009-07-29 18:40:24 +0000873}
Douglas Gregor751f9a42009-06-30 15:47:41 +0000874
Douglas Gregor83f6faf2009-08-31 23:41:50 +0000875/// \brief Build a MemberExpr AST node.
Mike Stump1eb44332009-09-09 15:08:12 +0000876static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow,
877 const CXXScopeSpec *SS, NamedDecl *Member,
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +0000878 SourceLocation Loc, QualType Ty) {
879 if (SS && SS->isSet())
Mike Stump1eb44332009-09-09 15:08:12 +0000880 return MemberExpr::Create(C, Base, isArrow,
Douglas Gregor83f6faf2009-08-31 23:41:50 +0000881 (NestedNameSpecifier *)SS->getScopeRep(),
Mike Stump1eb44332009-09-09 15:08:12 +0000882 SS->getRange(), Member, Loc,
Douglas Gregorc4bf26f2009-09-01 00:37:14 +0000883 // FIXME: Explicit template argument lists
884 false, SourceLocation(), 0, 0, SourceLocation(),
885 Ty);
Mike Stump1eb44332009-09-09 15:08:12 +0000886
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +0000887 return new (C) MemberExpr(Base, isArrow, Member, Loc, Ty);
888}
889
Douglas Gregor751f9a42009-06-30 15:47:41 +0000890/// \brief Complete semantic analysis for a reference to the given declaration.
891Sema::OwningExprResult
892Sema::BuildDeclarationNameExpr(SourceLocation Loc, NamedDecl *D,
893 bool HasTrailingLParen,
Mike Stump1eb44332009-09-09 15:08:12 +0000894 const CXXScopeSpec *SS,
Douglas Gregor751f9a42009-06-30 15:47:41 +0000895 bool isAddressOfOperand) {
896 assert(D && "Cannot refer to a NULL declaration");
897 DeclarationName Name = D->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +0000898
Sebastian Redlebc07d52009-02-03 20:19:35 +0000899 // If this is an expression of the form &Class::member, don't build an
900 // implicit member ref, because we want a pointer to the member in general,
901 // not any specific instance's member.
902 if (isAddressOfOperand && SS && !SS->isEmpty() && !HasTrailingLParen) {
Douglas Gregore4e5b052009-03-19 00:18:19 +0000903 DeclContext *DC = computeDeclContext(*SS);
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000904 if (D && isa<CXXRecordDecl>(DC)) {
Sebastian Redlebc07d52009-02-03 20:19:35 +0000905 QualType DType;
906 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
907 DType = FD->getType().getNonReferenceType();
908 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
909 DType = Method->getType();
910 } else if (isa<OverloadedFunctionDecl>(D)) {
911 DType = Context.OverloadTy;
912 }
913 // Could be an inner type. That's diagnosed below, so ignore it here.
914 if (!DType.isNull()) {
915 // The pointer is type- and value-dependent if it points into something
916 // dependent.
Douglas Gregor00c44862009-05-29 14:49:33 +0000917 bool Dependent = DC->isDependentContext();
Anders Carlssone41590d2009-06-24 00:10:43 +0000918 return BuildDeclRefExpr(D, DType, Loc, Dependent, Dependent, SS);
Sebastian Redlebc07d52009-02-03 20:19:35 +0000919 }
920 }
921 }
922
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000923 // We may have found a field within an anonymous union or struct
924 // (C++ [class.union]).
Douglas Gregore961afb2009-10-22 07:08:30 +0000925 // FIXME: This needs to happen post-isImplicitMemberReference?
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000926 if (FieldDecl *FD = dyn_cast<FieldDecl>(D))
927 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
928 return BuildAnonymousStructUnionMemberReference(Loc, FD);
Sebastian Redlcd965b92009-01-18 18:53:16 +0000929
Douglas Gregore961afb2009-10-22 07:08:30 +0000930 // Cope with an implicit member access in a C++ non-static member function.
931 QualType ThisType, MemberType;
932 if (isImplicitMemberReference(SS, D, Loc, ThisType, MemberType)) {
933 Expr *This = new (Context) CXXThisExpr(SourceLocation(), ThisType);
934 MarkDeclarationReferenced(Loc, D);
935 if (PerformObjectMemberConversion(This, D))
936 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +0000937
Douglas Gregore961afb2009-10-22 07:08:30 +0000938 bool ShouldCheckUse = true;
939 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
940 // Don't diagnose the use of a virtual member function unless it's
941 // explicitly qualified.
942 if (MD->isVirtual() && (!SS || !SS->isSet()))
943 ShouldCheckUse = false;
Douglas Gregor88a35142008-12-22 05:46:06 +0000944 }
Douglas Gregore961afb2009-10-22 07:08:30 +0000945
946 if (ShouldCheckUse && DiagnoseUseOfDecl(D, Loc))
947 return ExprError();
948 return Owned(BuildMemberExpr(Context, This, true, SS, D,
949 Loc, MemberType));
Douglas Gregor88a35142008-12-22 05:46:06 +0000950 }
951
Douglas Gregor44b43212008-12-11 16:49:14 +0000952 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000953 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
954 if (MD->isStatic())
955 // "invalid use of member 'x' in static member function"
Sebastian Redlcd965b92009-01-18 18:53:16 +0000956 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
957 << FD->getDeclName());
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000958 }
959
Douglas Gregor88a35142008-12-22 05:46:06 +0000960 // Any other ways we could have found the field in a well-formed
961 // program would have been turned into implicit member expressions
962 // above.
Sebastian Redlcd965b92009-01-18 18:53:16 +0000963 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
964 << FD->getDeclName());
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000965 }
Douglas Gregor88a35142008-12-22 05:46:06 +0000966
Reid Spencer5f016e22007-07-11 17:01:13 +0000967 if (isa<TypedefDecl>(D))
Sebastian Redlcd965b92009-01-18 18:53:16 +0000968 return ExprError(Diag(Loc, diag::err_unexpected_typedef) << Name);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000969 if (isa<ObjCInterfaceDecl>(D))
Sebastian Redlcd965b92009-01-18 18:53:16 +0000970 return ExprError(Diag(Loc, diag::err_unexpected_interface) << Name);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +0000971 if (isa<NamespaceDecl>(D))
Sebastian Redlcd965b92009-01-18 18:53:16 +0000972 return ExprError(Diag(Loc, diag::err_unexpected_namespace) << Name);
Reid Spencer5f016e22007-07-11 17:01:13 +0000973
Steve Naroffdd972f22008-09-05 22:11:13 +0000974 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000975 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
Anders Carlssone41590d2009-06-24 00:10:43 +0000976 return BuildDeclRefExpr(Ovl, Context.OverloadTy, Loc,
977 false, false, SS);
Douglas Gregorc15cb382009-02-09 23:23:08 +0000978 else if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
Anders Carlssone41590d2009-06-24 00:10:43 +0000979 return BuildDeclRefExpr(Template, Context.OverloadTy, Loc,
980 false, false, SS);
John McCall7ba107a2009-11-18 02:36:19 +0000981 else if (UnresolvedUsingValueDecl *UD = dyn_cast<UnresolvedUsingValueDecl>(D))
Mike Stump1eb44332009-09-09 15:08:12 +0000982 return BuildDeclRefExpr(UD, Context.DependentTy, Loc,
983 /*TypeDependent=*/true,
Anders Carlsson598da5b2009-08-29 01:06:32 +0000984 /*ValueDependent=*/true, SS);
985
Steve Naroffdd972f22008-09-05 22:11:13 +0000986 ValueDecl *VD = cast<ValueDecl>(D);
Sebastian Redlcd965b92009-01-18 18:53:16 +0000987
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000988 // Check whether this declaration can be used. Note that we suppress
989 // this check when we're going to perform argument-dependent lookup
990 // on this function name, because this might not be the function
991 // that overload resolution actually selects.
Mike Stump1eb44332009-09-09 15:08:12 +0000992 bool ADL = getLangOptions().CPlusPlus && (!SS || !SS->isSet()) &&
Douglas Gregor751f9a42009-06-30 15:47:41 +0000993 HasTrailingLParen;
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000994 if (!(ADL && isa<FunctionDecl>(VD)) && DiagnoseUseOfDecl(VD, Loc))
995 return ExprError();
996
Steve Naroffdd972f22008-09-05 22:11:13 +0000997 // Only create DeclRefExpr's for valid Decl's.
998 if (VD->isInvalidDecl())
Sebastian Redlcd965b92009-01-18 18:53:16 +0000999 return ExprError();
1000
Chris Lattner639e2d32008-10-20 05:16:36 +00001001 // If the identifier reference is inside a block, and it refers to a value
1002 // that is outside the block, create a BlockDeclRefExpr instead of a
1003 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
1004 // the block is formed.
Steve Naroffdd972f22008-09-05 22:11:13 +00001005 //
Chris Lattner639e2d32008-10-20 05:16:36 +00001006 // We do not do this for things like enum constants, global variables, etc,
1007 // as they do not get snapshotted.
1008 //
1009 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Douglas Gregore0762c92009-06-19 23:52:42 +00001010 MarkDeclarationReferenced(Loc, VD);
Eli Friedman5fdeae12009-03-22 23:00:19 +00001011 QualType ExprTy = VD->getType().getNonReferenceType();
Steve Naroff090276f2008-10-10 01:28:17 +00001012 // The BlocksAttr indicates the variable is bound by-reference.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001013 if (VD->getAttr<BlocksAttr>())
Eli Friedman5fdeae12009-03-22 23:00:19 +00001014 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, true));
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00001015 // This is to record that a 'const' was actually synthesize and added.
1016 bool constAdded = !ExprTy.isConstQualified();
Steve Naroff090276f2008-10-10 01:28:17 +00001017 // Variable will be bound by-copy, make it const within the closure.
Mike Stump1eb44332009-09-09 15:08:12 +00001018
Eli Friedman5fdeae12009-03-22 23:00:19 +00001019 ExprTy.addConst();
Mike Stump1eb44332009-09-09 15:08:12 +00001020 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, false,
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00001021 constAdded));
Steve Naroff090276f2008-10-10 01:28:17 +00001022 }
1023 // If this reference is not in a block or if the referenced variable is
1024 // within the block, create a normal DeclRefExpr.
Douglas Gregor898574e2008-12-05 23:32:09 +00001025
Douglas Gregor898574e2008-12-05 23:32:09 +00001026 bool TypeDependent = false;
Douglas Gregor83f96f62008-12-10 20:57:37 +00001027 bool ValueDependent = false;
1028 if (getLangOptions().CPlusPlus) {
1029 // C++ [temp.dep.expr]p3:
Mike Stump1eb44332009-09-09 15:08:12 +00001030 // An id-expression is type-dependent if it contains:
Douglas Gregor83f96f62008-12-10 20:57:37 +00001031 // - an identifier that was declared with a dependent type,
1032 if (VD->getType()->isDependentType())
1033 TypeDependent = true;
1034 // - FIXME: a template-id that is dependent,
1035 // - a conversion-function-id that specifies a dependent type,
1036 else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1037 Name.getCXXNameType()->isDependentType())
1038 TypeDependent = true;
1039 // - a nested-name-specifier that contains a class-name that
1040 // names a dependent type.
1041 else if (SS && !SS->isEmpty()) {
Douglas Gregore4e5b052009-03-19 00:18:19 +00001042 for (DeclContext *DC = computeDeclContext(*SS);
Douglas Gregor83f96f62008-12-10 20:57:37 +00001043 DC; DC = DC->getParent()) {
1044 // FIXME: could stop early at namespace scope.
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001045 if (DC->isRecord()) {
Douglas Gregor83f96f62008-12-10 20:57:37 +00001046 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
1047 if (Context.getTypeDeclType(Record)->isDependentType()) {
1048 TypeDependent = true;
1049 break;
1050 }
Douglas Gregor898574e2008-12-05 23:32:09 +00001051 }
1052 }
1053 }
Douglas Gregor898574e2008-12-05 23:32:09 +00001054
Douglas Gregor83f96f62008-12-10 20:57:37 +00001055 // C++ [temp.dep.constexpr]p2:
1056 //
1057 // An identifier is value-dependent if it is:
1058 // - a name declared with a dependent type,
1059 if (TypeDependent)
1060 ValueDependent = true;
1061 // - the name of a non-type template parameter,
1062 else if (isa<NonTypeTemplateParmDecl>(VD))
1063 ValueDependent = true;
1064 // - a constant with integral or enumeration type and is
1065 // initialized with an expression that is value-dependent
Eli Friedmanc1494122009-06-11 01:11:20 +00001066 else if (const VarDecl *Dcl = dyn_cast<VarDecl>(VD)) {
Mike Stumpfbf68702009-11-03 22:20:01 +00001067 if (Context.getCanonicalType(Dcl->getType()).getCVRQualifiers()
1068 == Qualifiers::Const &&
Eli Friedmanc1494122009-06-11 01:11:20 +00001069 Dcl->getInit()) {
1070 ValueDependent = Dcl->getInit()->isValueDependent();
1071 }
1072 }
Douglas Gregor83f96f62008-12-10 20:57:37 +00001073 }
Douglas Gregor898574e2008-12-05 23:32:09 +00001074
Anders Carlssone41590d2009-06-24 00:10:43 +00001075 return BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc,
1076 TypeDependent, ValueDependent, SS);
Reid Spencer5f016e22007-07-11 17:01:13 +00001077}
1078
Sebastian Redlcd965b92009-01-18 18:53:16 +00001079Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
1080 tok::TokenKind Kind) {
Chris Lattnerd9f69102008-08-10 01:53:14 +00001081 PredefinedExpr::IdentType IT;
Sebastian Redlcd965b92009-01-18 18:53:16 +00001082
Reid Spencer5f016e22007-07-11 17:01:13 +00001083 switch (Kind) {
Chris Lattner1423ea42008-01-12 18:39:25 +00001084 default: assert(0 && "Unknown simple primary expr!");
Chris Lattnerd9f69102008-08-10 01:53:14 +00001085 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
1086 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
1087 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00001088 }
Chris Lattner1423ea42008-01-12 18:39:25 +00001089
Chris Lattnerfa28b302008-01-12 08:14:25 +00001090 // Pre-defined identifiers are of type char[x], where x is the length of the
1091 // string.
Mike Stump1eb44332009-09-09 15:08:12 +00001092
Anders Carlsson3a082d82009-09-08 18:24:21 +00001093 Decl *currentDecl = getCurFunctionOrMethodDecl();
1094 if (!currentDecl) {
Chris Lattnerb0da9232008-12-12 05:05:20 +00001095 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson3a082d82009-09-08 18:24:21 +00001096 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerb0da9232008-12-12 05:05:20 +00001097 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001098
Anders Carlsson773f3972009-09-11 01:22:35 +00001099 QualType ResTy;
1100 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
1101 ResTy = Context.DependentTy;
1102 } else {
1103 unsigned Length =
1104 PredefinedExpr::ComputeName(Context, IT, currentDecl).length();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001105
Anders Carlsson773f3972009-09-11 01:22:35 +00001106 llvm::APInt LengthI(32, Length + 1);
John McCall0953e762009-09-24 19:53:00 +00001107 ResTy = Context.CharTy.withConst();
Anders Carlsson773f3972009-09-11 01:22:35 +00001108 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
1109 }
Steve Naroff6ece14c2009-01-21 00:14:39 +00001110 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Reid Spencer5f016e22007-07-11 17:01:13 +00001111}
1112
Sebastian Redlcd965b92009-01-18 18:53:16 +00001113Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001114 llvm::SmallString<16> CharBuffer;
1115 CharBuffer.resize(Tok.getLength());
1116 const char *ThisTokBegin = &CharBuffer[0];
1117 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd965b92009-01-18 18:53:16 +00001118
Reid Spencer5f016e22007-07-11 17:01:13 +00001119 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1120 Tok.getLocation(), PP);
1121 if (Literal.hadError())
Sebastian Redlcd965b92009-01-18 18:53:16 +00001122 return ExprError();
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00001123
1124 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
1125
Sebastian Redle91b3bc2009-01-20 22:23:13 +00001126 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
1127 Literal.isWide(),
1128 type, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00001129}
1130
Sebastian Redlcd965b92009-01-18 18:53:16 +00001131Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
1132 // Fast path for a single digit (which is quite common). A single digit
Reid Spencer5f016e22007-07-11 17:01:13 +00001133 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
1134 if (Tok.getLength() == 1) {
Chris Lattner7216dc92009-01-26 22:36:52 +00001135 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattner0c21e842009-01-16 07:10:29 +00001136 unsigned IntSize = Context.Target.getIntWidth();
Steve Naroff6ece14c2009-01-21 00:14:39 +00001137 return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
Steve Naroff0a473932009-01-20 19:53:53 +00001138 Context.IntTy, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00001139 }
Ted Kremenek28396602009-01-13 23:19:12 +00001140
Reid Spencer5f016e22007-07-11 17:01:13 +00001141 llvm::SmallString<512> IntegerBuffer;
Chris Lattner2a299042008-09-30 20:53:45 +00001142 // Add padding so that NumericLiteralParser can overread by one character.
1143 IntegerBuffer.resize(Tok.getLength()+1);
Reid Spencer5f016e22007-07-11 17:01:13 +00001144 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd965b92009-01-18 18:53:16 +00001145
Reid Spencer5f016e22007-07-11 17:01:13 +00001146 // Get the spelling of the token, which eliminates trigraphs, etc.
1147 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd965b92009-01-18 18:53:16 +00001148
Mike Stump1eb44332009-09-09 15:08:12 +00001149 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Reid Spencer5f016e22007-07-11 17:01:13 +00001150 Tok.getLocation(), PP);
1151 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +00001152 return ExprError();
1153
Chris Lattner5d661452007-08-26 03:42:43 +00001154 Expr *Res;
Sebastian Redlcd965b92009-01-18 18:53:16 +00001155
Chris Lattner5d661452007-08-26 03:42:43 +00001156 if (Literal.isFloatingLiteral()) {
Chris Lattner525a0502007-09-22 18:29:59 +00001157 QualType Ty;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001158 if (Literal.isFloat)
Chris Lattner525a0502007-09-22 18:29:59 +00001159 Ty = Context.FloatTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001160 else if (!Literal.isLong)
Chris Lattner525a0502007-09-22 18:29:59 +00001161 Ty = Context.DoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001162 else
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001163 Ty = Context.LongDoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001164
1165 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
1166
Ted Kremenek720c4ec2007-11-29 00:56:49 +00001167 // isExact will be set by GetFloatValue().
1168 bool isExact = false;
Chris Lattner001d64d2009-06-29 17:34:55 +00001169 llvm::APFloat Val = Literal.GetFloatValue(Format, &isExact);
1170 Res = new (Context) FloatingLiteral(Val, isExact, Ty, Tok.getLocation());
Sebastian Redlcd965b92009-01-18 18:53:16 +00001171
Chris Lattner5d661452007-08-26 03:42:43 +00001172 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00001173 return ExprError();
Chris Lattner5d661452007-08-26 03:42:43 +00001174 } else {
Chris Lattnerf0467b32008-04-02 04:24:33 +00001175 QualType Ty;
Reid Spencer5f016e22007-07-11 17:01:13 +00001176
Neil Boothb9449512007-08-29 22:00:19 +00001177 // long long is a C99 feature.
1178 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth79859c32007-08-29 22:13:52 +00001179 Literal.isLongLong)
Neil Boothb9449512007-08-29 22:00:19 +00001180 Diag(Tok.getLocation(), diag::ext_longlong);
1181
Reid Spencer5f016e22007-07-11 17:01:13 +00001182 // Get the value in the widest-possible width.
Chris Lattner98be4942008-03-05 18:54:05 +00001183 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlcd965b92009-01-18 18:53:16 +00001184
Reid Spencer5f016e22007-07-11 17:01:13 +00001185 if (Literal.GetIntegerValue(ResultVal)) {
1186 // If this value didn't fit into uintmax_t, warn and force to ull.
1187 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattnerf0467b32008-04-02 04:24:33 +00001188 Ty = Context.UnsignedLongLongTy;
1189 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner98be4942008-03-05 18:54:05 +00001190 "long long is not intmax_t?");
Reid Spencer5f016e22007-07-11 17:01:13 +00001191 } else {
1192 // If this value fits into a ULL, try to figure out what else it fits into
1193 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd965b92009-01-18 18:53:16 +00001194
Reid Spencer5f016e22007-07-11 17:01:13 +00001195 // Octal, Hexadecimal, and integers with a U suffix are allowed to
1196 // be an unsigned int.
1197 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
1198
1199 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001200 unsigned Width = 0;
Chris Lattner97c51562007-08-23 21:58:08 +00001201 if (!Literal.isLong && !Literal.isLongLong) {
1202 // Are int/unsigned possibilities?
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001203 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001204
Reid Spencer5f016e22007-07-11 17:01:13 +00001205 // Does it fit in a unsigned int?
1206 if (ResultVal.isIntN(IntSize)) {
1207 // Does it fit in a signed int?
1208 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001209 Ty = Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001210 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001211 Ty = Context.UnsignedIntTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001212 Width = IntSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00001213 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001214 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001215
Reid Spencer5f016e22007-07-11 17:01:13 +00001216 // Are long/unsigned long possibilities?
Chris Lattnerf0467b32008-04-02 04:24:33 +00001217 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001218 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001219
Reid Spencer5f016e22007-07-11 17:01:13 +00001220 // Does it fit in a unsigned long?
1221 if (ResultVal.isIntN(LongSize)) {
1222 // Does it fit in a signed long?
1223 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001224 Ty = Context.LongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001225 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001226 Ty = Context.UnsignedLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001227 Width = LongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00001228 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001229 }
1230
Reid Spencer5f016e22007-07-11 17:01:13 +00001231 // Finally, check long long if needed.
Chris Lattnerf0467b32008-04-02 04:24:33 +00001232 if (Ty.isNull()) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001233 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001234
Reid Spencer5f016e22007-07-11 17:01:13 +00001235 // Does it fit in a unsigned long long?
1236 if (ResultVal.isIntN(LongLongSize)) {
1237 // Does it fit in a signed long long?
1238 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001239 Ty = Context.LongLongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001240 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001241 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001242 Width = LongLongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00001243 }
1244 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001245
Reid Spencer5f016e22007-07-11 17:01:13 +00001246 // If we still couldn't decide a type, we probably have something that
1247 // does not fit in a signed long long, but has no U suffix.
Chris Lattnerf0467b32008-04-02 04:24:33 +00001248 if (Ty.isNull()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001249 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattnerf0467b32008-04-02 04:24:33 +00001250 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001251 Width = Context.Target.getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +00001252 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001253
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001254 if (ResultVal.getBitWidth() != Width)
1255 ResultVal.trunc(Width);
Reid Spencer5f016e22007-07-11 17:01:13 +00001256 }
Sebastian Redle91b3bc2009-01-20 22:23:13 +00001257 Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00001258 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001259
Chris Lattner5d661452007-08-26 03:42:43 +00001260 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
1261 if (Literal.isImaginary)
Mike Stump1eb44332009-09-09 15:08:12 +00001262 Res = new (Context) ImaginaryLiteral(Res,
Steve Naroff6ece14c2009-01-21 00:14:39 +00001263 Context.getComplexType(Res->getType()));
Sebastian Redlcd965b92009-01-18 18:53:16 +00001264
1265 return Owned(Res);
Reid Spencer5f016e22007-07-11 17:01:13 +00001266}
1267
Sebastian Redlcd965b92009-01-18 18:53:16 +00001268Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1269 SourceLocation R, ExprArg Val) {
Anders Carlssone9146f22009-05-01 19:49:17 +00001270 Expr *E = Val.takeAs<Expr>();
Chris Lattnerf0467b32008-04-02 04:24:33 +00001271 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff6ece14c2009-01-21 00:14:39 +00001272 return Owned(new (Context) ParenExpr(L, R, E));
Reid Spencer5f016e22007-07-11 17:01:13 +00001273}
1274
1275/// The UsualUnaryConversions() function is *not* called by this routine.
1276/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl28507842009-02-26 14:39:58 +00001277bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Sebastian Redl05189992008-11-11 17:56:53 +00001278 SourceLocation OpLoc,
1279 const SourceRange &ExprRange,
1280 bool isSizeof) {
Sebastian Redl28507842009-02-26 14:39:58 +00001281 if (exprType->isDependentType())
1282 return false;
1283
Reid Spencer5f016e22007-07-11 17:01:13 +00001284 // C99 6.5.3.4p1:
John McCall5ab75172009-11-04 07:28:41 +00001285 if (exprType->isFunctionType()) {
Chris Lattner1efaa952009-04-24 00:30:45 +00001286 // alignof(function) is allowed as an extension.
Chris Lattner01072922009-01-24 19:46:37 +00001287 if (isSizeof)
1288 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
1289 return false;
1290 }
Mike Stump1eb44332009-09-09 15:08:12 +00001291
Chris Lattner1efaa952009-04-24 00:30:45 +00001292 // Allow sizeof(void)/alignof(void) as an extension.
Chris Lattner01072922009-01-24 19:46:37 +00001293 if (exprType->isVoidType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001294 Diag(OpLoc, diag::ext_sizeof_void_type)
1295 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattner01072922009-01-24 19:46:37 +00001296 return false;
1297 }
Mike Stump1eb44332009-09-09 15:08:12 +00001298
Chris Lattner1efaa952009-04-24 00:30:45 +00001299 if (RequireCompleteType(OpLoc, exprType,
Mike Stump1eb44332009-09-09 15:08:12 +00001300 isSizeof ? diag::err_sizeof_incomplete_type :
Anders Carlssonb7906612009-08-26 23:45:07 +00001301 PDiag(diag::err_alignof_incomplete_type)
1302 << ExprRange))
Chris Lattner1efaa952009-04-24 00:30:45 +00001303 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001304
Chris Lattner1efaa952009-04-24 00:30:45 +00001305 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
Fariborz Jahanianced1e282009-04-24 17:34:33 +00001306 if (LangOpts.ObjCNonFragileABI && exprType->isObjCInterfaceType()) {
Chris Lattner1efaa952009-04-24 00:30:45 +00001307 Diag(OpLoc, diag::err_sizeof_nonfragile_interface)
Chris Lattner5cb10d32009-04-24 22:30:50 +00001308 << exprType << isSizeof << ExprRange;
1309 return true;
Chris Lattnerca790922009-04-21 19:55:16 +00001310 }
Mike Stump1eb44332009-09-09 15:08:12 +00001311
Chris Lattner1efaa952009-04-24 00:30:45 +00001312 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001313}
1314
Chris Lattner31e21e02009-01-24 20:17:12 +00001315bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
1316 const SourceRange &ExprRange) {
1317 E = E->IgnoreParens();
Sebastian Redl28507842009-02-26 14:39:58 +00001318
Mike Stump1eb44332009-09-09 15:08:12 +00001319 // alignof decl is always ok.
Chris Lattner31e21e02009-01-24 20:17:12 +00001320 if (isa<DeclRefExpr>(E))
1321 return false;
Sebastian Redl28507842009-02-26 14:39:58 +00001322
1323 // Cannot know anything else if the expression is dependent.
1324 if (E->isTypeDependent())
1325 return false;
1326
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001327 if (E->getBitField()) {
1328 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
1329 return true;
Chris Lattner31e21e02009-01-24 20:17:12 +00001330 }
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001331
1332 // Alignment of a field access is always okay, so long as it isn't a
1333 // bit-field.
1334 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump8e1fab22009-07-22 18:58:19 +00001335 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001336 return false;
1337
Chris Lattner31e21e02009-01-24 20:17:12 +00001338 return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
1339}
1340
Douglas Gregorba498172009-03-13 21:01:28 +00001341/// \brief Build a sizeof or alignof expression given a type operand.
Mike Stump1eb44332009-09-09 15:08:12 +00001342Action::OwningExprResult
John McCall5ab75172009-11-04 07:28:41 +00001343Sema::CreateSizeOfAlignOfExpr(DeclaratorInfo *DInfo,
1344 SourceLocation OpLoc,
Douglas Gregorba498172009-03-13 21:01:28 +00001345 bool isSizeOf, SourceRange R) {
John McCall5ab75172009-11-04 07:28:41 +00001346 if (!DInfo)
Douglas Gregorba498172009-03-13 21:01:28 +00001347 return ExprError();
1348
John McCall5ab75172009-11-04 07:28:41 +00001349 QualType T = DInfo->getType();
1350
Douglas Gregorba498172009-03-13 21:01:28 +00001351 if (!T->isDependentType() &&
1352 CheckSizeOfAlignOfOperand(T, OpLoc, R, isSizeOf))
1353 return ExprError();
1354
1355 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
John McCall5ab75172009-11-04 07:28:41 +00001356 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, DInfo,
Douglas Gregorba498172009-03-13 21:01:28 +00001357 Context.getSizeType(), OpLoc,
1358 R.getEnd()));
1359}
1360
1361/// \brief Build a sizeof or alignof expression given an expression
1362/// operand.
Mike Stump1eb44332009-09-09 15:08:12 +00001363Action::OwningExprResult
1364Sema::CreateSizeOfAlignOfExpr(Expr *E, SourceLocation OpLoc,
Douglas Gregorba498172009-03-13 21:01:28 +00001365 bool isSizeOf, SourceRange R) {
1366 // Verify that the operand is valid.
1367 bool isInvalid = false;
1368 if (E->isTypeDependent()) {
1369 // Delay type-checking for type-dependent expressions.
1370 } else if (!isSizeOf) {
1371 isInvalid = CheckAlignOfExpr(E, OpLoc, R);
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001372 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Douglas Gregorba498172009-03-13 21:01:28 +00001373 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
1374 isInvalid = true;
1375 } else {
1376 isInvalid = CheckSizeOfAlignOfOperand(E->getType(), OpLoc, R, true);
1377 }
1378
1379 if (isInvalid)
1380 return ExprError();
1381
1382 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1383 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, E,
1384 Context.getSizeType(), OpLoc,
1385 R.getEnd()));
1386}
1387
Sebastian Redl05189992008-11-11 17:56:53 +00001388/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1389/// the same for @c alignof and @c __alignof
1390/// Note that the ArgRange is invalid if isType is false.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001391Action::OwningExprResult
Sebastian Redl05189992008-11-11 17:56:53 +00001392Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1393 void *TyOrEx, const SourceRange &ArgRange) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001394 // If error parsing type, ignore.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001395 if (TyOrEx == 0) return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001396
Sebastian Redl05189992008-11-11 17:56:53 +00001397 if (isType) {
John McCall5ab75172009-11-04 07:28:41 +00001398 DeclaratorInfo *DInfo;
1399 (void) GetTypeFromParser(TyOrEx, &DInfo);
1400 return CreateSizeOfAlignOfExpr(DInfo, OpLoc, isSizeof, ArgRange);
Mike Stump1eb44332009-09-09 15:08:12 +00001401 }
Sebastian Redl05189992008-11-11 17:56:53 +00001402
Douglas Gregorba498172009-03-13 21:01:28 +00001403 Expr *ArgEx = (Expr *)TyOrEx;
1404 Action::OwningExprResult Result
1405 = CreateSizeOfAlignOfExpr(ArgEx, OpLoc, isSizeof, ArgEx->getSourceRange());
1406
1407 if (Result.isInvalid())
1408 DeleteExpr(ArgEx);
1409
1410 return move(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00001411}
1412
Chris Lattnerba27e2a2009-02-17 08:12:06 +00001413QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc, bool isReal) {
Sebastian Redl28507842009-02-26 14:39:58 +00001414 if (V->isTypeDependent())
1415 return Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00001416
Chris Lattnercc26ed72007-08-26 05:39:26 +00001417 // These operators return the element type of a complex type.
John McCall183700f2009-09-21 23:43:11 +00001418 if (const ComplexType *CT = V->getType()->getAs<ComplexType>())
Chris Lattnerdbb36972007-08-24 21:16:53 +00001419 return CT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00001420
Chris Lattnercc26ed72007-08-26 05:39:26 +00001421 // Otherwise they pass through real integer and floating point types here.
1422 if (V->getType()->isArithmeticType())
1423 return V->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001424
Chris Lattnercc26ed72007-08-26 05:39:26 +00001425 // Reject anything else.
Chris Lattnerba27e2a2009-02-17 08:12:06 +00001426 Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
1427 << (isReal ? "__real" : "__imag");
Chris Lattnercc26ed72007-08-26 05:39:26 +00001428 return QualType();
Chris Lattnerdbb36972007-08-24 21:16:53 +00001429}
1430
1431
Reid Spencer5f016e22007-07-11 17:01:13 +00001432
Sebastian Redl0eb23302009-01-19 00:08:26 +00001433Action::OwningExprResult
1434Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
1435 tok::TokenKind Kind, ExprArg Input) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001436 UnaryOperator::Opcode Opc;
1437 switch (Kind) {
1438 default: assert(0 && "Unknown unary op!");
1439 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
1440 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1441 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00001442
Eli Friedmane4216e92009-11-18 03:38:04 +00001443 return BuildUnaryOp(S, OpLoc, Opc, move(Input));
Reid Spencer5f016e22007-07-11 17:01:13 +00001444}
1445
Sebastian Redl0eb23302009-01-19 00:08:26 +00001446Action::OwningExprResult
1447Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
1448 ExprArg Idx, SourceLocation RLoc) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00001449 // Since this might be a postfix expression, get rid of ParenListExprs.
1450 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
1451
Sebastian Redl0eb23302009-01-19 00:08:26 +00001452 Expr *LHSExp = static_cast<Expr*>(Base.get()),
1453 *RHSExp = static_cast<Expr*>(Idx.get());
Mike Stump1eb44332009-09-09 15:08:12 +00001454
Douglas Gregor337c6b92008-11-19 17:17:41 +00001455 if (getLangOptions().CPlusPlus &&
Douglas Gregor3384c9c2009-05-19 00:01:19 +00001456 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
1457 Base.release();
1458 Idx.release();
1459 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
1460 Context.DependentTy, RLoc));
1461 }
1462
Mike Stump1eb44332009-09-09 15:08:12 +00001463 if (getLangOptions().CPlusPlus &&
Sebastian Redl0eb23302009-01-19 00:08:26 +00001464 (LHSExp->getType()->isRecordType() ||
Eli Friedman03f332a2008-12-15 22:34:21 +00001465 LHSExp->getType()->isEnumeralType() ||
1466 RHSExp->getType()->isRecordType() ||
1467 RHSExp->getType()->isEnumeralType())) {
Sebastian Redlf322ed62009-10-29 20:17:01 +00001468 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, move(Base),move(Idx));
Douglas Gregor337c6b92008-11-19 17:17:41 +00001469 }
1470
Sebastian Redlf322ed62009-10-29 20:17:01 +00001471 return CreateBuiltinArraySubscriptExpr(move(Base), LLoc, move(Idx), RLoc);
1472}
1473
1474
1475Action::OwningExprResult
1476Sema::CreateBuiltinArraySubscriptExpr(ExprArg Base, SourceLocation LLoc,
1477 ExprArg Idx, SourceLocation RLoc) {
1478 Expr *LHSExp = static_cast<Expr*>(Base.get());
1479 Expr *RHSExp = static_cast<Expr*>(Idx.get());
1480
Chris Lattner12d9ff62007-07-16 00:14:47 +00001481 // Perform default conversions.
1482 DefaultFunctionArrayConversion(LHSExp);
1483 DefaultFunctionArrayConversion(RHSExp);
Sebastian Redl0eb23302009-01-19 00:08:26 +00001484
Chris Lattner12d9ff62007-07-16 00:14:47 +00001485 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001486
Reid Spencer5f016e22007-07-11 17:01:13 +00001487 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner73d0d4f2007-08-30 17:45:32 +00001488 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stumpeed9cac2009-02-19 03:04:26 +00001489 // in the subscript position. As a result, we need to derive the array base
Reid Spencer5f016e22007-07-11 17:01:13 +00001490 // and index from the expression types.
Chris Lattner12d9ff62007-07-16 00:14:47 +00001491 Expr *BaseExpr, *IndexExpr;
1492 QualType ResultType;
Sebastian Redl28507842009-02-26 14:39:58 +00001493 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
1494 BaseExpr = LHSExp;
1495 IndexExpr = RHSExp;
1496 ResultType = Context.DependentTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00001497 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner12d9ff62007-07-16 00:14:47 +00001498 BaseExpr = LHSExp;
1499 IndexExpr = RHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00001500 ResultType = PTy->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001501 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattner7a2e0472007-07-16 00:23:25 +00001502 // Handle the uncommon case of "123[Ptr]".
Chris Lattner12d9ff62007-07-16 00:14:47 +00001503 BaseExpr = RHSExp;
1504 IndexExpr = LHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00001505 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00001506 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00001507 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00001508 BaseExpr = LHSExp;
1509 IndexExpr = RHSExp;
1510 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00001511 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00001512 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00001513 // Handle the uncommon case of "123[Ptr]".
1514 BaseExpr = RHSExp;
1515 IndexExpr = LHSExp;
1516 ResultType = PTy->getPointeeType();
John McCall183700f2009-09-21 23:43:11 +00001517 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattnerc8629632007-07-31 19:29:30 +00001518 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner12d9ff62007-07-16 00:14:47 +00001519 IndexExpr = RHSExp;
Nate Begeman334a8022009-01-18 00:45:31 +00001520
Chris Lattner12d9ff62007-07-16 00:14:47 +00001521 // FIXME: need to deal with const...
1522 ResultType = VTy->getElementType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00001523 } else if (LHSTy->isArrayType()) {
1524 // If we see an array that wasn't promoted by
1525 // DefaultFunctionArrayConversion, it must be an array that
1526 // wasn't promoted because of the C90 rule that doesn't
1527 // allow promoting non-lvalue arrays. Warn, then
1528 // force the promotion here.
1529 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
1530 LHSExp->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00001531 ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
1532 CastExpr::CK_ArrayToPointerDecay);
Eli Friedman7c32f8e2009-04-25 23:46:54 +00001533 LHSTy = LHSExp->getType();
1534
1535 BaseExpr = LHSExp;
1536 IndexExpr = RHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00001537 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00001538 } else if (RHSTy->isArrayType()) {
1539 // Same as previous, except for 123[f().a] case
1540 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
1541 RHSExp->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00001542 ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
1543 CastExpr::CK_ArrayToPointerDecay);
Eli Friedman7c32f8e2009-04-25 23:46:54 +00001544 RHSTy = RHSExp->getType();
1545
1546 BaseExpr = RHSExp;
1547 IndexExpr = LHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00001548 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001549 } else {
Chris Lattner338395d2009-04-25 22:50:55 +00001550 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
1551 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00001552 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001553 // C99 6.5.2.1p1
Nate Begeman2ef13e52009-08-10 23:49:36 +00001554 if (!(IndexExpr->getType()->isIntegerType() &&
1555 IndexExpr->getType()->isScalarType()) && !IndexExpr->isTypeDependent())
Chris Lattner338395d2009-04-25 22:50:55 +00001556 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
1557 << IndexExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00001558
Daniel Dunbar7e88a602009-09-17 06:31:17 +00001559 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinig0f9a5b52009-09-14 20:14:57 +00001560 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
1561 && !IndexExpr->isTypeDependent())
Sam Weinig76e2b712009-09-14 01:58:58 +00001562 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
1563
Douglas Gregore7450f52009-03-24 19:52:54 +00001564 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump1eb44332009-09-09 15:08:12 +00001565 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
1566 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregore7450f52009-03-24 19:52:54 +00001567 // incomplete types are not object types.
1568 if (ResultType->isFunctionType()) {
1569 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
1570 << ResultType << BaseExpr->getSourceRange();
1571 return ExprError();
1572 }
Mike Stump1eb44332009-09-09 15:08:12 +00001573
Douglas Gregore7450f52009-03-24 19:52:54 +00001574 if (!ResultType->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00001575 RequireCompleteType(LLoc, ResultType,
Anders Carlssonb7906612009-08-26 23:45:07 +00001576 PDiag(diag::err_subscript_incomplete_type)
1577 << BaseExpr->getSourceRange()))
Douglas Gregore7450f52009-03-24 19:52:54 +00001578 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001579
Chris Lattner1efaa952009-04-24 00:30:45 +00001580 // Diagnose bad cases where we step over interface counts.
1581 if (ResultType->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
1582 Diag(LLoc, diag::err_subscript_nonfragile_interface)
1583 << ResultType << BaseExpr->getSourceRange();
1584 return ExprError();
1585 }
Mike Stump1eb44332009-09-09 15:08:12 +00001586
Sebastian Redl0eb23302009-01-19 00:08:26 +00001587 Base.release();
1588 Idx.release();
Mike Stumpeed9cac2009-02-19 03:04:26 +00001589 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
Steve Naroff6ece14c2009-01-21 00:14:39 +00001590 ResultType, RLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00001591}
1592
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001593QualType Sema::
Nate Begeman213541a2008-04-18 23:10:10 +00001594CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00001595 const IdentifierInfo *CompName,
Anders Carlsson8f28f992009-08-26 18:25:21 +00001596 SourceLocation CompLoc) {
Daniel Dunbar2ad32892009-10-18 02:09:38 +00001597 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
1598 // see FIXME there.
1599 //
1600 // FIXME: This logic can be greatly simplified by splitting it along
1601 // halving/not halving and reworking the component checking.
John McCall183700f2009-09-21 23:43:11 +00001602 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
Nate Begeman8a997642008-05-09 06:41:27 +00001603
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001604 // The vector accessor can't exceed the number of elements.
Daniel Dunbare013d682009-10-18 20:26:12 +00001605 const char *compStr = CompName->getNameStart();
Nate Begeman353417a2009-01-18 01:47:54 +00001606
Mike Stumpeed9cac2009-02-19 03:04:26 +00001607 // This flag determines whether or not the component is one of the four
Nate Begeman353417a2009-01-18 01:47:54 +00001608 // special names that indicate a subset of exactly half the elements are
1609 // to be selected.
1610 bool HalvingSwizzle = false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00001611
Nate Begeman353417a2009-01-18 01:47:54 +00001612 // This flag determines whether or not CompName has an 's' char prefix,
1613 // indicating that it is a string of hex values to be used as vector indices.
Nate Begeman131f4652009-06-25 21:06:09 +00001614 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
Nate Begeman8a997642008-05-09 06:41:27 +00001615
1616 // Check that we've found one of the special components, or that the component
1617 // names must come from the same set.
Mike Stumpeed9cac2009-02-19 03:04:26 +00001618 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begeman353417a2009-01-18 01:47:54 +00001619 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
1620 HalvingSwizzle = true;
Nate Begeman8a997642008-05-09 06:41:27 +00001621 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner88dca042007-08-02 22:33:49 +00001622 do
1623 compStr++;
1624 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
Nate Begeman353417a2009-01-18 01:47:54 +00001625 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
Chris Lattner88dca042007-08-02 22:33:49 +00001626 do
1627 compStr++;
Nate Begeman353417a2009-01-18 01:47:54 +00001628 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
Chris Lattner88dca042007-08-02 22:33:49 +00001629 }
Nate Begeman353417a2009-01-18 01:47:54 +00001630
Mike Stumpeed9cac2009-02-19 03:04:26 +00001631 if (!HalvingSwizzle && *compStr) {
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001632 // We didn't get to the end of the string. This means the component names
1633 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001634 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
1635 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001636 return QualType();
1637 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00001638
Nate Begeman353417a2009-01-18 01:47:54 +00001639 // Ensure no component accessor exceeds the width of the vector type it
1640 // operates on.
1641 if (!HalvingSwizzle) {
Daniel Dunbare013d682009-10-18 20:26:12 +00001642 compStr = CompName->getNameStart();
Nate Begeman353417a2009-01-18 01:47:54 +00001643
1644 if (HexSwizzle)
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001645 compStr++;
Nate Begeman353417a2009-01-18 01:47:54 +00001646
1647 while (*compStr) {
1648 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
1649 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
1650 << baseType << SourceRange(CompLoc);
1651 return QualType();
1652 }
1653 }
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001654 }
Nate Begeman8a997642008-05-09 06:41:27 +00001655
Nate Begeman353417a2009-01-18 01:47:54 +00001656 // If this is a halving swizzle, verify that the base type has an even
1657 // number of elements.
1658 if (HalvingSwizzle && (vecType->getNumElements() & 1U)) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001659 Diag(OpLoc, diag::err_ext_vector_component_requires_even)
Chris Lattnerd1625842008-11-24 06:25:27 +00001660 << baseType << SourceRange(CompLoc);
Nate Begeman8a997642008-05-09 06:41:27 +00001661 return QualType();
1662 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00001663
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001664 // The component accessor looks fine - now we need to compute the actual type.
Mike Stumpeed9cac2009-02-19 03:04:26 +00001665 // The vector type is implied by the component accessor. For example,
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001666 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman353417a2009-01-18 01:47:54 +00001667 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begeman8a997642008-05-09 06:41:27 +00001668 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begeman353417a2009-01-18 01:47:54 +00001669 unsigned CompSize = HalvingSwizzle ? vecType->getNumElements() / 2
Anders Carlsson8f28f992009-08-26 18:25:21 +00001670 : CompName->getLength();
Nate Begeman353417a2009-01-18 01:47:54 +00001671 if (HexSwizzle)
1672 CompSize--;
1673
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001674 if (CompSize == 1)
1675 return vecType->getElementType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00001676
Nate Begeman213541a2008-04-18 23:10:10 +00001677 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stumpeed9cac2009-02-19 03:04:26 +00001678 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begeman213541a2008-04-18 23:10:10 +00001679 // diagostics look bad. We want extended vector types to appear built-in.
1680 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
1681 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
1682 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroffbea0b342007-07-29 16:33:31 +00001683 }
1684 return VT; // should never get here (a typedef type should always be found).
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001685}
1686
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00001687static Decl *FindGetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
Anders Carlsson8f28f992009-08-26 18:25:21 +00001688 IdentifierInfo *Member,
Douglas Gregor6ab35242009-04-09 21:40:53 +00001689 const Selector &Sel,
1690 ASTContext &Context) {
Mike Stump1eb44332009-09-09 15:08:12 +00001691
Anders Carlsson8f28f992009-08-26 18:25:21 +00001692 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00001693 return PD;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001694 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00001695 return OMD;
Mike Stump1eb44332009-09-09 15:08:12 +00001696
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00001697 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
1698 E = PDecl->protocol_end(); I != E; ++I) {
Mike Stump1eb44332009-09-09 15:08:12 +00001699 if (Decl *D = FindGetterNameDeclFromProtocolList(*I, Member, Sel,
Douglas Gregor6ab35242009-04-09 21:40:53 +00001700 Context))
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00001701 return D;
1702 }
1703 return 0;
1704}
1705
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001706static Decl *FindGetterNameDecl(const ObjCObjectPointerType *QIdTy,
Anders Carlsson8f28f992009-08-26 18:25:21 +00001707 IdentifierInfo *Member,
Douglas Gregor6ab35242009-04-09 21:40:53 +00001708 const Selector &Sel,
1709 ASTContext &Context) {
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00001710 // Check protocols on qualified interfaces.
1711 Decl *GDecl = 0;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001712 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00001713 E = QIdTy->qual_end(); I != E; ++I) {
Anders Carlsson8f28f992009-08-26 18:25:21 +00001714 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00001715 GDecl = PD;
1716 break;
1717 }
1718 // Also must look for a getter name which uses property syntax.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001719 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00001720 GDecl = OMD;
1721 break;
1722 }
1723 }
1724 if (!GDecl) {
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001725 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00001726 E = QIdTy->qual_end(); I != E; ++I) {
1727 // Search in the protocol-qualifier list of current protocol.
Douglas Gregor6ab35242009-04-09 21:40:53 +00001728 GDecl = FindGetterNameDeclFromProtocolList(*I, Member, Sel, Context);
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00001729 if (GDecl)
1730 return GDecl;
1731 }
1732 }
1733 return GDecl;
1734}
Chris Lattner76a642f2009-02-15 22:43:40 +00001735
Mike Stump1eb44332009-09-09 15:08:12 +00001736Action::OwningExprResult
Anders Carlsson8f28f992009-08-26 18:25:21 +00001737Sema::BuildMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc,
Sebastian Redl0eb23302009-01-19 00:08:26 +00001738 tok::TokenKind OpKind, SourceLocation MemberLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00001739 DeclarationName MemberName,
Douglas Gregorc4bf26f2009-09-01 00:37:14 +00001740 bool HasExplicitTemplateArgs,
1741 SourceLocation LAngleLoc,
John McCall833ca992009-10-29 08:12:44 +00001742 const TemplateArgumentLoc *ExplicitTemplateArgs,
Douglas Gregorc4bf26f2009-09-01 00:37:14 +00001743 unsigned NumExplicitTemplateArgs,
1744 SourceLocation RAngleLoc,
Douglas Gregorc68afe22009-09-03 21:38:09 +00001745 DeclPtrTy ObjCImpDecl, const CXXScopeSpec *SS,
1746 NamedDecl *FirstQualifierInScope) {
Douglas Gregorfe85ced2009-08-06 03:17:00 +00001747 if (SS && SS->isInvalid())
1748 return ExprError();
1749
Nate Begeman2ef13e52009-08-10 23:49:36 +00001750 // Since this might be a postfix expression, get rid of ParenListExprs.
1751 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
1752
Anders Carlssonf1b1d592009-05-01 19:30:39 +00001753 Expr *BaseExpr = Base.takeAs<Expr>();
Douglas Gregora71d8192009-09-04 17:36:40 +00001754 assert(BaseExpr && "no base expression");
Mike Stump1eb44332009-09-09 15:08:12 +00001755
Steve Naroff3cc4af82007-12-16 21:42:28 +00001756 // Perform default conversions.
1757 DefaultFunctionArrayConversion(BaseExpr);
Sebastian Redl0eb23302009-01-19 00:08:26 +00001758
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001759 QualType BaseType = BaseExpr->getType();
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00001760
1761 // If the user is trying to apply -> or . to a function pointer
1762 // type, it's probably because the forgot parentheses to call that
1763 // function. Suggest the addition of those parentheses, build the
1764 // call, and continue on.
1765 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
1766 if (const FunctionProtoType *Fun
1767 = Ptr->getPointeeType()->getAs<FunctionProtoType>()) {
1768 QualType ResultTy = Fun->getResultType();
1769 if (Fun->getNumArgs() == 0 &&
1770 ((OpKind == tok::period && ResultTy->isRecordType()) ||
1771 (OpKind == tok::arrow && ResultTy->isPointerType() &&
1772 ResultTy->getAs<PointerType>()->getPointeeType()
1773 ->isRecordType()))) {
1774 SourceLocation Loc = PP.getLocForEndOfToken(BaseExpr->getLocEnd());
1775 Diag(Loc, diag::err_member_reference_needs_call)
1776 << QualType(Fun, 0)
1777 << CodeModificationHint::CreateInsertion(Loc, "()");
1778
1779 OwningExprResult NewBase
1780 = ActOnCallExpr(S, ExprArg(*this, BaseExpr), Loc,
1781 MultiExprArg(*this, 0, 0), 0, Loc);
1782 if (NewBase.isInvalid())
1783 return move(NewBase);
1784
1785 BaseExpr = NewBase.takeAs<Expr>();
1786 DefaultFunctionArrayConversion(BaseExpr);
1787 BaseType = BaseExpr->getType();
1788 }
1789 }
1790 }
1791
David Chisnall0f436562009-08-17 16:35:33 +00001792 // If this is an Objective-C pseudo-builtin and a definition is provided then
1793 // use that.
1794 if (BaseType->isObjCIdType()) {
1795 // We have an 'id' type. Rather than fall through, we check if this
1796 // is a reference to 'isa'.
1797 if (BaseType != Context.ObjCIdRedefinitionType) {
1798 BaseType = Context.ObjCIdRedefinitionType;
Eli Friedman73c39ab2009-10-20 08:27:19 +00001799 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
David Chisnall0f436562009-08-17 16:35:33 +00001800 }
David Chisnall0f436562009-08-17 16:35:33 +00001801 }
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001802 assert(!BaseType.isNull() && "no type for member expression");
Sebastian Redl0eb23302009-01-19 00:08:26 +00001803
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00001804 // Handle properties on ObjC 'Class' types.
1805 if (OpKind == tok::period && BaseType->isObjCClassType()) {
1806 // Also must look for a getter name which uses property syntax.
1807 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1808 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
1809 if (ObjCMethodDecl *MD = getCurMethodDecl()) {
1810 ObjCInterfaceDecl *IFace = MD->getClassInterface();
1811 ObjCMethodDecl *Getter;
1812 // FIXME: need to also look locally in the implementation.
1813 if ((Getter = IFace->lookupClassMethod(Sel))) {
1814 // Check the use of this method.
1815 if (DiagnoseUseOfDecl(Getter, MemberLoc))
1816 return ExprError();
1817 }
1818 // If we found a getter then this may be a valid dot-reference, we
1819 // will look for the matching setter, in case it is needed.
1820 Selector SetterSel =
1821 SelectorTable::constructSetterName(PP.getIdentifierTable(),
1822 PP.getSelectorTable(), Member);
1823 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
1824 if (!Setter) {
1825 // If this reference is in an @implementation, also check for 'private'
1826 // methods.
Steve Naroffd789d3d2009-10-01 23:46:04 +00001827 Setter = IFace->lookupPrivateInstanceMethod(SetterSel);
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00001828 }
1829 // Look through local category implementations associated with the class.
1830 if (!Setter)
1831 Setter = IFace->getCategoryClassMethod(SetterSel);
1832
1833 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
1834 return ExprError();
1835
1836 if (Getter || Setter) {
1837 QualType PType;
1838
1839 if (Getter)
1840 PType = Getter->getResultType();
1841 else
1842 // Get the expression type from Setter's incoming parameter.
1843 PType = (*(Setter->param_end() -1))->getType();
1844 // FIXME: we must check that the setter has property type.
1845 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter,
1846 PType,
1847 Setter, MemberLoc, BaseExpr));
1848 }
1849 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1850 << MemberName << BaseType);
1851 }
1852 }
1853
1854 if (BaseType->isObjCClassType() &&
1855 BaseType != Context.ObjCClassRedefinitionType) {
1856 BaseType = Context.ObjCClassRedefinitionType;
Eli Friedman73c39ab2009-10-20 08:27:19 +00001857 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00001858 }
1859
Chris Lattner68a057b2008-07-21 04:36:39 +00001860 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
1861 // must have pointer type, and the accessed type is the pointee.
Reid Spencer5f016e22007-07-11 17:01:13 +00001862 if (OpKind == tok::arrow) {
Douglas Gregorc68afe22009-09-03 21:38:09 +00001863 if (BaseType->isDependentType()) {
1864 NestedNameSpecifier *Qualifier = 0;
1865 if (SS) {
1866 Qualifier = static_cast<NestedNameSpecifier *>(SS->getScopeRep());
1867 if (!FirstQualifierInScope)
1868 FirstQualifierInScope = FindFirstQualifierInScope(S, Qualifier);
1869 }
Mike Stump1eb44332009-09-09 15:08:12 +00001870
1871 return Owned(CXXUnresolvedMemberExpr::Create(Context, BaseExpr, true,
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00001872 OpLoc, Qualifier,
Douglas Gregora38c6872009-09-03 16:14:30 +00001873 SS? SS->getRange() : SourceRange(),
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00001874 FirstQualifierInScope,
1875 MemberName,
1876 MemberLoc,
1877 HasExplicitTemplateArgs,
1878 LAngleLoc,
1879 ExplicitTemplateArgs,
1880 NumExplicitTemplateArgs,
1881 RAngleLoc));
Douglas Gregorc68afe22009-09-03 21:38:09 +00001882 }
Ted Kremenek6217b802009-07-29 21:53:49 +00001883 else if (const PointerType *PT = BaseType->getAs<PointerType>())
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001884 BaseType = PT->getPointeeType();
Steve Naroff14108da2009-07-10 23:34:53 +00001885 else if (BaseType->isObjCObjectPointerType())
1886 ;
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001887 else
Sebastian Redl0eb23302009-01-19 00:08:26 +00001888 return ExprError(Diag(MemberLoc,
1889 diag::err_typecheck_member_reference_arrow)
1890 << BaseType << BaseExpr->getSourceRange());
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00001891 } else if (BaseType->isDependentType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001892 // Require that the base type isn't a pointer type
Anders Carlsson4ef27702009-05-16 20:31:20 +00001893 // (so we'll report an error for)
1894 // T* t;
1895 // t.f;
Mike Stump1eb44332009-09-09 15:08:12 +00001896 //
Anders Carlsson4ef27702009-05-16 20:31:20 +00001897 // In Obj-C++, however, the above expression is valid, since it could be
1898 // accessing the 'f' property if T is an Obj-C interface. The extra check
1899 // allows this, while still reporting an error if T is a struct pointer.
Ted Kremenek6217b802009-07-29 21:53:49 +00001900 const PointerType *PT = BaseType->getAs<PointerType>();
Anders Carlsson4ef27702009-05-16 20:31:20 +00001901
Mike Stump1eb44332009-09-09 15:08:12 +00001902 if (!PT || (getLangOptions().ObjC1 &&
Douglas Gregorc68afe22009-09-03 21:38:09 +00001903 !PT->getPointeeType()->isRecordType())) {
1904 NestedNameSpecifier *Qualifier = 0;
1905 if (SS) {
1906 Qualifier = static_cast<NestedNameSpecifier *>(SS->getScopeRep());
1907 if (!FirstQualifierInScope)
1908 FirstQualifierInScope = FindFirstQualifierInScope(S, Qualifier);
1909 }
Mike Stump1eb44332009-09-09 15:08:12 +00001910
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00001911 return Owned(CXXUnresolvedMemberExpr::Create(Context,
Mike Stump1eb44332009-09-09 15:08:12 +00001912 BaseExpr, false,
1913 OpLoc,
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00001914 Qualifier,
Douglas Gregora38c6872009-09-03 16:14:30 +00001915 SS? SS->getRange() : SourceRange(),
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00001916 FirstQualifierInScope,
1917 MemberName,
1918 MemberLoc,
1919 HasExplicitTemplateArgs,
1920 LAngleLoc,
1921 ExplicitTemplateArgs,
1922 NumExplicitTemplateArgs,
1923 RAngleLoc));
Douglas Gregorc68afe22009-09-03 21:38:09 +00001924 }
Anders Carlsson4ef27702009-05-16 20:31:20 +00001925 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00001926
Chris Lattner68a057b2008-07-21 04:36:39 +00001927 // Handle field access to simple records. This also handles access to fields
1928 // of the ObjC 'id' struct.
Ted Kremenek6217b802009-07-29 21:53:49 +00001929 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001930 RecordDecl *RDecl = RTy->getDecl();
Douglas Gregor86447ec2009-03-09 16:13:40 +00001931 if (RequireCompleteType(OpLoc, BaseType,
Anders Carlssonb7906612009-08-26 23:45:07 +00001932 PDiag(diag::err_typecheck_incomplete_tag)
1933 << BaseExpr->getSourceRange()))
Douglas Gregor4ec339f2009-01-19 19:26:10 +00001934 return ExprError();
1935
Douglas Gregorfe85ced2009-08-06 03:17:00 +00001936 DeclContext *DC = RDecl;
1937 if (SS && SS->isSet()) {
1938 // If the member name was a qualified-id, look into the
1939 // nested-name-specifier.
1940 DC = computeDeclContext(*SS, false);
Douglas Gregor8d1c9ae2009-10-17 22:37:54 +00001941
1942 if (!isa<TypeDecl>(DC)) {
1943 Diag(MemberLoc, diag::err_qualified_member_nonclass)
1944 << DC << SS->getRange();
1945 return ExprError();
1946 }
Mike Stump1eb44332009-09-09 15:08:12 +00001947
1948 // FIXME: If DC is not computable, we should build a
Douglas Gregorfe85ced2009-08-06 03:17:00 +00001949 // CXXUnresolvedMemberExpr.
1950 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
1951 }
1952
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001953 // The record definition is complete, now make sure the member is valid.
John McCalla24dc2e2009-11-17 02:14:36 +00001954 LookupResult Result(*this, MemberName, MemberLoc, LookupMemberName);
1955 LookupQualifiedName(Result, DC);
Douglas Gregor7176fff2009-01-15 00:26:24 +00001956
John McCallf36e02d2009-10-09 21:13:30 +00001957 if (Result.empty())
Douglas Gregor3f093272009-10-13 21:16:44 +00001958 return ExprError(Diag(MemberLoc, diag::err_no_member)
1959 << MemberName << DC << BaseExpr->getSourceRange());
John McCalla24dc2e2009-11-17 02:14:36 +00001960 if (Result.isAmbiguous())
Sebastian Redl0eb23302009-01-19 00:08:26 +00001961 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001962
John McCallf36e02d2009-10-09 21:13:30 +00001963 NamedDecl *MemberDecl = Result.getAsSingleDecl(Context);
1964
Douglas Gregora38c6872009-09-03 16:14:30 +00001965 if (SS && SS->isSet()) {
John McCallf36e02d2009-10-09 21:13:30 +00001966 TypeDecl* TyD = cast<TypeDecl>(MemberDecl->getDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +00001967 QualType BaseTypeCanon
Douglas Gregora38c6872009-09-03 16:14:30 +00001968 = Context.getCanonicalType(BaseType).getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +00001969 QualType MemberTypeCanon
John McCallf36e02d2009-10-09 21:13:30 +00001970 = Context.getCanonicalType(Context.getTypeDeclType(TyD));
Mike Stump1eb44332009-09-09 15:08:12 +00001971
Douglas Gregora38c6872009-09-03 16:14:30 +00001972 if (BaseTypeCanon != MemberTypeCanon &&
1973 !IsDerivedFrom(BaseTypeCanon, MemberTypeCanon))
1974 return ExprError(Diag(SS->getBeginLoc(),
1975 diag::err_not_direct_base_or_virtual)
1976 << MemberTypeCanon << BaseTypeCanon);
1977 }
Mike Stump1eb44332009-09-09 15:08:12 +00001978
Chris Lattner56cd21b2009-02-13 22:08:30 +00001979 // If the decl being referenced had an error, return an error for this
1980 // sub-expr without emitting another error, in order to avoid cascading
1981 // error cases.
1982 if (MemberDecl->isInvalidDecl())
1983 return ExprError();
Mike Stumpeed9cac2009-02-19 03:04:26 +00001984
Anders Carlsson0f728562009-09-10 20:48:14 +00001985 bool ShouldCheckUse = true;
1986 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
1987 // Don't diagnose the use of a virtual member function unless it's
1988 // explicitly qualified.
1989 if (MD->isVirtual() && (!SS || !SS->isSet()))
1990 ShouldCheckUse = false;
1991 }
Daniel Dunbar7e88a602009-09-17 06:31:17 +00001992
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001993 // Check the use of this field
Anders Carlsson0f728562009-09-10 20:48:14 +00001994 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001995 return ExprError();
Chris Lattner56cd21b2009-02-13 22:08:30 +00001996
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001997 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001998 // We may have found a field within an anonymous union or struct
1999 // (C++ [class.union]).
2000 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
Sebastian Redlcd965b92009-01-18 18:53:16 +00002001 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
Sebastian Redl0eb23302009-01-19 00:08:26 +00002002 BaseExpr, OpLoc);
Douglas Gregorbcbffc42009-01-07 00:43:41 +00002003
Douglas Gregor86f19402008-12-20 23:49:58 +00002004 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
Douglas Gregor3fc749d2008-12-23 00:26:44 +00002005 QualType MemberType = FD->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002006 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>())
Douglas Gregor86f19402008-12-20 23:49:58 +00002007 MemberType = Ref->getPointeeType();
2008 else {
John McCall0953e762009-09-24 19:53:00 +00002009 Qualifiers BaseQuals = BaseType.getQualifiers();
2010 BaseQuals.removeObjCGCAttr();
2011 if (FD->isMutable()) BaseQuals.removeConst();
2012
2013 Qualifiers MemberQuals
2014 = Context.getCanonicalType(MemberType).getQualifiers();
2015
2016 Qualifiers Combined = BaseQuals + MemberQuals;
2017 if (Combined != MemberQuals)
2018 MemberType = Context.getQualifiedType(MemberType, Combined);
Douglas Gregor86f19402008-12-20 23:49:58 +00002019 }
Eli Friedman51019072008-02-06 22:48:16 +00002020
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002021 MarkDeclarationReferenced(MemberLoc, FD);
Fariborz Jahanianf3e53d32009-07-29 19:40:11 +00002022 if (PerformObjectMemberConversion(BaseExpr, FD))
2023 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00002024 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +00002025 FD, MemberLoc, MemberType));
Chris Lattnera3d25242009-03-31 08:18:48 +00002026 }
Mike Stump1eb44332009-09-09 15:08:12 +00002027
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002028 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
2029 MarkDeclarationReferenced(MemberLoc, MemberDecl);
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +00002030 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2031 Var, MemberLoc,
2032 Var->getType().getNonReferenceType()));
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002033 }
2034 if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl)) {
2035 MarkDeclarationReferenced(MemberLoc, MemberDecl);
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +00002036 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2037 MemberFn, MemberLoc,
2038 MemberFn->getType()));
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002039 }
Mike Stump1eb44332009-09-09 15:08:12 +00002040 if (FunctionTemplateDecl *FunTmpl
Douglas Gregor6b906862009-08-21 00:16:32 +00002041 = dyn_cast<FunctionTemplateDecl>(MemberDecl)) {
2042 MarkDeclarationReferenced(MemberLoc, MemberDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00002043
Douglas Gregorc4bf26f2009-09-01 00:37:14 +00002044 if (HasExplicitTemplateArgs)
Mike Stump1eb44332009-09-09 15:08:12 +00002045 return Owned(MemberExpr::Create(Context, BaseExpr, OpKind == tok::arrow,
2046 (NestedNameSpecifier *)(SS? SS->getScopeRep() : 0),
Douglas Gregorc4bf26f2009-09-01 00:37:14 +00002047 SS? SS->getRange() : SourceRange(),
Mike Stump1eb44332009-09-09 15:08:12 +00002048 FunTmpl, MemberLoc, true,
2049 LAngleLoc, ExplicitTemplateArgs,
2050 NumExplicitTemplateArgs, RAngleLoc,
Douglas Gregorc4bf26f2009-09-01 00:37:14 +00002051 Context.OverloadTy));
Mike Stump1eb44332009-09-09 15:08:12 +00002052
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +00002053 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2054 FunTmpl, MemberLoc,
2055 Context.OverloadTy));
Douglas Gregor6b906862009-08-21 00:16:32 +00002056 }
Chris Lattnera3d25242009-03-31 08:18:48 +00002057 if (OverloadedFunctionDecl *Ovl
Douglas Gregorc4bf26f2009-09-01 00:37:14 +00002058 = dyn_cast<OverloadedFunctionDecl>(MemberDecl)) {
2059 if (HasExplicitTemplateArgs)
Mike Stump1eb44332009-09-09 15:08:12 +00002060 return Owned(MemberExpr::Create(Context, BaseExpr, OpKind == tok::arrow,
2061 (NestedNameSpecifier *)(SS? SS->getScopeRep() : 0),
Douglas Gregorc4bf26f2009-09-01 00:37:14 +00002062 SS? SS->getRange() : SourceRange(),
Mike Stump1eb44332009-09-09 15:08:12 +00002063 Ovl, MemberLoc, true,
2064 LAngleLoc, ExplicitTemplateArgs,
2065 NumExplicitTemplateArgs, RAngleLoc,
Douglas Gregorc4bf26f2009-09-01 00:37:14 +00002066 Context.OverloadTy));
2067
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +00002068 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2069 Ovl, MemberLoc, Context.OverloadTy));
Douglas Gregorc4bf26f2009-09-01 00:37:14 +00002070 }
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002071 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
2072 MarkDeclarationReferenced(MemberLoc, MemberDecl);
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +00002073 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2074 Enum, MemberLoc, Enum->getType()));
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002075 }
Chris Lattnera3d25242009-03-31 08:18:48 +00002076 if (isa<TypeDecl>(MemberDecl))
Sebastian Redl0eb23302009-01-19 00:08:26 +00002077 return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
Anders Carlsson8f28f992009-08-26 18:25:21 +00002078 << MemberName << int(OpKind == tok::arrow));
Eli Friedman51019072008-02-06 22:48:16 +00002079
Douglas Gregor86f19402008-12-20 23:49:58 +00002080 // We found a declaration kind that we didn't expect. This is a
2081 // generic error message that tells the user that she can't refer
2082 // to this member with '.' or '->'.
Sebastian Redl0eb23302009-01-19 00:08:26 +00002083 return ExprError(Diag(MemberLoc,
2084 diag::err_typecheck_member_reference_unknown)
Anders Carlsson8f28f992009-08-26 18:25:21 +00002085 << MemberName << int(OpKind == tok::arrow));
Chris Lattnerfb173ec2008-07-21 04:28:12 +00002086 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002087
Douglas Gregora71d8192009-09-04 17:36:40 +00002088 // Handle pseudo-destructors (C++ [expr.pseudo]). Since anything referring
2089 // into a record type was handled above, any destructor we see here is a
2090 // pseudo-destructor.
2091 if (MemberName.getNameKind() == DeclarationName::CXXDestructorName) {
2092 // C++ [expr.pseudo]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00002093 // The left hand side of the dot operator shall be of scalar type. The
2094 // left hand side of the arrow operator shall be of pointer to scalar
Douglas Gregora71d8192009-09-04 17:36:40 +00002095 // type.
2096 if (!BaseType->isScalarType())
2097 return Owned(Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
2098 << BaseType << BaseExpr->getSourceRange());
Mike Stump1eb44332009-09-09 15:08:12 +00002099
Douglas Gregora71d8192009-09-04 17:36:40 +00002100 // [...] The type designated by the pseudo-destructor-name shall be the
2101 // same as the object type.
2102 if (!MemberName.getCXXNameType()->isDependentType() &&
2103 !Context.hasSameUnqualifiedType(BaseType, MemberName.getCXXNameType()))
2104 return Owned(Diag(OpLoc, diag::err_pseudo_dtor_type_mismatch)
2105 << BaseType << MemberName.getCXXNameType()
2106 << BaseExpr->getSourceRange() << SourceRange(MemberLoc));
Mike Stump1eb44332009-09-09 15:08:12 +00002107
2108 // [...] Furthermore, the two type-names in a pseudo-destructor-name of
Douglas Gregora71d8192009-09-04 17:36:40 +00002109 // the form
2110 //
Mike Stump1eb44332009-09-09 15:08:12 +00002111 // ::[opt] nested-name-specifier[opt] type-name :: ̃ type-name
2112 //
Douglas Gregora71d8192009-09-04 17:36:40 +00002113 // shall designate the same scalar type.
2114 //
2115 // FIXME: DPG can't see any way to trigger this particular clause, so it
2116 // isn't checked here.
Mike Stump1eb44332009-09-09 15:08:12 +00002117
Douglas Gregora71d8192009-09-04 17:36:40 +00002118 // FIXME: We've lost the precise spelling of the type by going through
2119 // DeclarationName. Can we do better?
2120 return Owned(new (Context) CXXPseudoDestructorExpr(Context, BaseExpr,
Mike Stump1eb44332009-09-09 15:08:12 +00002121 OpKind == tok::arrow,
Douglas Gregora71d8192009-09-04 17:36:40 +00002122 OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00002123 (NestedNameSpecifier *)(SS? SS->getScopeRep() : 0),
Douglas Gregora71d8192009-09-04 17:36:40 +00002124 SS? SS->getRange() : SourceRange(),
2125 MemberName.getCXXNameType(),
2126 MemberLoc));
2127 }
Mike Stump1eb44332009-09-09 15:08:12 +00002128
Chris Lattnera38e6b12008-07-21 04:59:05 +00002129 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
2130 // (*Obj).ivar.
Steve Naroff14108da2009-07-10 23:34:53 +00002131 if ((OpKind == tok::arrow && BaseType->isObjCObjectPointerType()) ||
2132 (OpKind == tok::period && BaseType->isObjCInterfaceType())) {
John McCall183700f2009-09-21 23:43:11 +00002133 const ObjCObjectPointerType *OPT = BaseType->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00002134 const ObjCInterfaceType *IFaceT =
John McCall183700f2009-09-21 23:43:11 +00002135 OPT ? OPT->getInterfaceType() : BaseType->getAs<ObjCInterfaceType>();
Steve Naroffc70e8d92009-07-16 00:25:06 +00002136 if (IFaceT) {
Anders Carlsson8f28f992009-08-26 18:25:21 +00002137 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
2138
Steve Naroffc70e8d92009-07-16 00:25:06 +00002139 ObjCInterfaceDecl *IDecl = IFaceT->getDecl();
2140 ObjCInterfaceDecl *ClassDeclared;
Anders Carlsson8f28f992009-08-26 18:25:21 +00002141 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
Mike Stump1eb44332009-09-09 15:08:12 +00002142
Steve Naroffc70e8d92009-07-16 00:25:06 +00002143 if (IV) {
2144 // If the decl being referenced had an error, return an error for this
2145 // sub-expr without emitting another error, in order to avoid cascading
2146 // error cases.
2147 if (IV->isInvalidDecl())
2148 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002149
Steve Naroffc70e8d92009-07-16 00:25:06 +00002150 // Check whether we can reference this field.
2151 if (DiagnoseUseOfDecl(IV, MemberLoc))
2152 return ExprError();
2153 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
2154 IV->getAccessControl() != ObjCIvarDecl::Package) {
2155 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
2156 if (ObjCMethodDecl *MD = getCurMethodDecl())
2157 ClassOfMethodDecl = MD->getClassInterface();
2158 else if (ObjCImpDecl && getCurFunctionDecl()) {
2159 // Case of a c-function declared inside an objc implementation.
2160 // FIXME: For a c-style function nested inside an objc implementation
2161 // class, there is no implementation context available, so we pass
2162 // down the context as argument to this routine. Ideally, this context
2163 // need be passed down in the AST node and somehow calculated from the
2164 // AST for a function decl.
2165 Decl *ImplDecl = ObjCImpDecl.getAs<Decl>();
Mike Stump1eb44332009-09-09 15:08:12 +00002166 if (ObjCImplementationDecl *IMPD =
Steve Naroffc70e8d92009-07-16 00:25:06 +00002167 dyn_cast<ObjCImplementationDecl>(ImplDecl))
2168 ClassOfMethodDecl = IMPD->getClassInterface();
2169 else if (ObjCCategoryImplDecl* CatImplClass =
2170 dyn_cast<ObjCCategoryImplDecl>(ImplDecl))
2171 ClassOfMethodDecl = CatImplClass->getClassInterface();
2172 }
Mike Stump1eb44332009-09-09 15:08:12 +00002173
2174 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
2175 if (ClassDeclared != IDecl ||
Steve Naroffc70e8d92009-07-16 00:25:06 +00002176 ClassOfMethodDecl != ClassDeclared)
Mike Stump1eb44332009-09-09 15:08:12 +00002177 Diag(MemberLoc, diag::error_private_ivar_access)
Steve Naroffc70e8d92009-07-16 00:25:06 +00002178 << IV->getDeclName();
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002179 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
2180 // @protected
Mike Stump1eb44332009-09-09 15:08:12 +00002181 Diag(MemberLoc, diag::error_protected_ivar_access)
Steve Naroffc70e8d92009-07-16 00:25:06 +00002182 << IV->getDeclName();
Steve Naroffb06d8752009-03-04 18:34:24 +00002183 }
Steve Naroffc70e8d92009-07-16 00:25:06 +00002184
2185 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
2186 MemberLoc, BaseExpr,
2187 OpKind == tok::arrow));
Fariborz Jahanian935fd762009-03-03 01:21:12 +00002188 }
Steve Naroffc70e8d92009-07-16 00:25:06 +00002189 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
Anders Carlsson8f28f992009-08-26 18:25:21 +00002190 << IDecl->getDeclName() << MemberName
Steve Naroffc70e8d92009-07-16 00:25:06 +00002191 << BaseExpr->getSourceRange());
Fariborz Jahanianaaa63a72008-12-13 22:20:28 +00002192 }
Chris Lattnerfb173ec2008-07-21 04:28:12 +00002193 }
Steve Naroffde2e22d2009-07-15 18:40:39 +00002194 // Handle properties on 'id' and qualified "id".
Mike Stump1eb44332009-09-09 15:08:12 +00002195 if (OpKind == tok::period && (BaseType->isObjCIdType() ||
Steve Naroffde2e22d2009-07-15 18:40:39 +00002196 BaseType->isObjCQualifiedIdType())) {
John McCall183700f2009-09-21 23:43:11 +00002197 const ObjCObjectPointerType *QIdTy = BaseType->getAs<ObjCObjectPointerType>();
Anders Carlsson8f28f992009-08-26 18:25:21 +00002198 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Mike Stump1eb44332009-09-09 15:08:12 +00002199
Steve Naroff14108da2009-07-10 23:34:53 +00002200 // Check protocols on qualified interfaces.
Anders Carlsson8f28f992009-08-26 18:25:21 +00002201 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Steve Naroff14108da2009-07-10 23:34:53 +00002202 if (Decl *PMDecl = FindGetterNameDecl(QIdTy, Member, Sel, Context)) {
2203 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
2204 // Check the use of this declaration
2205 if (DiagnoseUseOfDecl(PD, MemberLoc))
2206 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00002207
Steve Naroff14108da2009-07-10 23:34:53 +00002208 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
2209 MemberLoc, BaseExpr));
2210 }
2211 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
2212 // Check the use of this method.
2213 if (DiagnoseUseOfDecl(OMD, MemberLoc))
2214 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00002215
Steve Naroff14108da2009-07-10 23:34:53 +00002216 return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel,
Mike Stump1eb44332009-09-09 15:08:12 +00002217 OMD->getResultType(),
2218 OMD, OpLoc, MemberLoc,
Steve Naroff14108da2009-07-10 23:34:53 +00002219 NULL, 0));
2220 }
2221 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002222
Steve Naroff14108da2009-07-10 23:34:53 +00002223 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlsson8f28f992009-08-26 18:25:21 +00002224 << MemberName << BaseType);
Steve Naroff14108da2009-07-10 23:34:53 +00002225 }
Chris Lattnera38e6b12008-07-21 04:59:05 +00002226 // Handle Objective-C property access, which is "Obj.property" where Obj is a
2227 // pointer to a (potentially qualified) interface type.
Steve Naroff14108da2009-07-10 23:34:53 +00002228 const ObjCObjectPointerType *OPT;
Mike Stump1eb44332009-09-09 15:08:12 +00002229 if (OpKind == tok::period &&
Steve Naroff14108da2009-07-10 23:34:53 +00002230 (OPT = BaseType->getAsObjCInterfacePointerType())) {
2231 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
2232 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
Anders Carlsson8f28f992009-08-26 18:25:21 +00002233 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Mike Stump1eb44332009-09-09 15:08:12 +00002234
Daniel Dunbar2307d312008-09-03 01:05:41 +00002235 // Search for a declared property first.
Anders Carlsson8f28f992009-08-26 18:25:21 +00002236 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002237 // Check whether we can reference this property.
2238 if (DiagnoseUseOfDecl(PD, MemberLoc))
2239 return ExprError();
Fariborz Jahanian4c2743f2009-05-08 19:36:34 +00002240 QualType ResTy = PD->getType();
Anders Carlsson8f28f992009-08-26 18:25:21 +00002241 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002242 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Fariborz Jahanianc001e892009-05-08 20:20:55 +00002243 if (DiagnosePropertyAccessorMismatch(PD, Getter, MemberLoc))
2244 ResTy = Getter->getResultType();
Fariborz Jahanian4c2743f2009-05-08 19:36:34 +00002245 return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
Chris Lattner7eba82e2009-02-16 18:35:08 +00002246 MemberLoc, BaseExpr));
2247 }
Daniel Dunbar2307d312008-09-03 01:05:41 +00002248 // Check protocols on qualified interfaces.
Steve Naroff67ef8ea2009-07-20 17:56:53 +00002249 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
2250 E = OPT->qual_end(); I != E; ++I)
Anders Carlsson8f28f992009-08-26 18:25:21 +00002251 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002252 // Check whether we can reference this property.
2253 if (DiagnoseUseOfDecl(PD, MemberLoc))
2254 return ExprError();
Chris Lattner7eba82e2009-02-16 18:35:08 +00002255
Steve Naroff6ece14c2009-01-21 00:14:39 +00002256 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner7eba82e2009-02-16 18:35:08 +00002257 MemberLoc, BaseExpr));
2258 }
Daniel Dunbar2307d312008-09-03 01:05:41 +00002259 // If that failed, look for an "implicit" property by seeing if the nullary
2260 // selector is implemented.
2261
2262 // FIXME: The logic for looking up nullary and unary selectors should be
2263 // shared with the code in ActOnInstanceMessage.
2264
Anders Carlsson8f28f992009-08-26 18:25:21 +00002265 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002266 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Sebastian Redl0eb23302009-01-19 00:08:26 +00002267
Daniel Dunbar2307d312008-09-03 01:05:41 +00002268 // If this reference is in an @implementation, check for 'private' methods.
2269 if (!Getter)
Steve Naroffd789d3d2009-10-01 23:46:04 +00002270 Getter = IFace->lookupPrivateInstanceMethod(Sel);
Daniel Dunbar2307d312008-09-03 01:05:41 +00002271
Steve Naroff7692ed62008-10-22 19:16:27 +00002272 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +00002273 if (!Getter)
2274 Getter = IFace->getCategoryInstanceMethod(Sel);
Daniel Dunbar2307d312008-09-03 01:05:41 +00002275 if (Getter) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002276 // Check if we can reference this property.
2277 if (DiagnoseUseOfDecl(Getter, MemberLoc))
2278 return ExprError();
Steve Naroff1ca66942009-03-11 13:48:17 +00002279 }
2280 // If we found a getter then this may be a valid dot-reference, we
2281 // will look for the matching setter, in case it is needed.
Mike Stump1eb44332009-09-09 15:08:12 +00002282 Selector SetterSel =
2283 SelectorTable::constructSetterName(PP.getIdentifierTable(),
Anders Carlsson8f28f992009-08-26 18:25:21 +00002284 PP.getSelectorTable(), Member);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002285 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
Steve Naroff1ca66942009-03-11 13:48:17 +00002286 if (!Setter) {
2287 // If this reference is in an @implementation, also check for 'private'
2288 // methods.
Steve Naroffd789d3d2009-10-01 23:46:04 +00002289 Setter = IFace->lookupPrivateInstanceMethod(SetterSel);
Steve Naroff1ca66942009-03-11 13:48:17 +00002290 }
2291 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +00002292 if (!Setter)
2293 Setter = IFace->getCategoryInstanceMethod(SetterSel);
Sebastian Redl0eb23302009-01-19 00:08:26 +00002294
Steve Naroff1ca66942009-03-11 13:48:17 +00002295 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2296 return ExprError();
2297
2298 if (Getter || Setter) {
2299 QualType PType;
2300
2301 if (Getter)
2302 PType = Getter->getResultType();
Fariborz Jahanian154440e2009-08-18 20:50:23 +00002303 else
2304 // Get the expression type from Setter's incoming parameter.
2305 PType = (*(Setter->param_end() -1))->getType();
Steve Naroff1ca66942009-03-11 13:48:17 +00002306 // FIXME: we must check that the setter has property type.
Fariborz Jahanian09105f52009-08-20 17:02:02 +00002307 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter, PType,
Steve Naroff1ca66942009-03-11 13:48:17 +00002308 Setter, MemberLoc, BaseExpr));
2309 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002310 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlsson8f28f992009-08-26 18:25:21 +00002311 << MemberName << BaseType);
Fariborz Jahanian232220c2007-11-12 22:29:28 +00002312 }
Mike Stump1eb44332009-09-09 15:08:12 +00002313
Steve Narofff242b1b2009-07-24 17:54:45 +00002314 // Handle the following exceptional case (*Obj).isa.
Mike Stump1eb44332009-09-09 15:08:12 +00002315 if (OpKind == tok::period &&
Steve Narofff242b1b2009-07-24 17:54:45 +00002316 BaseType->isSpecificBuiltinType(BuiltinType::ObjCId) &&
Anders Carlsson8f28f992009-08-26 18:25:21 +00002317 MemberName.getAsIdentifierInfo()->isStr("isa"))
Steve Narofff242b1b2009-07-24 17:54:45 +00002318 return Owned(new (Context) ObjCIsaExpr(BaseExpr, false, MemberLoc,
2319 Context.getObjCIdType()));
2320
Chris Lattnerfb173ec2008-07-21 04:28:12 +00002321 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner73525de2009-02-16 21:11:58 +00002322 if (BaseType->isExtVectorType()) {
Anders Carlsson8f28f992009-08-26 18:25:21 +00002323 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Chris Lattnerfb173ec2008-07-21 04:28:12 +00002324 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
2325 if (ret.isNull())
Sebastian Redl0eb23302009-01-19 00:08:26 +00002326 return ExprError();
Anders Carlsson8f28f992009-08-26 18:25:21 +00002327 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, *Member,
Steve Naroff6ece14c2009-01-21 00:14:39 +00002328 MemberLoc));
Chris Lattnerfb173ec2008-07-21 04:28:12 +00002329 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002330
Douglas Gregor214f31a2009-03-27 06:00:30 +00002331 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
2332 << BaseType << BaseExpr->getSourceRange();
2333
Douglas Gregor214f31a2009-03-27 06:00:30 +00002334 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00002335}
2336
Douglas Gregor2d1c2142009-11-03 19:44:04 +00002337Sema::OwningExprResult Sema::ActOnMemberAccessExpr(Scope *S, ExprArg Base,
2338 SourceLocation OpLoc,
2339 tok::TokenKind OpKind,
2340 const CXXScopeSpec &SS,
2341 UnqualifiedId &Member,
2342 DeclPtrTy ObjCImpDecl,
2343 bool HasTrailingLParen) {
2344 if (Member.getKind() == UnqualifiedId::IK_TemplateId) {
2345 TemplateName Template
2346 = TemplateName::getFromVoidPointer(Member.TemplateId->Template);
2347
2348 // FIXME: We're going to end up looking up the template based on its name,
2349 // twice!
2350 DeclarationName Name;
2351 if (TemplateDecl *ActualTemplate = Template.getAsTemplateDecl())
2352 Name = ActualTemplate->getDeclName();
2353 else if (OverloadedFunctionDecl *Ovl = Template.getAsOverloadedFunctionDecl())
2354 Name = Ovl->getDeclName();
Douglas Gregorca1bdd72009-11-04 00:56:37 +00002355 else {
2356 DependentTemplateName *DTN = Template.getAsDependentTemplateName();
2357 if (DTN->isIdentifier())
2358 Name = DTN->getIdentifier();
2359 else
2360 Name = Context.DeclarationNames.getCXXOperatorName(DTN->getOperator());
2361 }
Douglas Gregor2d1c2142009-11-03 19:44:04 +00002362
2363 // Translate the parser's template argument list in our AST format.
2364 ASTTemplateArgsPtr TemplateArgsPtr(*this,
2365 Member.TemplateId->getTemplateArgs(),
Douglas Gregor2d1c2142009-11-03 19:44:04 +00002366 Member.TemplateId->NumArgs);
2367
2368 llvm::SmallVector<TemplateArgumentLoc, 16> TemplateArgs;
2369 translateTemplateArguments(TemplateArgsPtr,
Douglas Gregor2d1c2142009-11-03 19:44:04 +00002370 TemplateArgs);
2371 TemplateArgsPtr.release();
2372
2373 // Do we have the save the actual template name? We might need it...
2374 return BuildMemberReferenceExpr(S, move(Base), OpLoc, OpKind,
2375 Member.TemplateId->TemplateNameLoc,
2376 Name, true, Member.TemplateId->LAngleLoc,
2377 TemplateArgs.data(), TemplateArgs.size(),
2378 Member.TemplateId->RAngleLoc, DeclPtrTy(),
2379 &SS);
2380 }
2381
2382 // FIXME: We lose a lot of source information by mapping directly to the
2383 // DeclarationName.
2384 OwningExprResult Result
2385 = BuildMemberReferenceExpr(S, move(Base), OpLoc, OpKind,
2386 Member.getSourceRange().getBegin(),
2387 GetNameFromUnqualifiedId(Member),
2388 ObjCImpDecl, &SS);
2389
2390 if (Result.isInvalid() || HasTrailingLParen ||
2391 Member.getKind() != UnqualifiedId::IK_DestructorName)
2392 return move(Result);
2393
2394 // The only way a reference to a destructor can be used is to
2395 // immediately call them. Since the next token is not a '(', produce a
2396 // diagnostic and build the call now.
2397 Expr *E = (Expr *)Result.get();
2398 SourceLocation ExpectedLParenLoc
2399 = PP.getLocForEndOfToken(Member.getSourceRange().getEnd());
2400 Diag(E->getLocStart(), diag::err_dtor_expr_without_call)
2401 << isa<CXXPseudoDestructorExpr>(E)
2402 << CodeModificationHint::CreateInsertion(ExpectedLParenLoc, "()");
2403
2404 return ActOnCallExpr(0, move(Result), ExpectedLParenLoc,
2405 MultiExprArg(*this, 0, 0), 0, ExpectedLParenLoc);
Anders Carlsson8f28f992009-08-26 18:25:21 +00002406}
2407
Anders Carlsson56c5e332009-08-25 03:49:14 +00002408Sema::OwningExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
2409 FunctionDecl *FD,
2410 ParmVarDecl *Param) {
2411 if (Param->hasUnparsedDefaultArg()) {
2412 Diag (CallLoc,
2413 diag::err_use_of_default_argument_to_function_declared_later) <<
2414 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00002415 Diag(UnparsedDefaultArgLocs[Param],
Anders Carlsson56c5e332009-08-25 03:49:14 +00002416 diag::note_default_argument_declared_here);
2417 } else {
2418 if (Param->hasUninstantiatedDefaultArg()) {
2419 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
2420
2421 // Instantiate the expression.
Douglas Gregord6350ae2009-08-28 20:31:08 +00002422 MultiLevelTemplateArgumentList ArgList = getTemplateInstantiationArgs(FD);
Anders Carlsson25cae7f2009-09-05 05:14:19 +00002423
Mike Stump1eb44332009-09-09 15:08:12 +00002424 InstantiatingTemplate Inst(*this, CallLoc, Param,
2425 ArgList.getInnermost().getFlatArgumentList(),
Douglas Gregord6350ae2009-08-28 20:31:08 +00002426 ArgList.getInnermost().flat_size());
Anders Carlsson56c5e332009-08-25 03:49:14 +00002427
John McCallce3ff2b2009-08-25 22:02:44 +00002428 OwningExprResult Result = SubstExpr(UninstExpr, ArgList);
Mike Stump1eb44332009-09-09 15:08:12 +00002429 if (Result.isInvalid())
Anders Carlsson56c5e332009-08-25 03:49:14 +00002430 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00002431
2432 if (SetParamDefaultArgument(Param, move(Result),
Anders Carlsson56c5e332009-08-25 03:49:14 +00002433 /*FIXME:EqualLoc*/
2434 UninstExpr->getSourceRange().getBegin()))
2435 return ExprError();
2436 }
Mike Stump1eb44332009-09-09 15:08:12 +00002437
Anders Carlsson56c5e332009-08-25 03:49:14 +00002438 Expr *DefaultExpr = Param->getDefaultArg();
Mike Stump1eb44332009-09-09 15:08:12 +00002439
Anders Carlsson56c5e332009-08-25 03:49:14 +00002440 // If the default expression creates temporaries, we need to
2441 // push them to the current stack of expression temporaries so they'll
2442 // be properly destroyed.
Mike Stump1eb44332009-09-09 15:08:12 +00002443 if (CXXExprWithTemporaries *E
Anders Carlsson56c5e332009-08-25 03:49:14 +00002444 = dyn_cast_or_null<CXXExprWithTemporaries>(DefaultExpr)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002445 assert(!E->shouldDestroyTemporaries() &&
Anders Carlsson56c5e332009-08-25 03:49:14 +00002446 "Can't destroy temporaries in a default argument expr!");
2447 for (unsigned I = 0, N = E->getNumTemporaries(); I != N; ++I)
2448 ExprTemporaries.push_back(E->getTemporary(I));
2449 }
2450 }
2451
2452 // We already type-checked the argument, so we know it works.
2453 return Owned(CXXDefaultArgExpr::Create(Context, Param));
2454}
2455
Douglas Gregor88a35142008-12-22 05:46:06 +00002456/// ConvertArgumentsForCall - Converts the arguments specified in
2457/// Args/NumArgs to the parameter types of the function FDecl with
2458/// function prototype Proto. Call is the call expression itself, and
2459/// Fn is the function expression. For a C++ member function, this
2460/// routine does not attempt to convert the object argument. Returns
2461/// true if the call is ill-formed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00002462bool
2463Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor88a35142008-12-22 05:46:06 +00002464 FunctionDecl *FDecl,
Douglas Gregor72564e72009-02-26 23:50:07 +00002465 const FunctionProtoType *Proto,
Douglas Gregor88a35142008-12-22 05:46:06 +00002466 Expr **Args, unsigned NumArgs,
2467 SourceLocation RParenLoc) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00002468 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor88a35142008-12-22 05:46:06 +00002469 // assignment, to the types of the corresponding parameter, ...
2470 unsigned NumArgsInProto = Proto->getNumArgs();
2471 unsigned NumArgsToCheck = NumArgs;
Douglas Gregor3fd56d72009-01-23 21:30:56 +00002472 bool Invalid = false;
2473
Douglas Gregor88a35142008-12-22 05:46:06 +00002474 // If too few arguments are available (and we don't have default
2475 // arguments for the remaining parameters), don't make the call.
2476 if (NumArgs < NumArgsInProto) {
2477 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
2478 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
2479 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
2480 // Use default arguments for missing arguments
2481 NumArgsToCheck = NumArgsInProto;
Ted Kremenek8189cde2009-02-07 01:47:29 +00002482 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor88a35142008-12-22 05:46:06 +00002483 }
2484
2485 // If too many are passed and not variadic, error on the extras and drop
2486 // them.
2487 if (NumArgs > NumArgsInProto) {
2488 if (!Proto->isVariadic()) {
2489 Diag(Args[NumArgsInProto]->getLocStart(),
2490 diag::err_typecheck_call_too_many_args)
2491 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
2492 << SourceRange(Args[NumArgsInProto]->getLocStart(),
2493 Args[NumArgs-1]->getLocEnd());
2494 // This deletes the extra arguments.
Ted Kremenek8189cde2009-02-07 01:47:29 +00002495 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor3fd56d72009-01-23 21:30:56 +00002496 Invalid = true;
Douglas Gregor88a35142008-12-22 05:46:06 +00002497 }
2498 NumArgsToCheck = NumArgsInProto;
2499 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00002500
Douglas Gregor88a35142008-12-22 05:46:06 +00002501 // Continue to check argument types (even if we have too few/many args).
2502 for (unsigned i = 0; i != NumArgsToCheck; i++) {
2503 QualType ProtoArgType = Proto->getArgType(i);
Mike Stumpeed9cac2009-02-19 03:04:26 +00002504
Douglas Gregor88a35142008-12-22 05:46:06 +00002505 Expr *Arg;
Douglas Gregor61366e92008-12-24 00:01:03 +00002506 if (i < NumArgs) {
Douglas Gregor88a35142008-12-22 05:46:06 +00002507 Arg = Args[i];
Douglas Gregor61366e92008-12-24 00:01:03 +00002508
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00002509 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
2510 ProtoArgType,
Anders Carlssonb7906612009-08-26 23:45:07 +00002511 PDiag(diag::err_call_incomplete_argument)
2512 << Arg->getSourceRange()))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00002513 return true;
2514
Douglas Gregor61366e92008-12-24 00:01:03 +00002515 // Pass the argument.
2516 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
2517 return true;
Anders Carlsson03d8ed42009-11-13 04:34:45 +00002518
Anders Carlsson4b3cbea2009-11-13 17:04:35 +00002519 if (!ProtoArgType->isReferenceType())
2520 Arg = MaybeBindToTemporary(Arg).takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00002521 } else {
Anders Carlssoned961f92009-08-25 02:29:20 +00002522 ParmVarDecl *Param = FDecl->getParamDecl(i);
Mike Stump1eb44332009-09-09 15:08:12 +00002523
2524 OwningExprResult ArgExpr =
Anders Carlsson56c5e332009-08-25 03:49:14 +00002525 BuildCXXDefaultArgExpr(Call->getSourceRange().getBegin(),
2526 FDecl, Param);
2527 if (ArgExpr.isInvalid())
2528 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002529
Anders Carlsson56c5e332009-08-25 03:49:14 +00002530 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00002531 }
Mike Stump1eb44332009-09-09 15:08:12 +00002532
Douglas Gregor88a35142008-12-22 05:46:06 +00002533 Call->setArg(i, Arg);
2534 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00002535
Douglas Gregor88a35142008-12-22 05:46:06 +00002536 // If this is a variadic call, handle args passed through "...".
2537 if (Proto->isVariadic()) {
Anders Carlssondce5e2c2009-01-16 16:48:51 +00002538 VariadicCallType CallType = VariadicFunction;
2539 if (Fn->getType()->isBlockPointerType())
2540 CallType = VariadicBlock; // Block
2541 else if (isa<MemberExpr>(Fn))
2542 CallType = VariadicMethod;
2543
Douglas Gregor88a35142008-12-22 05:46:06 +00002544 // Promote the arguments (C99 6.5.2.2p7).
Eli Friedman3e42ffd2009-11-14 04:43:10 +00002545 for (unsigned i = NumArgsInProto; i < NumArgs; i++) {
Douglas Gregor88a35142008-12-22 05:46:06 +00002546 Expr *Arg = Args[i];
Chris Lattner312531a2009-04-12 08:11:20 +00002547 Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType);
Douglas Gregor88a35142008-12-22 05:46:06 +00002548 Call->setArg(i, Arg);
2549 }
2550 }
2551
Douglas Gregor3fd56d72009-01-23 21:30:56 +00002552 return Invalid;
Douglas Gregor88a35142008-12-22 05:46:06 +00002553}
2554
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002555/// \brief "Deconstruct" the function argument of a call expression to find
2556/// the underlying declaration (if any), the name of the called function,
2557/// whether argument-dependent lookup is available, whether it has explicit
2558/// template arguments, etc.
2559void Sema::DeconstructCallFunction(Expr *FnExpr,
2560 NamedDecl *&Function,
2561 DeclarationName &Name,
2562 NestedNameSpecifier *&Qualifier,
2563 SourceRange &QualifierRange,
2564 bool &ArgumentDependentLookup,
2565 bool &HasExplicitTemplateArguments,
John McCall833ca992009-10-29 08:12:44 +00002566 const TemplateArgumentLoc *&ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002567 unsigned &NumExplicitTemplateArgs) {
2568 // Set defaults for all of the output parameters.
2569 Function = 0;
2570 Name = DeclarationName();
2571 Qualifier = 0;
2572 QualifierRange = SourceRange();
2573 ArgumentDependentLookup = getLangOptions().CPlusPlus;
2574 HasExplicitTemplateArguments = false;
2575
2576 // If we're directly calling a function, get the appropriate declaration.
2577 // Also, in C++, keep track of whether we should perform argument-dependent
2578 // lookup and whether there were any explicitly-specified template arguments.
2579 while (true) {
2580 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(FnExpr))
2581 FnExpr = IcExpr->getSubExpr();
2582 else if (ParenExpr *PExpr = dyn_cast<ParenExpr>(FnExpr)) {
2583 // Parentheses around a function disable ADL
2584 // (C++0x [basic.lookup.argdep]p1).
2585 ArgumentDependentLookup = false;
2586 FnExpr = PExpr->getSubExpr();
2587 } else if (isa<UnaryOperator>(FnExpr) &&
2588 cast<UnaryOperator>(FnExpr)->getOpcode()
2589 == UnaryOperator::AddrOf) {
2590 FnExpr = cast<UnaryOperator>(FnExpr)->getSubExpr();
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002591 } else if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(FnExpr)) {
2592 Function = dyn_cast<NamedDecl>(DRExpr->getDecl());
Douglas Gregora2813ce2009-10-23 18:54:35 +00002593 if ((Qualifier = DRExpr->getQualifier())) {
2594 ArgumentDependentLookup = false;
2595 QualifierRange = DRExpr->getQualifierRange();
2596 }
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002597 break;
2598 } else if (UnresolvedFunctionNameExpr *DepName
2599 = dyn_cast<UnresolvedFunctionNameExpr>(FnExpr)) {
2600 Name = DepName->getName();
2601 break;
2602 } else if (TemplateIdRefExpr *TemplateIdRef
2603 = dyn_cast<TemplateIdRefExpr>(FnExpr)) {
2604 Function = TemplateIdRef->getTemplateName().getAsTemplateDecl();
2605 if (!Function)
2606 Function = TemplateIdRef->getTemplateName().getAsOverloadedFunctionDecl();
2607 HasExplicitTemplateArguments = true;
2608 ExplicitTemplateArgs = TemplateIdRef->getTemplateArgs();
2609 NumExplicitTemplateArgs = TemplateIdRef->getNumTemplateArgs();
2610
2611 // C++ [temp.arg.explicit]p6:
2612 // [Note: For simple function names, argument dependent lookup (3.4.2)
2613 // applies even when the function name is not visible within the
2614 // scope of the call. This is because the call still has the syntactic
2615 // form of a function call (3.4.1). But when a function template with
2616 // explicit template arguments is used, the call does not have the
2617 // correct syntactic form unless there is a function template with
2618 // that name visible at the point of the call. If no such name is
2619 // visible, the call is not syntactically well-formed and
2620 // argument-dependent lookup does not apply. If some such name is
2621 // visible, argument dependent lookup applies and additional function
2622 // templates may be found in other namespaces.
2623 //
2624 // The summary of this paragraph is that, if we get to this point and the
2625 // template-id was not a qualified name, then argument-dependent lookup
2626 // is still possible.
2627 if ((Qualifier = TemplateIdRef->getQualifier())) {
2628 ArgumentDependentLookup = false;
2629 QualifierRange = TemplateIdRef->getQualifierRange();
2630 }
2631 break;
2632 } else {
2633 // Any kind of name that does not refer to a declaration (or
2634 // set of declarations) disables ADL (C++0x [basic.lookup.argdep]p3).
2635 ArgumentDependentLookup = false;
2636 break;
2637 }
2638 }
2639}
2640
Steve Narofff69936d2007-09-16 03:34:24 +00002641/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Reid Spencer5f016e22007-07-11 17:01:13 +00002642/// This provides the location of the left/right parens and a list of comma
2643/// locations.
Sebastian Redl0eb23302009-01-19 00:08:26 +00002644Action::OwningExprResult
2645Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
2646 MultiExprArg args,
Douglas Gregor88a35142008-12-22 05:46:06 +00002647 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Sebastian Redl0eb23302009-01-19 00:08:26 +00002648 unsigned NumArgs = args.size();
Nate Begeman2ef13e52009-08-10 23:49:36 +00002649
2650 // Since this might be a postfix expression, get rid of ParenListExprs.
2651 fn = MaybeConvertParenListExprToParenExpr(S, move(fn));
Mike Stump1eb44332009-09-09 15:08:12 +00002652
Anders Carlssonf1b1d592009-05-01 19:30:39 +00002653 Expr *Fn = fn.takeAs<Expr>();
Sebastian Redl0eb23302009-01-19 00:08:26 +00002654 Expr **Args = reinterpret_cast<Expr**>(args.release());
Chris Lattner74c469f2007-07-21 03:03:59 +00002655 assert(Fn && "no function call expression");
Chris Lattner04421082008-04-08 04:40:51 +00002656 FunctionDecl *FDecl = NULL;
Fariborz Jahaniandaf04152009-05-15 20:33:25 +00002657 NamedDecl *NDecl = NULL;
Douglas Gregor17330012009-02-04 15:01:18 +00002658 DeclarationName UnqualifiedName;
Mike Stump1eb44332009-09-09 15:08:12 +00002659
Douglas Gregor88a35142008-12-22 05:46:06 +00002660 if (getLangOptions().CPlusPlus) {
Douglas Gregora71d8192009-09-04 17:36:40 +00002661 // If this is a pseudo-destructor expression, build the call immediately.
2662 if (isa<CXXPseudoDestructorExpr>(Fn)) {
2663 if (NumArgs > 0) {
2664 // Pseudo-destructor calls should not have any arguments.
2665 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
2666 << CodeModificationHint::CreateRemoval(
2667 SourceRange(Args[0]->getLocStart(),
2668 Args[NumArgs-1]->getLocEnd()));
Mike Stump1eb44332009-09-09 15:08:12 +00002669
Douglas Gregora71d8192009-09-04 17:36:40 +00002670 for (unsigned I = 0; I != NumArgs; ++I)
2671 Args[I]->Destroy(Context);
Mike Stump1eb44332009-09-09 15:08:12 +00002672
Douglas Gregora71d8192009-09-04 17:36:40 +00002673 NumArgs = 0;
2674 }
Mike Stump1eb44332009-09-09 15:08:12 +00002675
Douglas Gregora71d8192009-09-04 17:36:40 +00002676 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
2677 RParenLoc));
2678 }
Mike Stump1eb44332009-09-09 15:08:12 +00002679
Douglas Gregor17330012009-02-04 15:01:18 +00002680 // Determine whether this is a dependent call inside a C++ template,
Mike Stumpeed9cac2009-02-19 03:04:26 +00002681 // in which case we won't do any semantic analysis now.
Mike Stump390b4cc2009-05-16 07:39:55 +00002682 // FIXME: Will need to cache the results of name lookup (including ADL) in
2683 // Fn.
Douglas Gregor17330012009-02-04 15:01:18 +00002684 bool Dependent = false;
2685 if (Fn->isTypeDependent())
2686 Dependent = true;
2687 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
2688 Dependent = true;
2689
2690 if (Dependent)
Ted Kremenek668bf912009-02-09 20:51:47 +00002691 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
Douglas Gregor17330012009-02-04 15:01:18 +00002692 Context.DependentTy, RParenLoc));
2693
2694 // Determine whether this is a call to an object (C++ [over.call.object]).
2695 if (Fn->getType()->isRecordType())
2696 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
2697 CommaLocs, RParenLoc));
2698
Douglas Gregorfa047642009-02-04 00:32:51 +00002699 // Determine whether this is a call to a member function.
Douglas Gregore53060f2009-06-25 22:08:12 +00002700 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(Fn->IgnoreParens())) {
2701 NamedDecl *MemDecl = MemExpr->getMemberDecl();
2702 if (isa<OverloadedFunctionDecl>(MemDecl) ||
2703 isa<CXXMethodDecl>(MemDecl) ||
2704 (isa<FunctionTemplateDecl>(MemDecl) &&
2705 isa<CXXMethodDecl>(
2706 cast<FunctionTemplateDecl>(MemDecl)->getTemplatedDecl())))
Sebastian Redl0eb23302009-01-19 00:08:26 +00002707 return Owned(BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
2708 CommaLocs, RParenLoc));
Douglas Gregore53060f2009-06-25 22:08:12 +00002709 }
Anders Carlsson83ccfc32009-10-03 17:40:22 +00002710
2711 // Determine whether this is a call to a pointer-to-member function.
2712 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Fn->IgnoreParens())) {
2713 if (BO->getOpcode() == BinaryOperator::PtrMemD ||
2714 BO->getOpcode() == BinaryOperator::PtrMemI) {
Fariborz Jahanian5de24502009-10-28 16:49:46 +00002715 if (const FunctionProtoType *FPT =
2716 dyn_cast<FunctionProtoType>(BO->getType())) {
2717 QualType ResultTy = FPT->getResultType().getNonReferenceType();
Anders Carlsson83ccfc32009-10-03 17:40:22 +00002718
Fariborz Jahanian5de24502009-10-28 16:49:46 +00002719 ExprOwningPtr<CXXMemberCallExpr>
2720 TheCall(this, new (Context) CXXMemberCallExpr(Context, BO, Args,
2721 NumArgs, ResultTy,
2722 RParenLoc));
Anders Carlsson83ccfc32009-10-03 17:40:22 +00002723
Fariborz Jahanian5de24502009-10-28 16:49:46 +00002724 if (CheckCallReturnType(FPT->getResultType(),
2725 BO->getRHS()->getSourceRange().getBegin(),
2726 TheCall.get(), 0))
2727 return ExprError();
Anders Carlsson8d6d90d2009-10-15 00:41:48 +00002728
Fariborz Jahanian5de24502009-10-28 16:49:46 +00002729 if (ConvertArgumentsForCall(&*TheCall, BO, 0, FPT, Args, NumArgs,
2730 RParenLoc))
2731 return ExprError();
Anders Carlsson83ccfc32009-10-03 17:40:22 +00002732
Fariborz Jahanian5de24502009-10-28 16:49:46 +00002733 return Owned(MaybeBindToTemporary(TheCall.release()).release());
2734 }
2735 return ExprError(Diag(Fn->getLocStart(),
2736 diag::err_typecheck_call_not_function)
2737 << Fn->getType() << Fn->getSourceRange());
Anders Carlsson83ccfc32009-10-03 17:40:22 +00002738 }
2739 }
Douglas Gregor88a35142008-12-22 05:46:06 +00002740 }
2741
Douglas Gregorfa047642009-02-04 00:32:51 +00002742 // If we're directly calling a function, get the appropriate declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00002743 // Also, in C++, keep track of whether we should perform argument-dependent
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002744 // lookup and whether there were any explicitly-specified template arguments.
Douglas Gregorfa047642009-02-04 00:32:51 +00002745 bool ADL = true;
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002746 bool HasExplicitTemplateArgs = 0;
John McCall833ca992009-10-29 08:12:44 +00002747 const TemplateArgumentLoc *ExplicitTemplateArgs = 0;
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002748 unsigned NumExplicitTemplateArgs = 0;
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002749 NestedNameSpecifier *Qualifier = 0;
2750 SourceRange QualifierRange;
2751 DeconstructCallFunction(Fn, NDecl, UnqualifiedName, Qualifier, QualifierRange,
2752 ADL,HasExplicitTemplateArgs, ExplicitTemplateArgs,
2753 NumExplicitTemplateArgs);
Mike Stumpeed9cac2009-02-19 03:04:26 +00002754
Douglas Gregor17330012009-02-04 15:01:18 +00002755 OverloadedFunctionDecl *Ovl = 0;
Douglas Gregore53060f2009-06-25 22:08:12 +00002756 FunctionTemplateDecl *FunctionTemplate = 0;
Douglas Gregoredce4dd2009-06-30 22:34:41 +00002757 if (NDecl) {
2758 FDecl = dyn_cast<FunctionDecl>(NDecl);
2759 if ((FunctionTemplate = dyn_cast<FunctionTemplateDecl>(NDecl)))
Douglas Gregore53060f2009-06-25 22:08:12 +00002760 FDecl = FunctionTemplate->getTemplatedDecl();
2761 else
Douglas Gregoredce4dd2009-06-30 22:34:41 +00002762 FDecl = dyn_cast<FunctionDecl>(NDecl);
2763 Ovl = dyn_cast<OverloadedFunctionDecl>(NDecl);
Douglas Gregor17330012009-02-04 15:01:18 +00002764 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002765
Mike Stump1eb44332009-09-09 15:08:12 +00002766 if (Ovl || FunctionTemplate ||
Douglas Gregore53060f2009-06-25 22:08:12 +00002767 (getLangOptions().CPlusPlus && (FDecl || UnqualifiedName))) {
Douglas Gregor3e41d602009-02-13 23:20:09 +00002768 // We don't perform ADL for implicit declarations of builtins.
Douglas Gregor7814e6d2009-09-12 00:22:50 +00002769 if (FDecl && FDecl->getBuiltinID() && FDecl->isImplicit())
Douglas Gregorfa047642009-02-04 00:32:51 +00002770 ADL = false;
2771
Douglas Gregorf9201e02009-02-11 23:02:49 +00002772 // We don't perform ADL in C.
2773 if (!getLangOptions().CPlusPlus)
2774 ADL = false;
2775
Douglas Gregore53060f2009-06-25 22:08:12 +00002776 if (Ovl || FunctionTemplate || ADL) {
Mike Stump1eb44332009-09-09 15:08:12 +00002777 FDecl = ResolveOverloadedCallFn(Fn, NDecl, UnqualifiedName,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002778 HasExplicitTemplateArgs,
2779 ExplicitTemplateArgs,
2780 NumExplicitTemplateArgs,
Mike Stump1eb44332009-09-09 15:08:12 +00002781 LParenLoc, Args, NumArgs, CommaLocs,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002782 RParenLoc, ADL);
Douglas Gregorfa047642009-02-04 00:32:51 +00002783 if (!FDecl)
2784 return ExprError();
2785
Douglas Gregor097bfb12009-10-23 22:18:25 +00002786 Fn = FixOverloadedFunctionReference(Fn, FDecl);
Douglas Gregorfa047642009-02-04 00:32:51 +00002787 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002788 }
Chris Lattner04421082008-04-08 04:40:51 +00002789
2790 // Promote the function operand.
2791 UsualUnaryConversions(Fn);
2792
Chris Lattner925e60d2007-12-28 05:29:59 +00002793 // Make the call expr early, before semantic checks. This guarantees cleanup
2794 // of arguments and function on error.
Ted Kremenek668bf912009-02-09 20:51:47 +00002795 ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
2796 Args, NumArgs,
2797 Context.BoolTy,
2798 RParenLoc));
Sebastian Redl0eb23302009-01-19 00:08:26 +00002799
Steve Naroffdd972f22008-09-05 22:11:13 +00002800 const FunctionType *FuncT;
2801 if (!Fn->getType()->isBlockPointerType()) {
2802 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
2803 // have type pointer to function".
Ted Kremenek6217b802009-07-29 21:53:49 +00002804 const PointerType *PT = Fn->getType()->getAs<PointerType>();
Steve Naroffdd972f22008-09-05 22:11:13 +00002805 if (PT == 0)
Sebastian Redl0eb23302009-01-19 00:08:26 +00002806 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2807 << Fn->getType() << Fn->getSourceRange());
John McCall183700f2009-09-21 23:43:11 +00002808 FuncT = PT->getPointeeType()->getAs<FunctionType>();
Steve Naroffdd972f22008-09-05 22:11:13 +00002809 } else { // This is a block call.
Ted Kremenek6217b802009-07-29 21:53:49 +00002810 FuncT = Fn->getType()->getAs<BlockPointerType>()->getPointeeType()->
John McCall183700f2009-09-21 23:43:11 +00002811 getAs<FunctionType>();
Steve Naroffdd972f22008-09-05 22:11:13 +00002812 }
Chris Lattner925e60d2007-12-28 05:29:59 +00002813 if (FuncT == 0)
Sebastian Redl0eb23302009-01-19 00:08:26 +00002814 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2815 << Fn->getType() << Fn->getSourceRange());
2816
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00002817 // Check for a valid return type
Anders Carlsson8c8d9192009-10-09 23:51:55 +00002818 if (CheckCallReturnType(FuncT->getResultType(),
2819 Fn->getSourceRange().getBegin(), TheCall.get(),
2820 FDecl))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00002821 return ExprError();
2822
Chris Lattner925e60d2007-12-28 05:29:59 +00002823 // We know the result type of the call, set it.
Douglas Gregor15da57e2008-10-29 02:00:59 +00002824 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Sebastian Redl0eb23302009-01-19 00:08:26 +00002825
Douglas Gregor72564e72009-02-26 23:50:07 +00002826 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00002827 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00002828 RParenLoc))
Sebastian Redl0eb23302009-01-19 00:08:26 +00002829 return ExprError();
Chris Lattner925e60d2007-12-28 05:29:59 +00002830 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00002831 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redl0eb23302009-01-19 00:08:26 +00002832
Douglas Gregor74734d52009-04-02 15:37:10 +00002833 if (FDecl) {
2834 // Check if we have too few/too many template arguments, based
2835 // on our knowledge of the function definition.
2836 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00002837 if (FDecl->getBody(Def) && NumArgs != Def->param_size()) {
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00002838 const FunctionProtoType *Proto =
John McCall183700f2009-09-21 23:43:11 +00002839 Def->getType()->getAs<FunctionProtoType>();
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00002840 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size())) {
2841 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
2842 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
2843 }
2844 }
Douglas Gregor74734d52009-04-02 15:37:10 +00002845 }
2846
Steve Naroffb291ab62007-08-28 23:30:39 +00002847 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner925e60d2007-12-28 05:29:59 +00002848 for (unsigned i = 0; i != NumArgs; i++) {
2849 Expr *Arg = Args[i];
2850 DefaultArgumentPromotion(Arg);
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00002851 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
2852 Arg->getType(),
Anders Carlssonb7906612009-08-26 23:45:07 +00002853 PDiag(diag::err_call_incomplete_argument)
2854 << Arg->getSourceRange()))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00002855 return ExprError();
Chris Lattner925e60d2007-12-28 05:29:59 +00002856 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +00002857 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002858 }
Chris Lattner925e60d2007-12-28 05:29:59 +00002859
Douglas Gregor88a35142008-12-22 05:46:06 +00002860 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
2861 if (!Method->isStatic())
Sebastian Redl0eb23302009-01-19 00:08:26 +00002862 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
2863 << Fn->getSourceRange());
Douglas Gregor88a35142008-12-22 05:46:06 +00002864
Fariborz Jahaniandaf04152009-05-15 20:33:25 +00002865 // Check for sentinels
2866 if (NDecl)
2867 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00002868
Chris Lattner59907c42007-08-10 20:18:51 +00002869 // Do special checking on direct calls to functions.
Anders Carlssond406bf02009-08-16 01:56:34 +00002870 if (FDecl) {
2871 if (CheckFunctionCall(FDecl, TheCall.get()))
2872 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00002873
Douglas Gregor7814e6d2009-09-12 00:22:50 +00002874 if (unsigned BuiltinID = FDecl->getBuiltinID())
Anders Carlssond406bf02009-08-16 01:56:34 +00002875 return CheckBuiltinFunctionCall(BuiltinID, TheCall.take());
2876 } else if (NDecl) {
2877 if (CheckBlockCall(NDecl, TheCall.get()))
2878 return ExprError();
2879 }
Chris Lattner59907c42007-08-10 20:18:51 +00002880
Anders Carlssonec74c592009-08-16 03:06:32 +00002881 return MaybeBindToTemporary(TheCall.take());
Reid Spencer5f016e22007-07-11 17:01:13 +00002882}
2883
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002884Action::OwningExprResult
2885Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
2886 SourceLocation RParenLoc, ExprArg InitExpr) {
Steve Narofff69936d2007-09-16 03:34:24 +00002887 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00002888 //FIXME: Preserve type source info.
2889 QualType literalType = GetTypeFromParser(Ty);
Steve Naroffaff1edd2007-07-19 21:32:11 +00002890 // FIXME: put back this assert when initializers are worked out.
Steve Narofff69936d2007-09-16 03:34:24 +00002891 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002892 Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
Anders Carlssond35c8322007-12-05 07:24:19 +00002893
Eli Friedman6223c222008-05-20 05:22:08 +00002894 if (literalType->isArrayType()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002895 if (literalType->isVariableArrayType())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002896 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
2897 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor690dc7f2009-05-21 23:48:18 +00002898 } else if (!literalType->isDependentType() &&
2899 RequireCompleteType(LParenLoc, literalType,
Anders Carlssonb7906612009-08-26 23:45:07 +00002900 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump1eb44332009-09-09 15:08:12 +00002901 << SourceRange(LParenLoc,
Anders Carlssonb7906612009-08-26 23:45:07 +00002902 literalExpr->getSourceRange().getEnd())))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002903 return ExprError();
Eli Friedman6223c222008-05-20 05:22:08 +00002904
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002905 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002906 DeclarationName(), /*FIXME:DirectInit=*/false))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002907 return ExprError();
Steve Naroffe9b12192008-01-14 18:19:28 +00002908
Chris Lattner371f2582008-12-04 23:50:19 +00002909 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffe9b12192008-01-14 18:19:28 +00002910 if (isFileScope) { // 6.5.2.5p3
Steve Naroffd0091aa2008-01-10 22:15:12 +00002911 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002912 return ExprError();
Steve Naroffd0091aa2008-01-10 22:15:12 +00002913 }
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002914 InitExpr.release();
Mike Stumpeed9cac2009-02-19 03:04:26 +00002915 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType,
Steve Naroff6ece14c2009-01-21 00:14:39 +00002916 literalExpr, isFileScope));
Steve Naroff4aa88f82007-07-19 01:06:55 +00002917}
2918
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002919Action::OwningExprResult
2920Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002921 SourceLocation RBraceLoc) {
2922 unsigned NumInit = initlist.size();
2923 Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00002924
Steve Naroff08d92e42007-09-15 18:49:24 +00002925 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stumpeed9cac2009-02-19 03:04:26 +00002926 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002927
Mike Stumpeed9cac2009-02-19 03:04:26 +00002928 InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
Douglas Gregor4c678342009-01-28 21:54:33 +00002929 RBraceLoc);
Chris Lattnerf0467b32008-04-02 04:24:33 +00002930 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002931 return Owned(E);
Steve Naroff4aa88f82007-07-19 01:06:55 +00002932}
2933
Anders Carlsson82debc72009-10-18 18:12:03 +00002934static CastExpr::CastKind getScalarCastKind(ASTContext &Context,
2935 QualType SrcTy, QualType DestTy) {
Douglas Gregora4923eb2009-11-16 21:35:15 +00002936 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
Anders Carlsson82debc72009-10-18 18:12:03 +00002937 return CastExpr::CK_NoOp;
2938
2939 if (SrcTy->hasPointerRepresentation()) {
2940 if (DestTy->hasPointerRepresentation())
2941 return CastExpr::CK_BitCast;
2942 if (DestTy->isIntegerType())
2943 return CastExpr::CK_PointerToIntegral;
2944 }
2945
2946 if (SrcTy->isIntegerType()) {
2947 if (DestTy->isIntegerType())
2948 return CastExpr::CK_IntegralCast;
2949 if (DestTy->hasPointerRepresentation())
2950 return CastExpr::CK_IntegralToPointer;
2951 if (DestTy->isRealFloatingType())
2952 return CastExpr::CK_IntegralToFloating;
2953 }
2954
2955 if (SrcTy->isRealFloatingType()) {
2956 if (DestTy->isRealFloatingType())
2957 return CastExpr::CK_FloatingCast;
2958 if (DestTy->isIntegerType())
2959 return CastExpr::CK_FloatingToIntegral;
2960 }
2961
2962 // FIXME: Assert here.
2963 // assert(false && "Unhandled cast combination!");
2964 return CastExpr::CK_Unknown;
2965}
2966
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00002967/// CheckCastTypes - Check type constraints for casting between types.
Sebastian Redlef0cb8e2009-07-29 13:50:23 +00002968bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr,
Mike Stump1eb44332009-09-09 15:08:12 +00002969 CastExpr::CastKind& Kind,
Fariborz Jahaniane9f42082009-08-26 18:55:36 +00002970 CXXMethodDecl *& ConversionDecl,
2971 bool FunctionalStyle) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00002972 if (getLangOptions().CPlusPlus)
Fariborz Jahaniane9f42082009-08-26 18:55:36 +00002973 return CXXCheckCStyleCast(TyR, castType, castExpr, Kind, FunctionalStyle,
2974 ConversionDecl);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00002975
Eli Friedman199ea952009-08-15 19:02:19 +00002976 DefaultFunctionArrayConversion(castExpr);
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00002977
2978 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
2979 // type needs to be scalar.
2980 if (castType->isVoidType()) {
2981 // Cast to void allows any expr type.
Anders Carlssonebeaf202009-10-16 02:35:04 +00002982 Kind = CastExpr::CK_ToVoid;
2983 return false;
2984 }
2985
2986 if (!castType->isScalarType() && !castType->isVectorType()) {
Douglas Gregora4923eb2009-11-16 21:35:15 +00002987 if (Context.hasSameUnqualifiedType(castType, castExpr->getType()) &&
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00002988 (castType->isStructureType() || castType->isUnionType())) {
2989 // GCC struct/union extension: allow cast to self.
Eli Friedmanb1d796d2009-03-23 00:24:07 +00002990 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00002991 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
2992 << castType << castExpr->getSourceRange();
Anders Carlsson4d8673b2009-08-07 23:22:37 +00002993 Kind = CastExpr::CK_NoOp;
Anders Carlssonc3516322009-10-16 02:48:28 +00002994 return false;
2995 }
2996
2997 if (castType->isUnionType()) {
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00002998 // GCC cast to union extension
Ted Kremenek6217b802009-07-29 21:53:49 +00002999 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003000 RecordDecl::field_iterator Field, FieldEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003001 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003002 Field != FieldEnd; ++Field) {
Douglas Gregora4923eb2009-11-16 21:35:15 +00003003 if (Context.hasSameUnqualifiedType(Field->getType(),
3004 castExpr->getType())) {
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003005 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
3006 << castExpr->getSourceRange();
3007 break;
3008 }
3009 }
3010 if (Field == FieldEnd)
3011 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
3012 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlsson4d8673b2009-08-07 23:22:37 +00003013 Kind = CastExpr::CK_ToUnion;
Anders Carlssonc3516322009-10-16 02:48:28 +00003014 return false;
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003015 }
Anders Carlssonc3516322009-10-16 02:48:28 +00003016
3017 // Reject any other conversions to non-scalar types.
3018 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
3019 << castType << castExpr->getSourceRange();
3020 }
3021
3022 if (!castExpr->getType()->isScalarType() &&
3023 !castExpr->getType()->isVectorType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003024 return Diag(castExpr->getLocStart(),
3025 diag::err_typecheck_expect_scalar_operand)
Chris Lattnerd1625842008-11-24 06:25:27 +00003026 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlssonc3516322009-10-16 02:48:28 +00003027 }
3028
Anders Carlsson16a89042009-10-16 05:23:41 +00003029 if (castType->isExtVectorType())
3030 return CheckExtVectorCast(TyR, castType, castExpr, Kind);
3031
Anders Carlssonc3516322009-10-16 02:48:28 +00003032 if (castType->isVectorType())
3033 return CheckVectorCast(TyR, castType, castExpr->getType(), Kind);
3034 if (castExpr->getType()->isVectorType())
3035 return CheckVectorCast(TyR, castExpr->getType(), castType, Kind);
3036
3037 if (getLangOptions().ObjC1 && isa<ObjCSuperExpr>(castExpr))
Steve Naroffa0c3e9c2009-04-08 23:52:26 +00003038 return Diag(castExpr->getLocStart(), diag::err_illegal_super_cast) << TyR;
Anders Carlssonc3516322009-10-16 02:48:28 +00003039
Anders Carlsson16a89042009-10-16 05:23:41 +00003040 if (isa<ObjCSelectorExpr>(castExpr))
3041 return Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
3042
Anders Carlssonc3516322009-10-16 02:48:28 +00003043 if (!castType->isArithmeticType()) {
Eli Friedman41826bb2009-05-01 02:23:58 +00003044 QualType castExprType = castExpr->getType();
3045 if (!castExprType->isIntegralType() && castExprType->isArithmeticType())
3046 return Diag(castExpr->getLocStart(),
3047 diag::err_cast_pointer_from_non_pointer_int)
3048 << castExprType << castExpr->getSourceRange();
3049 } else if (!castExpr->getType()->isArithmeticType()) {
3050 if (!castType->isIntegralType() && castType->isArithmeticType())
3051 return Diag(castExpr->getLocStart(),
3052 diag::err_cast_pointer_to_non_pointer_int)
3053 << castType << castExpr->getSourceRange();
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003054 }
Anders Carlsson82debc72009-10-18 18:12:03 +00003055
3056 Kind = getScalarCastKind(Context, castExpr->getType(), castType);
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003057 return false;
3058}
3059
Anders Carlssonc3516322009-10-16 02:48:28 +00003060bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
3061 CastExpr::CastKind &Kind) {
Anders Carlssona64db8f2007-11-27 05:51:55 +00003062 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00003063
Anders Carlssona64db8f2007-11-27 05:51:55 +00003064 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner98be4942008-03-05 18:54:05 +00003065 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssona64db8f2007-11-27 05:51:55 +00003066 return Diag(R.getBegin(),
Mike Stumpeed9cac2009-02-19 03:04:26 +00003067 Ty->isVectorType() ?
Anders Carlssona64db8f2007-11-27 05:51:55 +00003068 diag::err_invalid_conversion_between_vectors :
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003069 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00003070 << VectorTy << Ty << R;
Anders Carlssona64db8f2007-11-27 05:51:55 +00003071 } else
3072 return Diag(R.getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003073 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattnerd1625842008-11-24 06:25:27 +00003074 << VectorTy << Ty << R;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003075
Anders Carlssonc3516322009-10-16 02:48:28 +00003076 Kind = CastExpr::CK_BitCast;
Anders Carlssona64db8f2007-11-27 05:51:55 +00003077 return false;
3078}
3079
Anders Carlsson16a89042009-10-16 05:23:41 +00003080bool Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *&CastExpr,
3081 CastExpr::CastKind &Kind) {
Nate Begeman58d29a42009-06-26 00:50:28 +00003082 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Anders Carlsson16a89042009-10-16 05:23:41 +00003083
3084 QualType SrcTy = CastExpr->getType();
3085
Nate Begeman9b10da62009-06-27 22:05:55 +00003086 // If SrcTy is a VectorType, the total size must match to explicitly cast to
3087 // an ExtVectorType.
Nate Begeman58d29a42009-06-26 00:50:28 +00003088 if (SrcTy->isVectorType()) {
3089 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
3090 return Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
3091 << DestTy << SrcTy << R;
Anders Carlsson16a89042009-10-16 05:23:41 +00003092 Kind = CastExpr::CK_BitCast;
Nate Begeman58d29a42009-06-26 00:50:28 +00003093 return false;
3094 }
3095
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00003096 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begeman58d29a42009-06-26 00:50:28 +00003097 // conversion will take place first from scalar to elt type, and then
3098 // splat from elt type to vector.
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00003099 if (SrcTy->isPointerType())
3100 return Diag(R.getBegin(),
3101 diag::err_invalid_conversion_between_vector_and_scalar)
3102 << DestTy << SrcTy << R;
Eli Friedman73c39ab2009-10-20 08:27:19 +00003103
3104 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
3105 ImpCastExprToType(CastExpr, DestElemTy,
3106 getScalarCastKind(Context, SrcTy, DestElemTy));
Anders Carlsson16a89042009-10-16 05:23:41 +00003107
3108 Kind = CastExpr::CK_VectorSplat;
Nate Begeman58d29a42009-06-26 00:50:28 +00003109 return false;
3110}
3111
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003112Action::OwningExprResult
Nate Begeman2ef13e52009-08-10 23:49:36 +00003113Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, TypeTy *Ty,
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003114 SourceLocation RParenLoc, ExprArg Op) {
Anders Carlssoncdb61972009-08-07 22:21:05 +00003115 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Mike Stump1eb44332009-09-09 15:08:12 +00003116
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003117 assert((Ty != 0) && (Op.get() != 0) &&
3118 "ActOnCastExpr(): missing type or expr");
Steve Naroff16beff82007-07-16 23:25:18 +00003119
Nate Begeman2ef13e52009-08-10 23:49:36 +00003120 Expr *castExpr = (Expr *)Op.get();
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00003121 //FIXME: Preserve type source info.
3122 QualType castType = GetTypeFromParser(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00003123
Nate Begeman2ef13e52009-08-10 23:49:36 +00003124 // If the Expr being casted is a ParenListExpr, handle it specially.
3125 if (isa<ParenListExpr>(castExpr))
3126 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, move(Op),castType);
Anders Carlsson0aebc812009-09-09 21:33:21 +00003127 CXXMethodDecl *Method = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003128 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr,
Anders Carlsson0aebc812009-09-09 21:33:21 +00003129 Kind, Method))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003130 return ExprError();
Anders Carlsson0aebc812009-09-09 21:33:21 +00003131
3132 if (Method) {
Daniel Dunbar7e88a602009-09-17 06:31:17 +00003133 OwningExprResult CastArg = BuildCXXCastArgument(LParenLoc, castType, Kind,
Anders Carlsson0aebc812009-09-09 21:33:21 +00003134 Method, move(Op));
Daniel Dunbar7e88a602009-09-17 06:31:17 +00003135
Anders Carlsson0aebc812009-09-09 21:33:21 +00003136 if (CastArg.isInvalid())
3137 return ExprError();
Daniel Dunbar7e88a602009-09-17 06:31:17 +00003138
Anders Carlsson0aebc812009-09-09 21:33:21 +00003139 castExpr = CastArg.takeAs<Expr>();
3140 } else {
3141 Op.release();
Fariborz Jahanian31976592009-08-29 19:15:16 +00003142 }
Mike Stump1eb44332009-09-09 15:08:12 +00003143
Sebastian Redl9cc11e72009-07-25 15:41:38 +00003144 return Owned(new (Context) CStyleCastExpr(castType.getNonReferenceType(),
Mike Stump1eb44332009-09-09 15:08:12 +00003145 Kind, castExpr, castType,
Anders Carlssoncdb61972009-08-07 22:21:05 +00003146 LParenLoc, RParenLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00003147}
3148
Nate Begeman2ef13e52009-08-10 23:49:36 +00003149/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
3150/// of comma binary operators.
3151Action::OwningExprResult
3152Sema::MaybeConvertParenListExprToParenExpr(Scope *S, ExprArg EA) {
3153 Expr *expr = EA.takeAs<Expr>();
3154 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
3155 if (!E)
3156 return Owned(expr);
Mike Stump1eb44332009-09-09 15:08:12 +00003157
Nate Begeman2ef13e52009-08-10 23:49:36 +00003158 OwningExprResult Result(*this, E->getExpr(0));
Mike Stump1eb44332009-09-09 15:08:12 +00003159
Nate Begeman2ef13e52009-08-10 23:49:36 +00003160 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
3161 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, move(Result),
3162 Owned(E->getExpr(i)));
Mike Stump1eb44332009-09-09 15:08:12 +00003163
Nate Begeman2ef13e52009-08-10 23:49:36 +00003164 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), move(Result));
3165}
3166
3167Action::OwningExprResult
3168Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
3169 SourceLocation RParenLoc, ExprArg Op,
3170 QualType Ty) {
3171 ParenListExpr *PE = (ParenListExpr *)Op.get();
Mike Stump1eb44332009-09-09 15:08:12 +00003172
3173 // If this is an altivec initializer, '(' type ')' '(' init, ..., init ')'
Nate Begeman2ef13e52009-08-10 23:49:36 +00003174 // then handle it as such.
3175 if (getLangOptions().AltiVec && Ty->isVectorType()) {
3176 if (PE->getNumExprs() == 0) {
3177 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
3178 return ExprError();
3179 }
3180
3181 llvm::SmallVector<Expr *, 8> initExprs;
3182 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
3183 initExprs.push_back(PE->getExpr(i));
3184
3185 // FIXME: This means that pretty-printing the final AST will produce curly
3186 // braces instead of the original commas.
3187 Op.release();
Mike Stump1eb44332009-09-09 15:08:12 +00003188 InitListExpr *E = new (Context) InitListExpr(LParenLoc, &initExprs[0],
Nate Begeman2ef13e52009-08-10 23:49:36 +00003189 initExprs.size(), RParenLoc);
3190 E->setType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00003191 return ActOnCompoundLiteral(LParenLoc, Ty.getAsOpaquePtr(), RParenLoc,
Nate Begeman2ef13e52009-08-10 23:49:36 +00003192 Owned(E));
3193 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00003194 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
Nate Begeman2ef13e52009-08-10 23:49:36 +00003195 // sequence of BinOp comma operators.
3196 Op = MaybeConvertParenListExprToParenExpr(S, move(Op));
3197 return ActOnCastExpr(S, LParenLoc, Ty.getAsOpaquePtr(), RParenLoc,move(Op));
3198 }
3199}
3200
3201Action::OwningExprResult Sema::ActOnParenListExpr(SourceLocation L,
3202 SourceLocation R,
3203 MultiExprArg Val) {
3204 unsigned nexprs = Val.size();
3205 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
3206 assert((exprs != 0) && "ActOnParenListExpr() missing expr list");
3207 Expr *expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
3208 return Owned(expr);
3209}
3210
Sebastian Redl28507842009-02-26 14:39:58 +00003211/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
3212/// In that case, lhs = cond.
Chris Lattnera119a3b2009-02-18 04:38:20 +00003213/// C99 6.5.15
3214QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
3215 SourceLocation QuestionLoc) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003216 // C++ is sufficiently different to merit its own checker.
3217 if (getLangOptions().CPlusPlus)
3218 return CXXCheckConditionalOperands(Cond, LHS, RHS, QuestionLoc);
3219
John McCallb13c87f2009-11-05 09:23:39 +00003220 CheckSignCompare(LHS, RHS, QuestionLoc, diag::warn_mixed_sign_conditional);
3221
Chris Lattnerefdc39d2009-02-18 04:28:32 +00003222 UsualUnaryConversions(Cond);
3223 UsualUnaryConversions(LHS);
3224 UsualUnaryConversions(RHS);
3225 QualType CondTy = Cond->getType();
3226 QualType LHSTy = LHS->getType();
3227 QualType RHSTy = RHS->getType();
Steve Naroffc80b4ee2007-07-16 21:54:35 +00003228
Reid Spencer5f016e22007-07-11 17:01:13 +00003229 // first, check the condition.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003230 if (!CondTy->isScalarType()) { // C99 6.5.15p2
3231 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
3232 << CondTy;
3233 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003234 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003235
Chris Lattner70d67a92008-01-06 22:42:25 +00003236 // Now check the two expressions.
Nate Begeman2ef13e52009-08-10 23:49:36 +00003237 if (LHSTy->isVectorType() || RHSTy->isVectorType())
3238 return CheckVectorOperands(QuestionLoc, LHS, RHS);
Douglas Gregor898574e2008-12-05 23:32:09 +00003239
Chris Lattner70d67a92008-01-06 22:42:25 +00003240 // If both operands have arithmetic type, do the usual arithmetic conversions
3241 // to find a common type: C99 6.5.15p3,5.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00003242 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
3243 UsualArithmeticConversions(LHS, RHS);
3244 return LHS->getType();
Steve Naroffa4332e22007-07-17 00:58:39 +00003245 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003246
Chris Lattner70d67a92008-01-06 22:42:25 +00003247 // If both operands are the same structure or union type, the result is that
3248 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00003249 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
3250 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattnera21ddb32007-11-26 01:40:58 +00003251 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stumpeed9cac2009-02-19 03:04:26 +00003252 // "If both the operands have structure or union type, the result has
Chris Lattner70d67a92008-01-06 22:42:25 +00003253 // that type." This implies that CV qualifiers are dropped.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00003254 return LHSTy.getUnqualifiedType();
Eli Friedmanb1d796d2009-03-23 00:24:07 +00003255 // FIXME: Type of conditional expression must be complete in C mode.
Reid Spencer5f016e22007-07-11 17:01:13 +00003256 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003257
Chris Lattner70d67a92008-01-06 22:42:25 +00003258 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffe701c0a2008-05-12 21:44:38 +00003259 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnerefdc39d2009-02-18 04:28:32 +00003260 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
3261 if (!LHSTy->isVoidType())
3262 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
3263 << RHS->getSourceRange();
3264 if (!RHSTy->isVoidType())
3265 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
3266 << LHS->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00003267 ImpCastExprToType(LHS, Context.VoidTy, CastExpr::CK_ToVoid);
3268 ImpCastExprToType(RHS, Context.VoidTy, CastExpr::CK_ToVoid);
Eli Friedman0e724012008-06-04 19:47:51 +00003269 return Context.VoidTy;
Steve Naroffe701c0a2008-05-12 21:44:38 +00003270 }
Steve Naroffb6d54e52008-01-08 01:11:38 +00003271 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
3272 // the type of the other operand."
Steve Naroff58f9f2c2009-07-14 18:25:06 +00003273 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
Douglas Gregorce940492009-09-25 04:25:58 +00003274 RHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003275 // promote the null to a pointer.
3276 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_Unknown);
Chris Lattnerefdc39d2009-02-18 04:28:32 +00003277 return LHSTy;
Steve Naroffb6d54e52008-01-08 01:11:38 +00003278 }
Steve Naroff58f9f2c2009-07-14 18:25:06 +00003279 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
Douglas Gregorce940492009-09-25 04:25:58 +00003280 LHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003281 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_Unknown);
Chris Lattnerefdc39d2009-02-18 04:28:32 +00003282 return RHSTy;
Steve Naroffb6d54e52008-01-08 01:11:38 +00003283 }
David Chisnall0f436562009-08-17 16:35:33 +00003284 // Handle things like Class and struct objc_class*. Here we case the result
3285 // to the pseudo-builtin, because that will be implicitly cast back to the
3286 // redefinition type if an attempt is made to access its fields.
3287 if (LHSTy->isObjCClassType() &&
3288 (RHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003289 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
David Chisnall0f436562009-08-17 16:35:33 +00003290 return LHSTy;
3291 }
3292 if (RHSTy->isObjCClassType() &&
3293 (LHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003294 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
David Chisnall0f436562009-08-17 16:35:33 +00003295 return RHSTy;
3296 }
3297 // And the same for struct objc_object* / id
3298 if (LHSTy->isObjCIdType() &&
3299 (RHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003300 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
David Chisnall0f436562009-08-17 16:35:33 +00003301 return LHSTy;
3302 }
3303 if (RHSTy->isObjCIdType() &&
3304 (LHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003305 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
David Chisnall0f436562009-08-17 16:35:33 +00003306 return RHSTy;
3307 }
Steve Naroff7154a772009-07-01 14:36:47 +00003308 // Handle block pointer types.
3309 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
3310 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
3311 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
3312 QualType destType = Context.getPointerType(Context.VoidTy);
Eli Friedman73c39ab2009-10-20 08:27:19 +00003313 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
3314 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00003315 return destType;
3316 }
3317 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3318 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3319 return QualType();
Mike Stumpdd3e1662009-05-07 03:14:14 +00003320 }
Steve Naroff7154a772009-07-01 14:36:47 +00003321 // We have 2 block pointer types.
3322 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3323 // Two identical block pointer types are always compatible.
Mike Stumpdd3e1662009-05-07 03:14:14 +00003324 return LHSTy;
3325 }
Steve Naroff7154a772009-07-01 14:36:47 +00003326 // The block pointer types aren't identical, continue checking.
Ted Kremenek6217b802009-07-29 21:53:49 +00003327 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
3328 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00003329
Steve Naroff7154a772009-07-01 14:36:47 +00003330 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
3331 rhptee.getUnqualifiedType())) {
Mike Stumpdd3e1662009-05-07 03:14:14 +00003332 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
3333 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3334 // In this situation, we assume void* type. No especially good
3335 // reason, but this is what gcc does, and we do have to pick
3336 // to get a consistent AST.
3337 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Eli Friedman73c39ab2009-10-20 08:27:19 +00003338 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
3339 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
Mike Stumpdd3e1662009-05-07 03:14:14 +00003340 return incompatTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00003341 }
Steve Naroff7154a772009-07-01 14:36:47 +00003342 // The block pointer types are compatible.
Eli Friedman73c39ab2009-10-20 08:27:19 +00003343 ImpCastExprToType(LHS, LHSTy, CastExpr::CK_BitCast);
3344 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
Steve Naroff91588042009-04-08 17:05:15 +00003345 return LHSTy;
3346 }
Steve Naroff7154a772009-07-01 14:36:47 +00003347 // Check constraints for Objective-C object pointers types.
Steve Naroff14108da2009-07-10 23:34:53 +00003348 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003349
Steve Naroff7154a772009-07-01 14:36:47 +00003350 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3351 // Two identical object pointer types are always compatible.
3352 return LHSTy;
3353 }
John McCall183700f2009-09-21 23:43:11 +00003354 const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>();
3355 const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>();
Steve Naroff7154a772009-07-01 14:36:47 +00003356 QualType compositeType = LHSTy;
Mike Stump1eb44332009-09-09 15:08:12 +00003357
Steve Naroff7154a772009-07-01 14:36:47 +00003358 // If both operands are interfaces and either operand can be
3359 // assigned to the other, use that type as the composite
3360 // type. This allows
3361 // xxx ? (A*) a : (B*) b
3362 // where B is a subclass of A.
3363 //
3364 // Additionally, as for assignment, if either type is 'id'
3365 // allow silent coercion. Finally, if the types are
3366 // incompatible then make sure to use 'id' as the composite
3367 // type so the result is acceptable for sending messages to.
3368
3369 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
3370 // It could return the composite type.
Steve Naroff14108da2009-07-10 23:34:53 +00003371 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
Fariborz Jahanian9ec22a32009-08-22 22:27:17 +00003372 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
Steve Naroff14108da2009-07-10 23:34:53 +00003373 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
Fariborz Jahanian9ec22a32009-08-22 22:27:17 +00003374 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
Mike Stump1eb44332009-09-09 15:08:12 +00003375 } else if ((LHSTy->isObjCQualifiedIdType() ||
Steve Naroff14108da2009-07-10 23:34:53 +00003376 RHSTy->isObjCQualifiedIdType()) &&
Steve Naroff4084c302009-07-23 01:01:38 +00003377 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003378 // Need to handle "id<xx>" explicitly.
Steve Naroff14108da2009-07-10 23:34:53 +00003379 // GCC allows qualified id and any Objective-C type to devolve to
3380 // id. Currently localizing to here until clear this should be
3381 // part of ObjCQualifiedIdTypesAreCompatible.
3382 compositeType = Context.getObjCIdType();
3383 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
Steve Naroff7154a772009-07-01 14:36:47 +00003384 compositeType = Context.getObjCIdType();
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00003385 } else if (!(compositeType =
3386 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
3387 ;
3388 else {
Steve Naroff7154a772009-07-01 14:36:47 +00003389 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
3390 << LHSTy << RHSTy
3391 << LHS->getSourceRange() << RHS->getSourceRange();
3392 QualType incompatTy = Context.getObjCIdType();
Eli Friedman73c39ab2009-10-20 08:27:19 +00003393 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
3394 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00003395 return incompatTy;
3396 }
3397 // The object pointer types are compatible.
Eli Friedman73c39ab2009-10-20 08:27:19 +00003398 ImpCastExprToType(LHS, compositeType, CastExpr::CK_BitCast);
3399 ImpCastExprToType(RHS, compositeType, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00003400 return compositeType;
3401 }
Steve Naroffc715e782009-07-29 15:09:39 +00003402 // Check Objective-C object pointer types and 'void *'
3403 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003404 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
John McCall183700f2009-09-21 23:43:11 +00003405 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00003406 QualType destPointee
3407 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
Steve Naroffc715e782009-07-29 15:09:39 +00003408 QualType destType = Context.getPointerType(destPointee);
Eli Friedman73c39ab2009-10-20 08:27:19 +00003409 // Add qualifiers if necessary.
3410 ImpCastExprToType(LHS, destType, CastExpr::CK_NoOp);
3411 // Promote to void*.
3412 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
Steve Naroffc715e782009-07-29 15:09:39 +00003413 return destType;
3414 }
3415 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
John McCall183700f2009-09-21 23:43:11 +00003416 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003417 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00003418 QualType destPointee
3419 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
Steve Naroffc715e782009-07-29 15:09:39 +00003420 QualType destType = Context.getPointerType(destPointee);
Eli Friedman73c39ab2009-10-20 08:27:19 +00003421 // Add qualifiers if necessary.
3422 ImpCastExprToType(RHS, destType, CastExpr::CK_NoOp);
3423 // Promote to void*.
3424 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
Steve Naroffc715e782009-07-29 15:09:39 +00003425 return destType;
3426 }
Steve Naroff7154a772009-07-01 14:36:47 +00003427 // Check constraints for C object pointers types (C99 6.5.15p3,6).
3428 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
3429 // get the "pointed to" types
Ted Kremenek6217b802009-07-29 21:53:49 +00003430 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
3431 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff7154a772009-07-01 14:36:47 +00003432
3433 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
3434 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
3435 // Figure out necessary qualifiers (C99 6.5.15p6)
John McCall0953e762009-09-24 19:53:00 +00003436 QualType destPointee
3437 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
Steve Naroff7154a772009-07-01 14:36:47 +00003438 QualType destType = Context.getPointerType(destPointee);
Eli Friedman73c39ab2009-10-20 08:27:19 +00003439 // Add qualifiers if necessary.
3440 ImpCastExprToType(LHS, destType, CastExpr::CK_NoOp);
3441 // Promote to void*.
3442 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00003443 return destType;
3444 }
3445 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
John McCall0953e762009-09-24 19:53:00 +00003446 QualType destPointee
3447 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
Steve Naroff7154a772009-07-01 14:36:47 +00003448 QualType destType = Context.getPointerType(destPointee);
Eli Friedman73c39ab2009-10-20 08:27:19 +00003449 // Add qualifiers if necessary.
Eli Friedman16fea9b2009-11-17 01:22:05 +00003450 ImpCastExprToType(RHS, destType, CastExpr::CK_NoOp);
Eli Friedman73c39ab2009-10-20 08:27:19 +00003451 // Promote to void*.
Eli Friedman16fea9b2009-11-17 01:22:05 +00003452 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00003453 return destType;
3454 }
3455
3456 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3457 // Two identical pointer types are always compatible.
3458 return LHSTy;
3459 }
3460 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
3461 rhptee.getUnqualifiedType())) {
3462 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
3463 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3464 // In this situation, we assume void* type. No especially good
3465 // reason, but this is what gcc does, and we do have to pick
3466 // to get a consistent AST.
3467 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Eli Friedman73c39ab2009-10-20 08:27:19 +00003468 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
3469 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00003470 return incompatTy;
3471 }
3472 // The pointer types are compatible.
3473 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
3474 // differently qualified versions of compatible types, the result type is
3475 // a pointer to an appropriately qualified version of the *composite*
3476 // type.
3477 // FIXME: Need to calculate the composite type.
3478 // FIXME: Need to add qualifiers
Eli Friedman73c39ab2009-10-20 08:27:19 +00003479 ImpCastExprToType(LHS, LHSTy, CastExpr::CK_BitCast);
3480 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00003481 return LHSTy;
3482 }
Mike Stump1eb44332009-09-09 15:08:12 +00003483
Steve Naroff7154a772009-07-01 14:36:47 +00003484 // GCC compatibility: soften pointer/integer mismatch.
3485 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
3486 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
3487 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00003488 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_IntegralToPointer);
Steve Naroff7154a772009-07-01 14:36:47 +00003489 return RHSTy;
3490 }
3491 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
3492 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
3493 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00003494 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_IntegralToPointer);
Steve Naroff7154a772009-07-01 14:36:47 +00003495 return LHSTy;
3496 }
Daniel Dunbar5e155f02008-09-11 23:12:46 +00003497
Chris Lattner70d67a92008-01-06 22:42:25 +00003498 // Otherwise, the operands are not compatible.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00003499 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3500 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00003501 return QualType();
3502}
3503
Steve Narofff69936d2007-09-16 03:34:24 +00003504/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Reid Spencer5f016e22007-07-11 17:01:13 +00003505/// in the case of a the GNU conditional expr extension.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003506Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
3507 SourceLocation ColonLoc,
3508 ExprArg Cond, ExprArg LHS,
3509 ExprArg RHS) {
3510 Expr *CondExpr = (Expr *) Cond.get();
3511 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
Chris Lattnera21ddb32007-11-26 01:40:58 +00003512
3513 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
3514 // was the condition.
3515 bool isLHSNull = LHSExpr == 0;
3516 if (isLHSNull)
3517 LHSExpr = CondExpr;
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003518
3519 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
Chris Lattner26824902007-07-16 21:39:03 +00003520 RHSExpr, QuestionLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00003521 if (result.isNull())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003522 return ExprError();
3523
3524 Cond.release();
3525 LHS.release();
3526 RHS.release();
Douglas Gregor47e1f7c2009-08-26 14:37:04 +00003527 return Owned(new (Context) ConditionalOperator(CondExpr, QuestionLoc,
Steve Naroff6ece14c2009-01-21 00:14:39 +00003528 isLHSNull ? 0 : LHSExpr,
Douglas Gregor47e1f7c2009-08-26 14:37:04 +00003529 ColonLoc, RHSExpr, result));
Reid Spencer5f016e22007-07-11 17:01:13 +00003530}
3531
Reid Spencer5f016e22007-07-11 17:01:13 +00003532// CheckPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stumpeed9cac2009-02-19 03:04:26 +00003533// being closely modeled after the C99 spec:-). The odd characteristic of this
Reid Spencer5f016e22007-07-11 17:01:13 +00003534// routine is it effectively iqnores the qualifiers on the top level pointee.
3535// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
3536// FIXME: add a couple examples in this comment.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003537Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00003538Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
3539 QualType lhptee, rhptee;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003540
David Chisnall0f436562009-08-17 16:35:33 +00003541 if ((lhsType->isObjCClassType() &&
3542 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
3543 (rhsType->isObjCClassType() &&
3544 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
3545 return Compatible;
3546 }
3547
Reid Spencer5f016e22007-07-11 17:01:13 +00003548 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenek6217b802009-07-29 21:53:49 +00003549 lhptee = lhsType->getAs<PointerType>()->getPointeeType();
3550 rhptee = rhsType->getAs<PointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00003551
Reid Spencer5f016e22007-07-11 17:01:13 +00003552 // make sure we operate on the canonical type
Chris Lattnerb77792e2008-07-26 22:17:49 +00003553 lhptee = Context.getCanonicalType(lhptee);
3554 rhptee = Context.getCanonicalType(rhptee);
Reid Spencer5f016e22007-07-11 17:01:13 +00003555
Chris Lattner5cf216b2008-01-04 18:04:52 +00003556 AssignConvertType ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003557
3558 // C99 6.5.16.1p1: This following citation is common to constraints
3559 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
3560 // qualifiers of the type *pointed to* by the right;
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00003561 // FIXME: Handle ExtQualType
Douglas Gregor98cd5992008-10-21 23:43:52 +00003562 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner5cf216b2008-01-04 18:04:52 +00003563 ConvTy = CompatiblePointerDiscardsQualifiers;
Reid Spencer5f016e22007-07-11 17:01:13 +00003564
Mike Stumpeed9cac2009-02-19 03:04:26 +00003565 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
3566 // incomplete type and the other is a pointer to a qualified or unqualified
Reid Spencer5f016e22007-07-11 17:01:13 +00003567 // version of void...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00003568 if (lhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00003569 if (rhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00003570 return ConvTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003571
Chris Lattnerbfe639e2008-01-03 22:56:36 +00003572 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00003573 assert(rhptee->isFunctionType());
3574 return FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00003575 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003576
Chris Lattnerbfe639e2008-01-03 22:56:36 +00003577 if (rhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00003578 if (lhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00003579 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00003580
3581 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00003582 assert(lhptee->isFunctionType());
3583 return FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00003584 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003585 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Reid Spencer5f016e22007-07-11 17:01:13 +00003586 // unqualified versions of compatible types, ...
Eli Friedmanf05c05d2009-03-22 23:59:44 +00003587 lhptee = lhptee.getUnqualifiedType();
3588 rhptee = rhptee.getUnqualifiedType();
3589 if (!Context.typesAreCompatible(lhptee, rhptee)) {
3590 // Check if the pointee types are compatible ignoring the sign.
3591 // We explicitly check for char so that we catch "char" vs
3592 // "unsigned char" on systems where "char" is unsigned.
Chris Lattner6a2b9262009-10-17 20:33:28 +00003593 if (lhptee->isCharType())
Eli Friedmanf05c05d2009-03-22 23:59:44 +00003594 lhptee = Context.UnsignedCharTy;
Chris Lattner6a2b9262009-10-17 20:33:28 +00003595 else if (lhptee->isSignedIntegerType())
Eli Friedmanf05c05d2009-03-22 23:59:44 +00003596 lhptee = Context.getCorrespondingUnsignedType(lhptee);
Chris Lattner6a2b9262009-10-17 20:33:28 +00003597
3598 if (rhptee->isCharType())
Eli Friedmanf05c05d2009-03-22 23:59:44 +00003599 rhptee = Context.UnsignedCharTy;
Chris Lattner6a2b9262009-10-17 20:33:28 +00003600 else if (rhptee->isSignedIntegerType())
Eli Friedmanf05c05d2009-03-22 23:59:44 +00003601 rhptee = Context.getCorrespondingUnsignedType(rhptee);
Chris Lattner6a2b9262009-10-17 20:33:28 +00003602
Eli Friedmanf05c05d2009-03-22 23:59:44 +00003603 if (lhptee == rhptee) {
3604 // Types are compatible ignoring the sign. Qualifier incompatibility
3605 // takes priority over sign incompatibility because the sign
3606 // warning can be disabled.
3607 if (ConvTy != Compatible)
3608 return ConvTy;
3609 return IncompatiblePointerSign;
3610 }
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00003611
3612 // If we are a multi-level pointer, it's possible that our issue is simply
3613 // one of qualification - e.g. char ** -> const char ** is not allowed. If
3614 // the eventual target type is the same and the pointers have the same
3615 // level of indirection, this must be the issue.
3616 if (lhptee->isPointerType() && rhptee->isPointerType()) {
3617 do {
3618 lhptee = lhptee->getAs<PointerType>()->getPointeeType();
3619 rhptee = rhptee->getAs<PointerType>()->getPointeeType();
3620
3621 lhptee = Context.getCanonicalType(lhptee);
3622 rhptee = Context.getCanonicalType(rhptee);
3623 } while (lhptee->isPointerType() && rhptee->isPointerType());
3624
Douglas Gregora4923eb2009-11-16 21:35:15 +00003625 if (Context.hasSameUnqualifiedType(lhptee, rhptee))
Sean Huntc9132b62009-11-08 07:46:34 +00003626 return IncompatibleNestedPointerQualifiers;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00003627 }
3628
Eli Friedmanf05c05d2009-03-22 23:59:44 +00003629 // General pointer incompatibility takes priority over qualifiers.
Mike Stump1eb44332009-09-09 15:08:12 +00003630 return IncompatiblePointer;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00003631 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00003632 return ConvTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00003633}
3634
Steve Naroff1c7d0672008-09-04 15:10:53 +00003635/// CheckBlockPointerTypesForAssignment - This routine determines whether two
3636/// block pointer types are compatible or whether a block and normal pointer
3637/// are compatible. It is more restrict than comparing two function pointer
3638// types.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003639Sema::AssignConvertType
3640Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
Steve Naroff1c7d0672008-09-04 15:10:53 +00003641 QualType rhsType) {
3642 QualType lhptee, rhptee;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003643
Steve Naroff1c7d0672008-09-04 15:10:53 +00003644 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenek6217b802009-07-29 21:53:49 +00003645 lhptee = lhsType->getAs<BlockPointerType>()->getPointeeType();
3646 rhptee = rhsType->getAs<BlockPointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00003647
Steve Naroff1c7d0672008-09-04 15:10:53 +00003648 // make sure we operate on the canonical type
3649 lhptee = Context.getCanonicalType(lhptee);
3650 rhptee = Context.getCanonicalType(rhptee);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003651
Steve Naroff1c7d0672008-09-04 15:10:53 +00003652 AssignConvertType ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003653
Steve Naroff1c7d0672008-09-04 15:10:53 +00003654 // For blocks we enforce that qualifiers are identical.
Douglas Gregora4923eb2009-11-16 21:35:15 +00003655 if (lhptee.getLocalCVRQualifiers() != rhptee.getLocalCVRQualifiers())
Steve Naroff1c7d0672008-09-04 15:10:53 +00003656 ConvTy = CompatiblePointerDiscardsQualifiers;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003657
Eli Friedman26784c12009-06-08 05:08:54 +00003658 if (!Context.typesAreCompatible(lhptee, rhptee))
Mike Stumpeed9cac2009-02-19 03:04:26 +00003659 return IncompatibleBlockPointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00003660 return ConvTy;
3661}
3662
Mike Stumpeed9cac2009-02-19 03:04:26 +00003663/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
3664/// has code to accommodate several GCC extensions when type checking
Reid Spencer5f016e22007-07-11 17:01:13 +00003665/// pointers. Here are some objectionable examples that GCC considers warnings:
3666///
3667/// int a, *pint;
3668/// short *pshort;
3669/// struct foo *pfoo;
3670///
3671/// pint = pshort; // warning: assignment from incompatible pointer type
3672/// a = pint; // warning: assignment makes integer from pointer without a cast
3673/// pint = a; // warning: assignment makes pointer from integer without a cast
3674/// pint = pfoo; // warning: assignment from incompatible pointer type
3675///
3676/// As a result, the code for dealing with pointers is more complex than the
Mike Stumpeed9cac2009-02-19 03:04:26 +00003677/// C99 spec dictates.
Reid Spencer5f016e22007-07-11 17:01:13 +00003678///
Chris Lattner5cf216b2008-01-04 18:04:52 +00003679Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00003680Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattnerfc144e22008-01-04 23:18:45 +00003681 // Get canonical types. We're not formatting these types, just comparing
3682 // them.
Chris Lattnerb77792e2008-07-26 22:17:49 +00003683 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
3684 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedmanf8f873d2008-05-30 18:07:22 +00003685
3686 if (lhsType == rhsType)
Chris Lattnerd2656dd2008-01-07 17:51:46 +00003687 return Compatible; // Common case: fast path an exact match.
Steve Naroff700204c2007-07-24 21:46:40 +00003688
David Chisnall0f436562009-08-17 16:35:33 +00003689 if ((lhsType->isObjCClassType() &&
3690 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
3691 (rhsType->isObjCClassType() &&
3692 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
3693 return Compatible;
3694 }
3695
Douglas Gregor9d293df2008-10-28 00:22:11 +00003696 // If the left-hand side is a reference type, then we are in a
3697 // (rare!) case where we've allowed the use of references in C,
3698 // e.g., as a parameter type in a built-in function. In this case,
3699 // just make sure that the type referenced is compatible with the
3700 // right-hand side type. The caller is responsible for adjusting
3701 // lhsType so that the resulting expression does not have reference
3702 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00003703 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
Douglas Gregor9d293df2008-10-28 00:22:11 +00003704 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlsson793680e2007-10-12 23:56:29 +00003705 return Compatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00003706 return Incompatible;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00003707 }
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00003708 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
3709 // to the same ExtVector type.
3710 if (lhsType->isExtVectorType()) {
3711 if (rhsType->isExtVectorType())
3712 return lhsType == rhsType ? Compatible : Incompatible;
3713 if (!rhsType->isVectorType() && rhsType->isArithmeticType())
3714 return Compatible;
3715 }
Mike Stump1eb44332009-09-09 15:08:12 +00003716
Nate Begemanbe2341d2008-07-14 18:02:46 +00003717 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00003718 // If we are allowing lax vector conversions, and LHS and RHS are both
Mike Stumpeed9cac2009-02-19 03:04:26 +00003719 // vectors, the total size only needs to be the same. This is a bitcast;
Nate Begemanbe2341d2008-07-14 18:02:46 +00003720 // no bits are changed but the result type is different.
Chris Lattnere8b3e962008-01-04 23:32:24 +00003721 if (getLangOptions().LaxVectorConversions &&
3722 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00003723 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00003724 return IncompatibleVectors;
Chris Lattnere8b3e962008-01-04 23:32:24 +00003725 }
3726 return Incompatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003727 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00003728
Chris Lattnere8b3e962008-01-04 23:32:24 +00003729 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Reid Spencer5f016e22007-07-11 17:01:13 +00003730 return Compatible;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00003731
Chris Lattner78eca282008-04-07 06:49:41 +00003732 if (isa<PointerType>(lhsType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003733 if (rhsType->isIntegerType())
Chris Lattnerb7b61152008-01-04 18:22:42 +00003734 return IntToPointer;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00003735
Chris Lattner78eca282008-04-07 06:49:41 +00003736 if (isa<PointerType>(rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00003737 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003738
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003739 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff14108da2009-07-10 23:34:53 +00003740 if (isa<ObjCObjectPointerType>(rhsType)) {
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003741 if (lhsType->isVoidPointerType()) // an exception to the rule.
3742 return Compatible;
3743 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00003744 }
Ted Kremenek6217b802009-07-29 21:53:49 +00003745 if (rhsType->getAs<BlockPointerType>()) {
3746 if (lhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00003747 return Compatible;
Steve Naroffb4406862008-09-29 18:10:17 +00003748
3749 // Treat block pointers as objects.
Steve Naroff14108da2009-07-10 23:34:53 +00003750 if (getLangOptions().ObjC1 && lhsType->isObjCIdType())
Steve Naroffb4406862008-09-29 18:10:17 +00003751 return Compatible;
3752 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00003753 return Incompatible;
3754 }
3755
3756 if (isa<BlockPointerType>(lhsType)) {
3757 if (rhsType->isIntegerType())
Eli Friedmand8f4f432009-02-25 04:20:42 +00003758 return IntToBlockPointer;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003759
Steve Naroffb4406862008-09-29 18:10:17 +00003760 // Treat block pointers as objects.
Steve Naroff14108da2009-07-10 23:34:53 +00003761 if (getLangOptions().ObjC1 && rhsType->isObjCIdType())
Steve Naroffb4406862008-09-29 18:10:17 +00003762 return Compatible;
3763
Steve Naroff1c7d0672008-09-04 15:10:53 +00003764 if (rhsType->isBlockPointerType())
3765 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003766
Ted Kremenek6217b802009-07-29 21:53:49 +00003767 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff1c7d0672008-09-04 15:10:53 +00003768 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00003769 return Compatible;
Steve Naroff1c7d0672008-09-04 15:10:53 +00003770 }
Chris Lattnerfc144e22008-01-04 23:18:45 +00003771 return Incompatible;
3772 }
3773
Steve Naroff14108da2009-07-10 23:34:53 +00003774 if (isa<ObjCObjectPointerType>(lhsType)) {
3775 if (rhsType->isIntegerType())
3776 return IntToPointer;
Mike Stump1eb44332009-09-09 15:08:12 +00003777
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003778 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff14108da2009-07-10 23:34:53 +00003779 if (isa<PointerType>(rhsType)) {
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003780 if (rhsType->isVoidPointerType()) // an exception to the rule.
3781 return Compatible;
3782 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00003783 }
3784 if (rhsType->isObjCObjectPointerType()) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003785 if (lhsType->isObjCBuiltinType() || rhsType->isObjCBuiltinType())
3786 return Compatible;
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003787 if (Context.typesAreCompatible(lhsType, rhsType))
3788 return Compatible;
Steve Naroff4084c302009-07-23 01:01:38 +00003789 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
3790 return IncompatibleObjCQualifiedId;
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003791 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00003792 }
Ted Kremenek6217b802009-07-29 21:53:49 +00003793 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003794 if (RHSPT->getPointeeType()->isVoidType())
3795 return Compatible;
3796 }
3797 // Treat block pointers as objects.
3798 if (rhsType->isBlockPointerType())
3799 return Compatible;
3800 return Incompatible;
3801 }
Chris Lattner78eca282008-04-07 06:49:41 +00003802 if (isa<PointerType>(rhsType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003803 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedmanf8f873d2008-05-30 18:07:22 +00003804 if (lhsType == Context.BoolTy)
3805 return Compatible;
3806
3807 if (lhsType->isIntegerType())
Chris Lattnerb7b61152008-01-04 18:22:42 +00003808 return PointerToInt;
Reid Spencer5f016e22007-07-11 17:01:13 +00003809
Mike Stumpeed9cac2009-02-19 03:04:26 +00003810 if (isa<PointerType>(lhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00003811 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003812
3813 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenek6217b802009-07-29 21:53:49 +00003814 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00003815 return Compatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00003816 return Incompatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00003817 }
Steve Naroff14108da2009-07-10 23:34:53 +00003818 if (isa<ObjCObjectPointerType>(rhsType)) {
3819 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
3820 if (lhsType == Context.BoolTy)
3821 return Compatible;
3822
3823 if (lhsType->isIntegerType())
3824 return PointerToInt;
3825
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003826 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff14108da2009-07-10 23:34:53 +00003827 if (isa<PointerType>(lhsType)) {
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003828 if (lhsType->isVoidPointerType()) // an exception to the rule.
3829 return Compatible;
3830 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00003831 }
3832 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenek6217b802009-07-29 21:53:49 +00003833 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Steve Naroff14108da2009-07-10 23:34:53 +00003834 return Compatible;
3835 return Incompatible;
3836 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00003837
Chris Lattnerfc144e22008-01-04 23:18:45 +00003838 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner78eca282008-04-07 06:49:41 +00003839 if (Context.typesAreCompatible(lhsType, rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00003840 return Compatible;
Reid Spencer5f016e22007-07-11 17:01:13 +00003841 }
3842 return Incompatible;
3843}
3844
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00003845/// \brief Constructs a transparent union from an expression that is
3846/// used to initialize the transparent union.
Mike Stump1eb44332009-09-09 15:08:12 +00003847static void ConstructTransparentUnion(ASTContext &C, Expr *&E,
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00003848 QualType UnionType, FieldDecl *Field) {
3849 // Build an initializer list that designates the appropriate member
3850 // of the transparent union.
3851 InitListExpr *Initializer = new (C) InitListExpr(SourceLocation(),
3852 &E, 1,
3853 SourceLocation());
3854 Initializer->setType(UnionType);
3855 Initializer->setInitializedFieldInUnion(Field);
3856
3857 // Build a compound literal constructing a value of the transparent
3858 // union type from this initializer list.
3859 E = new (C) CompoundLiteralExpr(SourceLocation(), UnionType, Initializer,
3860 false);
3861}
3862
3863Sema::AssignConvertType
3864Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) {
3865 QualType FromType = rExpr->getType();
3866
Mike Stump1eb44332009-09-09 15:08:12 +00003867 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00003868 // transparent_union GCC extension.
3869 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00003870 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00003871 return Incompatible;
3872
3873 // The field to initialize within the transparent union.
3874 RecordDecl *UD = UT->getDecl();
3875 FieldDecl *InitField = 0;
3876 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003877 for (RecordDecl::field_iterator it = UD->field_begin(),
3878 itend = UD->field_end();
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00003879 it != itend; ++it) {
3880 if (it->getType()->isPointerType()) {
3881 // If the transparent union contains a pointer type, we allow:
3882 // 1) void pointer
3883 // 2) null pointer constant
3884 if (FromType->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +00003885 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003886 ImpCastExprToType(rExpr, it->getType(), CastExpr::CK_BitCast);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00003887 InitField = *it;
3888 break;
3889 }
Mike Stump1eb44332009-09-09 15:08:12 +00003890
Douglas Gregorce940492009-09-25 04:25:58 +00003891 if (rExpr->isNullPointerConstant(Context,
3892 Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003893 ImpCastExprToType(rExpr, it->getType(), CastExpr::CK_IntegralToPointer);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00003894 InitField = *it;
3895 break;
3896 }
3897 }
3898
3899 if (CheckAssignmentConstraints(it->getType(), rExpr->getType())
3900 == Compatible) {
3901 InitField = *it;
3902 break;
3903 }
3904 }
3905
3906 if (!InitField)
3907 return Incompatible;
3908
3909 ConstructTransparentUnion(Context, rExpr, ArgType, InitField);
3910 return Compatible;
3911}
3912
Chris Lattner5cf216b2008-01-04 18:04:52 +00003913Sema::AssignConvertType
Steve Naroff90045e82007-07-13 23:32:42 +00003914Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00003915 if (getLangOptions().CPlusPlus) {
3916 if (!lhsType->isRecordType()) {
3917 // C++ 5.17p3: If the left operand is not of class type, the
3918 // expression is implicitly converted (C++ 4) to the
3919 // cv-unqualified type of the left operand.
Douglas Gregor45920e82008-12-19 17:40:08 +00003920 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
3921 "assigning"))
Douglas Gregor98cd5992008-10-21 23:43:52 +00003922 return Incompatible;
Chris Lattner2c4463f2009-04-12 09:02:39 +00003923 return Compatible;
Douglas Gregor98cd5992008-10-21 23:43:52 +00003924 }
3925
3926 // FIXME: Currently, we fall through and treat C++ classes like C
3927 // structures.
3928 }
3929
Steve Naroff529a4ad2007-11-27 17:58:44 +00003930 // C99 6.5.16.1p1: the left operand is a pointer and the right is
3931 // a null pointer constant.
Mike Stump1eb44332009-09-09 15:08:12 +00003932 if ((lhsType->isPointerType() ||
3933 lhsType->isObjCObjectPointerType() ||
Mike Stumpeed9cac2009-02-19 03:04:26 +00003934 lhsType->isBlockPointerType())
Douglas Gregorce940492009-09-25 04:25:58 +00003935 && rExpr->isNullPointerConstant(Context,
3936 Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003937 ImpCastExprToType(rExpr, lhsType, CastExpr::CK_Unknown);
Steve Naroff529a4ad2007-11-27 17:58:44 +00003938 return Compatible;
3939 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003940
Chris Lattner943140e2007-10-16 02:55:40 +00003941 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroff90045e82007-07-13 23:32:42 +00003942 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregor02a24ee2009-11-03 16:56:39 +00003943 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Steve Naroff90045e82007-07-13 23:32:42 +00003944 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner943140e2007-10-16 02:55:40 +00003945 //
Mike Stumpeed9cac2009-02-19 03:04:26 +00003946 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner943140e2007-10-16 02:55:40 +00003947 if (!lhsType->isReferenceType())
3948 DefaultFunctionArrayConversion(rExpr);
Steve Narofff1120de2007-08-24 22:33:52 +00003949
Chris Lattner5cf216b2008-01-04 18:04:52 +00003950 Sema::AssignConvertType result =
3951 CheckAssignmentConstraints(lhsType, rExpr->getType());
Mike Stumpeed9cac2009-02-19 03:04:26 +00003952
Steve Narofff1120de2007-08-24 22:33:52 +00003953 // C99 6.5.16.1p2: The value of the right operand is converted to the
3954 // type of the assignment expression.
Douglas Gregor9d293df2008-10-28 00:22:11 +00003955 // CheckAssignmentConstraints allows the left-hand side to be a reference,
3956 // so that we can use references in built-in functions even in C.
3957 // The getNonReferenceType() call makes sure that the resulting expression
3958 // does not have reference type.
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00003959 if (result != Incompatible && rExpr->getType() != lhsType)
Eli Friedman73c39ab2009-10-20 08:27:19 +00003960 ImpCastExprToType(rExpr, lhsType.getNonReferenceType(),
3961 CastExpr::CK_Unknown);
Steve Narofff1120de2007-08-24 22:33:52 +00003962 return result;
Steve Naroff90045e82007-07-13 23:32:42 +00003963}
3964
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003965QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00003966 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattner22caddc2008-11-23 09:13:29 +00003967 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00003968 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerca5eede2007-12-12 05:47:28 +00003969 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003970}
3971
Mike Stumpeed9cac2009-02-19 03:04:26 +00003972inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Steve Naroff49b45262007-07-13 16:58:59 +00003973 Expr *&rex) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00003974 // For conversion purposes, we ignore any qualifiers.
Nate Begeman1330b0e2008-04-04 01:30:25 +00003975 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +00003976 QualType lhsType =
3977 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
3978 QualType rhsType =
3979 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00003980
Nate Begemanbe2341d2008-07-14 18:02:46 +00003981 // If the vector types are identical, return.
Nate Begeman1330b0e2008-04-04 01:30:25 +00003982 if (lhsType == rhsType)
Reid Spencer5f016e22007-07-11 17:01:13 +00003983 return lhsType;
Nate Begeman4119d1a2007-12-30 02:59:45 +00003984
Nate Begemanbe2341d2008-07-14 18:02:46 +00003985 // Handle the case of a vector & extvector type of the same size and element
3986 // type. It would be nice if we only had one vector type someday.
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00003987 if (getLangOptions().LaxVectorConversions) {
3988 // FIXME: Should we warn here?
John McCall183700f2009-09-21 23:43:11 +00003989 if (const VectorType *LV = lhsType->getAs<VectorType>()) {
3990 if (const VectorType *RV = rhsType->getAs<VectorType>())
Nate Begemanbe2341d2008-07-14 18:02:46 +00003991 if (LV->getElementType() == RV->getElementType() &&
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00003992 LV->getNumElements() == RV->getNumElements()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00003993 return lhsType->isExtVectorType() ? lhsType : rhsType;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00003994 }
3995 }
3996 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003997
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00003998 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
3999 // swap back (so that we don't reverse the inputs to a subtract, for instance.
4000 bool swapped = false;
4001 if (rhsType->isExtVectorType()) {
4002 swapped = true;
4003 std::swap(rex, lex);
4004 std::swap(rhsType, lhsType);
4005 }
Mike Stump1eb44332009-09-09 15:08:12 +00004006
Nate Begemandde25982009-06-28 19:12:57 +00004007 // Handle the case of an ext vector and scalar.
John McCall183700f2009-09-21 23:43:11 +00004008 if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) {
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004009 QualType EltTy = LV->getElementType();
4010 if (EltTy->isIntegralType() && rhsType->isIntegralType()) {
4011 if (Context.getIntegerTypeOrder(EltTy, rhsType) >= 0) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004012 ImpCastExprToType(rex, lhsType, CastExpr::CK_IntegralCast);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004013 if (swapped) std::swap(rex, lex);
4014 return lhsType;
4015 }
4016 }
4017 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
4018 rhsType->isRealFloatingType()) {
4019 if (Context.getFloatingTypeOrder(EltTy, rhsType) >= 0) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004020 ImpCastExprToType(rex, lhsType, CastExpr::CK_FloatingCast);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004021 if (swapped) std::swap(rex, lex);
4022 return lhsType;
4023 }
Nate Begeman4119d1a2007-12-30 02:59:45 +00004024 }
4025 }
Mike Stump1eb44332009-09-09 15:08:12 +00004026
Nate Begemandde25982009-06-28 19:12:57 +00004027 // Vectors of different size or scalar and non-ext-vector are errors.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004028 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattnerd1625842008-11-24 06:25:27 +00004029 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004030 << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00004031 return QualType();
Sebastian Redl22460502009-02-07 00:15:38 +00004032}
4033
Reid Spencer5f016e22007-07-11 17:01:13 +00004034inline QualType Sema::CheckMultiplyDivideOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00004035 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Daniel Dunbar69d1d002009-01-05 22:42:10 +00004036 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004037 return CheckVectorOperands(Loc, lex, rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004038
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004039 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004040
Steve Naroffa4332e22007-07-17 00:58:39 +00004041 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004042 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004043 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00004044}
4045
4046inline QualType Sema::CheckRemainderOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00004047 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Daniel Dunbar523aa602009-01-05 22:55:36 +00004048 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4049 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
4050 return CheckVectorOperands(Loc, lex, rex);
4051 return InvalidOperands(Loc, lex, rex);
4052 }
Steve Naroff90045e82007-07-13 23:32:42 +00004053
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004054 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004055
Steve Naroffa4332e22007-07-17 00:58:39 +00004056 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004057 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004058 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00004059}
4060
4061inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Mike Stump1eb44332009-09-09 15:08:12 +00004062 Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00004063 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4064 QualType compType = CheckVectorOperands(Loc, lex, rex);
4065 if (CompLHSTy) *CompLHSTy = compType;
4066 return compType;
4067 }
Steve Naroff49b45262007-07-13 16:58:59 +00004068
Eli Friedmanab3a8522009-03-28 01:22:36 +00004069 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Eli Friedmand72d16e2008-05-18 18:08:51 +00004070
Reid Spencer5f016e22007-07-11 17:01:13 +00004071 // handle the common case first (both operands are arithmetic).
Eli Friedmanab3a8522009-03-28 01:22:36 +00004072 if (lex->getType()->isArithmeticType() &&
4073 rex->getType()->isArithmeticType()) {
4074 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004075 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00004076 }
Reid Spencer5f016e22007-07-11 17:01:13 +00004077
Eli Friedmand72d16e2008-05-18 18:08:51 +00004078 // Put any potential pointer into PExp
4079 Expr* PExp = lex, *IExp = rex;
Steve Naroff58f9f2c2009-07-14 18:25:06 +00004080 if (IExp->getType()->isAnyPointerType())
Eli Friedmand72d16e2008-05-18 18:08:51 +00004081 std::swap(PExp, IExp);
4082
Steve Naroff58f9f2c2009-07-14 18:25:06 +00004083 if (PExp->getType()->isAnyPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004084
Eli Friedmand72d16e2008-05-18 18:08:51 +00004085 if (IExp->getType()->isIntegerType()) {
Steve Naroff760e3c42009-07-13 21:20:41 +00004086 QualType PointeeTy = PExp->getType()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00004087
Chris Lattnerb5f15622009-04-24 23:50:08 +00004088 // Check for arithmetic on pointers to incomplete types.
4089 if (PointeeTy->isVoidType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +00004090 if (getLangOptions().CPlusPlus) {
4091 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004092 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004093 return QualType();
Eli Friedmand72d16e2008-05-18 18:08:51 +00004094 }
Douglas Gregore7450f52009-03-24 19:52:54 +00004095
4096 // GNU extension: arithmetic on pointer to void
4097 Diag(Loc, diag::ext_gnu_void_ptr)
4098 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerb5f15622009-04-24 23:50:08 +00004099 } else if (PointeeTy->isFunctionType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +00004100 if (getLangOptions().CPlusPlus) {
4101 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
4102 << lex->getType() << lex->getSourceRange();
4103 return QualType();
4104 }
4105
4106 // GNU extension: arithmetic on pointer to function
4107 Diag(Loc, diag::ext_gnu_ptr_func_arith)
4108 << lex->getType() << lex->getSourceRange();
Steve Naroff9deaeca2009-07-13 21:32:29 +00004109 } else {
Steve Naroff760e3c42009-07-13 21:20:41 +00004110 // Check if we require a complete type.
Mike Stump1eb44332009-09-09 15:08:12 +00004111 if (((PExp->getType()->isPointerType() &&
Steve Naroff9deaeca2009-07-13 21:32:29 +00004112 !PExp->getType()->isDependentType()) ||
Steve Naroff760e3c42009-07-13 21:20:41 +00004113 PExp->getType()->isObjCObjectPointerType()) &&
4114 RequireCompleteType(Loc, PointeeTy,
Mike Stump1eb44332009-09-09 15:08:12 +00004115 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
4116 << PExp->getSourceRange()
Anders Carlssond497ba72009-08-26 22:59:12 +00004117 << PExp->getType()))
Steve Naroff760e3c42009-07-13 21:20:41 +00004118 return QualType();
4119 }
Chris Lattnerb5f15622009-04-24 23:50:08 +00004120 // Diagnose bad cases where we step over interface counts.
4121 if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4122 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
4123 << PointeeTy << PExp->getSourceRange();
4124 return QualType();
4125 }
Mike Stump1eb44332009-09-09 15:08:12 +00004126
Eli Friedmanab3a8522009-03-28 01:22:36 +00004127 if (CompLHSTy) {
Eli Friedman04e83572009-08-20 04:21:42 +00004128 QualType LHSTy = Context.isPromotableBitField(lex);
4129 if (LHSTy.isNull()) {
4130 LHSTy = lex->getType();
4131 if (LHSTy->isPromotableIntegerType())
4132 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregor2d833e32009-05-02 00:36:19 +00004133 }
Eli Friedmanab3a8522009-03-28 01:22:36 +00004134 *CompLHSTy = LHSTy;
4135 }
Eli Friedmand72d16e2008-05-18 18:08:51 +00004136 return PExp->getType();
4137 }
4138 }
4139
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004140 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00004141}
4142
Chris Lattnereca7be62008-04-07 05:30:13 +00004143// C99 6.5.6
4144QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Eli Friedmanab3a8522009-03-28 01:22:36 +00004145 SourceLocation Loc, QualType* CompLHSTy) {
4146 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4147 QualType compType = CheckVectorOperands(Loc, lex, rex);
4148 if (CompLHSTy) *CompLHSTy = compType;
4149 return compType;
4150 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004151
Eli Friedmanab3a8522009-03-28 01:22:36 +00004152 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004153
Chris Lattner6e4ab612007-12-09 21:53:25 +00004154 // Enforce type constraints: C99 6.5.6p3.
Mike Stumpeed9cac2009-02-19 03:04:26 +00004155
Chris Lattner6e4ab612007-12-09 21:53:25 +00004156 // Handle the common case first (both operands are arithmetic).
Mike Stumpaf199f32009-05-07 18:43:07 +00004157 if (lex->getType()->isArithmeticType()
4158 && rex->getType()->isArithmeticType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00004159 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004160 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00004161 }
Mike Stump1eb44332009-09-09 15:08:12 +00004162
Chris Lattner6e4ab612007-12-09 21:53:25 +00004163 // Either ptr - int or ptr - ptr.
Steve Naroff58f9f2c2009-07-14 18:25:06 +00004164 if (lex->getType()->isAnyPointerType()) {
Steve Naroff430ee5a2009-07-13 17:19:15 +00004165 QualType lpointee = lex->getType()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004166
Douglas Gregore7450f52009-03-24 19:52:54 +00004167 // The LHS must be an completely-defined object type.
Douglas Gregorc983b862009-01-23 00:36:41 +00004168
Douglas Gregore7450f52009-03-24 19:52:54 +00004169 bool ComplainAboutVoid = false;
4170 Expr *ComplainAboutFunc = 0;
4171 if (lpointee->isVoidType()) {
4172 if (getLangOptions().CPlusPlus) {
4173 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
4174 << lex->getSourceRange() << rex->getSourceRange();
4175 return QualType();
4176 }
4177
4178 // GNU C extension: arithmetic on pointer to void
4179 ComplainAboutVoid = true;
4180 } else if (lpointee->isFunctionType()) {
4181 if (getLangOptions().CPlusPlus) {
4182 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattnerd1625842008-11-24 06:25:27 +00004183 << lex->getType() << lex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00004184 return QualType();
4185 }
Douglas Gregore7450f52009-03-24 19:52:54 +00004186
4187 // GNU C extension: arithmetic on pointer to function
4188 ComplainAboutFunc = lex;
4189 } else if (!lpointee->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00004190 RequireCompleteType(Loc, lpointee,
Anders Carlssond497ba72009-08-26 22:59:12 +00004191 PDiag(diag::err_typecheck_sub_ptr_object)
Mike Stump1eb44332009-09-09 15:08:12 +00004192 << lex->getSourceRange()
Anders Carlssond497ba72009-08-26 22:59:12 +00004193 << lex->getType()))
Douglas Gregore7450f52009-03-24 19:52:54 +00004194 return QualType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00004195
Chris Lattnerb5f15622009-04-24 23:50:08 +00004196 // Diagnose bad cases where we step over interface counts.
4197 if (lpointee->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4198 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
4199 << lpointee << lex->getSourceRange();
4200 return QualType();
4201 }
Mike Stump1eb44332009-09-09 15:08:12 +00004202
Chris Lattner6e4ab612007-12-09 21:53:25 +00004203 // The result type of a pointer-int computation is the pointer type.
Douglas Gregore7450f52009-03-24 19:52:54 +00004204 if (rex->getType()->isIntegerType()) {
4205 if (ComplainAboutVoid)
4206 Diag(Loc, diag::ext_gnu_void_ptr)
4207 << lex->getSourceRange() << rex->getSourceRange();
4208 if (ComplainAboutFunc)
4209 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump1eb44332009-09-09 15:08:12 +00004210 << ComplainAboutFunc->getType()
Douglas Gregore7450f52009-03-24 19:52:54 +00004211 << ComplainAboutFunc->getSourceRange();
4212
Eli Friedmanab3a8522009-03-28 01:22:36 +00004213 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00004214 return lex->getType();
Douglas Gregore7450f52009-03-24 19:52:54 +00004215 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004216
Chris Lattner6e4ab612007-12-09 21:53:25 +00004217 // Handle pointer-pointer subtractions.
Ted Kremenek6217b802009-07-29 21:53:49 +00004218 if (const PointerType *RHSPTy = rex->getType()->getAs<PointerType>()) {
Eli Friedman8e54ad02008-02-08 01:19:44 +00004219 QualType rpointee = RHSPTy->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004220
Douglas Gregore7450f52009-03-24 19:52:54 +00004221 // RHS must be a completely-type object type.
4222 // Handle the GNU void* extension.
4223 if (rpointee->isVoidType()) {
4224 if (getLangOptions().CPlusPlus) {
4225 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
4226 << lex->getSourceRange() << rex->getSourceRange();
4227 return QualType();
4228 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004229
Douglas Gregore7450f52009-03-24 19:52:54 +00004230 ComplainAboutVoid = true;
4231 } else if (rpointee->isFunctionType()) {
4232 if (getLangOptions().CPlusPlus) {
4233 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattnerd1625842008-11-24 06:25:27 +00004234 << rex->getType() << rex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00004235 return QualType();
4236 }
Douglas Gregore7450f52009-03-24 19:52:54 +00004237
4238 // GNU extension: arithmetic on pointer to function
4239 if (!ComplainAboutFunc)
4240 ComplainAboutFunc = rex;
4241 } else if (!rpointee->isDependentType() &&
4242 RequireCompleteType(Loc, rpointee,
Anders Carlssond497ba72009-08-26 22:59:12 +00004243 PDiag(diag::err_typecheck_sub_ptr_object)
4244 << rex->getSourceRange()
4245 << rex->getType()))
Douglas Gregore7450f52009-03-24 19:52:54 +00004246 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004247
Eli Friedman88d936b2009-05-16 13:54:38 +00004248 if (getLangOptions().CPlusPlus) {
4249 // Pointee types must be the same: C++ [expr.add]
4250 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
4251 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
4252 << lex->getType() << rex->getType()
4253 << lex->getSourceRange() << rex->getSourceRange();
4254 return QualType();
4255 }
4256 } else {
4257 // Pointee types must be compatible C99 6.5.6p3
4258 if (!Context.typesAreCompatible(
4259 Context.getCanonicalType(lpointee).getUnqualifiedType(),
4260 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
4261 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
4262 << lex->getType() << rex->getType()
4263 << lex->getSourceRange() << rex->getSourceRange();
4264 return QualType();
4265 }
Chris Lattner6e4ab612007-12-09 21:53:25 +00004266 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004267
Douglas Gregore7450f52009-03-24 19:52:54 +00004268 if (ComplainAboutVoid)
4269 Diag(Loc, diag::ext_gnu_void_ptr)
4270 << lex->getSourceRange() << rex->getSourceRange();
4271 if (ComplainAboutFunc)
4272 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump1eb44332009-09-09 15:08:12 +00004273 << ComplainAboutFunc->getType()
Douglas Gregore7450f52009-03-24 19:52:54 +00004274 << ComplainAboutFunc->getSourceRange();
Eli Friedmanab3a8522009-03-28 01:22:36 +00004275
4276 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00004277 return Context.getPointerDiffType();
4278 }
4279 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004280
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004281 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00004282}
4283
Chris Lattnereca7be62008-04-07 05:30:13 +00004284// C99 6.5.7
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004285QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnereca7be62008-04-07 05:30:13 +00004286 bool isCompAssign) {
Chris Lattnerca5eede2007-12-12 05:47:28 +00004287 // C99 6.5.7p2: Each of the operands shall have integer type.
4288 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004289 return InvalidOperands(Loc, lex, rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004290
Nate Begeman2207d792009-10-25 02:26:48 +00004291 // Vector shifts promote their scalar inputs to vector type.
4292 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
4293 return CheckVectorOperands(Loc, lex, rex);
4294
Chris Lattnerca5eede2007-12-12 05:47:28 +00004295 // Shifts don't perform usual arithmetic conversions, they just do integer
4296 // promotions on each operand. C99 6.5.7p3
Eli Friedman04e83572009-08-20 04:21:42 +00004297 QualType LHSTy = Context.isPromotableBitField(lex);
4298 if (LHSTy.isNull()) {
4299 LHSTy = lex->getType();
4300 if (LHSTy->isPromotableIntegerType())
4301 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregor2d833e32009-05-02 00:36:19 +00004302 }
Chris Lattner1dcf2c82007-12-13 07:28:16 +00004303 if (!isCompAssign)
Eli Friedman73c39ab2009-10-20 08:27:19 +00004304 ImpCastExprToType(lex, LHSTy, CastExpr::CK_IntegralCast);
Eli Friedmanab3a8522009-03-28 01:22:36 +00004305
Chris Lattnerca5eede2007-12-12 05:47:28 +00004306 UsualUnaryConversions(rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004307
Ryan Flynnd0439682009-08-07 16:20:20 +00004308 // Sanity-check shift operands
4309 llvm::APSInt Right;
4310 // Check right/shifter operand
Daniel Dunbar3f180c62009-09-17 06:31:27 +00004311 if (!rex->isValueDependent() &&
4312 rex->isIntegerConstantExpr(Right, Context)) {
Ryan Flynn8045c732009-08-08 19:18:23 +00004313 if (Right.isNegative())
Ryan Flynnd0439682009-08-07 16:20:20 +00004314 Diag(Loc, diag::warn_shift_negative) << rex->getSourceRange();
4315 else {
4316 llvm::APInt LeftBits(Right.getBitWidth(),
4317 Context.getTypeSize(lex->getType()));
4318 if (Right.uge(LeftBits))
4319 Diag(Loc, diag::warn_shift_gt_typewidth) << rex->getSourceRange();
4320 }
4321 }
4322
Chris Lattnerca5eede2007-12-12 05:47:28 +00004323 // "The type of the result is that of the promoted left operand."
Eli Friedmanab3a8522009-03-28 01:22:36 +00004324 return LHSTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00004325}
4326
John McCall5dbad3d2009-11-06 08:49:08 +00004327/// \brief Implements -Wsign-compare.
4328///
4329/// \param lex the left-hand expression
4330/// \param rex the right-hand expression
4331/// \param OpLoc the location of the joining operator
John McCall48f5e632009-11-06 08:53:51 +00004332/// \param Equality whether this is an "equality-like" join, which
4333/// suppresses the warning in some cases
John McCallb13c87f2009-11-05 09:23:39 +00004334void Sema::CheckSignCompare(Expr *lex, Expr *rex, SourceLocation OpLoc,
John McCall5dbad3d2009-11-06 08:49:08 +00004335 const PartialDiagnostic &PD, bool Equality) {
John McCall7d62a8f2009-11-06 18:16:06 +00004336 // Don't warn if we're in an unevaluated context.
4337 if (ExprEvalContext == Unevaluated)
4338 return;
4339
John McCall45aa4552009-11-05 00:40:04 +00004340 QualType lt = lex->getType(), rt = rex->getType();
4341
4342 // Only warn if both operands are integral.
4343 if (!lt->isIntegerType() || !rt->isIntegerType())
4344 return;
4345
Sebastian Redl732429c2009-11-05 21:09:23 +00004346 // If either expression is value-dependent, don't warn. We'll get another
4347 // chance at instantiation time.
4348 if (lex->isValueDependent() || rex->isValueDependent())
4349 return;
4350
John McCall45aa4552009-11-05 00:40:04 +00004351 // The rule is that the signed operand becomes unsigned, so isolate the
4352 // signed operand.
John McCall5dbad3d2009-11-06 08:49:08 +00004353 Expr *signedOperand, *unsignedOperand;
John McCall45aa4552009-11-05 00:40:04 +00004354 if (lt->isSignedIntegerType()) {
4355 if (rt->isSignedIntegerType()) return;
4356 signedOperand = lex;
John McCall5dbad3d2009-11-06 08:49:08 +00004357 unsignedOperand = rex;
John McCall45aa4552009-11-05 00:40:04 +00004358 } else {
4359 if (!rt->isSignedIntegerType()) return;
4360 signedOperand = rex;
John McCall5dbad3d2009-11-06 08:49:08 +00004361 unsignedOperand = lex;
John McCall45aa4552009-11-05 00:40:04 +00004362 }
4363
John McCall5dbad3d2009-11-06 08:49:08 +00004364 // If the unsigned type is strictly smaller than the signed type,
John McCall48f5e632009-11-06 08:53:51 +00004365 // then (1) the result type will be signed and (2) the unsigned
4366 // value will fit fully within the signed type, and thus the result
John McCall5dbad3d2009-11-06 08:49:08 +00004367 // of the comparison will be exact.
4368 if (Context.getIntWidth(signedOperand->getType()) >
4369 Context.getIntWidth(unsignedOperand->getType()))
4370 return;
4371
John McCall45aa4552009-11-05 00:40:04 +00004372 // If the value is a non-negative integer constant, then the
4373 // signed->unsigned conversion won't change it.
4374 llvm::APSInt value;
John McCallb13c87f2009-11-05 09:23:39 +00004375 if (signedOperand->isIntegerConstantExpr(value, Context)) {
John McCall45aa4552009-11-05 00:40:04 +00004376 assert(value.isSigned() && "result of signed expression not signed");
4377
4378 if (value.isNonNegative())
4379 return;
4380 }
4381
John McCall5dbad3d2009-11-06 08:49:08 +00004382 if (Equality) {
4383 // For (in)equality comparisons, if the unsigned operand is a
John McCall48f5e632009-11-06 08:53:51 +00004384 // constant which cannot collide with a overflowed signed operand,
4385 // then reinterpreting the signed operand as unsigned will not
4386 // change the result of the comparison.
John McCall5dbad3d2009-11-06 08:49:08 +00004387 if (unsignedOperand->isIntegerConstantExpr(value, Context)) {
4388 assert(!value.isSigned() && "result of unsigned expression is signed");
4389
4390 // 2's complement: test the top bit.
4391 if (value.isNonNegative())
4392 return;
4393 }
4394 }
4395
John McCallb13c87f2009-11-05 09:23:39 +00004396 Diag(OpLoc, PD)
John McCall45aa4552009-11-05 00:40:04 +00004397 << lex->getType() << rex->getType()
4398 << lex->getSourceRange() << rex->getSourceRange();
4399}
4400
Douglas Gregor0c6db942009-05-04 06:07:12 +00004401// C99 6.5.8, C++ [expr.rel]
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004402QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Douglas Gregora86b8322009-04-06 18:45:53 +00004403 unsigned OpaqueOpc, bool isRelational) {
4404 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)OpaqueOpc;
4405
Nate Begemanbe2341d2008-07-14 18:02:46 +00004406 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004407 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004408
John McCall5dbad3d2009-11-06 08:49:08 +00004409 CheckSignCompare(lex, rex, Loc, diag::warn_mixed_sign_comparison,
4410 (Opc == BinaryOperator::EQ || Opc == BinaryOperator::NE));
John McCall45aa4552009-11-05 00:40:04 +00004411
Chris Lattnera5937dd2007-08-26 01:18:55 +00004412 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroff30bf7712007-08-10 18:26:40 +00004413 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
4414 UsualArithmeticConversions(lex, rex);
4415 else {
4416 UsualUnaryConversions(lex);
4417 UsualUnaryConversions(rex);
4418 }
Steve Naroffc80b4ee2007-07-16 21:54:35 +00004419 QualType lType = lex->getType();
4420 QualType rType = rex->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004421
Mike Stumpaf199f32009-05-07 18:43:07 +00004422 if (!lType->isFloatingType()
4423 && !(lType->isBlockPointerType() && isRelational)) {
Chris Lattner55660a72009-03-08 19:39:53 +00004424 // For non-floating point types, check for self-comparisons of the form
4425 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
4426 // often indicate logic errors in the program.
Mike Stump1eb44332009-09-09 15:08:12 +00004427 // NOTE: Don't warn about comparisons of enum constants. These can arise
Ted Kremenek9ecede72009-03-20 19:57:37 +00004428 // from macro expansions, and are usually quite deliberate.
Chris Lattner55660a72009-03-08 19:39:53 +00004429 Expr *LHSStripped = lex->IgnoreParens();
4430 Expr *RHSStripped = rex->IgnoreParens();
4431 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped))
4432 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped))
Ted Kremenekb82dcd82009-03-20 18:35:45 +00004433 if (DRL->getDecl() == DRR->getDecl() &&
4434 !isa<EnumConstantDecl>(DRL->getDecl()))
Mike Stumpeed9cac2009-02-19 03:04:26 +00004435 Diag(Loc, diag::warn_selfcomparison);
Mike Stump1eb44332009-09-09 15:08:12 +00004436
Chris Lattner55660a72009-03-08 19:39:53 +00004437 if (isa<CastExpr>(LHSStripped))
4438 LHSStripped = LHSStripped->IgnoreParenCasts();
4439 if (isa<CastExpr>(RHSStripped))
4440 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00004441
Chris Lattner55660a72009-03-08 19:39:53 +00004442 // Warn about comparisons against a string constant (unless the other
4443 // operand is null), the user probably wants strcmp.
Douglas Gregora86b8322009-04-06 18:45:53 +00004444 Expr *literalString = 0;
4445 Expr *literalStringStripped = 0;
Chris Lattner55660a72009-03-08 19:39:53 +00004446 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Douglas Gregorce940492009-09-25 04:25:58 +00004447 !RHSStripped->isNullPointerConstant(Context,
4448 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregora86b8322009-04-06 18:45:53 +00004449 literalString = lex;
4450 literalStringStripped = LHSStripped;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00004451 } else if ((isa<StringLiteral>(RHSStripped) ||
4452 isa<ObjCEncodeExpr>(RHSStripped)) &&
Douglas Gregorce940492009-09-25 04:25:58 +00004453 !LHSStripped->isNullPointerConstant(Context,
4454 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregora86b8322009-04-06 18:45:53 +00004455 literalString = rex;
4456 literalStringStripped = RHSStripped;
4457 }
4458
4459 if (literalString) {
4460 std::string resultComparison;
4461 switch (Opc) {
4462 case BinaryOperator::LT: resultComparison = ") < 0"; break;
4463 case BinaryOperator::GT: resultComparison = ") > 0"; break;
4464 case BinaryOperator::LE: resultComparison = ") <= 0"; break;
4465 case BinaryOperator::GE: resultComparison = ") >= 0"; break;
4466 case BinaryOperator::EQ: resultComparison = ") == 0"; break;
4467 case BinaryOperator::NE: resultComparison = ") != 0"; break;
4468 default: assert(false && "Invalid comparison operator");
4469 }
4470 Diag(Loc, diag::warn_stringcompare)
4471 << isa<ObjCEncodeExpr>(literalStringStripped)
4472 << literalString->getSourceRange()
Douglas Gregora3a83512009-04-01 23:51:29 +00004473 << CodeModificationHint::CreateReplacement(SourceRange(Loc), ", ")
4474 << CodeModificationHint::CreateInsertion(lex->getLocStart(),
4475 "strcmp(")
4476 << CodeModificationHint::CreateInsertion(
4477 PP.getLocForEndOfToken(rex->getLocEnd()),
Douglas Gregora86b8322009-04-06 18:45:53 +00004478 resultComparison);
4479 }
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00004480 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004481
Douglas Gregor447b69e2008-11-19 03:25:36 +00004482 // The result of comparisons is 'bool' in C++, 'int' in C.
Chris Lattner55660a72009-03-08 19:39:53 +00004483 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy :Context.IntTy;
Douglas Gregor447b69e2008-11-19 03:25:36 +00004484
Chris Lattnera5937dd2007-08-26 01:18:55 +00004485 if (isRelational) {
4486 if (lType->isRealType() && rType->isRealType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00004487 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00004488 } else {
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00004489 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00004490 if (lType->isFloatingType()) {
Chris Lattner55660a72009-03-08 19:39:53 +00004491 assert(rType->isFloatingType());
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004492 CheckFloatComparison(Loc,lex,rex);
Ted Kremenek6a261552007-10-29 16:40:01 +00004493 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004494
Chris Lattnera5937dd2007-08-26 01:18:55 +00004495 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00004496 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00004497 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004498
Douglas Gregorce940492009-09-25 04:25:58 +00004499 bool LHSIsNull = lex->isNullPointerConstant(Context,
4500 Expr::NPC_ValueDependentIsNull);
4501 bool RHSIsNull = rex->isNullPointerConstant(Context,
4502 Expr::NPC_ValueDependentIsNull);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004503
Chris Lattnera5937dd2007-08-26 01:18:55 +00004504 // All of the following pointer related warnings are GCC extensions, except
4505 // when handling null pointer constants. One day, we can consider making them
4506 // errors (when -pedantic-errors is enabled).
Steve Naroff77878cc2007-08-27 04:08:11 +00004507 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00004508 QualType LCanPointeeTy =
Ted Kremenek6217b802009-07-29 21:53:49 +00004509 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattnerbc896f52008-04-03 05:07:25 +00004510 QualType RCanPointeeTy =
Ted Kremenek6217b802009-07-29 21:53:49 +00004511 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stumpeed9cac2009-02-19 03:04:26 +00004512
Douglas Gregor0c6db942009-05-04 06:07:12 +00004513 if (getLangOptions().CPlusPlus) {
Eli Friedman3075e762009-08-23 00:27:47 +00004514 if (LCanPointeeTy == RCanPointeeTy)
4515 return ResultTy;
4516
Douglas Gregor0c6db942009-05-04 06:07:12 +00004517 // C++ [expr.rel]p2:
4518 // [...] Pointer conversions (4.10) and qualification
4519 // conversions (4.4) are performed on pointer operands (or on
4520 // a pointer operand and a null pointer constant) to bring
4521 // them to their composite pointer type. [...]
4522 //
Douglas Gregor20b3e992009-08-24 17:42:35 +00004523 // C++ [expr.eq]p1 uses the same notion for (in)equality
Douglas Gregor0c6db942009-05-04 06:07:12 +00004524 // comparisons of pointers.
Douglas Gregorde866f32009-05-05 04:50:50 +00004525 QualType T = FindCompositePointerType(lex, rex);
Douglas Gregor0c6db942009-05-04 06:07:12 +00004526 if (T.isNull()) {
4527 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
4528 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4529 return QualType();
4530 }
4531
Eli Friedman73c39ab2009-10-20 08:27:19 +00004532 ImpCastExprToType(lex, T, CastExpr::CK_BitCast);
4533 ImpCastExprToType(rex, T, CastExpr::CK_BitCast);
Douglas Gregor0c6db942009-05-04 06:07:12 +00004534 return ResultTy;
4535 }
Eli Friedman3075e762009-08-23 00:27:47 +00004536 // C99 6.5.9p2 and C99 6.5.8p2
4537 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
4538 RCanPointeeTy.getUnqualifiedType())) {
4539 // Valid unless a relational comparison of function pointers
4540 if (isRelational && LCanPointeeTy->isFunctionType()) {
4541 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
4542 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4543 }
4544 } else if (!isRelational &&
4545 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
4546 // Valid unless comparison between non-null pointer and function pointer
4547 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
4548 && !LHSIsNull && !RHSIsNull) {
4549 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
4550 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4551 }
4552 } else {
4553 // Invalid
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004554 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattnerd1625842008-11-24 06:25:27 +00004555 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00004556 }
Eli Friedman3075e762009-08-23 00:27:47 +00004557 if (LCanPointeeTy != RCanPointeeTy)
Eli Friedman73c39ab2009-10-20 08:27:19 +00004558 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00004559 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00004560 }
Mike Stump1eb44332009-09-09 15:08:12 +00004561
Sebastian Redl6e8ed162009-05-10 18:38:11 +00004562 if (getLangOptions().CPlusPlus) {
Mike Stump1eb44332009-09-09 15:08:12 +00004563 // Comparison of pointers with null pointer constants and equality
Douglas Gregor20b3e992009-08-24 17:42:35 +00004564 // comparisons of member pointers to null pointer constants.
Mike Stump1eb44332009-09-09 15:08:12 +00004565 if (RHSIsNull &&
Douglas Gregor20b3e992009-08-24 17:42:35 +00004566 (lType->isPointerType() ||
4567 (!isRelational && lType->isMemberPointerType()))) {
Anders Carlsson26ba8502009-08-24 18:03:14 +00004568 ImpCastExprToType(rex, lType, CastExpr::CK_NullToMemberPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00004569 return ResultTy;
4570 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00004571 if (LHSIsNull &&
4572 (rType->isPointerType() ||
4573 (!isRelational && rType->isMemberPointerType()))) {
Anders Carlsson26ba8502009-08-24 18:03:14 +00004574 ImpCastExprToType(lex, rType, CastExpr::CK_NullToMemberPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00004575 return ResultTy;
4576 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00004577
4578 // Comparison of member pointers.
Mike Stump1eb44332009-09-09 15:08:12 +00004579 if (!isRelational &&
Douglas Gregor20b3e992009-08-24 17:42:35 +00004580 lType->isMemberPointerType() && rType->isMemberPointerType()) {
4581 // C++ [expr.eq]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00004582 // In addition, pointers to members can be compared, or a pointer to
4583 // member and a null pointer constant. Pointer to member conversions
4584 // (4.11) and qualification conversions (4.4) are performed to bring
4585 // them to a common type. If one operand is a null pointer constant,
4586 // the common type is the type of the other operand. Otherwise, the
4587 // common type is a pointer to member type similar (4.4) to the type
4588 // of one of the operands, with a cv-qualification signature (4.4)
4589 // that is the union of the cv-qualification signatures of the operand
Douglas Gregor20b3e992009-08-24 17:42:35 +00004590 // types.
4591 QualType T = FindCompositePointerType(lex, rex);
4592 if (T.isNull()) {
4593 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
4594 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4595 return QualType();
4596 }
Mike Stump1eb44332009-09-09 15:08:12 +00004597
Eli Friedman73c39ab2009-10-20 08:27:19 +00004598 ImpCastExprToType(lex, T, CastExpr::CK_BitCast);
4599 ImpCastExprToType(rex, T, CastExpr::CK_BitCast);
Douglas Gregor20b3e992009-08-24 17:42:35 +00004600 return ResultTy;
4601 }
Mike Stump1eb44332009-09-09 15:08:12 +00004602
Douglas Gregor20b3e992009-08-24 17:42:35 +00004603 // Comparison of nullptr_t with itself.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00004604 if (lType->isNullPtrType() && rType->isNullPtrType())
4605 return ResultTy;
4606 }
Mike Stump1eb44332009-09-09 15:08:12 +00004607
Steve Naroff1c7d0672008-09-04 15:10:53 +00004608 // Handle block pointer types.
Mike Stumpdd3e1662009-05-07 03:14:14 +00004609 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004610 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
4611 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004612
Steve Naroff1c7d0672008-09-04 15:10:53 +00004613 if (!LHSIsNull && !RHSIsNull &&
Eli Friedman26784c12009-06-08 05:08:54 +00004614 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004615 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattnerd1625842008-11-24 06:25:27 +00004616 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff1c7d0672008-09-04 15:10:53 +00004617 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00004618 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00004619 return ResultTy;
Steve Naroff1c7d0672008-09-04 15:10:53 +00004620 }
Steve Naroff59f53942008-09-28 01:11:11 +00004621 // Allow block pointers to be compared with null pointer constants.
Mike Stumpdd3e1662009-05-07 03:14:14 +00004622 if (!isRelational
4623 && ((lType->isBlockPointerType() && rType->isPointerType())
4624 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Naroff59f53942008-09-28 01:11:11 +00004625 if (!LHSIsNull && !RHSIsNull) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004626 if (!((rType->isPointerType() && rType->getAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00004627 ->getPointeeType()->isVoidType())
Ted Kremenek6217b802009-07-29 21:53:49 +00004628 || (lType->isPointerType() && lType->getAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00004629 ->getPointeeType()->isVoidType())))
4630 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
4631 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff59f53942008-09-28 01:11:11 +00004632 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00004633 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00004634 return ResultTy;
Steve Naroff59f53942008-09-28 01:11:11 +00004635 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00004636
Steve Naroff14108da2009-07-10 23:34:53 +00004637 if ((lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType())) {
Steve Naroffa5ad8632008-10-27 10:33:19 +00004638 if (lType->isPointerType() || rType->isPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004639 const PointerType *LPT = lType->getAs<PointerType>();
4640 const PointerType *RPT = rType->getAs<PointerType>();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004641 bool LPtrToVoid = LPT ?
Steve Naroffa8069f12008-11-17 19:49:16 +00004642 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004643 bool RPtrToVoid = RPT ?
Steve Naroffa8069f12008-11-17 19:49:16 +00004644 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004645
Steve Naroffa8069f12008-11-17 19:49:16 +00004646 if (!LPtrToVoid && !RPtrToVoid &&
4647 !Context.typesAreCompatible(lType, rType)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004648 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattnerd1625842008-11-24 06:25:27 +00004649 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroffa5ad8632008-10-27 10:33:19 +00004650 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00004651 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00004652 return ResultTy;
Steve Naroff87f3b932008-10-20 18:19:10 +00004653 }
Steve Naroff14108da2009-07-10 23:34:53 +00004654 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00004655 if (!Context.areComparableObjCPointerTypes(lType, rType))
Steve Naroff14108da2009-07-10 23:34:53 +00004656 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
4657 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00004658 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00004659 return ResultTy;
Steve Naroff20373222008-06-03 14:04:54 +00004660 }
Fariborz Jahanian7359f042007-12-20 01:06:58 +00004661 }
Steve Naroff58f9f2c2009-07-14 18:25:06 +00004662 if (lType->isAnyPointerType() && rType->isIntegerType()) {
Chris Lattner06c0f5b2009-08-23 00:03:44 +00004663 unsigned DiagID = 0;
4664 if (RHSIsNull) {
4665 if (isRelational)
4666 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
4667 } else if (isRelational)
4668 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
4669 else
4670 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump1eb44332009-09-09 15:08:12 +00004671
Chris Lattner06c0f5b2009-08-23 00:03:44 +00004672 if (DiagID) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00004673 Diag(Loc, DiagID)
Chris Lattner149f1382009-06-30 06:24:05 +00004674 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner6365e3e2009-08-22 18:58:31 +00004675 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00004676 ImpCastExprToType(rex, lType, CastExpr::CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00004677 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00004678 }
Steve Naroff58f9f2c2009-07-14 18:25:06 +00004679 if (lType->isIntegerType() && rType->isAnyPointerType()) {
Chris Lattner06c0f5b2009-08-23 00:03:44 +00004680 unsigned DiagID = 0;
4681 if (LHSIsNull) {
4682 if (isRelational)
4683 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
4684 } else if (isRelational)
4685 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
4686 else
4687 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump1eb44332009-09-09 15:08:12 +00004688
Chris Lattner06c0f5b2009-08-23 00:03:44 +00004689 if (DiagID) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00004690 Diag(Loc, DiagID)
Chris Lattner149f1382009-06-30 06:24:05 +00004691 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner6365e3e2009-08-22 18:58:31 +00004692 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00004693 ImpCastExprToType(lex, rType, CastExpr::CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00004694 return ResultTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00004695 }
Steve Naroff39218df2008-09-04 16:56:14 +00004696 // Handle block pointers.
Mike Stumpaf199f32009-05-07 18:43:07 +00004697 if (!isRelational && RHSIsNull
4698 && lType->isBlockPointerType() && rType->isIntegerType()) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004699 ImpCastExprToType(rex, lType, CastExpr::CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00004700 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00004701 }
Mike Stumpaf199f32009-05-07 18:43:07 +00004702 if (!isRelational && LHSIsNull
4703 && lType->isIntegerType() && rType->isBlockPointerType()) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004704 ImpCastExprToType(lex, rType, CastExpr::CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00004705 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00004706 }
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004707 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00004708}
4709
Nate Begemanbe2341d2008-07-14 18:02:46 +00004710/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stumpeed9cac2009-02-19 03:04:26 +00004711/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begemanbe2341d2008-07-14 18:02:46 +00004712/// like a scalar comparison, a vector comparison produces a vector of integer
4713/// types.
4714QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004715 SourceLocation Loc,
Nate Begemanbe2341d2008-07-14 18:02:46 +00004716 bool isRelational) {
4717 // Check to make sure we're operating on vectors of the same type and width,
4718 // Allowing one side to be a scalar of element type.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004719 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanbe2341d2008-07-14 18:02:46 +00004720 if (vType.isNull())
4721 return vType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004722
Nate Begemanbe2341d2008-07-14 18:02:46 +00004723 QualType lType = lex->getType();
4724 QualType rType = rex->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004725
Nate Begemanbe2341d2008-07-14 18:02:46 +00004726 // For non-floating point types, check for self-comparisons of the form
4727 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
4728 // often indicate logic errors in the program.
4729 if (!lType->isFloatingType()) {
4730 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
4731 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
4732 if (DRL->getDecl() == DRR->getDecl())
Mike Stumpeed9cac2009-02-19 03:04:26 +00004733 Diag(Loc, diag::warn_selfcomparison);
Nate Begemanbe2341d2008-07-14 18:02:46 +00004734 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004735
Nate Begemanbe2341d2008-07-14 18:02:46 +00004736 // Check for comparisons of floating point operands using != and ==.
4737 if (!isRelational && lType->isFloatingType()) {
4738 assert (rType->isFloatingType());
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004739 CheckFloatComparison(Loc,lex,rex);
Nate Begemanbe2341d2008-07-14 18:02:46 +00004740 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004741
Nate Begemanbe2341d2008-07-14 18:02:46 +00004742 // Return the type for the comparison, which is the same as vector type for
4743 // integer vectors, or an integer type of identical size and number of
4744 // elements for floating point vectors.
4745 if (lType->isIntegerType())
4746 return lType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004747
John McCall183700f2009-09-21 23:43:11 +00004748 const VectorType *VTy = lType->getAs<VectorType>();
Nate Begemanbe2341d2008-07-14 18:02:46 +00004749 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman59b5da62009-01-18 03:20:47 +00004750 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanbe2341d2008-07-14 18:02:46 +00004751 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattnerd013aa12009-03-31 07:46:52 +00004752 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman59b5da62009-01-18 03:20:47 +00004753 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
4754
Mike Stumpeed9cac2009-02-19 03:04:26 +00004755 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman59b5da62009-01-18 03:20:47 +00004756 "Unhandled vector element size in vector compare");
Nate Begemanbe2341d2008-07-14 18:02:46 +00004757 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
4758}
4759
Reid Spencer5f016e22007-07-11 17:01:13 +00004760inline QualType Sema::CheckBitwiseOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00004761 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Steve Naroff3e5e5562007-07-16 22:23:01 +00004762 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004763 return CheckVectorOperands(Loc, lex, rex);
Steve Naroff90045e82007-07-13 23:32:42 +00004764
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004765 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004766
Steve Naroffa4332e22007-07-17 00:58:39 +00004767 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004768 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004769 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00004770}
4771
4772inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Mike Stump1eb44332009-09-09 15:08:12 +00004773 Expr *&lex, Expr *&rex, SourceLocation Loc) {
Steve Naroffc80b4ee2007-07-16 21:54:35 +00004774 UsualUnaryConversions(lex);
4775 UsualUnaryConversions(rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004776
Anders Carlsson04905012009-10-16 01:44:21 +00004777 if (!lex->getType()->isScalarType() || !rex->getType()->isScalarType())
4778 return InvalidOperands(Loc, lex, rex);
4779
4780 if (Context.getLangOptions().CPlusPlus) {
4781 // C++ [expr.log.and]p2
4782 // C++ [expr.log.or]p2
4783 return Context.BoolTy;
4784 }
4785
4786 return Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00004787}
4788
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00004789/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
4790/// is a read-only property; return true if so. A readonly property expression
4791/// depends on various declarations and thus must be treated specially.
4792///
Mike Stump1eb44332009-09-09 15:08:12 +00004793static bool IsReadonlyProperty(Expr *E, Sema &S) {
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00004794 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
4795 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
4796 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
4797 QualType BaseType = PropExpr->getBase()->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00004798 if (const ObjCObjectPointerType *OPT =
Steve Naroff14108da2009-07-10 23:34:53 +00004799 BaseType->getAsObjCInterfacePointerType())
4800 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
4801 if (S.isPropertyReadonly(PDecl, IFace))
4802 return true;
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00004803 }
4804 }
4805 return false;
4806}
4807
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00004808/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
4809/// emit an error and return true. If so, return false.
4810static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbar44e35f72009-04-15 00:08:05 +00004811 SourceLocation OrigLoc = Loc;
Mike Stump1eb44332009-09-09 15:08:12 +00004812 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbar44e35f72009-04-15 00:08:05 +00004813 &Loc);
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00004814 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
4815 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00004816 if (IsLV == Expr::MLV_Valid)
4817 return false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004818
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00004819 unsigned Diag = 0;
4820 bool NeedType = false;
4821 switch (IsLV) { // C99 6.5.16p2
4822 default: assert(0 && "Unknown result from isModifiableLvalue!");
4823 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004824 case Expr::MLV_ArrayType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00004825 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
4826 NeedType = true;
4827 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004828 case Expr::MLV_NotObjectType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00004829 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
4830 NeedType = true;
4831 break;
Chris Lattnerca354fa2008-11-17 19:51:54 +00004832 case Expr::MLV_LValueCast:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00004833 Diag = diag::err_typecheck_lvalue_casts_not_supported;
4834 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00004835 case Expr::MLV_InvalidExpression:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00004836 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
4837 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00004838 case Expr::MLV_IncompleteType:
4839 case Expr::MLV_IncompleteVoidType:
Douglas Gregor86447ec2009-03-09 16:13:40 +00004840 return S.RequireCompleteType(Loc, E->getType(),
Anders Carlssonb7906612009-08-26 23:45:07 +00004841 PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
4842 << E->getSourceRange());
Chris Lattner5cf216b2008-01-04 18:04:52 +00004843 case Expr::MLV_DuplicateVectorComponents:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00004844 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
4845 break;
Steve Naroff4f6a7d72008-09-26 14:41:28 +00004846 case Expr::MLV_NotBlockQualified:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00004847 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
4848 break;
Fariborz Jahanian5daf5702008-11-22 18:39:36 +00004849 case Expr::MLV_ReadonlyProperty:
4850 Diag = diag::error_readonly_property_assignment;
4851 break;
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00004852 case Expr::MLV_NoSetterProperty:
4853 Diag = diag::error_nosetter_property_assignment;
4854 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00004855 }
Steve Naroffd1861fd2007-07-31 12:34:36 +00004856
Daniel Dunbar44e35f72009-04-15 00:08:05 +00004857 SourceRange Assign;
4858 if (Loc != OrigLoc)
4859 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00004860 if (NeedType)
Daniel Dunbar44e35f72009-04-15 00:08:05 +00004861 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00004862 else
Mike Stump1eb44332009-09-09 15:08:12 +00004863 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00004864 return true;
4865}
4866
4867
4868
4869// C99 6.5.16.1
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004870QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
4871 SourceLocation Loc,
4872 QualType CompoundType) {
4873 // Verify that LHS is a modifiable lvalue, and emit error if not.
4874 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00004875 return QualType();
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004876
4877 QualType LHSType = LHS->getType();
4878 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004879
Chris Lattner5cf216b2008-01-04 18:04:52 +00004880 AssignConvertType ConvTy;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004881 if (CompoundType.isNull()) {
Chris Lattner2c156472008-08-21 18:04:13 +00004882 // Simple assignment "x = y".
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004883 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004884 // Special case of NSObject attributes on c-style pointer types.
4885 if (ConvTy == IncompatiblePointer &&
4886 ((Context.isObjCNSObjectType(LHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00004887 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004888 (Context.isObjCNSObjectType(RHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00004889 LHSType->isObjCObjectPointerType())))
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004890 ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004891
Chris Lattner2c156472008-08-21 18:04:13 +00004892 // If the RHS is a unary plus or minus, check to see if they = and + are
4893 // right next to each other. If so, the user may have typo'd "x =+ 4"
4894 // instead of "x += 4".
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004895 Expr *RHSCheck = RHS;
Chris Lattner2c156472008-08-21 18:04:13 +00004896 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
4897 RHSCheck = ICE->getSubExpr();
4898 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
4899 if ((UO->getOpcode() == UnaryOperator::Plus ||
4900 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004901 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner2c156472008-08-21 18:04:13 +00004902 // Only if the two operators are exactly adjacent.
Chris Lattner399bd1b2009-03-08 06:51:10 +00004903 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
4904 // And there is a space or other character before the subexpr of the
4905 // unary +/-. We don't want to warn on "x=-1".
Chris Lattner3e872092009-03-09 07:11:10 +00004906 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
4907 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00004908 Diag(Loc, diag::warn_not_compound_assign)
4909 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
4910 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner399bd1b2009-03-08 06:51:10 +00004911 }
Chris Lattner2c156472008-08-21 18:04:13 +00004912 }
4913 } else {
4914 // Compound assignment "x += y"
Eli Friedman623712b2009-05-16 05:56:02 +00004915 ConvTy = CheckAssignmentConstraints(LHSType, RHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00004916 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00004917
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004918 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
4919 RHS, "assigning"))
Chris Lattner5cf216b2008-01-04 18:04:52 +00004920 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004921
Reid Spencer5f016e22007-07-11 17:01:13 +00004922 // C99 6.5.16p3: The type of an assignment expression is the type of the
4923 // left operand unless the left operand has qualified type, in which case
Mike Stumpeed9cac2009-02-19 03:04:26 +00004924 // it is the unqualified version of the type of the left operand.
Reid Spencer5f016e22007-07-11 17:01:13 +00004925 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
4926 // is converted to the type of the assignment expression (above).
Chris Lattner73d0d4f2007-08-30 17:45:32 +00004927 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregor2d833e32009-05-02 00:36:19 +00004928 // operand.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004929 return LHSType.getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +00004930}
4931
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004932// C99 6.5.17
4933QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
Chris Lattner53fcaa92008-07-25 20:54:07 +00004934 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004935 DefaultFunctionArrayConversion(RHS);
Eli Friedmanb1d796d2009-03-23 00:24:07 +00004936
4937 // FIXME: Check that RHS type is complete in C mode (it's legal for it to be
4938 // incomplete in C++).
4939
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004940 return RHS->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00004941}
4942
Steve Naroff49b45262007-07-13 16:58:59 +00004943/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
4944/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00004945QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
4946 bool isInc) {
Sebastian Redl28507842009-02-26 14:39:58 +00004947 if (Op->isTypeDependent())
4948 return Context.DependentTy;
4949
Chris Lattner3528d352008-11-21 07:05:48 +00004950 QualType ResType = Op->getType();
4951 assert(!ResType.isNull() && "no type for increment/decrement expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00004952
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00004953 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
4954 // Decrement of bool is not allowed.
4955 if (!isInc) {
4956 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
4957 return QualType();
4958 }
4959 // Increment of bool sets it to true, but is deprecated.
4960 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
4961 } else if (ResType->isRealType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00004962 // OK!
Steve Naroff58f9f2c2009-07-14 18:25:06 +00004963 } else if (ResType->isAnyPointerType()) {
4964 QualType PointeeTy = ResType->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00004965
Chris Lattner3528d352008-11-21 07:05:48 +00004966 // C99 6.5.2.4p2, 6.5.6p2
Steve Naroff14108da2009-07-10 23:34:53 +00004967 if (PointeeTy->isVoidType()) {
Douglas Gregorc983b862009-01-23 00:36:41 +00004968 if (getLangOptions().CPlusPlus) {
4969 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
4970 << Op->getSourceRange();
4971 return QualType();
4972 }
4973
4974 // Pointer to void is a GNU extension in C.
Chris Lattner3528d352008-11-21 07:05:48 +00004975 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Steve Naroff14108da2009-07-10 23:34:53 +00004976 } else if (PointeeTy->isFunctionType()) {
Douglas Gregorc983b862009-01-23 00:36:41 +00004977 if (getLangOptions().CPlusPlus) {
4978 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
4979 << Op->getType() << Op->getSourceRange();
4980 return QualType();
4981 }
4982
4983 Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattnerd1625842008-11-24 06:25:27 +00004984 << ResType << Op->getSourceRange();
Steve Naroff14108da2009-07-10 23:34:53 +00004985 } else if (RequireCompleteType(OpLoc, PointeeTy,
Anders Carlssond497ba72009-08-26 22:59:12 +00004986 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
Mike Stump1eb44332009-09-09 15:08:12 +00004987 << Op->getSourceRange()
Anders Carlssond497ba72009-08-26 22:59:12 +00004988 << ResType))
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004989 return QualType();
Fariborz Jahanian9f8a04f2009-07-16 17:59:14 +00004990 // Diagnose bad cases where we step over interface counts.
4991 else if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4992 Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
4993 << PointeeTy << Op->getSourceRange();
4994 return QualType();
4995 }
Chris Lattner3528d352008-11-21 07:05:48 +00004996 } else if (ResType->isComplexType()) {
4997 // C99 does not support ++/-- on complex types, we allow as an extension.
4998 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00004999 << ResType << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00005000 } else {
5001 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Chris Lattnerd1625842008-11-24 06:25:27 +00005002 << ResType << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00005003 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00005004 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005005 // At this point, we know we have a real, complex or pointer type.
Steve Naroffdd10e022007-08-23 21:37:33 +00005006 // Now make sure the operand is a modifiable lvalue.
Chris Lattner3528d352008-11-21 07:05:48 +00005007 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Reid Spencer5f016e22007-07-11 17:01:13 +00005008 return QualType();
Chris Lattner3528d352008-11-21 07:05:48 +00005009 return ResType;
Reid Spencer5f016e22007-07-11 17:01:13 +00005010}
5011
Anders Carlsson369dee42008-02-01 07:15:58 +00005012/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Reid Spencer5f016e22007-07-11 17:01:13 +00005013/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00005014/// where the declaration is needed for type checking. We only need to
5015/// handle cases when the expression references a function designator
5016/// or is an lvalue. Here are some examples:
5017/// - &(x) => x
5018/// - &*****f => f for f a function designator.
5019/// - &s.xx => s
5020/// - &s.zz[1].yy -> s, if zz is an array
5021/// - *(x + 1) -> x, if x is an array
5022/// - &"123"[2] -> 0
5023/// - & __real__ x -> x
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005024static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00005025 switch (E->getStmtClass()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00005026 case Stmt::DeclRefExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00005027 return cast<DeclRefExpr>(E)->getDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00005028 case Stmt::MemberExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00005029 // If this is an arrow operator, the address is an offset from
5030 // the base's value, so the object the base refers to is
5031 // irrelevant.
Chris Lattnerf0467b32008-04-02 04:24:33 +00005032 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnerf82228f2007-11-16 17:46:48 +00005033 return 0;
Eli Friedman23d58ce2009-04-20 08:23:18 +00005034 // Otherwise, the expression refers to a part of the base
Chris Lattnerf0467b32008-04-02 04:24:33 +00005035 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson369dee42008-02-01 07:15:58 +00005036 case Stmt::ArraySubscriptExprClass: {
Mike Stump390b4cc2009-05-16 07:39:55 +00005037 // FIXME: This code shouldn't be necessary! We should catch the implicit
5038 // promotion of register arrays earlier.
Eli Friedman23d58ce2009-04-20 08:23:18 +00005039 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
5040 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
5041 if (ICE->getSubExpr()->getType()->isArrayType())
5042 return getPrimaryDecl(ICE->getSubExpr());
5043 }
5044 return 0;
Anders Carlsson369dee42008-02-01 07:15:58 +00005045 }
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00005046 case Stmt::UnaryOperatorClass: {
5047 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005048
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00005049 switch(UO->getOpcode()) {
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00005050 case UnaryOperator::Real:
5051 case UnaryOperator::Imag:
5052 case UnaryOperator::Extension:
5053 return getPrimaryDecl(UO->getSubExpr());
5054 default:
5055 return 0;
5056 }
5057 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005058 case Stmt::ParenExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00005059 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnerf82228f2007-11-16 17:46:48 +00005060 case Stmt::ImplicitCastExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00005061 // If the result of an implicit cast is an l-value, we care about
5062 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattnerf0467b32008-04-02 04:24:33 +00005063 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Reid Spencer5f016e22007-07-11 17:01:13 +00005064 default:
5065 return 0;
5066 }
5067}
5068
5069/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stumpeed9cac2009-02-19 03:04:26 +00005070/// designator or an lvalue designating an object. If it is an lvalue, the
Reid Spencer5f016e22007-07-11 17:01:13 +00005071/// object cannot be declared with storage class register or be a bit field.
Mike Stumpeed9cac2009-02-19 03:04:26 +00005072/// Note: The usual conversions are *not* applied to the operand of the &
Reid Spencer5f016e22007-07-11 17:01:13 +00005073/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stumpeed9cac2009-02-19 03:04:26 +00005074/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregor904eed32008-11-10 20:40:00 +00005075/// we allow the '&' but retain the overloaded-function type.
Reid Spencer5f016e22007-07-11 17:01:13 +00005076QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Eli Friedman23d58ce2009-04-20 08:23:18 +00005077 // Make sure to ignore parentheses in subsequent checks
5078 op = op->IgnoreParens();
5079
Douglas Gregor9103bb22008-12-17 22:52:20 +00005080 if (op->isTypeDependent())
5081 return Context.DependentTy;
5082
Steve Naroff08f19672008-01-13 17:10:08 +00005083 if (getLangOptions().C99) {
5084 // Implement C99-only parts of addressof rules.
5085 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
5086 if (uOp->getOpcode() == UnaryOperator::Deref)
5087 // Per C99 6.5.3.2, the address of a deref always returns a valid result
5088 // (assuming the deref expression is valid).
5089 return uOp->getSubExpr()->getType();
5090 }
5091 // Technically, there should be a check for array subscript
5092 // expressions here, but the result of one is always an lvalue anyway.
5093 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005094 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner28be73f2008-07-26 21:30:36 +00005095 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes6b6609f2008-12-16 22:59:47 +00005096
Eli Friedman441cf102009-05-16 23:27:50 +00005097 if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
5098 // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00005099 // The operand must be either an l-value or a function designator
Eli Friedman441cf102009-05-16 23:27:50 +00005100 if (!op->getType()->isFunctionType()) {
Chris Lattnerf82228f2007-11-16 17:46:48 +00005101 // FIXME: emit more specific diag...
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00005102 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
5103 << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00005104 return QualType();
5105 }
Douglas Gregor33bbbc52009-05-02 02:18:30 +00005106 } else if (op->getBitField()) { // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00005107 // The operand cannot be a bit-field
5108 Diag(OpLoc, diag::err_typecheck_address_of)
5109 << "bit-field" << op->getSourceRange();
Douglas Gregor86f19402008-12-20 23:49:58 +00005110 return QualType();
Nate Begemanb104b1f2009-02-15 22:45:20 +00005111 } else if (isa<ExtVectorElementExpr>(op) || (isa<ArraySubscriptExpr>(op) &&
5112 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType())){
Eli Friedman23d58ce2009-04-20 08:23:18 +00005113 // The operand cannot be an element of a vector
Chris Lattnerd3a94e22008-11-20 06:06:08 +00005114 Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemanb104b1f2009-02-15 22:45:20 +00005115 << "vector element" << op->getSourceRange();
Steve Naroffbcb2b612008-02-29 23:30:25 +00005116 return QualType();
Fariborz Jahanian0337f212009-07-07 18:50:52 +00005117 } else if (isa<ObjCPropertyRefExpr>(op)) {
5118 // cannot take address of a property expression.
5119 Diag(OpLoc, diag::err_typecheck_address_of)
5120 << "property expression" << op->getSourceRange();
5121 return QualType();
Anders Carlsson1d524c32009-09-14 23:15:26 +00005122 } else if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(op)) {
5123 // FIXME: Can LHS ever be null here?
Anders Carlsson474e1022009-09-15 16:03:44 +00005124 if (!CheckAddressOfOperand(CO->getTrueExpr(), OpLoc).isNull())
5125 return CheckAddressOfOperand(CO->getFalseExpr(), OpLoc);
Steve Naroffbcb2b612008-02-29 23:30:25 +00005126 } else if (dcl) { // C99 6.5.3.2p1
Mike Stumpeed9cac2009-02-19 03:04:26 +00005127 // We have an lvalue with a decl. Make sure the decl is not declared
Reid Spencer5f016e22007-07-11 17:01:13 +00005128 // with the register storage-class specifier.
5129 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
5130 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00005131 Diag(OpLoc, diag::err_typecheck_address_of)
5132 << "register variable" << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00005133 return QualType();
5134 }
Douglas Gregor83314aa2009-07-08 20:55:45 +00005135 } else if (isa<OverloadedFunctionDecl>(dcl) ||
5136 isa<FunctionTemplateDecl>(dcl)) {
Douglas Gregor904eed32008-11-10 20:40:00 +00005137 return Context.OverloadTy;
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00005138 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(dcl)) {
Douglas Gregor29882052008-12-10 21:26:49 +00005139 // Okay: we can take the address of a field.
Sebastian Redlebc07d52009-02-03 20:19:35 +00005140 // Could be a pointer to member, though, if there is an explicit
5141 // scope qualifier for the class.
Douglas Gregora2813ce2009-10-23 18:54:35 +00005142 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redlebc07d52009-02-03 20:19:35 +00005143 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00005144 if (Ctx && Ctx->isRecord()) {
5145 if (FD->getType()->isReferenceType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00005146 Diag(OpLoc,
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00005147 diag::err_cannot_form_pointer_to_member_of_reference_type)
5148 << FD->getDeclName() << FD->getType();
5149 return QualType();
5150 }
Mike Stump1eb44332009-09-09 15:08:12 +00005151
Sebastian Redlebc07d52009-02-03 20:19:35 +00005152 return Context.getMemberPointerType(op->getType(),
5153 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00005154 }
Sebastian Redlebc07d52009-02-03 20:19:35 +00005155 }
Anders Carlsson196f7d02009-05-16 21:43:42 +00005156 } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(dcl)) {
Nuno Lopes6fea8d22008-12-16 22:58:26 +00005157 // Okay: we can take the address of a function.
Sebastian Redl33b399a2009-02-04 21:23:32 +00005158 // As above.
Douglas Gregora2813ce2009-10-23 18:54:35 +00005159 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier() &&
5160 MD->isInstance())
Anders Carlsson196f7d02009-05-16 21:43:42 +00005161 return Context.getMemberPointerType(op->getType(),
5162 Context.getTypeDeclType(MD->getParent()).getTypePtr());
5163 } else if (!isa<FunctionDecl>(dcl))
Reid Spencer5f016e22007-07-11 17:01:13 +00005164 assert(0 && "Unknown/unexpected decl type");
Reid Spencer5f016e22007-07-11 17:01:13 +00005165 }
Sebastian Redl33b399a2009-02-04 21:23:32 +00005166
Eli Friedman441cf102009-05-16 23:27:50 +00005167 if (lval == Expr::LV_IncompleteVoidType) {
5168 // Taking the address of a void variable is technically illegal, but we
5169 // allow it in cases which are otherwise valid.
5170 // Example: "extern void x; void* y = &x;".
5171 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
5172 }
5173
Reid Spencer5f016e22007-07-11 17:01:13 +00005174 // If the operand has type "type", the result has type "pointer to type".
5175 return Context.getPointerType(op->getType());
5176}
5177
Chris Lattner22caddc2008-11-23 09:13:29 +00005178QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
Sebastian Redl28507842009-02-26 14:39:58 +00005179 if (Op->isTypeDependent())
5180 return Context.DependentTy;
5181
Chris Lattner22caddc2008-11-23 09:13:29 +00005182 UsualUnaryConversions(Op);
5183 QualType Ty = Op->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005184
Chris Lattner22caddc2008-11-23 09:13:29 +00005185 // Note that per both C89 and C99, this is always legal, even if ptype is an
5186 // incomplete type or void. It would be possible to warn about dereferencing
5187 // a void pointer, but it's completely well-defined, and such a warning is
5188 // unlikely to catch any mistakes.
Ted Kremenek6217b802009-07-29 21:53:49 +00005189 if (const PointerType *PT = Ty->getAs<PointerType>())
Steve Naroff08f19672008-01-13 17:10:08 +00005190 return PT->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005191
John McCall183700f2009-09-21 23:43:11 +00005192 if (const ObjCObjectPointerType *OPT = Ty->getAs<ObjCObjectPointerType>())
Fariborz Jahanian16b10372009-09-03 00:43:07 +00005193 return OPT->getPointeeType();
Steve Naroff14108da2009-07-10 23:34:53 +00005194
Chris Lattnerd3a94e22008-11-20 06:06:08 +00005195 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner22caddc2008-11-23 09:13:29 +00005196 << Ty << Op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00005197 return QualType();
5198}
5199
5200static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
5201 tok::TokenKind Kind) {
5202 BinaryOperator::Opcode Opc;
5203 switch (Kind) {
5204 default: assert(0 && "Unknown binop!");
Sebastian Redl22460502009-02-07 00:15:38 +00005205 case tok::periodstar: Opc = BinaryOperator::PtrMemD; break;
5206 case tok::arrowstar: Opc = BinaryOperator::PtrMemI; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00005207 case tok::star: Opc = BinaryOperator::Mul; break;
5208 case tok::slash: Opc = BinaryOperator::Div; break;
5209 case tok::percent: Opc = BinaryOperator::Rem; break;
5210 case tok::plus: Opc = BinaryOperator::Add; break;
5211 case tok::minus: Opc = BinaryOperator::Sub; break;
5212 case tok::lessless: Opc = BinaryOperator::Shl; break;
5213 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
5214 case tok::lessequal: Opc = BinaryOperator::LE; break;
5215 case tok::less: Opc = BinaryOperator::LT; break;
5216 case tok::greaterequal: Opc = BinaryOperator::GE; break;
5217 case tok::greater: Opc = BinaryOperator::GT; break;
5218 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
5219 case tok::equalequal: Opc = BinaryOperator::EQ; break;
5220 case tok::amp: Opc = BinaryOperator::And; break;
5221 case tok::caret: Opc = BinaryOperator::Xor; break;
5222 case tok::pipe: Opc = BinaryOperator::Or; break;
5223 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
5224 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
5225 case tok::equal: Opc = BinaryOperator::Assign; break;
5226 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
5227 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
5228 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
5229 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
5230 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
5231 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
5232 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
5233 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
5234 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
5235 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
5236 case tok::comma: Opc = BinaryOperator::Comma; break;
5237 }
5238 return Opc;
5239}
5240
5241static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
5242 tok::TokenKind Kind) {
5243 UnaryOperator::Opcode Opc;
5244 switch (Kind) {
5245 default: assert(0 && "Unknown unary op!");
5246 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
5247 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
5248 case tok::amp: Opc = UnaryOperator::AddrOf; break;
5249 case tok::star: Opc = UnaryOperator::Deref; break;
5250 case tok::plus: Opc = UnaryOperator::Plus; break;
5251 case tok::minus: Opc = UnaryOperator::Minus; break;
5252 case tok::tilde: Opc = UnaryOperator::Not; break;
5253 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00005254 case tok::kw___real: Opc = UnaryOperator::Real; break;
5255 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
5256 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
5257 }
5258 return Opc;
5259}
5260
Douglas Gregoreaebc752008-11-06 23:29:22 +00005261/// CreateBuiltinBinOp - Creates a new built-in binary operation with
5262/// operator @p Opc at location @c TokLoc. This routine only supports
5263/// built-in operations; ActOnBinOp handles overloaded operators.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005264Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
5265 unsigned Op,
5266 Expr *lhs, Expr *rhs) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00005267 QualType ResultTy; // Result type of the binary operator.
Douglas Gregoreaebc752008-11-06 23:29:22 +00005268 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
Eli Friedmanab3a8522009-03-28 01:22:36 +00005269 // The following two variables are used for compound assignment operators
5270 QualType CompLHSTy; // Type of LHS after promotions for computation
5271 QualType CompResultTy; // Type of computation result
Douglas Gregoreaebc752008-11-06 23:29:22 +00005272
5273 switch (Opc) {
Douglas Gregoreaebc752008-11-06 23:29:22 +00005274 case BinaryOperator::Assign:
5275 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
5276 break;
Sebastian Redl22460502009-02-07 00:15:38 +00005277 case BinaryOperator::PtrMemD:
5278 case BinaryOperator::PtrMemI:
5279 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
5280 Opc == BinaryOperator::PtrMemI);
5281 break;
5282 case BinaryOperator::Mul:
Douglas Gregoreaebc752008-11-06 23:29:22 +00005283 case BinaryOperator::Div:
5284 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
5285 break;
5286 case BinaryOperator::Rem:
5287 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
5288 break;
5289 case BinaryOperator::Add:
5290 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
5291 break;
5292 case BinaryOperator::Sub:
5293 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
5294 break;
Sebastian Redl22460502009-02-07 00:15:38 +00005295 case BinaryOperator::Shl:
Douglas Gregoreaebc752008-11-06 23:29:22 +00005296 case BinaryOperator::Shr:
5297 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
5298 break;
5299 case BinaryOperator::LE:
5300 case BinaryOperator::LT:
5301 case BinaryOperator::GE:
5302 case BinaryOperator::GT:
Douglas Gregora86b8322009-04-06 18:45:53 +00005303 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregoreaebc752008-11-06 23:29:22 +00005304 break;
5305 case BinaryOperator::EQ:
5306 case BinaryOperator::NE:
Douglas Gregora86b8322009-04-06 18:45:53 +00005307 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregoreaebc752008-11-06 23:29:22 +00005308 break;
5309 case BinaryOperator::And:
5310 case BinaryOperator::Xor:
5311 case BinaryOperator::Or:
5312 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
5313 break;
5314 case BinaryOperator::LAnd:
5315 case BinaryOperator::LOr:
5316 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
5317 break;
5318 case BinaryOperator::MulAssign:
5319 case BinaryOperator::DivAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00005320 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
5321 CompLHSTy = CompResultTy;
5322 if (!CompResultTy.isNull())
5323 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00005324 break;
5325 case BinaryOperator::RemAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00005326 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
5327 CompLHSTy = CompResultTy;
5328 if (!CompResultTy.isNull())
5329 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00005330 break;
5331 case BinaryOperator::AddAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00005332 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
5333 if (!CompResultTy.isNull())
5334 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00005335 break;
5336 case BinaryOperator::SubAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00005337 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
5338 if (!CompResultTy.isNull())
5339 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00005340 break;
5341 case BinaryOperator::ShlAssign:
5342 case BinaryOperator::ShrAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00005343 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
5344 CompLHSTy = CompResultTy;
5345 if (!CompResultTy.isNull())
5346 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00005347 break;
5348 case BinaryOperator::AndAssign:
5349 case BinaryOperator::XorAssign:
5350 case BinaryOperator::OrAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00005351 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
5352 CompLHSTy = CompResultTy;
5353 if (!CompResultTy.isNull())
5354 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00005355 break;
5356 case BinaryOperator::Comma:
5357 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
5358 break;
5359 }
5360 if (ResultTy.isNull())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005361 return ExprError();
Eli Friedmanab3a8522009-03-28 01:22:36 +00005362 if (CompResultTy.isNull())
Steve Naroff6ece14c2009-01-21 00:14:39 +00005363 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
5364 else
5365 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
Eli Friedmanab3a8522009-03-28 01:22:36 +00005366 CompLHSTy, CompResultTy,
5367 OpLoc));
Douglas Gregoreaebc752008-11-06 23:29:22 +00005368}
5369
Sebastian Redlaee3c932009-10-27 12:10:02 +00005370/// SuggestParentheses - Emit a diagnostic together with a fixit hint that wraps
5371/// ParenRange in parentheses.
Sebastian Redl6b169ac2009-10-26 17:01:32 +00005372static void SuggestParentheses(Sema &Self, SourceLocation Loc,
5373 const PartialDiagnostic &PD,
5374 SourceRange ParenRange)
5375{
5376 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
5377 if (!ParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
5378 // We can't display the parentheses, so just dig the
5379 // warning/error and return.
5380 Self.Diag(Loc, PD);
5381 return;
5382 }
5383
5384 Self.Diag(Loc, PD)
5385 << CodeModificationHint::CreateInsertion(ParenRange.getBegin(), "(")
5386 << CodeModificationHint::CreateInsertion(EndLoc, ")");
5387}
5388
Sebastian Redlaee3c932009-10-27 12:10:02 +00005389/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
5390/// operators are mixed in a way that suggests that the programmer forgot that
5391/// comparison operators have higher precedence. The most typical example of
5392/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00005393static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperator::Opcode Opc,
5394 SourceLocation OpLoc,Expr *lhs,Expr *rhs){
Sebastian Redlaee3c932009-10-27 12:10:02 +00005395 typedef BinaryOperator BinOp;
5396 BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1),
5397 rhsopc = static_cast<BinOp::Opcode>(-1);
5398 if (BinOp *BO = dyn_cast<BinOp>(lhs))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00005399 lhsopc = BO->getOpcode();
Sebastian Redlaee3c932009-10-27 12:10:02 +00005400 if (BinOp *BO = dyn_cast<BinOp>(rhs))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00005401 rhsopc = BO->getOpcode();
5402
5403 // Subs are not binary operators.
5404 if (lhsopc == -1 && rhsopc == -1)
5405 return;
5406
5407 // Bitwise operations are sometimes used as eager logical ops.
5408 // Don't diagnose this.
Sebastian Redlaee3c932009-10-27 12:10:02 +00005409 if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) &&
5410 (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc)))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00005411 return;
5412
Sebastian Redlaee3c932009-10-27 12:10:02 +00005413 if (BinOp::isComparisonOp(lhsopc))
Sebastian Redl6b169ac2009-10-26 17:01:32 +00005414 SuggestParentheses(Self, OpLoc,
5415 PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redlaee3c932009-10-27 12:10:02 +00005416 << SourceRange(lhs->getLocStart(), OpLoc)
5417 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(lhsopc),
5418 SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(), rhs->getLocEnd()));
5419 else if (BinOp::isComparisonOp(rhsopc))
Sebastian Redl6b169ac2009-10-26 17:01:32 +00005420 SuggestParentheses(Self, OpLoc,
5421 PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redlaee3c932009-10-27 12:10:02 +00005422 << SourceRange(OpLoc, rhs->getLocEnd())
5423 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(rhsopc),
5424 SourceRange(lhs->getLocEnd(), cast<BinOp>(rhs)->getLHS()->getLocStart()));
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00005425}
5426
5427/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
5428/// precedence. This currently diagnoses only "arg1 'bitwise' arg2 'eq' arg3".
5429/// But it could also warn about arg1 && arg2 || arg3, as GCC 4.3+ does.
5430static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperator::Opcode Opc,
5431 SourceLocation OpLoc, Expr *lhs, Expr *rhs){
Sebastian Redlaee3c932009-10-27 12:10:02 +00005432 if (BinaryOperator::isBitwiseOp(Opc))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00005433 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs);
5434}
5435
Reid Spencer5f016e22007-07-11 17:01:13 +00005436// Binary Operators. 'Tok' is the token for the operator.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005437Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
5438 tok::TokenKind Kind,
5439 ExprArg LHS, ExprArg RHS) {
Reid Spencer5f016e22007-07-11 17:01:13 +00005440 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
Anders Carlssone9146f22009-05-01 19:49:17 +00005441 Expr *lhs = LHS.takeAs<Expr>(), *rhs = RHS.takeAs<Expr>();
Reid Spencer5f016e22007-07-11 17:01:13 +00005442
Steve Narofff69936d2007-09-16 03:34:24 +00005443 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
5444 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00005445
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00005446 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
5447 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs);
5448
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00005449 return BuildBinOp(S, TokLoc, Opc, lhs, rhs);
5450}
5451
5452Action::OwningExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
5453 BinaryOperator::Opcode Opc,
5454 Expr *lhs, Expr *rhs) {
Douglas Gregor063daf62009-03-13 18:40:31 +00005455 if (getLangOptions().CPlusPlus &&
Mike Stump1eb44332009-09-09 15:08:12 +00005456 (lhs->getType()->isOverloadableType() ||
Douglas Gregor063daf62009-03-13 18:40:31 +00005457 rhs->getType()->isOverloadableType())) {
5458 // Find all of the overloaded operators visible from this
5459 // point. We perform both an operator-name lookup from the local
5460 // scope and an argument-dependent lookup based on the types of
5461 // the arguments.
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00005462 FunctionSet Functions;
Douglas Gregor063daf62009-03-13 18:40:31 +00005463 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
5464 if (OverOp != OO_None) {
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00005465 if (S)
5466 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
5467 Functions);
Douglas Gregor063daf62009-03-13 18:40:31 +00005468 Expr *Args[2] = { lhs, rhs };
Mike Stump1eb44332009-09-09 15:08:12 +00005469 DeclarationName OpName
Douglas Gregor063daf62009-03-13 18:40:31 +00005470 = Context.DeclarationNames.getCXXOperatorName(OverOp);
Sebastian Redl644be852009-10-23 19:23:15 +00005471 ArgumentDependentLookup(OpName, /*Operator*/true, Args, 2, Functions);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005472 }
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00005473
Douglas Gregor063daf62009-03-13 18:40:31 +00005474 // Build the (potentially-overloaded, potentially-dependent)
5475 // binary operation.
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00005476 return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs);
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005477 }
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00005478
Douglas Gregoreaebc752008-11-06 23:29:22 +00005479 // Build a built-in binary operation.
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00005480 return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs);
Reid Spencer5f016e22007-07-11 17:01:13 +00005481}
5482
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005483Action::OwningExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00005484 unsigned OpcIn,
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005485 ExprArg InputArg) {
5486 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor74253732008-11-19 15:42:04 +00005487
Mike Stump390b4cc2009-05-16 07:39:55 +00005488 // FIXME: Input is modified below, but InputArg is not updated appropriately.
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005489 Expr *Input = (Expr *)InputArg.get();
Reid Spencer5f016e22007-07-11 17:01:13 +00005490 QualType resultType;
5491 switch (Opc) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005492 case UnaryOperator::OffsetOf:
5493 assert(false && "Invalid unary operator");
5494 break;
5495
Reid Spencer5f016e22007-07-11 17:01:13 +00005496 case UnaryOperator::PreInc:
5497 case UnaryOperator::PreDec:
Eli Friedmande99a452009-07-22 22:25:00 +00005498 case UnaryOperator::PostInc:
5499 case UnaryOperator::PostDec:
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00005500 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
Eli Friedmande99a452009-07-22 22:25:00 +00005501 Opc == UnaryOperator::PreInc ||
5502 Opc == UnaryOperator::PostInc);
Reid Spencer5f016e22007-07-11 17:01:13 +00005503 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005504 case UnaryOperator::AddrOf:
Reid Spencer5f016e22007-07-11 17:01:13 +00005505 resultType = CheckAddressOfOperand(Input, OpLoc);
5506 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005507 case UnaryOperator::Deref:
Steve Naroff1ca9b112007-12-18 04:06:57 +00005508 DefaultFunctionArrayConversion(Input);
Reid Spencer5f016e22007-07-11 17:01:13 +00005509 resultType = CheckIndirectionOperand(Input, OpLoc);
5510 break;
5511 case UnaryOperator::Plus:
5512 case UnaryOperator::Minus:
Steve Naroffc80b4ee2007-07-16 21:54:35 +00005513 UsualUnaryConversions(Input);
5514 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00005515 if (resultType->isDependentType())
5516 break;
Douglas Gregor74253732008-11-19 15:42:04 +00005517 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
5518 break;
5519 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
5520 resultType->isEnumeralType())
5521 break;
5522 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
5523 Opc == UnaryOperator::Plus &&
5524 resultType->isPointerType())
5525 break;
5526
Sebastian Redl0eb23302009-01-19 00:08:26 +00005527 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5528 << resultType << Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00005529 case UnaryOperator::Not: // bitwise complement
Steve Naroffc80b4ee2007-07-16 21:54:35 +00005530 UsualUnaryConversions(Input);
5531 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00005532 if (resultType->isDependentType())
5533 break;
Chris Lattner02a65142008-07-25 23:52:49 +00005534 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
5535 if (resultType->isComplexType() || resultType->isComplexIntegerType())
5536 // C99 does not support '~' for complex conjugation.
Chris Lattnerd3a94e22008-11-20 06:06:08 +00005537 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00005538 << resultType << Input->getSourceRange();
Chris Lattner02a65142008-07-25 23:52:49 +00005539 else if (!resultType->isIntegerType())
Sebastian Redl0eb23302009-01-19 00:08:26 +00005540 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5541 << resultType << Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00005542 break;
5543 case UnaryOperator::LNot: // logical negation
5544 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Steve Naroffc80b4ee2007-07-16 21:54:35 +00005545 DefaultFunctionArrayConversion(Input);
5546 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00005547 if (resultType->isDependentType())
5548 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00005549 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redl0eb23302009-01-19 00:08:26 +00005550 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5551 << resultType << Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00005552 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl0eb23302009-01-19 00:08:26 +00005553 // In C++, it's bool. C++ 5.3.1p8
5554 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00005555 break;
Chris Lattnerdbb36972007-08-24 21:16:53 +00005556 case UnaryOperator::Real:
Chris Lattnerdbb36972007-08-24 21:16:53 +00005557 case UnaryOperator::Imag:
Chris Lattnerba27e2a2009-02-17 08:12:06 +00005558 resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real);
Chris Lattnerdbb36972007-08-24 21:16:53 +00005559 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00005560 case UnaryOperator::Extension:
Reid Spencer5f016e22007-07-11 17:01:13 +00005561 resultType = Input->getType();
5562 break;
5563 }
5564 if (resultType.isNull())
Sebastian Redl0eb23302009-01-19 00:08:26 +00005565 return ExprError();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005566
5567 InputArg.release();
Steve Naroff6ece14c2009-01-21 00:14:39 +00005568 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00005569}
5570
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00005571Action::OwningExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
5572 UnaryOperator::Opcode Opc,
5573 ExprArg input) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005574 Expr *Input = (Expr*)input.get();
Anders Carlssona8a1e3d2009-11-14 21:26:41 +00005575 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
5576 Opc != UnaryOperator::Extension) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005577 // Find all of the overloaded operators visible from this
5578 // point. We perform both an operator-name lookup from the local
5579 // scope and an argument-dependent lookup based on the types of
5580 // the arguments.
5581 FunctionSet Functions;
5582 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
5583 if (OverOp != OO_None) {
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00005584 if (S)
5585 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
5586 Functions);
Mike Stump1eb44332009-09-09 15:08:12 +00005587 DeclarationName OpName
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005588 = Context.DeclarationNames.getCXXOperatorName(OverOp);
Sebastian Redl644be852009-10-23 19:23:15 +00005589 ArgumentDependentLookup(OpName, /*Operator*/true, &Input, 1, Functions);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005590 }
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00005591
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005592 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, move(input));
5593 }
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00005594
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005595 return CreateBuiltinUnaryOp(OpLoc, Opc, move(input));
5596}
5597
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00005598// Unary Operators. 'Tok' is the token for the operator.
5599Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
5600 tok::TokenKind Op, ExprArg input) {
5601 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), move(input));
5602}
5603
Steve Naroff1b273c42007-09-16 14:56:35 +00005604/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Sebastian Redlf53597f2009-03-15 17:47:39 +00005605Sema::OwningExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
5606 SourceLocation LabLoc,
5607 IdentifierInfo *LabelII) {
Reid Spencer5f016e22007-07-11 17:01:13 +00005608 // Look up the record for this label identifier.
Chris Lattnerea29a3a2009-04-18 20:01:55 +00005609 LabelStmt *&LabelDecl = getLabelMap()[LabelII];
Mike Stumpeed9cac2009-02-19 03:04:26 +00005610
Daniel Dunbar0ffb1252008-08-04 16:51:22 +00005611 // If we haven't seen this label yet, create a forward reference. It
5612 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Steve Naroffcaaacec2009-03-13 15:38:40 +00005613 if (LabelDecl == 0)
Steve Naroff6ece14c2009-01-21 00:14:39 +00005614 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005615
Reid Spencer5f016e22007-07-11 17:01:13 +00005616 // Create the AST node. The address of a label always has type 'void*'.
Sebastian Redlf53597f2009-03-15 17:47:39 +00005617 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
5618 Context.getPointerType(Context.VoidTy)));
Reid Spencer5f016e22007-07-11 17:01:13 +00005619}
5620
Sebastian Redlf53597f2009-03-15 17:47:39 +00005621Sema::OwningExprResult
5622Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtArg substmt,
5623 SourceLocation RPLoc) { // "({..})"
5624 Stmt *SubStmt = static_cast<Stmt*>(substmt.get());
Chris Lattnerab18c4c2007-07-24 16:58:17 +00005625 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
5626 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
5627
Eli Friedmandca2b732009-01-24 23:09:00 +00005628 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Chris Lattner4a049f02009-04-25 19:11:05 +00005629 if (isFileScope)
Sebastian Redlf53597f2009-03-15 17:47:39 +00005630 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedmandca2b732009-01-24 23:09:00 +00005631
Chris Lattnerab18c4c2007-07-24 16:58:17 +00005632 // FIXME: there are a variety of strange constraints to enforce here, for
5633 // example, it is not possible to goto into a stmt expression apparently.
5634 // More semantic analysis is needed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00005635
Chris Lattnerab18c4c2007-07-24 16:58:17 +00005636 // If there are sub stmts in the compound stmt, take the type of the last one
5637 // as the type of the stmtexpr.
5638 QualType Ty = Context.VoidTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005639
Chris Lattner611b2ec2008-07-26 19:51:01 +00005640 if (!Compound->body_empty()) {
5641 Stmt *LastStmt = Compound->body_back();
5642 // If LastStmt is a label, skip down through into the body.
5643 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
5644 LastStmt = Label->getSubStmt();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005645
Chris Lattner611b2ec2008-07-26 19:51:01 +00005646 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattnerab18c4c2007-07-24 16:58:17 +00005647 Ty = LastExpr->getType();
Chris Lattner611b2ec2008-07-26 19:51:01 +00005648 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005649
Eli Friedmanb1d796d2009-03-23 00:24:07 +00005650 // FIXME: Check that expression type is complete/non-abstract; statement
5651 // expressions are not lvalues.
5652
Sebastian Redlf53597f2009-03-15 17:47:39 +00005653 substmt.release();
5654 return Owned(new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc));
Chris Lattnerab18c4c2007-07-24 16:58:17 +00005655}
Steve Naroffd34e9152007-08-01 22:05:33 +00005656
Sebastian Redlf53597f2009-03-15 17:47:39 +00005657Sema::OwningExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
5658 SourceLocation BuiltinLoc,
5659 SourceLocation TypeLoc,
5660 TypeTy *argty,
5661 OffsetOfComponent *CompPtr,
5662 unsigned NumComponents,
5663 SourceLocation RPLoc) {
5664 // FIXME: This function leaks all expressions in the offset components on
5665 // error.
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00005666 // FIXME: Preserve type source info.
5667 QualType ArgTy = GetTypeFromParser(argty);
Chris Lattner73d0d4f2007-08-30 17:45:32 +00005668 assert(!ArgTy.isNull() && "Missing type argument!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00005669
Sebastian Redl28507842009-02-26 14:39:58 +00005670 bool Dependent = ArgTy->isDependentType();
5671
Chris Lattner73d0d4f2007-08-30 17:45:32 +00005672 // We must have at least one component that refers to the type, and the first
5673 // one is known to be a field designator. Verify that the ArgTy represents
5674 // a struct/union/class.
Sebastian Redl28507842009-02-26 14:39:58 +00005675 if (!Dependent && !ArgTy->isRecordType())
Sebastian Redlf53597f2009-03-15 17:47:39 +00005676 return ExprError(Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005677
Eli Friedmanb1d796d2009-03-23 00:24:07 +00005678 // FIXME: Type must be complete per C99 7.17p3 because a declaring a variable
5679 // with an incomplete type would be illegal.
Douglas Gregor4fdf1fa2009-03-11 16:48:53 +00005680
Eli Friedman35183ac2009-02-27 06:44:11 +00005681 // Otherwise, create a null pointer as the base, and iteratively process
5682 // the offsetof designators.
5683 QualType ArgTyPtr = Context.getPointerType(ArgTy);
5684 Expr* Res = new (Context) ImplicitValueInitExpr(ArgTyPtr);
Sebastian Redlf53597f2009-03-15 17:47:39 +00005685 Res = new (Context) UnaryOperator(Res, UnaryOperator::Deref,
Eli Friedman35183ac2009-02-27 06:44:11 +00005686 ArgTy, SourceLocation());
Eli Friedman1d242592009-01-26 01:33:06 +00005687
Chris Lattner9e2b75c2007-08-31 21:49:13 +00005688 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
5689 // GCC extension, diagnose them.
Eli Friedman35183ac2009-02-27 06:44:11 +00005690 // FIXME: This diagnostic isn't actually visible because the location is in
5691 // a system header!
Chris Lattner9e2b75c2007-08-31 21:49:13 +00005692 if (NumComponents != 1)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00005693 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
5694 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005695
Sebastian Redl28507842009-02-26 14:39:58 +00005696 if (!Dependent) {
Eli Friedmanc0d600c2009-05-03 21:22:18 +00005697 bool DidWarnAboutNonPOD = false;
Mike Stump1eb44332009-09-09 15:08:12 +00005698
John McCalld00f2002009-11-04 03:03:43 +00005699 if (RequireCompleteType(TypeLoc, Res->getType(),
5700 diag::err_offsetof_incomplete_type))
5701 return ExprError();
5702
Sebastian Redl28507842009-02-26 14:39:58 +00005703 // FIXME: Dependent case loses a lot of information here. And probably
5704 // leaks like a sieve.
5705 for (unsigned i = 0; i != NumComponents; ++i) {
5706 const OffsetOfComponent &OC = CompPtr[i];
5707 if (OC.isBrackets) {
5708 // Offset of an array sub-field. TODO: Should we allow vector elements?
5709 const ArrayType *AT = Context.getAsArrayType(Res->getType());
5710 if (!AT) {
5711 Res->Destroy(Context);
Sebastian Redlf53597f2009-03-15 17:47:39 +00005712 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
5713 << Res->getType());
Sebastian Redl28507842009-02-26 14:39:58 +00005714 }
5715
5716 // FIXME: C++: Verify that operator[] isn't overloaded.
5717
Eli Friedman35183ac2009-02-27 06:44:11 +00005718 // Promote the array so it looks more like a normal array subscript
5719 // expression.
5720 DefaultFunctionArrayConversion(Res);
5721
Sebastian Redl28507842009-02-26 14:39:58 +00005722 // C99 6.5.2.1p1
5723 Expr *Idx = static_cast<Expr*>(OC.U.E);
Sebastian Redlf53597f2009-03-15 17:47:39 +00005724 // FIXME: Leaks Res
Sebastian Redl28507842009-02-26 14:39:58 +00005725 if (!Idx->isTypeDependent() && !Idx->getType()->isIntegerType())
Sebastian Redlf53597f2009-03-15 17:47:39 +00005726 return ExprError(Diag(Idx->getLocStart(),
Chris Lattner338395d2009-04-25 22:50:55 +00005727 diag::err_typecheck_subscript_not_integer)
Sebastian Redlf53597f2009-03-15 17:47:39 +00005728 << Idx->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +00005729
5730 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
5731 OC.LocEnd);
5732 continue;
Chris Lattner73d0d4f2007-08-30 17:45:32 +00005733 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005734
Ted Kremenek6217b802009-07-29 21:53:49 +00005735 const RecordType *RC = Res->getType()->getAs<RecordType>();
Sebastian Redl28507842009-02-26 14:39:58 +00005736 if (!RC) {
5737 Res->Destroy(Context);
Sebastian Redlf53597f2009-03-15 17:47:39 +00005738 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
5739 << Res->getType());
Sebastian Redl28507842009-02-26 14:39:58 +00005740 }
Chris Lattner704fe352007-08-30 17:59:59 +00005741
Sebastian Redl28507842009-02-26 14:39:58 +00005742 // Get the decl corresponding to this.
5743 RecordDecl *RD = RC->getDecl();
Anders Carlsson6d7f1492009-05-01 23:20:30 +00005744 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
Anders Carlsson5992e4a2009-05-02 18:36:10 +00005745 if (!CRD->isPOD() && !DidWarnAboutNonPOD) {
Anders Carlssonf9b8bc62009-05-02 17:45:47 +00005746 ExprError(Diag(BuiltinLoc, diag::warn_offsetof_non_pod_type)
5747 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
5748 << Res->getType());
Anders Carlsson5992e4a2009-05-02 18:36:10 +00005749 DidWarnAboutNonPOD = true;
5750 }
Anders Carlsson6d7f1492009-05-01 23:20:30 +00005751 }
Mike Stump1eb44332009-09-09 15:08:12 +00005752
John McCalla24dc2e2009-11-17 02:14:36 +00005753 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
5754 LookupQualifiedName(R, RD);
John McCallf36e02d2009-10-09 21:13:30 +00005755
Sebastian Redl28507842009-02-26 14:39:58 +00005756 FieldDecl *MemberDecl
John McCallf36e02d2009-10-09 21:13:30 +00005757 = dyn_cast_or_null<FieldDecl>(R.getAsSingleDecl(Context));
Sebastian Redlf53597f2009-03-15 17:47:39 +00005758 // FIXME: Leaks Res
Sebastian Redl28507842009-02-26 14:39:58 +00005759 if (!MemberDecl)
Douglas Gregor3f093272009-10-13 21:16:44 +00005760 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
5761 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, OC.LocEnd));
Mike Stumpeed9cac2009-02-19 03:04:26 +00005762
Sebastian Redl28507842009-02-26 14:39:58 +00005763 // FIXME: C++: Verify that MemberDecl isn't a static field.
5764 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedmane9356962009-04-26 20:50:44 +00005765 if (cast<RecordDecl>(MemberDecl->getDeclContext())->isAnonymousStructOrUnion()) {
Anders Carlssonf1b1d592009-05-01 19:30:39 +00005766 Res = BuildAnonymousStructUnionMemberReference(
John McCall09b6d0e2009-11-11 03:23:23 +00005767 OC.LocEnd, MemberDecl, Res, OC.LocEnd).takeAs<Expr>();
Eli Friedmane9356962009-04-26 20:50:44 +00005768 } else {
5769 // MemberDecl->getType() doesn't get the right qualifiers, but it
5770 // doesn't matter here.
5771 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
5772 MemberDecl->getType().getNonReferenceType());
5773 }
Sebastian Redl28507842009-02-26 14:39:58 +00005774 }
Chris Lattner73d0d4f2007-08-30 17:45:32 +00005775 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005776
Sebastian Redlf53597f2009-03-15 17:47:39 +00005777 return Owned(new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
5778 Context.getSizeType(), BuiltinLoc));
Chris Lattner73d0d4f2007-08-30 17:45:32 +00005779}
5780
5781
Sebastian Redlf53597f2009-03-15 17:47:39 +00005782Sema::OwningExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
5783 TypeTy *arg1,TypeTy *arg2,
5784 SourceLocation RPLoc) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00005785 // FIXME: Preserve type source info.
5786 QualType argT1 = GetTypeFromParser(arg1);
5787 QualType argT2 = GetTypeFromParser(arg2);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005788
Steve Naroffd34e9152007-08-01 22:05:33 +00005789 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
Mike Stumpeed9cac2009-02-19 03:04:26 +00005790
Douglas Gregorc12a9c52009-05-19 22:28:02 +00005791 if (getLangOptions().CPlusPlus) {
5792 Diag(BuiltinLoc, diag::err_types_compatible_p_in_cplusplus)
5793 << SourceRange(BuiltinLoc, RPLoc);
5794 return ExprError();
5795 }
5796
Sebastian Redlf53597f2009-03-15 17:47:39 +00005797 return Owned(new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc,
5798 argT1, argT2, RPLoc));
Steve Naroffd34e9152007-08-01 22:05:33 +00005799}
5800
Sebastian Redlf53597f2009-03-15 17:47:39 +00005801Sema::OwningExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
5802 ExprArg cond,
5803 ExprArg expr1, ExprArg expr2,
5804 SourceLocation RPLoc) {
5805 Expr *CondExpr = static_cast<Expr*>(cond.get());
5806 Expr *LHSExpr = static_cast<Expr*>(expr1.get());
5807 Expr *RHSExpr = static_cast<Expr*>(expr2.get());
Mike Stumpeed9cac2009-02-19 03:04:26 +00005808
Steve Naroffd04fdd52007-08-03 21:21:27 +00005809 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
5810
Sebastian Redl28507842009-02-26 14:39:58 +00005811 QualType resType;
Douglas Gregorce940492009-09-25 04:25:58 +00005812 bool ValueDependent = false;
Douglas Gregorc9ecc572009-05-19 22:43:30 +00005813 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl28507842009-02-26 14:39:58 +00005814 resType = Context.DependentTy;
Douglas Gregorce940492009-09-25 04:25:58 +00005815 ValueDependent = true;
Sebastian Redl28507842009-02-26 14:39:58 +00005816 } else {
5817 // The conditional expression is required to be a constant expression.
5818 llvm::APSInt condEval(32);
5819 SourceLocation ExpLoc;
5820 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redlf53597f2009-03-15 17:47:39 +00005821 return ExprError(Diag(ExpLoc,
5822 diag::err_typecheck_choose_expr_requires_constant)
5823 << CondExpr->getSourceRange());
Steve Naroffd04fdd52007-08-03 21:21:27 +00005824
Sebastian Redl28507842009-02-26 14:39:58 +00005825 // If the condition is > zero, then the AST type is the same as the LSHExpr.
5826 resType = condEval.getZExtValue() ? LHSExpr->getType() : RHSExpr->getType();
Douglas Gregorce940492009-09-25 04:25:58 +00005827 ValueDependent = condEval.getZExtValue() ? LHSExpr->isValueDependent()
5828 : RHSExpr->isValueDependent();
Sebastian Redl28507842009-02-26 14:39:58 +00005829 }
5830
Sebastian Redlf53597f2009-03-15 17:47:39 +00005831 cond.release(); expr1.release(); expr2.release();
5832 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
Douglas Gregorce940492009-09-25 04:25:58 +00005833 resType, RPLoc,
5834 resType->isDependentType(),
5835 ValueDependent));
Steve Naroffd04fdd52007-08-03 21:21:27 +00005836}
5837
Steve Naroff4eb206b2008-09-03 18:15:37 +00005838//===----------------------------------------------------------------------===//
5839// Clang Extensions.
5840//===----------------------------------------------------------------------===//
5841
5842/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff090276f2008-10-10 01:28:17 +00005843void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00005844 // Analyze block parameters.
5845 BlockSemaInfo *BSI = new BlockSemaInfo();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005846
Steve Naroff4eb206b2008-09-03 18:15:37 +00005847 // Add BSI to CurBlock.
5848 BSI->PrevBlockInfo = CurBlock;
5849 CurBlock = BSI;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005850
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00005851 BSI->ReturnType = QualType();
Steve Naroff4eb206b2008-09-03 18:15:37 +00005852 BSI->TheScope = BlockScope;
Mike Stumpb83d2872009-02-19 22:01:56 +00005853 BSI->hasBlockDeclRefExprs = false;
Daniel Dunbar1d2154c2009-07-29 01:59:17 +00005854 BSI->hasPrototype = false;
Chris Lattner17a78302009-04-19 05:28:12 +00005855 BSI->SavedFunctionNeedsScopeChecking = CurFunctionNeedsScopeChecking;
5856 CurFunctionNeedsScopeChecking = false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005857
Steve Naroff090276f2008-10-10 01:28:17 +00005858 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Douglas Gregor44b43212008-12-11 16:49:14 +00005859 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff090276f2008-10-10 01:28:17 +00005860}
5861
Mike Stump98eb8a72009-02-04 22:31:32 +00005862void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpaf199f32009-05-07 18:43:07 +00005863 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
Mike Stump98eb8a72009-02-04 22:31:32 +00005864
5865 if (ParamInfo.getNumTypeObjects() == 0
5866 || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) {
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00005867 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
Mike Stump98eb8a72009-02-04 22:31:32 +00005868 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
5869
Mike Stump4eeab842009-04-28 01:10:27 +00005870 if (T->isArrayType()) {
5871 Diag(ParamInfo.getSourceRange().getBegin(),
5872 diag::err_block_returns_array);
5873 return;
5874 }
5875
Mike Stump98eb8a72009-02-04 22:31:32 +00005876 // The parameter list is optional, if there was none, assume ().
5877 if (!T->isFunctionType())
5878 T = Context.getFunctionType(T, NULL, 0, 0, 0);
5879
5880 CurBlock->hasPrototype = true;
5881 CurBlock->isVariadic = false;
Fariborz Jahanian2f7c3922009-05-14 20:53:39 +00005882 // Check for a valid sentinel attribute on this block.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00005883 if (CurBlock->TheDecl->getAttr<SentinelAttr>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00005884 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian3bba33d2009-05-15 21:18:04 +00005885 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian2f7c3922009-05-14 20:53:39 +00005886 // FIXME: remove the attribute.
5887 }
John McCall183700f2009-09-21 23:43:11 +00005888 QualType RetTy = T.getTypePtr()->getAs<FunctionType>()->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00005889
Chris Lattner9097af12009-04-11 19:27:54 +00005890 // Do not allow returning a objc interface by-value.
5891 if (RetTy->isObjCInterfaceType()) {
5892 Diag(ParamInfo.getSourceRange().getBegin(),
5893 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
5894 return;
5895 }
Mike Stump98eb8a72009-02-04 22:31:32 +00005896 return;
5897 }
5898
Steve Naroff4eb206b2008-09-03 18:15:37 +00005899 // Analyze arguments to block.
5900 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
5901 "Not a function declarator!");
5902 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005903
Steve Naroff090276f2008-10-10 01:28:17 +00005904 CurBlock->hasPrototype = FTI.hasPrototype;
5905 CurBlock->isVariadic = true;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005906
Steve Naroff4eb206b2008-09-03 18:15:37 +00005907 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
5908 // no arguments, not a function that takes a single void argument.
5909 if (FTI.hasPrototype &&
5910 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
Chris Lattnerb28317a2009-03-28 19:18:32 +00005911 (!FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType().getCVRQualifiers()&&
5912 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType())) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00005913 // empty arg list, don't push any params.
Steve Naroff090276f2008-10-10 01:28:17 +00005914 CurBlock->isVariadic = false;
Steve Naroff4eb206b2008-09-03 18:15:37 +00005915 } else if (FTI.hasPrototype) {
5916 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Chris Lattnerb28317a2009-03-28 19:18:32 +00005917 CurBlock->Params.push_back(FTI.ArgInfo[i].Param.getAs<ParmVarDecl>());
Steve Naroff090276f2008-10-10 01:28:17 +00005918 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroff4eb206b2008-09-03 18:15:37 +00005919 }
Jay Foadbeaaccd2009-05-21 09:52:38 +00005920 CurBlock->TheDecl->setParams(Context, CurBlock->Params.data(),
Chris Lattner9097af12009-04-11 19:27:54 +00005921 CurBlock->Params.size());
Fariborz Jahaniand66f22d2009-05-19 17:08:59 +00005922 CurBlock->TheDecl->setIsVariadic(CurBlock->isVariadic);
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00005923 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
Steve Naroff090276f2008-10-10 01:28:17 +00005924 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
5925 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
5926 // If this has an identifier, add it to the scope stack.
5927 if ((*AI)->getIdentifier())
5928 PushOnScopeChains(*AI, CurBlock->TheScope);
Chris Lattner9097af12009-04-11 19:27:54 +00005929
Fariborz Jahanian2f7c3922009-05-14 20:53:39 +00005930 // Check for a valid sentinel attribute on this block.
Mike Stump1eb44332009-09-09 15:08:12 +00005931 if (!CurBlock->isVariadic &&
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00005932 CurBlock->TheDecl->getAttr<SentinelAttr>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00005933 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian3bba33d2009-05-15 21:18:04 +00005934 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian2f7c3922009-05-14 20:53:39 +00005935 // FIXME: remove the attribute.
5936 }
Mike Stump1eb44332009-09-09 15:08:12 +00005937
Chris Lattner9097af12009-04-11 19:27:54 +00005938 // Analyze the return type.
5939 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
John McCall183700f2009-09-21 23:43:11 +00005940 QualType RetTy = T->getAs<FunctionType>()->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00005941
Chris Lattner9097af12009-04-11 19:27:54 +00005942 // Do not allow returning a objc interface by-value.
5943 if (RetTy->isObjCInterfaceType()) {
5944 Diag(ParamInfo.getSourceRange().getBegin(),
5945 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
5946 } else if (!RetTy->isDependentType())
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00005947 CurBlock->ReturnType = RetTy;
Steve Naroff4eb206b2008-09-03 18:15:37 +00005948}
5949
5950/// ActOnBlockError - If there is an error parsing a block, this callback
5951/// is invoked to pop the information about the block from the action impl.
5952void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
5953 // Ensure that CurBlock is deleted.
5954 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005955
Chris Lattner17a78302009-04-19 05:28:12 +00005956 CurFunctionNeedsScopeChecking = CurBlock->SavedFunctionNeedsScopeChecking;
5957
Steve Naroff4eb206b2008-09-03 18:15:37 +00005958 // Pop off CurBlock, handle nested blocks.
Chris Lattner5c59e2b2009-04-21 22:38:46 +00005959 PopDeclContext();
Steve Naroff4eb206b2008-09-03 18:15:37 +00005960 CurBlock = CurBlock->PrevBlockInfo;
Steve Naroff4eb206b2008-09-03 18:15:37 +00005961 // FIXME: Delete the ParmVarDecl objects as well???
Steve Naroff4eb206b2008-09-03 18:15:37 +00005962}
5963
5964/// ActOnBlockStmtExpr - This is called when the body of a block statement
5965/// literal was successfully completed. ^(int x){...}
Sebastian Redlf53597f2009-03-15 17:47:39 +00005966Sema::OwningExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
5967 StmtArg body, Scope *CurScope) {
Chris Lattner9af55002009-03-27 04:18:06 +00005968 // If blocks are disabled, emit an error.
5969 if (!LangOpts.Blocks)
5970 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump1eb44332009-09-09 15:08:12 +00005971
Steve Naroff4eb206b2008-09-03 18:15:37 +00005972 // Ensure that CurBlock is deleted.
5973 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
Steve Naroff4eb206b2008-09-03 18:15:37 +00005974
Steve Naroff090276f2008-10-10 01:28:17 +00005975 PopDeclContext();
5976
Steve Naroff4eb206b2008-09-03 18:15:37 +00005977 // Pop off CurBlock, handle nested blocks.
5978 CurBlock = CurBlock->PrevBlockInfo;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005979
Steve Naroff4eb206b2008-09-03 18:15:37 +00005980 QualType RetTy = Context.VoidTy;
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00005981 if (!BSI->ReturnType.isNull())
5982 RetTy = BSI->ReturnType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005983
Steve Naroff4eb206b2008-09-03 18:15:37 +00005984 llvm::SmallVector<QualType, 8> ArgTypes;
5985 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
5986 ArgTypes.push_back(BSI->Params[i]->getType());
Mike Stumpeed9cac2009-02-19 03:04:26 +00005987
Mike Stump56925862009-07-28 22:04:01 +00005988 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroff4eb206b2008-09-03 18:15:37 +00005989 QualType BlockTy;
5990 if (!BSI->hasPrototype)
Mike Stump56925862009-07-28 22:04:01 +00005991 BlockTy = Context.getFunctionType(RetTy, 0, 0, false, 0, false, false, 0, 0,
5992 NoReturn);
Steve Naroff4eb206b2008-09-03 18:15:37 +00005993 else
Jay Foadbeaaccd2009-05-21 09:52:38 +00005994 BlockTy = Context.getFunctionType(RetTy, ArgTypes.data(), ArgTypes.size(),
Mike Stump56925862009-07-28 22:04:01 +00005995 BSI->isVariadic, 0, false, false, 0, 0,
5996 NoReturn);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005997
Eli Friedmanb1d796d2009-03-23 00:24:07 +00005998 // FIXME: Check that return/parameter types are complete/non-abstract
Douglas Gregore0762c92009-06-19 23:52:42 +00005999 DiagnoseUnusedParameters(BSI->Params.begin(), BSI->Params.end());
Steve Naroff4eb206b2008-09-03 18:15:37 +00006000 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006001
Chris Lattner17a78302009-04-19 05:28:12 +00006002 // If needed, diagnose invalid gotos and switches in the block.
6003 if (CurFunctionNeedsScopeChecking)
6004 DiagnoseInvalidJumps(static_cast<CompoundStmt*>(body.get()));
6005 CurFunctionNeedsScopeChecking = BSI->SavedFunctionNeedsScopeChecking;
Mike Stump1eb44332009-09-09 15:08:12 +00006006
Anders Carlssone9146f22009-05-01 19:49:17 +00006007 BSI->TheDecl->setBody(body.takeAs<CompoundStmt>());
Mike Stump56925862009-07-28 22:04:01 +00006008 CheckFallThroughForBlock(BlockTy, BSI->TheDecl->getBody());
Sebastian Redlf53597f2009-03-15 17:47:39 +00006009 return Owned(new (Context) BlockExpr(BSI->TheDecl, BlockTy,
6010 BSI->hasBlockDeclRefExprs));
Steve Naroff4eb206b2008-09-03 18:15:37 +00006011}
6012
Sebastian Redlf53597f2009-03-15 17:47:39 +00006013Sema::OwningExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
6014 ExprArg expr, TypeTy *type,
6015 SourceLocation RPLoc) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00006016 QualType T = GetTypeFromParser(type);
Chris Lattner0d20b8a2009-04-05 15:49:53 +00006017 Expr *E = static_cast<Expr*>(expr.get());
6018 Expr *OrigExpr = E;
Mike Stump1eb44332009-09-09 15:08:12 +00006019
Anders Carlsson7c50aca2007-10-15 20:28:48 +00006020 InitBuiltinVaListType();
Eli Friedmanc34bcde2008-08-09 23:32:40 +00006021
6022 // Get the va_list type
6023 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedman5c091ba2009-05-16 12:46:54 +00006024 if (VaListType->isArrayType()) {
6025 // Deal with implicit array decay; for example, on x86-64,
6026 // va_list is an array, but it's supposed to decay to
6027 // a pointer for va_arg.
Eli Friedmanc34bcde2008-08-09 23:32:40 +00006028 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman5c091ba2009-05-16 12:46:54 +00006029 // Make sure the input expression also decays appropriately.
6030 UsualUnaryConversions(E);
6031 } else {
6032 // Otherwise, the va_list argument must be an l-value because
6033 // it is modified by va_arg.
Mike Stump1eb44332009-09-09 15:08:12 +00006034 if (!E->isTypeDependent() &&
Douglas Gregordd027302009-05-19 23:10:31 +00006035 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedman5c091ba2009-05-16 12:46:54 +00006036 return ExprError();
6037 }
Eli Friedmanc34bcde2008-08-09 23:32:40 +00006038
Douglas Gregordd027302009-05-19 23:10:31 +00006039 if (!E->isTypeDependent() &&
6040 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redlf53597f2009-03-15 17:47:39 +00006041 return ExprError(Diag(E->getLocStart(),
6042 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner0d20b8a2009-04-05 15:49:53 +00006043 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner9dc8f192009-04-05 00:59:53 +00006044 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006045
Eli Friedmanb1d796d2009-03-23 00:24:07 +00006046 // FIXME: Check that type is complete/non-abstract
Anders Carlsson7c50aca2007-10-15 20:28:48 +00006047 // FIXME: Warn if a non-POD type is passed in.
Mike Stumpeed9cac2009-02-19 03:04:26 +00006048
Sebastian Redlf53597f2009-03-15 17:47:39 +00006049 expr.release();
6050 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(),
6051 RPLoc));
Anders Carlsson7c50aca2007-10-15 20:28:48 +00006052}
6053
Sebastian Redlf53597f2009-03-15 17:47:39 +00006054Sema::OwningExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor2d8b2732008-11-29 04:51:27 +00006055 // The type of __null will be int or long, depending on the size of
6056 // pointers on the target.
6057 QualType Ty;
6058 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
6059 Ty = Context.IntTy;
6060 else
6061 Ty = Context.LongTy;
6062
Sebastian Redlf53597f2009-03-15 17:47:39 +00006063 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor2d8b2732008-11-29 04:51:27 +00006064}
6065
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00006066static void
6067MakeObjCStringLiteralCodeModificationHint(Sema& SemaRef,
6068 QualType DstType,
6069 Expr *SrcExpr,
6070 CodeModificationHint &Hint) {
6071 if (!SemaRef.getLangOptions().ObjC1)
6072 return;
6073
6074 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
6075 if (!PT)
6076 return;
6077
6078 // Check if the destination is of type 'id'.
6079 if (!PT->isObjCIdType()) {
6080 // Check if the destination is the 'NSString' interface.
6081 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
6082 if (!ID || !ID->getIdentifier()->isStr("NSString"))
6083 return;
6084 }
6085
6086 // Strip off any parens and casts.
6087 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
6088 if (!SL || SL->isWide())
6089 return;
6090
6091 Hint = CodeModificationHint::CreateInsertion(SL->getLocStart(), "@");
6092}
6093
Chris Lattner5cf216b2008-01-04 18:04:52 +00006094bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
6095 SourceLocation Loc,
6096 QualType DstType, QualType SrcType,
6097 Expr *SrcExpr, const char *Flavor) {
6098 // Decode the result (notice that AST's are still created for extensions).
6099 bool isInvalid = false;
6100 unsigned DiagKind;
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00006101 CodeModificationHint Hint;
6102
Chris Lattner5cf216b2008-01-04 18:04:52 +00006103 switch (ConvTy) {
6104 default: assert(0 && "Unknown conversion type");
6105 case Compatible: return false;
Chris Lattnerb7b61152008-01-04 18:22:42 +00006106 case PointerToInt:
Chris Lattner5cf216b2008-01-04 18:04:52 +00006107 DiagKind = diag::ext_typecheck_convert_pointer_int;
6108 break;
Chris Lattnerb7b61152008-01-04 18:22:42 +00006109 case IntToPointer:
6110 DiagKind = diag::ext_typecheck_convert_int_pointer;
6111 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00006112 case IncompatiblePointer:
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00006113 MakeObjCStringLiteralCodeModificationHint(*this, DstType, SrcExpr, Hint);
Chris Lattner5cf216b2008-01-04 18:04:52 +00006114 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
6115 break;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00006116 case IncompatiblePointerSign:
6117 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
6118 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00006119 case FunctionVoidPointer:
6120 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
6121 break;
6122 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor77a52232008-09-12 00:47:35 +00006123 // If the qualifiers lost were because we were applying the
6124 // (deprecated) C++ conversion from a string literal to a char*
6125 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
6126 // Ideally, this check would be performed in
6127 // CheckPointerTypesForAssignment. However, that would require a
6128 // bit of refactoring (so that the second argument is an
6129 // expression, rather than a type), which should be done as part
6130 // of a larger effort to fix CheckPointerTypesForAssignment for
6131 // C++ semantics.
6132 if (getLangOptions().CPlusPlus &&
6133 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
6134 return false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00006135 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
6136 break;
Sean Huntc9132b62009-11-08 07:46:34 +00006137 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanian3451e922009-11-09 22:16:37 +00006138 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00006139 break;
Steve Naroff1c7d0672008-09-04 15:10:53 +00006140 case IntToBlockPointer:
6141 DiagKind = diag::err_int_to_block_pointer;
6142 break;
6143 case IncompatibleBlockPointer:
Mike Stump25efa102009-04-21 22:51:42 +00006144 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00006145 break;
Steve Naroff39579072008-10-14 22:18:38 +00006146 case IncompatibleObjCQualifiedId:
Mike Stumpeed9cac2009-02-19 03:04:26 +00006147 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff39579072008-10-14 22:18:38 +00006148 // it can give a more specific diagnostic.
6149 DiagKind = diag::warn_incompatible_qualified_id;
6150 break;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00006151 case IncompatibleVectors:
6152 DiagKind = diag::warn_incompatible_vectors;
6153 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00006154 case Incompatible:
6155 DiagKind = diag::err_typecheck_convert_incompatible;
6156 isInvalid = true;
6157 break;
6158 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006159
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00006160 Diag(Loc, DiagKind) << DstType << SrcType << Flavor
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00006161 << SrcExpr->getSourceRange() << Hint;
Chris Lattner5cf216b2008-01-04 18:04:52 +00006162 return isInvalid;
6163}
Anders Carlssone21555e2008-11-30 19:50:32 +00006164
Chris Lattner3bf68932009-04-25 21:59:05 +00006165bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedman3b5ccca2009-04-25 22:26:58 +00006166 llvm::APSInt ICEResult;
6167 if (E->isIntegerConstantExpr(ICEResult, Context)) {
6168 if (Result)
6169 *Result = ICEResult;
6170 return false;
6171 }
6172
Anders Carlssone21555e2008-11-30 19:50:32 +00006173 Expr::EvalResult EvalResult;
6174
Mike Stumpeed9cac2009-02-19 03:04:26 +00006175 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone21555e2008-11-30 19:50:32 +00006176 EvalResult.HasSideEffects) {
6177 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
6178
6179 if (EvalResult.Diag) {
6180 // We only show the note if it's not the usual "invalid subexpression"
6181 // or if it's actually in a subexpression.
6182 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
6183 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
6184 Diag(EvalResult.DiagLoc, EvalResult.Diag);
6185 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006186
Anders Carlssone21555e2008-11-30 19:50:32 +00006187 return true;
6188 }
6189
Eli Friedman3b5ccca2009-04-25 22:26:58 +00006190 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
6191 E->getSourceRange();
Anders Carlssone21555e2008-11-30 19:50:32 +00006192
Eli Friedman3b5ccca2009-04-25 22:26:58 +00006193 if (EvalResult.Diag &&
6194 Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
6195 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006196
Anders Carlssone21555e2008-11-30 19:50:32 +00006197 if (Result)
6198 *Result = EvalResult.Val.getInt();
6199 return false;
6200}
Douglas Gregore0762c92009-06-19 23:52:42 +00006201
Mike Stump1eb44332009-09-09 15:08:12 +00006202Sema::ExpressionEvaluationContext
6203Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregorac7610d2009-06-22 20:57:11 +00006204 // Introduce a new set of potentially referenced declarations to the stack.
6205 if (NewContext == PotentiallyPotentiallyEvaluated)
6206 PotentiallyReferencedDeclStack.push_back(PotentiallyReferencedDecls());
Mike Stump1eb44332009-09-09 15:08:12 +00006207
Douglas Gregorac7610d2009-06-22 20:57:11 +00006208 std::swap(ExprEvalContext, NewContext);
6209 return NewContext;
6210}
6211
Mike Stump1eb44332009-09-09 15:08:12 +00006212void
Douglas Gregorac7610d2009-06-22 20:57:11 +00006213Sema::PopExpressionEvaluationContext(ExpressionEvaluationContext OldContext,
6214 ExpressionEvaluationContext NewContext) {
6215 ExprEvalContext = NewContext;
6216
6217 if (OldContext == PotentiallyPotentiallyEvaluated) {
6218 // Mark any remaining declarations in the current position of the stack
6219 // as "referenced". If they were not meant to be referenced, semantic
6220 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
6221 PotentiallyReferencedDecls RemainingDecls;
6222 RemainingDecls.swap(PotentiallyReferencedDeclStack.back());
6223 PotentiallyReferencedDeclStack.pop_back();
Mike Stump1eb44332009-09-09 15:08:12 +00006224
Douglas Gregorac7610d2009-06-22 20:57:11 +00006225 for (PotentiallyReferencedDecls::iterator I = RemainingDecls.begin(),
6226 IEnd = RemainingDecls.end();
6227 I != IEnd; ++I)
6228 MarkDeclarationReferenced(I->first, I->second);
6229 }
6230}
Douglas Gregore0762c92009-06-19 23:52:42 +00006231
6232/// \brief Note that the given declaration was referenced in the source code.
6233///
6234/// This routine should be invoke whenever a given declaration is referenced
6235/// in the source code, and where that reference occurred. If this declaration
6236/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
6237/// C99 6.9p3), then the declaration will be marked as used.
6238///
6239/// \param Loc the location where the declaration was referenced.
6240///
6241/// \param D the declaration that has been referenced by the source code.
6242void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
6243 assert(D && "No declaration?");
Mike Stump1eb44332009-09-09 15:08:12 +00006244
Douglas Gregord7f37bf2009-06-22 23:06:13 +00006245 if (D->isUsed())
6246 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006247
Douglas Gregorb5352cf2009-10-08 21:35:42 +00006248 // Mark a parameter or variable declaration "used", regardless of whether we're in a
6249 // template or not. The reason for this is that unevaluated expressions
6250 // (e.g. (void)sizeof()) constitute a use for warning purposes (-Wunused-variables and
6251 // -Wunused-parameters)
6252 if (isa<ParmVarDecl>(D) ||
6253 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod()))
Douglas Gregore0762c92009-06-19 23:52:42 +00006254 D->setUsed(true);
Mike Stump1eb44332009-09-09 15:08:12 +00006255
Douglas Gregore0762c92009-06-19 23:52:42 +00006256 // Do not mark anything as "used" within a dependent context; wait for
6257 // an instantiation.
6258 if (CurContext->isDependentContext())
6259 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006260
Douglas Gregorac7610d2009-06-22 20:57:11 +00006261 switch (ExprEvalContext) {
6262 case Unevaluated:
6263 // We are in an expression that is not potentially evaluated; do nothing.
6264 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006265
Douglas Gregorac7610d2009-06-22 20:57:11 +00006266 case PotentiallyEvaluated:
6267 // We are in a potentially-evaluated expression, so this declaration is
6268 // "used"; handle this below.
6269 break;
Mike Stump1eb44332009-09-09 15:08:12 +00006270
Douglas Gregorac7610d2009-06-22 20:57:11 +00006271 case PotentiallyPotentiallyEvaluated:
6272 // We are in an expression that may be potentially evaluated; queue this
6273 // declaration reference until we know whether the expression is
6274 // potentially evaluated.
6275 PotentiallyReferencedDeclStack.back().push_back(std::make_pair(Loc, D));
6276 return;
6277 }
Mike Stump1eb44332009-09-09 15:08:12 +00006278
Douglas Gregore0762c92009-06-19 23:52:42 +00006279 // Note that this declaration has been used.
Fariborz Jahanianb7f4cc02009-06-22 17:30:33 +00006280 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00006281 unsigned TypeQuals;
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00006282 if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) {
6283 if (!Constructor->isUsed())
6284 DefineImplicitDefaultConstructor(Loc, Constructor);
Mike Stump1eb44332009-09-09 15:08:12 +00006285 } else if (Constructor->isImplicit() &&
Mike Stumpac5fc7c2009-08-04 21:02:39 +00006286 Constructor->isCopyConstructor(Context, TypeQuals)) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00006287 if (!Constructor->isUsed())
6288 DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals);
6289 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00006290 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
6291 if (Destructor->isImplicit() && !Destructor->isUsed())
6292 DefineImplicitDestructor(Loc, Destructor);
Mike Stump1eb44332009-09-09 15:08:12 +00006293
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00006294 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
6295 if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
6296 MethodDecl->getOverloadedOperator() == OO_Equal) {
6297 if (!MethodDecl->isUsed())
6298 DefineImplicitOverloadedAssign(Loc, MethodDecl);
6299 }
6300 }
Fariborz Jahanianf5ed9e02009-06-24 22:09:44 +00006301 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Mike Stump1eb44332009-09-09 15:08:12 +00006302 // Implicit instantiation of function templates and member functions of
Douglas Gregor1637be72009-06-26 00:10:03 +00006303 // class templates.
Douglas Gregor3b846b62009-10-27 20:53:28 +00006304 if (!Function->getBody() && Function->isImplicitlyInstantiable()) {
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00006305 bool AlreadyInstantiated = false;
6306 if (FunctionTemplateSpecializationInfo *SpecInfo
6307 = Function->getTemplateSpecializationInfo()) {
6308 if (SpecInfo->getPointOfInstantiation().isInvalid())
6309 SpecInfo->setPointOfInstantiation(Loc);
Douglas Gregor3b846b62009-10-27 20:53:28 +00006310 else if (SpecInfo->getTemplateSpecializationKind()
6311 == TSK_ImplicitInstantiation)
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00006312 AlreadyInstantiated = true;
6313 } else if (MemberSpecializationInfo *MSInfo
6314 = Function->getMemberSpecializationInfo()) {
6315 if (MSInfo->getPointOfInstantiation().isInvalid())
6316 MSInfo->setPointOfInstantiation(Loc);
Douglas Gregor3b846b62009-10-27 20:53:28 +00006317 else if (MSInfo->getTemplateSpecializationKind()
6318 == TSK_ImplicitInstantiation)
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00006319 AlreadyInstantiated = true;
6320 }
6321
6322 if (!AlreadyInstantiated)
6323 PendingImplicitInstantiations.push_back(std::make_pair(Function, Loc));
6324 }
6325
Douglas Gregore0762c92009-06-19 23:52:42 +00006326 // FIXME: keep track of references to static functions
Douglas Gregore0762c92009-06-19 23:52:42 +00006327 Function->setUsed(true);
6328 return;
Douglas Gregord7f37bf2009-06-22 23:06:13 +00006329 }
Mike Stump1eb44332009-09-09 15:08:12 +00006330
Douglas Gregore0762c92009-06-19 23:52:42 +00006331 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00006332 // Implicit instantiation of static data members of class templates.
Mike Stump1eb44332009-09-09 15:08:12 +00006333 if (Var->isStaticDataMember() &&
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00006334 Var->getInstantiatedFromStaticDataMember()) {
6335 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
6336 assert(MSInfo && "Missing member specialization information?");
6337 if (MSInfo->getPointOfInstantiation().isInvalid() &&
6338 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
6339 MSInfo->setPointOfInstantiation(Loc);
6340 PendingImplicitInstantiations.push_back(std::make_pair(Var, Loc));
6341 }
6342 }
Mike Stump1eb44332009-09-09 15:08:12 +00006343
Douglas Gregore0762c92009-06-19 23:52:42 +00006344 // FIXME: keep track of references to static data?
Douglas Gregor7caa6822009-07-24 20:34:43 +00006345
Douglas Gregore0762c92009-06-19 23:52:42 +00006346 D->setUsed(true);
Douglas Gregor7caa6822009-07-24 20:34:43 +00006347 return;
Sam Weinigcce6ebc2009-09-11 03:29:30 +00006348 }
Douglas Gregore0762c92009-06-19 23:52:42 +00006349}
Anders Carlsson8c8d9192009-10-09 23:51:55 +00006350
6351bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
6352 CallExpr *CE, FunctionDecl *FD) {
6353 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
6354 return false;
6355
6356 PartialDiagnostic Note =
6357 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
6358 << FD->getDeclName() : PDiag();
6359 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
6360
6361 if (RequireCompleteType(Loc, ReturnType,
6362 FD ?
6363 PDiag(diag::err_call_function_incomplete_return)
6364 << CE->getSourceRange() << FD->getDeclName() :
6365 PDiag(diag::err_call_incomplete_return)
6366 << CE->getSourceRange(),
6367 std::make_pair(NoteLoc, Note)))
6368 return true;
6369
6370 return false;
6371}
6372
John McCall5a881bb2009-10-12 21:59:07 +00006373// Diagnose the common s/=/==/ typo. Note that adding parentheses
6374// will prevent this condition from triggering, which is what we want.
6375void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
6376 SourceLocation Loc;
6377
John McCalla52ef082009-11-11 02:41:58 +00006378 unsigned diagnostic = diag::warn_condition_is_assignment;
6379
John McCall5a881bb2009-10-12 21:59:07 +00006380 if (isa<BinaryOperator>(E)) {
6381 BinaryOperator *Op = cast<BinaryOperator>(E);
6382 if (Op->getOpcode() != BinaryOperator::Assign)
6383 return;
6384
John McCallc8d8ac52009-11-12 00:06:05 +00006385 // Greylist some idioms by putting them into a warning subcategory.
6386 if (ObjCMessageExpr *ME
6387 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
6388 Selector Sel = ME->getSelector();
6389
John McCallc8d8ac52009-11-12 00:06:05 +00006390 // self = [<foo> init...]
6391 if (isSelfExpr(Op->getLHS())
6392 && Sel.getIdentifierInfoForSlot(0)->getName().startswith("init"))
6393 diagnostic = diag::warn_condition_is_idiomatic_assignment;
6394
6395 // <foo> = [<bar> nextObject]
6396 else if (Sel.isUnarySelector() &&
6397 Sel.getIdentifierInfoForSlot(0)->getName() == "nextObject")
6398 diagnostic = diag::warn_condition_is_idiomatic_assignment;
6399 }
John McCalla52ef082009-11-11 02:41:58 +00006400
John McCall5a881bb2009-10-12 21:59:07 +00006401 Loc = Op->getOperatorLoc();
6402 } else if (isa<CXXOperatorCallExpr>(E)) {
6403 CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(E);
6404 if (Op->getOperator() != OO_Equal)
6405 return;
6406
6407 Loc = Op->getOperatorLoc();
6408 } else {
6409 // Not an assignment.
6410 return;
6411 }
6412
John McCall5a881bb2009-10-12 21:59:07 +00006413 SourceLocation Open = E->getSourceRange().getBegin();
John McCall2d152152009-10-12 22:25:59 +00006414 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
John McCall5a881bb2009-10-12 21:59:07 +00006415
John McCalla52ef082009-11-11 02:41:58 +00006416 Diag(Loc, diagnostic)
John McCall5a881bb2009-10-12 21:59:07 +00006417 << E->getSourceRange()
6418 << CodeModificationHint::CreateInsertion(Open, "(")
6419 << CodeModificationHint::CreateInsertion(Close, ")");
6420}
6421
6422bool Sema::CheckBooleanCondition(Expr *&E, SourceLocation Loc) {
6423 DiagnoseAssignmentAsCondition(E);
6424
6425 if (!E->isTypeDependent()) {
6426 DefaultFunctionArrayConversion(E);
6427
6428 QualType T = E->getType();
6429
6430 if (getLangOptions().CPlusPlus) {
6431 if (CheckCXXBooleanCondition(E)) // C++ 6.4p4
6432 return true;
6433 } else if (!T->isScalarType()) { // C99 6.8.4.1p1
6434 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
6435 << T << E->getSourceRange();
6436 return true;
6437 }
6438 }
6439
6440 return false;
6441}