blob: 9bff8f3a748e43bc54621864da01fe22e71e644f [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
Douglas Gregore737f502010-08-12 20:07:10 +000014#include "clang/Sema/Sema.h"
15#include "clang/Sema/Initialization.h"
16#include "clang/Sema/Lookup.h"
17#include "clang/Sema/AnalysisBasedWarnings.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000018#include "clang/AST/ASTContext.h"
Douglas Gregorcc8a5d52010-04-29 00:18:15 +000019#include "clang/AST/CXXInheritance.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000020#include "clang/AST/DeclObjC.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000021#include "clang/AST/DeclTemplate.h"
Douglas Gregor8ecdb652010-04-28 22:16:22 +000022#include "clang/AST/Expr.h"
Chris Lattner04421082008-04-08 04:40:51 +000023#include "clang/AST/ExprCXX.h"
Steve Narofff494b572008-05-29 21:12:08 +000024#include "clang/AST/ExprObjC.h"
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000025#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregor8ecdb652010-04-28 22:16:22 +000026#include "clang/AST/TypeLoc.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000027#include "clang/Basic/PartialDiagnostic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000028#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000029#include "clang/Basic/TargetInfo.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000030#include "clang/Lex/LiteralSupport.h"
31#include "clang/Lex/Preprocessor.h"
John McCall19510852010-08-20 18:27:03 +000032#include "clang/Sema/DeclSpec.h"
33#include "clang/Sema/Designator.h"
34#include "clang/Sema/Scope.h"
35#include "clang/Sema/ParsedTemplate.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000036using namespace clang;
37
David Chisnall0f436562009-08-17 16:35:33 +000038
Douglas Gregor48f3bb92009-02-18 21:56:37 +000039/// \brief Determine whether the use of this declaration is valid, and
40/// emit any corresponding diagnostics.
41///
42/// This routine diagnoses various problems with referencing
43/// declarations that can occur when using a declaration. For example,
44/// it might warn if a deprecated or unavailable declaration is being
45/// used, or produce an error (and return true) if a C++0x deleted
46/// function is being used.
47///
Chris Lattner52338262009-10-25 22:31:57 +000048/// If IgnoreDeprecated is set to true, this should not want about deprecated
49/// decls.
50///
Douglas Gregor48f3bb92009-02-18 21:56:37 +000051/// \returns true if there was an error (this declaration cannot be
52/// referenced), false otherwise.
Chris Lattner52338262009-10-25 22:31:57 +000053///
John McCall54abf7d2009-11-04 02:18:39 +000054bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc) {
Chris Lattner76a642f2009-02-15 22:43:40 +000055 // See if the decl is deprecated.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +000056 if (D->getAttr<DeprecatedAttr>()) {
John McCall54abf7d2009-11-04 02:18:39 +000057 EmitDeprecationWarning(D, Loc);
Chris Lattner76a642f2009-02-15 22:43:40 +000058 }
59
Chris Lattnerffb93682009-10-25 17:21:40 +000060 // See if the decl is unavailable
61 if (D->getAttr<UnavailableAttr>()) {
Ted Kremenek042411c2010-07-21 20:43:11 +000062 Diag(Loc, diag::err_unavailable) << D->getDeclName();
Chris Lattnerffb93682009-10-25 17:21:40 +000063 Diag(D->getLocation(), diag::note_unavailable_here) << 0;
64 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000065
Douglas Gregor48f3bb92009-02-18 21:56:37 +000066 // See if this is a deleted function.
Douglas Gregor25d944a2009-02-24 04:26:15 +000067 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +000068 if (FD->isDeleted()) {
69 Diag(Loc, diag::err_deleted_function_use);
70 Diag(D->getLocation(), diag::note_unavailable_here) << true;
71 return true;
72 }
Douglas Gregor25d944a2009-02-24 04:26:15 +000073 }
Douglas Gregor48f3bb92009-02-18 21:56:37 +000074
Douglas Gregor48f3bb92009-02-18 21:56:37 +000075 return false;
Chris Lattner76a642f2009-02-15 22:43:40 +000076}
77
Fariborz Jahanian5b530052009-05-13 18:09:35 +000078/// DiagnoseSentinelCalls - This routine checks on method dispatch calls
Mike Stump1eb44332009-09-09 15:08:12 +000079/// (and other functions in future), which have been declared with sentinel
Fariborz Jahanian5b530052009-05-13 18:09:35 +000080/// attribute. It warns if call does not have the sentinel argument.
81///
82void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +000083 Expr **Args, unsigned NumArgs) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +000084 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Mike Stump1eb44332009-09-09 15:08:12 +000085 if (!attr)
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +000086 return;
Douglas Gregor92e986e2010-04-22 16:44:27 +000087
88 // FIXME: In C++0x, if any of the arguments are parameter pack
89 // expansions, we can't check for the sentinel now.
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +000090 int sentinelPos = attr->getSentinel();
91 int nullPos = attr->getNullPos();
Mike Stump1eb44332009-09-09 15:08:12 +000092
Mike Stump390b4cc2009-05-16 07:39:55 +000093 // FIXME. ObjCMethodDecl and FunctionDecl need be derived from the same common
94 // base class. Then we won't be needing two versions of the same code.
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +000095 unsigned int i = 0;
Fariborz Jahanian236673e2009-05-14 18:00:00 +000096 bool warnNotEnoughArgs = false;
97 int isMethod = 0;
98 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
99 // skip over named parameters.
100 ObjCMethodDecl::param_iterator P, E = MD->param_end();
101 for (P = MD->param_begin(); (P != E && i < NumArgs); ++P) {
102 if (nullPos)
103 --nullPos;
104 else
105 ++i;
106 }
107 warnNotEnoughArgs = (P != E || i >= NumArgs);
108 isMethod = 1;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000109 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000110 // skip over named parameters.
111 ObjCMethodDecl::param_iterator P, E = FD->param_end();
112 for (P = FD->param_begin(); (P != E && i < NumArgs); ++P) {
113 if (nullPos)
114 --nullPos;
115 else
116 ++i;
117 }
118 warnNotEnoughArgs = (P != E || i >= NumArgs);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000119 } else if (VarDecl *V = dyn_cast<VarDecl>(D)) {
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000120 // block or function pointer call.
121 QualType Ty = V->getType();
122 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000123 const FunctionType *FT = Ty->isFunctionPointerType()
John McCall183700f2009-09-21 23:43:11 +0000124 ? Ty->getAs<PointerType>()->getPointeeType()->getAs<FunctionType>()
125 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000126 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT)) {
127 unsigned NumArgsInProto = Proto->getNumArgs();
128 unsigned k;
129 for (k = 0; (k != NumArgsInProto && i < NumArgs); k++) {
130 if (nullPos)
131 --nullPos;
132 else
133 ++i;
134 }
135 warnNotEnoughArgs = (k != NumArgsInProto || i >= NumArgs);
136 }
137 if (Ty->isBlockPointerType())
138 isMethod = 2;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000139 } else
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000140 return;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000141 } else
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000142 return;
143
144 if (warnNotEnoughArgs) {
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000145 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000146 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000147 return;
148 }
149 int sentinel = i;
150 while (sentinelPos > 0 && i < NumArgs-1) {
151 --sentinelPos;
152 ++i;
153 }
154 if (sentinelPos > 0) {
155 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000156 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000157 return;
158 }
159 while (i < NumArgs-1) {
160 ++i;
161 ++sentinel;
162 }
163 Expr *sentinelExpr = Args[sentinel];
John McCall8eb662e2010-05-06 23:53:00 +0000164 if (!sentinelExpr) return;
165 if (sentinelExpr->isTypeDependent()) return;
166 if (sentinelExpr->isValueDependent()) return;
Fariborz Jahanian9ccd7252010-07-14 16:37:51 +0000167 if (sentinelExpr->getType()->isAnyPointerType() &&
John McCall8eb662e2010-05-06 23:53:00 +0000168 sentinelExpr->IgnoreParenCasts()->isNullPointerConstant(Context,
169 Expr::NPC_ValueDependentIsNull))
170 return;
171
172 // Unfortunately, __null has type 'int'.
173 if (isa<GNUNullExpr>(sentinelExpr)) return;
174
175 Diag(Loc, diag::warn_missing_sentinel) << isMethod;
176 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian5b530052009-05-13 18:09:35 +0000177}
178
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000179SourceRange Sema::getExprRange(ExprTy *E) const {
180 Expr *Ex = (Expr *)E;
181 return Ex? Ex->getSourceRange() : SourceRange();
182}
183
Chris Lattnere7a2e912008-07-25 21:10:04 +0000184//===----------------------------------------------------------------------===//
185// Standard Promotions and Conversions
186//===----------------------------------------------------------------------===//
187
Chris Lattnere7a2e912008-07-25 21:10:04 +0000188/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
189void Sema::DefaultFunctionArrayConversion(Expr *&E) {
190 QualType Ty = E->getType();
191 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
192
Chris Lattnere7a2e912008-07-25 21:10:04 +0000193 if (Ty->isFunctionType())
Mike Stump1eb44332009-09-09 15:08:12 +0000194 ImpCastExprToType(E, Context.getPointerType(Ty),
Anders Carlssonb633c4e2009-09-01 20:37:18 +0000195 CastExpr::CK_FunctionToPointerDecay);
Chris Lattner67d33d82008-07-25 21:33:13 +0000196 else if (Ty->isArrayType()) {
197 // In C90 mode, arrays only promote to pointers if the array expression is
198 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
199 // type 'array of type' is converted to an expression that has type 'pointer
200 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
201 // that has type 'array of type' ...". The relevant change is "an lvalue"
202 // (C90) to "an expression" (C99).
Argyrios Kyrtzidisc39a3d72008-09-11 04:25:59 +0000203 //
204 // C++ 4.2p1:
205 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
206 // T" can be converted to an rvalue of type "pointer to T".
207 //
208 if (getLangOptions().C99 || getLangOptions().CPlusPlus ||
209 E->isLvalue(Context) == Expr::LV_Valid)
Anders Carlsson112a0a82009-08-07 23:48:20 +0000210 ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
211 CastExpr::CK_ArrayToPointerDecay);
Chris Lattner67d33d82008-07-25 21:33:13 +0000212 }
Chris Lattnere7a2e912008-07-25 21:10:04 +0000213}
214
Douglas Gregora873dfc2010-02-03 00:27:59 +0000215void Sema::DefaultFunctionArrayLvalueConversion(Expr *&E) {
216 DefaultFunctionArrayConversion(E);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000217
Douglas Gregora873dfc2010-02-03 00:27:59 +0000218 QualType Ty = E->getType();
219 assert(!Ty.isNull() && "DefaultFunctionArrayLvalueConversion - missing type");
220 if (!Ty->isDependentType() && Ty.hasQualifiers() &&
221 (!getLangOptions().CPlusPlus || !Ty->isRecordType()) &&
222 E->isLvalue(Context) == Expr::LV_Valid) {
223 // C++ [conv.lval]p1:
224 // [...] If T is a non-class type, the type of the rvalue is the
225 // cv-unqualified version of T. Otherwise, the type of the
226 // rvalue is T
227 //
228 // C99 6.3.2.1p2:
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000229 // If the lvalue has qualified type, the value has the unqualified
230 // version of the type of the lvalue; otherwise, the value has the
Douglas Gregora873dfc2010-02-03 00:27:59 +0000231 // type of the lvalue.
232 ImpCastExprToType(E, Ty.getUnqualifiedType(), CastExpr::CK_NoOp);
233 }
234}
235
236
Chris Lattnere7a2e912008-07-25 21:10:04 +0000237/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump1eb44332009-09-09 15:08:12 +0000238/// operators (C99 6.3). The conversions of array and function types are
Chris Lattnere7a2e912008-07-25 21:10:04 +0000239/// sometimes surpressed. For example, the array->pointer conversion doesn't
240/// apply if the array is an argument to the sizeof or address (&) operators.
241/// In these instances, this routine should *not* be called.
242Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
243 QualType Ty = Expr->getType();
244 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
Mike Stump1eb44332009-09-09 15:08:12 +0000245
Douglas Gregorfc24e442009-05-01 20:41:21 +0000246 // C99 6.3.1.1p2:
247 //
248 // The following may be used in an expression wherever an int or
249 // unsigned int may be used:
250 // - an object or expression with an integer type whose integer
251 // conversion rank is less than or equal to the rank of int
252 // and unsigned int.
253 // - A bit-field of type _Bool, int, signed int, or unsigned int.
254 //
255 // If an int can represent all values of the original type, the
256 // value is converted to an int; otherwise, it is converted to an
257 // unsigned int. These are called the integer promotions. All
258 // other types are unchanged by the integer promotions.
Eli Friedman04e83572009-08-20 04:21:42 +0000259 QualType PTy = Context.isPromotableBitField(Expr);
260 if (!PTy.isNull()) {
Eli Friedman73c39ab2009-10-20 08:27:19 +0000261 ImpCastExprToType(Expr, PTy, CastExpr::CK_IntegralCast);
Eli Friedman04e83572009-08-20 04:21:42 +0000262 return Expr;
263 }
Douglas Gregorfc24e442009-05-01 20:41:21 +0000264 if (Ty->isPromotableIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +0000265 QualType PT = Context.getPromotedIntegerType(Ty);
Eli Friedman73c39ab2009-10-20 08:27:19 +0000266 ImpCastExprToType(Expr, PT, CastExpr::CK_IntegralCast);
Douglas Gregorfc24e442009-05-01 20:41:21 +0000267 return Expr;
Eli Friedman04e83572009-08-20 04:21:42 +0000268 }
269
Douglas Gregora873dfc2010-02-03 00:27:59 +0000270 DefaultFunctionArrayLvalueConversion(Expr);
Chris Lattnere7a2e912008-07-25 21:10:04 +0000271 return Expr;
272}
273
Chris Lattner05faf172008-07-25 22:25:12 +0000274/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Mike Stump1eb44332009-09-09 15:08:12 +0000275/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner05faf172008-07-25 22:25:12 +0000276/// double. All other argument types are converted by UsualUnaryConversions().
277void Sema::DefaultArgumentPromotion(Expr *&Expr) {
278 QualType Ty = Expr->getType();
279 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump1eb44332009-09-09 15:08:12 +0000280
Chris Lattner05faf172008-07-25 22:25:12 +0000281 // If this is a 'float' (CVR qualified or typedef) promote to double.
Chris Lattner40378332010-05-16 04:01:30 +0000282 if (Ty->isSpecificBuiltinType(BuiltinType::Float))
283 return ImpCastExprToType(Expr, Context.DoubleTy,
284 CastExpr::CK_FloatingCast);
Mike Stump1eb44332009-09-09 15:08:12 +0000285
Chris Lattner05faf172008-07-25 22:25:12 +0000286 UsualUnaryConversions(Expr);
287}
288
Chris Lattner312531a2009-04-12 08:11:20 +0000289/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
290/// will warn if the resulting type is not a POD type, and rejects ObjC
291/// interfaces passed by value. This returns true if the argument type is
292/// completely illegal.
Chris Lattner40378332010-05-16 04:01:30 +0000293bool Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT,
294 FunctionDecl *FDecl) {
Anders Carlssondce5e2c2009-01-16 16:48:51 +0000295 DefaultArgumentPromotion(Expr);
Mike Stump1eb44332009-09-09 15:08:12 +0000296
Chris Lattner40378332010-05-16 04:01:30 +0000297 // __builtin_va_start takes the second argument as a "varargs" argument, but
298 // it doesn't actually do anything with it. It doesn't need to be non-pod
299 // etc.
300 if (FDecl && FDecl->getBuiltinID() == Builtin::BI__builtin_va_start)
301 return false;
302
John McCallc12c5bb2010-05-15 11:32:37 +0000303 if (Expr->getType()->isObjCObjectType() &&
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +0000304 DiagRuntimeBehavior(Expr->getLocStart(),
305 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
306 << Expr->getType() << CT))
307 return true;
Douglas Gregor75b699a2009-12-12 07:25:49 +0000308
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +0000309 if (!Expr->getType()->isPODType() &&
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000310 DiagRuntimeBehavior(Expr->getLocStart(),
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +0000311 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
312 << Expr->getType() << CT))
313 return true;
Chris Lattner312531a2009-04-12 08:11:20 +0000314
315 return false;
Anders Carlssondce5e2c2009-01-16 16:48:51 +0000316}
317
318
Chris Lattnere7a2e912008-07-25 21:10:04 +0000319/// UsualArithmeticConversions - Performs various conversions that are common to
320/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump1eb44332009-09-09 15:08:12 +0000321/// routine returns the first non-arithmetic type found. The client is
Chris Lattnere7a2e912008-07-25 21:10:04 +0000322/// responsible for emitting appropriate error diagnostics.
323/// FIXME: verify the conversion rules for "complex int" are consistent with
324/// GCC.
325QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
326 bool isCompAssign) {
Eli Friedmanab3a8522009-03-28 01:22:36 +0000327 if (!isCompAssign)
Chris Lattnere7a2e912008-07-25 21:10:04 +0000328 UsualUnaryConversions(lhsExpr);
Eli Friedmanab3a8522009-03-28 01:22:36 +0000329
330 UsualUnaryConversions(rhsExpr);
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000331
Mike Stump1eb44332009-09-09 15:08:12 +0000332 // For conversion purposes, we ignore any qualifiers.
Chris Lattnere7a2e912008-07-25 21:10:04 +0000333 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +0000334 QualType lhs =
335 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +0000336 QualType rhs =
Chris Lattnerb77792e2008-07-26 22:17:49 +0000337 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000338
339 // If both types are identical, no conversion is needed.
340 if (lhs == rhs)
341 return lhs;
342
343 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
344 // The caller can deal with this (e.g. pointer + int).
345 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
346 return lhs;
347
Douglas Gregor2d833e32009-05-02 00:36:19 +0000348 // Perform bitfield promotions.
Eli Friedman04e83572009-08-20 04:21:42 +0000349 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr);
Douglas Gregor2d833e32009-05-02 00:36:19 +0000350 if (!LHSBitfieldPromoteTy.isNull())
351 lhs = LHSBitfieldPromoteTy;
Eli Friedman04e83572009-08-20 04:21:42 +0000352 QualType RHSBitfieldPromoteTy = Context.isPromotableBitField(rhsExpr);
Douglas Gregor2d833e32009-05-02 00:36:19 +0000353 if (!RHSBitfieldPromoteTy.isNull())
354 rhs = RHSBitfieldPromoteTy;
355
Eli Friedmana95d7572009-08-19 07:44:53 +0000356 QualType destType = Context.UsualArithmeticConversionsType(lhs, rhs);
Eli Friedmanab3a8522009-03-28 01:22:36 +0000357 if (!isCompAssign)
Eli Friedman73c39ab2009-10-20 08:27:19 +0000358 ImpCastExprToType(lhsExpr, destType, CastExpr::CK_Unknown);
359 ImpCastExprToType(rhsExpr, destType, CastExpr::CK_Unknown);
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000360 return destType;
361}
362
Chris Lattnere7a2e912008-07-25 21:10:04 +0000363//===----------------------------------------------------------------------===//
364// Semantic Analysis for various Expression Types
365//===----------------------------------------------------------------------===//
366
367
Steve Narofff69936d2007-09-16 03:34:24 +0000368/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Reid Spencer5f016e22007-07-11 17:01:13 +0000369/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
370/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
371/// multiple tokens. However, the common case is that StringToks points to one
372/// string.
Sebastian Redlcd965b92009-01-18 18:53:16 +0000373///
374Action::OwningExprResult
Steve Narofff69936d2007-09-16 03:34:24 +0000375Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000376 assert(NumStringToks && "Must have at least one string!");
377
Chris Lattnerbbee00b2009-01-16 18:51:42 +0000378 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Reid Spencer5f016e22007-07-11 17:01:13 +0000379 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +0000380 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +0000381
382 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
383 for (unsigned i = 0; i != NumStringToks; ++i)
384 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000385
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000386 QualType StrTy = Context.CharTy;
Argyrios Kyrtzidis55f4b022008-08-09 17:20:01 +0000387 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000388 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregor77a52232008-09-12 00:47:35 +0000389
390 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
Chris Lattner7dc480f2010-06-15 18:05:34 +0000391 if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
Douglas Gregor77a52232008-09-12 00:47:35 +0000392 StrTy.addConst();
Sebastian Redlcd965b92009-01-18 18:53:16 +0000393
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000394 // Get an array type for the string, according to C99 6.4.5. This includes
395 // the nul terminator character as well as the string length for pascal
396 // strings.
397 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerdbb1ecc2009-02-26 23:01:51 +0000398 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000399 ArrayType::Normal, 0);
Mike Stump1eb44332009-09-09 15:08:12 +0000400
Reid Spencer5f016e22007-07-11 17:01:13 +0000401 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Mike Stump1eb44332009-09-09 15:08:12 +0000402 return Owned(StringLiteral::Create(Context, Literal.GetString(),
Chris Lattner2085fd62009-02-18 06:40:38 +0000403 Literal.GetStringLength(),
404 Literal.AnyWide, StrTy,
405 &StringTokLocs[0],
406 StringTokLocs.size()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000407}
408
Chris Lattner639e2d32008-10-20 05:16:36 +0000409/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
410/// CurBlock to VD should cause it to be snapshotted (as we do for auto
411/// variables defined outside the block) or false if this is not needed (e.g.
412/// for values inside the block or for globals).
413///
Douglas Gregor076ceb02010-03-01 20:44:28 +0000414/// This also keeps the 'hasBlockDeclRefExprs' in the BlockScopeInfo records
Chris Lattner17f3a6d2009-04-21 22:26:47 +0000415/// up-to-date.
416///
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +0000417static bool ShouldSnapshotBlockValueReference(Sema &S, BlockScopeInfo *CurBlock,
Chris Lattner639e2d32008-10-20 05:16:36 +0000418 ValueDecl *VD) {
419 // If the value is defined inside the block, we couldn't snapshot it even if
420 // we wanted to.
421 if (CurBlock->TheDecl == VD->getDeclContext())
422 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000423
Chris Lattner639e2d32008-10-20 05:16:36 +0000424 // If this is an enum constant or function, it is constant, don't snapshot.
425 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
426 return false;
427
428 // If this is a reference to an extern, static, or global variable, no need to
429 // snapshot it.
430 // FIXME: What about 'const' variables in C++?
431 if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
Chris Lattner17f3a6d2009-04-21 22:26:47 +0000432 if (!Var->hasLocalStorage())
433 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000434
Chris Lattner17f3a6d2009-04-21 22:26:47 +0000435 // Blocks that have these can't be constant.
436 CurBlock->hasBlockDeclRefExprs = true;
437
438 // If we have nested blocks, the decl may be declared in an outer block (in
439 // which case that outer block doesn't get "hasBlockDeclRefExprs") or it may
440 // be defined outside all of the current blocks (in which case the blocks do
441 // all get the bit). Walk the nesting chain.
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +0000442 for (unsigned I = S.FunctionScopes.size() - 1; I; --I) {
443 BlockScopeInfo *NextBlock = dyn_cast<BlockScopeInfo>(S.FunctionScopes[I]);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000444
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +0000445 if (!NextBlock)
446 continue;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000447
Chris Lattner17f3a6d2009-04-21 22:26:47 +0000448 // If we found the defining block for the variable, don't mark the block as
449 // having a reference outside it.
450 if (NextBlock->TheDecl == VD->getDeclContext())
451 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000452
Chris Lattner17f3a6d2009-04-21 22:26:47 +0000453 // Otherwise, the DeclRef from the inner block causes the outer one to need
454 // a snapshot as well.
455 NextBlock->hasBlockDeclRefExprs = true;
456 }
Mike Stump1eb44332009-09-09 15:08:12 +0000457
Chris Lattner639e2d32008-10-20 05:16:36 +0000458 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000459}
460
Chris Lattner639e2d32008-10-20 05:16:36 +0000461
Anders Carlssone41590d2009-06-24 00:10:43 +0000462Sema::OwningExprResult
John McCalldbd872f2009-12-08 09:08:17 +0000463Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, SourceLocation Loc,
Sebastian Redlebc07d52009-02-03 20:19:35 +0000464 const CXXScopeSpec *SS) {
Abramo Bagnara25777432010-08-11 22:01:17 +0000465 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
466 return BuildDeclRefExpr(D, Ty, NameInfo, SS);
467}
468
469/// BuildDeclRefExpr - Build a DeclRefExpr.
470Sema::OwningExprResult
471Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty,
472 const DeclarationNameInfo &NameInfo,
473 const CXXScopeSpec *SS) {
Anders Carlssone2bb2242009-06-26 19:16:07 +0000474 if (Context.getCanonicalType(Ty) == Context.UndeducedAutoTy) {
Abramo Bagnara25777432010-08-11 22:01:17 +0000475 Diag(NameInfo.getLoc(),
Mike Stump1eb44332009-09-09 15:08:12 +0000476 diag::err_auto_variable_cannot_appear_in_own_initializer)
Anders Carlssone2bb2242009-06-26 19:16:07 +0000477 << D->getDeclName();
478 return ExprError();
479 }
Mike Stump1eb44332009-09-09 15:08:12 +0000480
Anders Carlssone41590d2009-06-24 00:10:43 +0000481 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Douglas Gregor15dedf02010-04-27 21:10:04 +0000482 if (isa<NonTypeTemplateParmDecl>(VD)) {
483 // Non-type template parameters can be referenced anywhere they are
484 // visible.
Douglas Gregor63982352010-07-13 18:40:04 +0000485 Ty = Ty.getNonLValueExprType(Context);
Douglas Gregor15dedf02010-04-27 21:10:04 +0000486 } else if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
Anders Carlssone41590d2009-06-24 00:10:43 +0000487 if (const FunctionDecl *FD = MD->getParent()->isLocalClass()) {
488 if (VD->hasLocalStorage() && VD->getDeclContext() != CurContext) {
Abramo Bagnara25777432010-08-11 22:01:17 +0000489 Diag(NameInfo.getLoc(),
490 diag::err_reference_to_local_var_in_enclosing_function)
Anders Carlssone41590d2009-06-24 00:10:43 +0000491 << D->getIdentifier() << FD->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +0000492 Diag(D->getLocation(), diag::note_local_variable_declared_here)
Anders Carlssone41590d2009-06-24 00:10:43 +0000493 << D->getIdentifier();
494 return ExprError();
495 }
496 }
497 }
498 }
Mike Stump1eb44332009-09-09 15:08:12 +0000499
Abramo Bagnara25777432010-08-11 22:01:17 +0000500 MarkDeclarationReferenced(NameInfo.getLoc(), D);
Mike Stump1eb44332009-09-09 15:08:12 +0000501
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000502 return Owned(DeclRefExpr::Create(Context,
503 SS? (NestedNameSpecifier *)SS->getScopeRep() : 0,
504 SS? SS->getRange() : SourceRange(),
Abramo Bagnara25777432010-08-11 22:01:17 +0000505 D, NameInfo, Ty));
Douglas Gregor1a49af92009-01-06 05:10:23 +0000506}
507
Douglas Gregorffb4b6e2009-04-15 06:41:24 +0000508/// \brief Given a field that represents a member of an anonymous
509/// struct/union, build the path from that field's context to the
510/// actual member.
511///
512/// Construct the sequence of field member references we'll have to
513/// perform to get to the field in the anonymous union/struct. The
514/// list of members is built from the field outward, so traverse it
515/// backwards to go from an object in the current context to the field
516/// we found.
517///
518/// \returns The variable from which the field access should begin,
519/// for an anonymous struct/union that is not a member of another
520/// class. Otherwise, returns NULL.
521VarDecl *Sema::BuildAnonymousStructUnionMemberPath(FieldDecl *Field,
522 llvm::SmallVectorImpl<FieldDecl *> &Path) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000523 assert(Field->getDeclContext()->isRecord() &&
524 cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion()
525 && "Field must be stored inside an anonymous struct or union");
526
Douglas Gregorffb4b6e2009-04-15 06:41:24 +0000527 Path.push_back(Field);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000528 VarDecl *BaseObject = 0;
529 DeclContext *Ctx = Field->getDeclContext();
530 do {
531 RecordDecl *Record = cast<RecordDecl>(Ctx);
John McCallbc365c52010-05-21 01:17:40 +0000532 ValueDecl *AnonObject = Record->getAnonymousStructOrUnionObject();
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000533 if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject))
Douglas Gregorffb4b6e2009-04-15 06:41:24 +0000534 Path.push_back(AnonField);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000535 else {
536 BaseObject = cast<VarDecl>(AnonObject);
537 break;
538 }
539 Ctx = Ctx->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +0000540 } while (Ctx->isRecord() &&
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000541 cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion());
Douglas Gregorffb4b6e2009-04-15 06:41:24 +0000542
543 return BaseObject;
544}
545
546Sema::OwningExprResult
547Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
548 FieldDecl *Field,
549 Expr *BaseObjectExpr,
550 SourceLocation OpLoc) {
551 llvm::SmallVector<FieldDecl *, 4> AnonFields;
Mike Stump1eb44332009-09-09 15:08:12 +0000552 VarDecl *BaseObject = BuildAnonymousStructUnionMemberPath(Field,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +0000553 AnonFields);
554
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000555 // Build the expression that refers to the base object, from
556 // which we will build a sequence of member references to each
557 // of the anonymous union objects and, eventually, the field we
558 // found via name lookup.
559 bool BaseObjectIsPointer = false;
John McCall0953e762009-09-24 19:53:00 +0000560 Qualifiers BaseQuals;
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000561 if (BaseObject) {
562 // BaseObject is an anonymous struct/union variable (and is,
563 // therefore, not part of another non-anonymous record).
Douglas Gregore0762c92009-06-19 23:52:42 +0000564 MarkDeclarationReferenced(Loc, BaseObject);
Steve Naroff6ece14c2009-01-21 00:14:39 +0000565 BaseObjectExpr = new (Context) DeclRefExpr(BaseObject,BaseObject->getType(),
Mike Stumpeed9cac2009-02-19 03:04:26 +0000566 SourceLocation());
John McCall0953e762009-09-24 19:53:00 +0000567 BaseQuals
568 = Context.getCanonicalType(BaseObject->getType()).getQualifiers();
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000569 } else if (BaseObjectExpr) {
570 // The caller provided the base object expression. Determine
571 // whether its a pointer and whether it adds any qualifiers to the
572 // anonymous struct/union fields we're looking into.
573 QualType ObjectType = BaseObjectExpr->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000574 if (const PointerType *ObjectPtr = ObjectType->getAs<PointerType>()) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000575 BaseObjectIsPointer = true;
576 ObjectType = ObjectPtr->getPointeeType();
577 }
John McCall0953e762009-09-24 19:53:00 +0000578 BaseQuals
579 = Context.getCanonicalType(ObjectType).getQualifiers();
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000580 } else {
581 // We've found a member of an anonymous struct/union that is
582 // inside a non-anonymous struct/union, so in a well-formed
583 // program our base object expression is "this".
John McCallea1471e2010-05-20 01:18:31 +0000584 DeclContext *DC = getFunctionLevelDeclContext();
585 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000586 if (!MD->isStatic()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000587 QualType AnonFieldType
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000588 = Context.getTagDeclType(
589 cast<RecordDecl>(AnonFields.back()->getDeclContext()));
590 QualType ThisType = Context.getTagDeclType(MD->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +0000591 if ((Context.getCanonicalType(AnonFieldType)
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000592 == Context.getCanonicalType(ThisType)) ||
593 IsDerivedFrom(ThisType, AnonFieldType)) {
594 // Our base object expression is "this".
Douglas Gregor8aa5f402009-12-24 20:23:34 +0000595 BaseObjectExpr = new (Context) CXXThisExpr(Loc,
Douglas Gregor828a1972010-01-07 23:12:05 +0000596 MD->getThisType(Context),
597 /*isImplicit=*/true);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000598 BaseObjectIsPointer = true;
599 }
600 } else {
Sebastian Redlcd965b92009-01-18 18:53:16 +0000601 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
602 << Field->getDeclName());
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000603 }
John McCall0953e762009-09-24 19:53:00 +0000604 BaseQuals = Qualifiers::fromCVRMask(MD->getTypeQualifiers());
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000605 }
606
Mike Stump1eb44332009-09-09 15:08:12 +0000607 if (!BaseObjectExpr)
Sebastian Redlcd965b92009-01-18 18:53:16 +0000608 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
609 << Field->getDeclName());
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000610 }
611
612 // Build the implicit member references to the field of the
613 // anonymous struct/union.
614 Expr *Result = BaseObjectExpr;
John McCall0953e762009-09-24 19:53:00 +0000615 Qualifiers ResultQuals = BaseQuals;
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000616 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
617 FI = AnonFields.rbegin(), FIEnd = AnonFields.rend();
618 FI != FIEnd; ++FI) {
619 QualType MemberType = (*FI)->getType();
John McCall0953e762009-09-24 19:53:00 +0000620 Qualifiers MemberTypeQuals =
621 Context.getCanonicalType(MemberType).getQualifiers();
622
623 // CVR attributes from the base are picked up by members,
624 // except that 'mutable' members don't pick up 'const'.
625 if ((*FI)->isMutable())
626 ResultQuals.removeConst();
627
628 // GC attributes are never picked up by members.
629 ResultQuals.removeObjCGCAttr();
630
631 // TR 18037 does not allow fields to be declared with address spaces.
632 assert(!MemberTypeQuals.hasAddressSpace());
633
634 Qualifiers NewQuals = ResultQuals + MemberTypeQuals;
635 if (NewQuals != MemberTypeQuals)
636 MemberType = Context.getQualifiedType(MemberType, NewQuals);
637
Douglas Gregore0762c92009-06-19 23:52:42 +0000638 MarkDeclarationReferenced(Loc, *FI);
John McCall6bb80172010-03-30 21:47:33 +0000639 PerformObjectMemberConversion(Result, /*FIXME:Qualifier=*/0, *FI, *FI);
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +0000640 // FIXME: Might this end up being a qualified name?
Steve Naroff6ece14c2009-01-21 00:14:39 +0000641 Result = new (Context) MemberExpr(Result, BaseObjectIsPointer, *FI,
642 OpLoc, MemberType);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000643 BaseObjectIsPointer = false;
John McCall0953e762009-09-24 19:53:00 +0000644 ResultQuals = NewQuals;
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000645 }
646
Sebastian Redlcd965b92009-01-18 18:53:16 +0000647 return Owned(Result);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000648}
649
Abramo Bagnara25777432010-08-11 22:01:17 +0000650/// Decomposes the given name into a DeclarationNameInfo, its location, and
John McCall129e2df2009-11-30 22:42:35 +0000651/// possibly a list of template arguments.
652///
653/// If this produces template arguments, it is permitted to call
654/// DecomposeTemplateName.
655///
656/// This actually loses a lot of source location information for
657/// non-standard name kinds; we should consider preserving that in
658/// some way.
659static void DecomposeUnqualifiedId(Sema &SemaRef,
660 const UnqualifiedId &Id,
661 TemplateArgumentListInfo &Buffer,
Abramo Bagnara25777432010-08-11 22:01:17 +0000662 DeclarationNameInfo &NameInfo,
John McCall129e2df2009-11-30 22:42:35 +0000663 const TemplateArgumentListInfo *&TemplateArgs) {
664 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
665 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
666 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
667
668 ASTTemplateArgsPtr TemplateArgsPtr(SemaRef,
669 Id.TemplateId->getTemplateArgs(),
670 Id.TemplateId->NumArgs);
671 SemaRef.translateTemplateArguments(TemplateArgsPtr, Buffer);
672 TemplateArgsPtr.release();
673
John McCall2b5289b2010-08-23 07:28:44 +0000674 TemplateName TName = Id.TemplateId->Template.get();
Abramo Bagnara25777432010-08-11 22:01:17 +0000675 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
676 NameInfo = SemaRef.Context.getNameForTemplate(TName, TNameLoc);
John McCall129e2df2009-11-30 22:42:35 +0000677 TemplateArgs = &Buffer;
678 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +0000679 NameInfo = SemaRef.GetNameFromUnqualifiedId(Id);
John McCall129e2df2009-11-30 22:42:35 +0000680 TemplateArgs = 0;
681 }
682}
683
John McCall4c72d3e2010-02-08 19:26:07 +0000684/// Determines whether the given record is "fully-formed" at the given
685/// location, i.e. whether a qualified lookup into it is assured of
686/// getting consistent results already.
John McCall129e2df2009-11-30 22:42:35 +0000687static bool IsFullyFormedScope(Sema &SemaRef, CXXRecordDecl *Record) {
John McCall4c72d3e2010-02-08 19:26:07 +0000688 if (!Record->hasDefinition())
689 return false;
690
John McCall129e2df2009-11-30 22:42:35 +0000691 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
692 E = Record->bases_end(); I != E; ++I) {
693 CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
694 CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
695 if (!BaseRT) return false;
696
697 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall4c72d3e2010-02-08 19:26:07 +0000698 if (!BaseRecord->hasDefinition() ||
John McCall129e2df2009-11-30 22:42:35 +0000699 !IsFullyFormedScope(SemaRef, BaseRecord))
700 return false;
701 }
702
703 return true;
704}
705
John McCallaa81e162009-12-01 22:10:20 +0000706/// Determines if the given class is provably not derived from all of
707/// the prospective base classes.
708static bool IsProvablyNotDerivedFrom(Sema &SemaRef,
709 CXXRecordDecl *Record,
710 const llvm::SmallPtrSet<CXXRecordDecl*, 4> &Bases) {
John McCallb1b42562009-12-01 22:28:41 +0000711 if (Bases.count(Record->getCanonicalDecl()))
John McCallaa81e162009-12-01 22:10:20 +0000712 return false;
713
Douglas Gregor952b0172010-02-11 01:04:33 +0000714 RecordDecl *RD = Record->getDefinition();
John McCallb1b42562009-12-01 22:28:41 +0000715 if (!RD) return false;
716 Record = cast<CXXRecordDecl>(RD);
717
John McCallaa81e162009-12-01 22:10:20 +0000718 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
719 E = Record->bases_end(); I != E; ++I) {
720 CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
721 CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
722 if (!BaseRT) return false;
723
724 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCallaa81e162009-12-01 22:10:20 +0000725 if (!IsProvablyNotDerivedFrom(SemaRef, BaseRecord, Bases))
726 return false;
727 }
728
729 return true;
730}
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000731
John McCallaa81e162009-12-01 22:10:20 +0000732enum IMAKind {
733 /// The reference is definitely not an instance member access.
734 IMA_Static,
735
736 /// The reference may be an implicit instance member access.
737 IMA_Mixed,
738
739 /// The reference may be to an instance member, but it is invalid if
740 /// so, because the context is not an instance method.
741 IMA_Mixed_StaticContext,
742
743 /// The reference may be to an instance member, but it is invalid if
744 /// so, because the context is from an unrelated class.
745 IMA_Mixed_Unrelated,
746
747 /// The reference is definitely an implicit instance member access.
748 IMA_Instance,
749
750 /// The reference may be to an unresolved using declaration.
751 IMA_Unresolved,
752
753 /// The reference may be to an unresolved using declaration and the
754 /// context is not an instance method.
755 IMA_Unresolved_StaticContext,
756
757 /// The reference is to a member of an anonymous structure in a
758 /// non-class context.
759 IMA_AnonymousMember,
760
761 /// All possible referrents are instance members and the current
762 /// context is not an instance method.
763 IMA_Error_StaticContext,
764
765 /// All possible referrents are instance members of an unrelated
766 /// class.
767 IMA_Error_Unrelated
768};
769
770/// The given lookup names class member(s) and is not being used for
771/// an address-of-member expression. Classify the type of access
772/// according to whether it's possible that this reference names an
773/// instance member. This is best-effort; it is okay to
774/// conservatively answer "yes", in which case some errors will simply
775/// not be caught until template-instantiation.
776static IMAKind ClassifyImplicitMemberAccess(Sema &SemaRef,
777 const LookupResult &R) {
John McCall3b4294e2009-12-16 12:17:52 +0000778 assert(!R.empty() && (*R.begin())->isCXXClassMember());
John McCallaa81e162009-12-01 22:10:20 +0000779
John McCallea1471e2010-05-20 01:18:31 +0000780 DeclContext *DC = SemaRef.getFunctionLevelDeclContext();
John McCallaa81e162009-12-01 22:10:20 +0000781 bool isStaticContext =
John McCallea1471e2010-05-20 01:18:31 +0000782 (!isa<CXXMethodDecl>(DC) ||
783 cast<CXXMethodDecl>(DC)->isStatic());
John McCallaa81e162009-12-01 22:10:20 +0000784
785 if (R.isUnresolvableResult())
786 return isStaticContext ? IMA_Unresolved_StaticContext : IMA_Unresolved;
787
788 // Collect all the declaring classes of instance members we find.
789 bool hasNonInstance = false;
790 llvm::SmallPtrSet<CXXRecordDecl*, 4> Classes;
791 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
John McCall161755a2010-04-06 21:38:20 +0000792 NamedDecl *D = *I;
793 if (D->isCXXInstanceMember()) {
John McCallaa81e162009-12-01 22:10:20 +0000794 CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext());
795
796 // If this is a member of an anonymous record, move out to the
797 // innermost non-anonymous struct or union. If there isn't one,
798 // that's a special case.
799 while (R->isAnonymousStructOrUnion()) {
800 R = dyn_cast<CXXRecordDecl>(R->getParent());
801 if (!R) return IMA_AnonymousMember;
802 }
803 Classes.insert(R->getCanonicalDecl());
804 }
805 else
806 hasNonInstance = true;
807 }
808
809 // If we didn't find any instance members, it can't be an implicit
810 // member reference.
811 if (Classes.empty())
812 return IMA_Static;
813
814 // If the current context is not an instance method, it can't be
815 // an implicit member reference.
816 if (isStaticContext)
817 return (hasNonInstance ? IMA_Mixed_StaticContext : IMA_Error_StaticContext);
818
819 // If we can prove that the current context is unrelated to all the
820 // declaring classes, it can't be an implicit member reference (in
821 // which case it's an error if any of those members are selected).
822 if (IsProvablyNotDerivedFrom(SemaRef,
John McCallea1471e2010-05-20 01:18:31 +0000823 cast<CXXMethodDecl>(DC)->getParent(),
John McCallaa81e162009-12-01 22:10:20 +0000824 Classes))
825 return (hasNonInstance ? IMA_Mixed_Unrelated : IMA_Error_Unrelated);
826
827 return (hasNonInstance ? IMA_Mixed : IMA_Instance);
828}
829
830/// Diagnose a reference to a field with no object available.
831static void DiagnoseInstanceReference(Sema &SemaRef,
832 const CXXScopeSpec &SS,
833 const LookupResult &R) {
834 SourceLocation Loc = R.getNameLoc();
835 SourceRange Range(Loc);
836 if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
837
838 if (R.getAsSingle<FieldDecl>()) {
839 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(SemaRef.CurContext)) {
840 if (MD->isStatic()) {
841 // "invalid use of member 'x' in static member function"
842 SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method)
843 << Range << R.getLookupName();
844 return;
845 }
846 }
847
848 SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
849 << R.getLookupName() << Range;
850 return;
851 }
852
853 SemaRef.Diag(Loc, diag::err_member_call_without_object) << Range;
John McCall129e2df2009-11-30 22:42:35 +0000854}
855
John McCall578b69b2009-12-16 08:11:27 +0000856/// Diagnose an empty lookup.
857///
858/// \return false if new lookup candidates were found
Nick Lewycky03d98c52010-07-06 19:51:49 +0000859bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
860 CorrectTypoContext CTC) {
John McCall578b69b2009-12-16 08:11:27 +0000861 DeclarationName Name = R.getLookupName();
862
John McCall578b69b2009-12-16 08:11:27 +0000863 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregorbb092ba2009-12-31 05:20:13 +0000864 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCall578b69b2009-12-16 08:11:27 +0000865 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
866 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregorbb092ba2009-12-31 05:20:13 +0000867 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCall578b69b2009-12-16 08:11:27 +0000868 diagnostic = diag::err_undeclared_use;
Douglas Gregorbb092ba2009-12-31 05:20:13 +0000869 diagnostic_suggest = diag::err_undeclared_use_suggest;
870 }
John McCall578b69b2009-12-16 08:11:27 +0000871
Douglas Gregorbb092ba2009-12-31 05:20:13 +0000872 // If the original lookup was an unqualified lookup, fake an
873 // unqualified lookup. This is useful when (for example) the
874 // original lookup would not have found something because it was a
875 // dependent name.
Nick Lewycky03d98c52010-07-06 19:51:49 +0000876 for (DeclContext *DC = SS.isEmpty() ? CurContext : 0;
Douglas Gregorbb092ba2009-12-31 05:20:13 +0000877 DC; DC = DC->getParent()) {
John McCall578b69b2009-12-16 08:11:27 +0000878 if (isa<CXXRecordDecl>(DC)) {
879 LookupQualifiedName(R, DC);
880
881 if (!R.empty()) {
882 // Don't give errors about ambiguities in this lookup.
883 R.suppressDiagnostics();
884
885 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
886 bool isInstance = CurMethod &&
887 CurMethod->isInstance() &&
888 DC == CurMethod->getParent();
889
890 // Give a code modification hint to insert 'this->'.
891 // TODO: fixit for inserting 'Base<T>::' in the other cases.
892 // Actually quite difficult!
Nick Lewycky03d98c52010-07-06 19:51:49 +0000893 if (isInstance) {
Nick Lewycky03d98c52010-07-06 19:51:49 +0000894 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
895 CallsUndergoingInstantiation.back()->getCallee());
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +0000896 CXXMethodDecl *DepMethod = cast_or_null<CXXMethodDecl>(
Nick Lewycky03d98c52010-07-06 19:51:49 +0000897 CurMethod->getInstantiatedFromMemberFunction());
Eli Friedmana7e68452010-08-22 01:00:03 +0000898 if (DepMethod) {
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +0000899 Diag(R.getNameLoc(), diagnostic) << Name
900 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
901 QualType DepThisType = DepMethod->getThisType(Context);
902 CXXThisExpr *DepThis = new (Context) CXXThisExpr(
903 R.getNameLoc(), DepThisType, false);
904 TemplateArgumentListInfo TList;
905 if (ULE->hasExplicitTemplateArgs())
906 ULE->copyTemplateArgumentsInto(TList);
907 CXXDependentScopeMemberExpr *DepExpr =
908 CXXDependentScopeMemberExpr::Create(
909 Context, DepThis, DepThisType, true, SourceLocation(),
910 ULE->getQualifier(), ULE->getQualifierRange(), NULL,
911 R.getLookupNameInfo(), &TList);
912 CallsUndergoingInstantiation.back()->setCallee(DepExpr);
Eli Friedmana7e68452010-08-22 01:00:03 +0000913 } else {
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +0000914 // FIXME: we should be able to handle this case too. It is correct
915 // to add this-> here. This is a workaround for PR7947.
916 Diag(R.getNameLoc(), diagnostic) << Name;
Eli Friedmana7e68452010-08-22 01:00:03 +0000917 }
Nick Lewycky03d98c52010-07-06 19:51:49 +0000918 } else {
John McCall578b69b2009-12-16 08:11:27 +0000919 Diag(R.getNameLoc(), diagnostic) << Name;
Nick Lewycky03d98c52010-07-06 19:51:49 +0000920 }
John McCall578b69b2009-12-16 08:11:27 +0000921
922 // Do we really want to note all of these?
923 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
924 Diag((*I)->getLocation(), diag::note_dependent_var_use);
925
926 // Tell the callee to try to recover.
927 return false;
928 }
Douglas Gregore26f0432010-08-09 22:38:14 +0000929
930 R.clear();
John McCall578b69b2009-12-16 08:11:27 +0000931 }
932 }
933
Douglas Gregorbb092ba2009-12-31 05:20:13 +0000934 // We didn't find anything, so try to correct for a typo.
Douglas Gregoraaf87162010-04-14 20:04:41 +0000935 DeclarationName Corrected;
Daniel Dunbardc32cdf2010-06-02 15:46:52 +0000936 if (S && (Corrected = CorrectTypo(R, S, &SS, 0, false, CTC))) {
Douglas Gregoraaf87162010-04-14 20:04:41 +0000937 if (!R.empty()) {
938 if (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin())) {
939 if (SS.isEmpty())
940 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName()
941 << FixItHint::CreateReplacement(R.getNameLoc(),
942 R.getLookupName().getAsString());
943 else
944 Diag(R.getNameLoc(), diag::err_no_member_suggest)
945 << Name << computeDeclContext(SS, false) << R.getLookupName()
946 << SS.getRange()
947 << FixItHint::CreateReplacement(R.getNameLoc(),
948 R.getLookupName().getAsString());
949 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
950 Diag(ND->getLocation(), diag::note_previous_decl)
951 << ND->getDeclName();
952
953 // Tell the callee to try to recover.
954 return false;
955 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +0000956
Douglas Gregoraaf87162010-04-14 20:04:41 +0000957 if (isa<TypeDecl>(*R.begin()) || isa<ObjCInterfaceDecl>(*R.begin())) {
958 // FIXME: If we ended up with a typo for a type name or
959 // Objective-C class name, we're in trouble because the parser
960 // is in the wrong place to recover. Suggest the typo
961 // correction, but don't make it a fix-it since we're not going
962 // to recover well anyway.
963 if (SS.isEmpty())
964 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName();
965 else
966 Diag(R.getNameLoc(), diag::err_no_member_suggest)
967 << Name << computeDeclContext(SS, false) << R.getLookupName()
968 << SS.getRange();
969
970 // Don't try to recover; it won't work.
971 return true;
972 }
973 } else {
Sean Hunt1e3f5ba2010-04-28 23:02:27 +0000974 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
Douglas Gregoraaf87162010-04-14 20:04:41 +0000975 // because we aren't able to recover.
Douglas Gregord203a162010-01-01 00:15:04 +0000976 if (SS.isEmpty())
Douglas Gregoraaf87162010-04-14 20:04:41 +0000977 Diag(R.getNameLoc(), diagnostic_suggest) << Name << Corrected;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000978 else
Douglas Gregord203a162010-01-01 00:15:04 +0000979 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregoraaf87162010-04-14 20:04:41 +0000980 << Name << computeDeclContext(SS, false) << Corrected
981 << SS.getRange();
Douglas Gregord203a162010-01-01 00:15:04 +0000982 return true;
983 }
Douglas Gregord203a162010-01-01 00:15:04 +0000984 R.clear();
Douglas Gregorbb092ba2009-12-31 05:20:13 +0000985 }
986
987 // Emit a special diagnostic for failed member lookups.
988 // FIXME: computing the declaration context might fail here (?)
989 if (!SS.isEmpty()) {
990 Diag(R.getNameLoc(), diag::err_no_member)
991 << Name << computeDeclContext(SS, false)
992 << SS.getRange();
993 return true;
994 }
995
John McCall578b69b2009-12-16 08:11:27 +0000996 // Give up, we can't recover.
997 Diag(R.getNameLoc(), diagnostic) << Name;
998 return true;
999}
1000
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001001static ObjCPropertyDecl *OkToSynthesizeProvisionalIvar(Sema &SemaRef,
Fariborz Jahanian73f666f2010-07-30 16:59:05 +00001002 IdentifierInfo *II,
1003 SourceLocation NameLoc) {
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001004 ObjCMethodDecl *CurMeth = SemaRef.getCurMethodDecl();
1005 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1006 if (!IDecl)
1007 return 0;
1008 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1009 if (!ClassImpDecl)
1010 return 0;
1011 ObjCPropertyDecl *property = SemaRef.LookupPropertyDecl(IDecl, II);
1012 if (!property)
1013 return 0;
1014 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II))
1015 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
1016 return 0;
1017 return property;
1018}
1019
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001020static ObjCIvarDecl *SynthesizeProvisionalIvar(Sema &SemaRef,
Fariborz Jahanian73f666f2010-07-30 16:59:05 +00001021 LookupResult &Lookup,
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001022 IdentifierInfo *II,
1023 SourceLocation NameLoc) {
1024 ObjCMethodDecl *CurMeth = SemaRef.getCurMethodDecl();
Fariborz Jahanian73f666f2010-07-30 16:59:05 +00001025 bool LookForIvars;
1026 if (Lookup.empty())
1027 LookForIvars = true;
1028 else if (CurMeth->isClassMethod())
1029 LookForIvars = false;
1030 else
1031 LookForIvars = (Lookup.isSingleResult() &&
1032 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
1033 if (!LookForIvars)
1034 return 0;
1035
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001036 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1037 if (!IDecl)
1038 return 0;
1039 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
Fariborz Jahanian84ef4b22010-07-19 16:14:33 +00001040 if (!ClassImpDecl)
1041 return 0;
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001042 bool DynamicImplSeen = false;
1043 ObjCPropertyDecl *property = SemaRef.LookupPropertyDecl(IDecl, II);
1044 if (!property)
1045 return 0;
1046 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II))
1047 DynamicImplSeen =
1048 (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic);
1049 if (!DynamicImplSeen) {
Fariborz Jahanian84ef4b22010-07-19 16:14:33 +00001050 QualType PropType = SemaRef.Context.getCanonicalType(property->getType());
1051 ObjCIvarDecl *Ivar = ObjCIvarDecl::Create(SemaRef.Context, ClassImpDecl,
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001052 NameLoc,
1053 II, PropType, /*Dinfo=*/0,
1054 ObjCIvarDecl::Protected,
1055 (Expr *)0, true);
1056 ClassImpDecl->addDecl(Ivar);
1057 IDecl->makeDeclVisibleInContext(Ivar, false);
1058 property->setPropertyIvarDecl(Ivar);
1059 return Ivar;
1060 }
1061 return 0;
1062}
1063
John McCallf7a1a742009-11-24 19:00:30 +00001064Sema::OwningExprResult Sema::ActOnIdExpression(Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001065 CXXScopeSpec &SS,
John McCallf7a1a742009-11-24 19:00:30 +00001066 UnqualifiedId &Id,
1067 bool HasTrailingLParen,
1068 bool isAddressOfOperand) {
1069 assert(!(isAddressOfOperand && HasTrailingLParen) &&
1070 "cannot be direct & operand and have a trailing lparen");
1071
1072 if (SS.isInvalid())
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001073 return ExprError();
Douglas Gregor5953d8b2009-03-19 17:26:29 +00001074
John McCall129e2df2009-11-30 22:42:35 +00001075 TemplateArgumentListInfo TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +00001076
1077 // Decompose the UnqualifiedId into the following data.
Abramo Bagnara25777432010-08-11 22:01:17 +00001078 DeclarationNameInfo NameInfo;
John McCallf7a1a742009-11-24 19:00:30 +00001079 const TemplateArgumentListInfo *TemplateArgs;
Abramo Bagnara25777432010-08-11 22:01:17 +00001080 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
Douglas Gregor5953d8b2009-03-19 17:26:29 +00001081
Abramo Bagnara25777432010-08-11 22:01:17 +00001082 DeclarationName Name = NameInfo.getName();
Douglas Gregor10c42622008-11-18 15:03:34 +00001083 IdentifierInfo *II = Name.getAsIdentifierInfo();
Abramo Bagnara25777432010-08-11 22:01:17 +00001084 SourceLocation NameLoc = NameInfo.getLoc();
John McCallba135432009-11-21 08:51:07 +00001085
John McCallf7a1a742009-11-24 19:00:30 +00001086 // C++ [temp.dep.expr]p3:
1087 // An id-expression is type-dependent if it contains:
Douglas Gregor48026d22010-01-11 18:40:55 +00001088 // -- an identifier that was declared with a dependent type,
1089 // (note: handled after lookup)
1090 // -- a template-id that is dependent,
1091 // (note: handled in BuildTemplateIdExpr)
1092 // -- a conversion-function-id that specifies a dependent type,
John McCallf7a1a742009-11-24 19:00:30 +00001093 // -- a nested-name-specifier that contains a class-name that
1094 // names a dependent type.
1095 // Determine whether this is a member of an unknown specialization;
1096 // we need to handle these differently.
Eli Friedman647c8b32010-08-06 23:41:47 +00001097 bool DependentID = false;
1098 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1099 Name.getCXXNameType()->isDependentType()) {
1100 DependentID = true;
1101 } else if (SS.isSet()) {
1102 DeclContext *DC = computeDeclContext(SS, false);
1103 if (DC) {
1104 if (RequireCompleteDeclContext(SS, DC))
1105 return ExprError();
1106 // FIXME: We should be checking whether DC is the current instantiation.
1107 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC))
1108 DependentID = !IsFullyFormedScope(*this, RD);
1109 } else {
1110 DependentID = true;
1111 }
1112 }
1113
1114 if (DependentID) {
Abramo Bagnara25777432010-08-11 22:01:17 +00001115 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
John McCallf7a1a742009-11-24 19:00:30 +00001116 TemplateArgs);
1117 }
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001118 bool IvarLookupFollowUp = false;
John McCallf7a1a742009-11-24 19:00:30 +00001119 // Perform the required lookup.
Abramo Bagnara25777432010-08-11 22:01:17 +00001120 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCallf7a1a742009-11-24 19:00:30 +00001121 if (TemplateArgs) {
Douglas Gregord2235f62010-05-20 20:58:56 +00001122 // Lookup the template name again to correctly establish the context in
1123 // which it was found. This is really unfortunate as we already did the
1124 // lookup to determine that it was a template name in the first place. If
1125 // this becomes a performance hit, we can work harder to preserve those
1126 // results until we get here but it's likely not worth it.
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001127 bool MemberOfUnknownSpecialization;
1128 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1129 MemberOfUnknownSpecialization);
John McCallf7a1a742009-11-24 19:00:30 +00001130 } else {
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001131 IvarLookupFollowUp = (!SS.isSet() && II && getCurMethodDecl());
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001132 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump1eb44332009-09-09 15:08:12 +00001133
John McCallf7a1a742009-11-24 19:00:30 +00001134 // If this reference is in an Objective-C method, then we need to do
1135 // some special Objective-C lookup, too.
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001136 if (IvarLookupFollowUp) {
1137 OwningExprResult E(LookupInObjCMethod(R, S, II, true));
John McCallf7a1a742009-11-24 19:00:30 +00001138 if (E.isInvalid())
1139 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001140
John McCallf7a1a742009-11-24 19:00:30 +00001141 Expr *Ex = E.takeAs<Expr>();
1142 if (Ex) return Owned(Ex);
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001143 // Synthesize ivars lazily
1144 if (getLangOptions().ObjCNonFragileABI2) {
Fariborz Jahanian73f666f2010-07-30 16:59:05 +00001145 if (SynthesizeProvisionalIvar(*this, R, II, NameLoc))
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001146 return ActOnIdExpression(S, SS, Id, HasTrailingLParen,
1147 isAddressOfOperand);
1148 }
Fariborz Jahanianf759b4d2010-08-13 18:09:39 +00001149 // for further use, this must be set to false if in class method.
1150 IvarLookupFollowUp = getCurMethodDecl()->isInstanceMethod();
Steve Naroffe3e9add2008-06-02 23:03:37 +00001151 }
Chris Lattner8a934232008-03-31 00:36:02 +00001152 }
Douglas Gregorc71e28c2009-02-16 19:28:42 +00001153
John McCallf7a1a742009-11-24 19:00:30 +00001154 if (R.isAmbiguous())
1155 return ExprError();
1156
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001157 // Determine whether this name might be a candidate for
1158 // argument-dependent lookup.
John McCallf7a1a742009-11-24 19:00:30 +00001159 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001160
John McCallf7a1a742009-11-24 19:00:30 +00001161 if (R.empty() && !ADL) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001162 // Otherwise, this could be an implicitly declared function reference (legal
John McCallf7a1a742009-11-24 19:00:30 +00001163 // in C90, extension in C99, forbidden in C++).
1164 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
1165 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1166 if (D) R.addDecl(D);
1167 }
1168
1169 // If this name wasn't predeclared and if this is not a function
1170 // call, diagnose the problem.
1171 if (R.empty()) {
Douglas Gregor91f7ac72010-05-18 16:14:23 +00001172 if (DiagnoseEmptyLookup(S, SS, R, CTC_Unknown))
John McCall578b69b2009-12-16 08:11:27 +00001173 return ExprError();
1174
1175 assert(!R.empty() &&
1176 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001177
1178 // If we found an Objective-C instance variable, let
1179 // LookupInObjCMethod build the appropriate expression to
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001180 // reference the ivar.
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001181 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1182 R.clear();
1183 OwningExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
1184 assert(E.isInvalid() || E.get());
1185 return move(E);
1186 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001187 }
1188 }
Mike Stump1eb44332009-09-09 15:08:12 +00001189
John McCallf7a1a742009-11-24 19:00:30 +00001190 // This is guaranteed from this point on.
1191 assert(!R.empty() || ADL);
1192
1193 if (VarDecl *Var = R.getAsSingle<VarDecl>()) {
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001194 if (getLangOptions().ObjCNonFragileABI && IvarLookupFollowUp &&
Fariborz Jahanianb1d58e32010-07-29 16:53:53 +00001195 !getLangOptions().ObjCNonFragileABI2 &&
1196 Var->isFileVarDecl()) {
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001197 ObjCPropertyDecl *Property =
1198 OkToSynthesizeProvisionalIvar(*this, II, NameLoc);
1199 if (Property) {
1200 Diag(NameLoc, diag::warn_ivar_variable_conflict) << Var->getDeclName();
1201 Diag(Property->getLocation(), diag::note_property_declare);
Fariborz Jahanianf759b4d2010-08-13 18:09:39 +00001202 Diag(Var->getLocation(), diag::note_global_declared_at);
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001203 }
1204 }
John McCallf7a1a742009-11-24 19:00:30 +00001205 } else if (FunctionDecl *Func = R.getAsSingle<FunctionDecl>()) {
Douglas Gregor751f9a42009-06-30 15:47:41 +00001206 if (!getLangOptions().CPlusPlus && !Func->hasPrototype()) {
1207 // C99 DR 316 says that, if a function type comes from a
1208 // function definition (without a prototype), that type is only
1209 // used for checking compatibility. Therefore, when referencing
1210 // the function, we pretend that we don't have the full function
1211 // type.
John McCallf7a1a742009-11-24 19:00:30 +00001212 if (DiagnoseUseOfDecl(Func, NameLoc))
Douglas Gregor751f9a42009-06-30 15:47:41 +00001213 return ExprError();
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001214
Douglas Gregor751f9a42009-06-30 15:47:41 +00001215 QualType T = Func->getType();
1216 QualType NoProtoType = T;
John McCall183700f2009-09-21 23:43:11 +00001217 if (const FunctionProtoType *Proto = T->getAs<FunctionProtoType>())
Eli Friedman9a0fcfe2010-05-17 02:50:18 +00001218 NoProtoType = Context.getFunctionNoProtoType(Proto->getResultType(),
1219 Proto->getExtInfo());
John McCallf7a1a742009-11-24 19:00:30 +00001220 return BuildDeclRefExpr(Func, NoProtoType, NameLoc, &SS);
Douglas Gregor751f9a42009-06-30 15:47:41 +00001221 }
1222 }
Mike Stump1eb44332009-09-09 15:08:12 +00001223
John McCallaa81e162009-12-01 22:10:20 +00001224 // Check whether this might be a C++ implicit instance member access.
1225 // C++ [expr.prim.general]p6:
1226 // Within the definition of a non-static member function, an
1227 // identifier that names a non-static member is transformed to a
1228 // class member access expression.
1229 // But note that &SomeClass::foo is grammatically distinct, even
1230 // though we don't parse it that way.
John McCall3b4294e2009-12-16 12:17:52 +00001231 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCallf7a1a742009-11-24 19:00:30 +00001232 bool isAbstractMemberPointer = (isAddressOfOperand && !SS.isEmpty());
John McCall3b4294e2009-12-16 12:17:52 +00001233 if (!isAbstractMemberPointer)
1234 return BuildPossibleImplicitMemberExpr(SS, R, TemplateArgs);
John McCall5b3f9132009-11-22 01:44:31 +00001235 }
1236
John McCallf7a1a742009-11-24 19:00:30 +00001237 if (TemplateArgs)
1238 return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
John McCall5b3f9132009-11-22 01:44:31 +00001239
John McCallf7a1a742009-11-24 19:00:30 +00001240 return BuildDeclarationNameExpr(SS, R, ADL);
1241}
1242
John McCall3b4294e2009-12-16 12:17:52 +00001243/// Builds an expression which might be an implicit member expression.
1244Sema::OwningExprResult
1245Sema::BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
1246 LookupResult &R,
1247 const TemplateArgumentListInfo *TemplateArgs) {
1248 switch (ClassifyImplicitMemberAccess(*this, R)) {
1249 case IMA_Instance:
1250 return BuildImplicitMemberExpr(SS, R, TemplateArgs, true);
1251
1252 case IMA_AnonymousMember:
1253 assert(R.isSingleResult());
1254 return BuildAnonymousStructUnionMemberReference(R.getNameLoc(),
1255 R.getAsSingle<FieldDecl>());
1256
1257 case IMA_Mixed:
1258 case IMA_Mixed_Unrelated:
1259 case IMA_Unresolved:
1260 return BuildImplicitMemberExpr(SS, R, TemplateArgs, false);
1261
1262 case IMA_Static:
1263 case IMA_Mixed_StaticContext:
1264 case IMA_Unresolved_StaticContext:
1265 if (TemplateArgs)
1266 return BuildTemplateIdExpr(SS, R, false, *TemplateArgs);
1267 return BuildDeclarationNameExpr(SS, R, false);
1268
1269 case IMA_Error_StaticContext:
1270 case IMA_Error_Unrelated:
1271 DiagnoseInstanceReference(*this, SS, R);
1272 return ExprError();
1273 }
1274
1275 llvm_unreachable("unexpected instance member access kind");
1276 return ExprError();
1277}
1278
John McCall129e2df2009-11-30 22:42:35 +00001279/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1280/// declaration name, generally during template instantiation.
1281/// There's a large number of things which don't need to be done along
1282/// this path.
John McCallf7a1a742009-11-24 19:00:30 +00001283Sema::OwningExprResult
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001284Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00001285 const DeclarationNameInfo &NameInfo) {
John McCallf7a1a742009-11-24 19:00:30 +00001286 DeclContext *DC;
Douglas Gregore6ec5c42010-04-28 07:04:26 +00001287 if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
Abramo Bagnara25777432010-08-11 22:01:17 +00001288 return BuildDependentDeclRefExpr(SS, NameInfo, 0);
John McCallf7a1a742009-11-24 19:00:30 +00001289
John McCall77bb1aa2010-05-01 00:40:08 +00001290 if (RequireCompleteDeclContext(SS, DC))
Douglas Gregore6ec5c42010-04-28 07:04:26 +00001291 return ExprError();
1292
Abramo Bagnara25777432010-08-11 22:01:17 +00001293 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCallf7a1a742009-11-24 19:00:30 +00001294 LookupQualifiedName(R, DC);
1295
1296 if (R.isAmbiguous())
1297 return ExprError();
1298
1299 if (R.empty()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00001300 Diag(NameInfo.getLoc(), diag::err_no_member)
1301 << NameInfo.getName() << DC << SS.getRange();
John McCallf7a1a742009-11-24 19:00:30 +00001302 return ExprError();
1303 }
1304
1305 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1306}
1307
1308/// LookupInObjCMethod - The parser has read a name in, and Sema has
1309/// detected that we're currently inside an ObjC method. Perform some
1310/// additional lookup.
1311///
1312/// Ideally, most of this would be done by lookup, but there's
1313/// actually quite a lot of extra work involved.
1314///
1315/// Returns a null sentinel to indicate trivial success.
1316Sema::OwningExprResult
1317Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Chris Lattnereb483eb2010-04-11 08:28:14 +00001318 IdentifierInfo *II, bool AllowBuiltinCreation) {
John McCallf7a1a742009-11-24 19:00:30 +00001319 SourceLocation Loc = Lookup.getNameLoc();
Chris Lattneraec43db2010-04-12 05:10:17 +00001320 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001321
John McCallf7a1a742009-11-24 19:00:30 +00001322 // There are two cases to handle here. 1) scoped lookup could have failed,
1323 // in which case we should look for an ivar. 2) scoped lookup could have
1324 // found a decl, but that decl is outside the current instance method (i.e.
1325 // a global variable). In these two cases, we do a lookup for an ivar with
1326 // this name, if the lookup sucedes, we replace it our current decl.
1327
1328 // If we're in a class method, we don't normally want to look for
1329 // ivars. But if we don't find anything else, and there's an
1330 // ivar, that's an error.
Chris Lattneraec43db2010-04-12 05:10:17 +00001331 bool IsClassMethod = CurMethod->isClassMethod();
John McCallf7a1a742009-11-24 19:00:30 +00001332
1333 bool LookForIvars;
1334 if (Lookup.empty())
1335 LookForIvars = true;
1336 else if (IsClassMethod)
1337 LookForIvars = false;
1338 else
1339 LookForIvars = (Lookup.isSingleResult() &&
1340 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
Fariborz Jahanian412e7982010-02-09 19:31:38 +00001341 ObjCInterfaceDecl *IFace = 0;
John McCallf7a1a742009-11-24 19:00:30 +00001342 if (LookForIvars) {
Chris Lattneraec43db2010-04-12 05:10:17 +00001343 IFace = CurMethod->getClassInterface();
John McCallf7a1a742009-11-24 19:00:30 +00001344 ObjCInterfaceDecl *ClassDeclared;
1345 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1346 // Diagnose using an ivar in a class method.
1347 if (IsClassMethod)
1348 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1349 << IV->getDeclName());
1350
1351 // If we're referencing an invalid decl, just return this as a silent
1352 // error node. The error diagnostic was already emitted on the decl.
1353 if (IV->isInvalidDecl())
1354 return ExprError();
1355
1356 // Check if referencing a field with __attribute__((deprecated)).
1357 if (DiagnoseUseOfDecl(IV, Loc))
1358 return ExprError();
1359
1360 // Diagnose the use of an ivar outside of the declaring class.
1361 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
1362 ClassDeclared != IFace)
1363 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1364
1365 // FIXME: This should use a new expr for a direct reference, don't
1366 // turn this into Self->ivar, just return a BareIVarExpr or something.
1367 IdentifierInfo &II = Context.Idents.get("self");
1368 UnqualifiedId SelfName;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001369 SelfName.setIdentifier(&II, SourceLocation());
John McCallf7a1a742009-11-24 19:00:30 +00001370 CXXScopeSpec SelfScopeSpec;
1371 OwningExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
1372 SelfName, false, false);
1373 MarkDeclarationReferenced(Loc, IV);
1374 return Owned(new (Context)
1375 ObjCIvarRefExpr(IV, IV->getType(), Loc,
1376 SelfExpr.takeAs<Expr>(), true, true));
1377 }
Chris Lattneraec43db2010-04-12 05:10:17 +00001378 } else if (CurMethod->isInstanceMethod()) {
John McCallf7a1a742009-11-24 19:00:30 +00001379 // We should warn if a local variable hides an ivar.
Chris Lattneraec43db2010-04-12 05:10:17 +00001380 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
John McCallf7a1a742009-11-24 19:00:30 +00001381 ObjCInterfaceDecl *ClassDeclared;
1382 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1383 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
1384 IFace == ClassDeclared)
1385 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
1386 }
1387 }
1388
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001389 if (Lookup.empty() && II && AllowBuiltinCreation) {
1390 // FIXME. Consolidate this with similar code in LookupName.
1391 if (unsigned BuiltinID = II->getBuiltinID()) {
1392 if (!(getLangOptions().CPlusPlus &&
1393 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
1394 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
1395 S, Lookup.isForRedeclaration(),
1396 Lookup.getNameLoc());
1397 if (D) Lookup.addDecl(D);
1398 }
1399 }
1400 }
John McCallf7a1a742009-11-24 19:00:30 +00001401 // Sentinel value saying that we didn't do anything special.
1402 return Owned((Expr*) 0);
Douglas Gregor751f9a42009-06-30 15:47:41 +00001403}
John McCallba135432009-11-21 08:51:07 +00001404
John McCall6bb80172010-03-30 21:47:33 +00001405/// \brief Cast a base object to a member's actual type.
1406///
1407/// Logically this happens in three phases:
1408///
1409/// * First we cast from the base type to the naming class.
1410/// The naming class is the class into which we were looking
1411/// when we found the member; it's the qualifier type if a
1412/// qualifier was provided, and otherwise it's the base type.
1413///
1414/// * Next we cast from the naming class to the declaring class.
1415/// If the member we found was brought into a class's scope by
1416/// a using declaration, this is that class; otherwise it's
1417/// the class declaring the member.
1418///
1419/// * Finally we cast from the declaring class to the "true"
1420/// declaring class of the member. This conversion does not
1421/// obey access control.
Fariborz Jahanianf3e53d32009-07-29 19:40:11 +00001422bool
Douglas Gregor5fccd362010-03-03 23:55:11 +00001423Sema::PerformObjectMemberConversion(Expr *&From,
1424 NestedNameSpecifier *Qualifier,
John McCall6bb80172010-03-30 21:47:33 +00001425 NamedDecl *FoundDecl,
Douglas Gregor5fccd362010-03-03 23:55:11 +00001426 NamedDecl *Member) {
1427 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
1428 if (!RD)
1429 return false;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001430
Douglas Gregor5fccd362010-03-03 23:55:11 +00001431 QualType DestRecordType;
1432 QualType DestType;
1433 QualType FromRecordType;
1434 QualType FromType = From->getType();
1435 bool PointerConversions = false;
1436 if (isa<FieldDecl>(Member)) {
1437 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001438
Douglas Gregor5fccd362010-03-03 23:55:11 +00001439 if (FromType->getAs<PointerType>()) {
1440 DestType = Context.getPointerType(DestRecordType);
1441 FromRecordType = FromType->getPointeeType();
1442 PointerConversions = true;
1443 } else {
1444 DestType = DestRecordType;
1445 FromRecordType = FromType;
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00001446 }
Douglas Gregor5fccd362010-03-03 23:55:11 +00001447 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
1448 if (Method->isStatic())
1449 return false;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001450
Douglas Gregor5fccd362010-03-03 23:55:11 +00001451 DestType = Method->getThisType(Context);
1452 DestRecordType = DestType->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001453
Douglas Gregor5fccd362010-03-03 23:55:11 +00001454 if (FromType->getAs<PointerType>()) {
1455 FromRecordType = FromType->getPointeeType();
1456 PointerConversions = true;
1457 } else {
1458 FromRecordType = FromType;
1459 DestType = DestRecordType;
1460 }
1461 } else {
1462 // No conversion necessary.
1463 return false;
1464 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001465
Douglas Gregor5fccd362010-03-03 23:55:11 +00001466 if (DestType->isDependentType() || FromType->isDependentType())
1467 return false;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001468
Douglas Gregor5fccd362010-03-03 23:55:11 +00001469 // If the unqualified types are the same, no conversion is necessary.
1470 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
1471 return false;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001472
John McCall6bb80172010-03-30 21:47:33 +00001473 SourceRange FromRange = From->getSourceRange();
1474 SourceLocation FromLoc = FromRange.getBegin();
1475
Sebastian Redl906082e2010-07-20 04:20:21 +00001476 ImplicitCastExpr::ResultCategory Category = CastCategory(From);
1477
Douglas Gregor5fccd362010-03-03 23:55:11 +00001478 // C++ [class.member.lookup]p8:
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001479 // [...] Ambiguities can often be resolved by qualifying a name with its
Douglas Gregor5fccd362010-03-03 23:55:11 +00001480 // class name.
1481 //
1482 // If the member was a qualified name and the qualified referred to a
1483 // specific base subobject type, we'll cast to that intermediate type
1484 // first and then to the object in which the member is declared. That allows
1485 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
1486 //
1487 // class Base { public: int x; };
1488 // class Derived1 : public Base { };
1489 // class Derived2 : public Base { };
1490 // class VeryDerived : public Derived1, public Derived2 { void f(); };
1491 //
1492 // void VeryDerived::f() {
1493 // x = 17; // error: ambiguous base subobjects
1494 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
1495 // }
Douglas Gregor5fccd362010-03-03 23:55:11 +00001496 if (Qualifier) {
John McCall6bb80172010-03-30 21:47:33 +00001497 QualType QType = QualType(Qualifier->getAsType(), 0);
1498 assert(!QType.isNull() && "lookup done with dependent qualifier?");
1499 assert(QType->isRecordType() && "lookup done with non-record type");
1500
1501 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
1502
1503 // In C++98, the qualifier type doesn't actually have to be a base
1504 // type of the object type, in which case we just ignore it.
1505 // Otherwise build the appropriate casts.
1506 if (IsDerivedFrom(FromRecordType, QRecordType)) {
John McCallf871d0c2010-08-07 06:22:56 +00001507 CXXCastPath BasePath;
John McCall6bb80172010-03-30 21:47:33 +00001508 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
Anders Carlssoncee22422010-04-24 19:22:20 +00001509 FromLoc, FromRange, &BasePath))
John McCall6bb80172010-03-30 21:47:33 +00001510 return true;
1511
Douglas Gregor5fccd362010-03-03 23:55:11 +00001512 if (PointerConversions)
John McCall6bb80172010-03-30 21:47:33 +00001513 QType = Context.getPointerType(QType);
John McCall23cba802010-03-30 23:58:03 +00001514 ImpCastExprToType(From, QType, CastExpr::CK_UncheckedDerivedToBase,
John McCallf871d0c2010-08-07 06:22:56 +00001515 Category, &BasePath);
John McCall6bb80172010-03-30 21:47:33 +00001516
1517 FromType = QType;
1518 FromRecordType = QRecordType;
1519
1520 // If the qualifier type was the same as the destination type,
1521 // we're done.
1522 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
1523 return false;
Douglas Gregor5fccd362010-03-03 23:55:11 +00001524 }
1525 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001526
John McCall6bb80172010-03-30 21:47:33 +00001527 bool IgnoreAccess = false;
Douglas Gregor5fccd362010-03-03 23:55:11 +00001528
John McCall6bb80172010-03-30 21:47:33 +00001529 // If we actually found the member through a using declaration, cast
1530 // down to the using declaration's type.
1531 //
1532 // Pointer equality is fine here because only one declaration of a
1533 // class ever has member declarations.
1534 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
1535 assert(isa<UsingShadowDecl>(FoundDecl));
1536 QualType URecordType = Context.getTypeDeclType(
1537 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
1538
1539 // We only need to do this if the naming-class to declaring-class
1540 // conversion is non-trivial.
1541 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
1542 assert(IsDerivedFrom(FromRecordType, URecordType));
John McCallf871d0c2010-08-07 06:22:56 +00001543 CXXCastPath BasePath;
John McCall6bb80172010-03-30 21:47:33 +00001544 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
Anders Carlssoncee22422010-04-24 19:22:20 +00001545 FromLoc, FromRange, &BasePath))
John McCall6bb80172010-03-30 21:47:33 +00001546 return true;
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001547
John McCall6bb80172010-03-30 21:47:33 +00001548 QualType UType = URecordType;
1549 if (PointerConversions)
1550 UType = Context.getPointerType(UType);
John McCall23cba802010-03-30 23:58:03 +00001551 ImpCastExprToType(From, UType, CastExpr::CK_UncheckedDerivedToBase,
John McCallf871d0c2010-08-07 06:22:56 +00001552 Category, &BasePath);
John McCall6bb80172010-03-30 21:47:33 +00001553 FromType = UType;
1554 FromRecordType = URecordType;
1555 }
1556
1557 // We don't do access control for the conversion from the
1558 // declaring class to the true declaring class.
1559 IgnoreAccess = true;
Douglas Gregor5fccd362010-03-03 23:55:11 +00001560 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001561
John McCallf871d0c2010-08-07 06:22:56 +00001562 CXXCastPath BasePath;
Anders Carlssoncee22422010-04-24 19:22:20 +00001563 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
1564 FromLoc, FromRange, &BasePath,
John McCall6bb80172010-03-30 21:47:33 +00001565 IgnoreAccess))
Douglas Gregor5fccd362010-03-03 23:55:11 +00001566 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001567
John McCall23cba802010-03-30 23:58:03 +00001568 ImpCastExprToType(From, DestType, CastExpr::CK_UncheckedDerivedToBase,
John McCallf871d0c2010-08-07 06:22:56 +00001569 Category, &BasePath);
Fariborz Jahanianf3e53d32009-07-29 19:40:11 +00001570 return false;
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00001571}
Douglas Gregor751f9a42009-06-30 15:47:41 +00001572
Douglas Gregor83f6faf2009-08-31 23:41:50 +00001573/// \brief Build a MemberExpr AST node.
Mike Stump1eb44332009-09-09 15:08:12 +00001574static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow,
Eli Friedmanf595cc42009-12-04 06:40:45 +00001575 const CXXScopeSpec &SS, ValueDecl *Member,
John McCall161755a2010-04-06 21:38:20 +00001576 DeclAccessPair FoundDecl,
Abramo Bagnara25777432010-08-11 22:01:17 +00001577 const DeclarationNameInfo &MemberNameInfo,
1578 QualType Ty,
John McCallf7a1a742009-11-24 19:00:30 +00001579 const TemplateArgumentListInfo *TemplateArgs = 0) {
1580 NestedNameSpecifier *Qualifier = 0;
1581 SourceRange QualifierRange;
John McCall129e2df2009-11-30 22:42:35 +00001582 if (SS.isSet()) {
1583 Qualifier = (NestedNameSpecifier *) SS.getScopeRep();
1584 QualifierRange = SS.getRange();
John McCallf7a1a742009-11-24 19:00:30 +00001585 }
Mike Stump1eb44332009-09-09 15:08:12 +00001586
John McCallf7a1a742009-11-24 19:00:30 +00001587 return MemberExpr::Create(C, Base, isArrow, Qualifier, QualifierRange,
Abramo Bagnara25777432010-08-11 22:01:17 +00001588 Member, FoundDecl, MemberNameInfo,
1589 TemplateArgs, Ty);
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +00001590}
1591
John McCallaa81e162009-12-01 22:10:20 +00001592/// Builds an implicit member access expression. The current context
1593/// is known to be an instance method, and the given unqualified lookup
1594/// set is known to contain only instance members, at least one of which
1595/// is from an appropriate type.
John McCall5b3f9132009-11-22 01:44:31 +00001596Sema::OwningExprResult
John McCallaa81e162009-12-01 22:10:20 +00001597Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
1598 LookupResult &R,
1599 const TemplateArgumentListInfo *TemplateArgs,
1600 bool IsKnownInstance) {
John McCallf7a1a742009-11-24 19:00:30 +00001601 assert(!R.empty() && !R.isAmbiguous());
1602
John McCallba135432009-11-21 08:51:07 +00001603 SourceLocation Loc = R.getNameLoc();
Sebastian Redlebc07d52009-02-03 20:19:35 +00001604
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001605 // We may have found a field within an anonymous union or struct
1606 // (C++ [class.union]).
Douglas Gregore961afb2009-10-22 07:08:30 +00001607 // FIXME: This needs to happen post-isImplicitMemberReference?
John McCallf7a1a742009-11-24 19:00:30 +00001608 // FIXME: template-ids inside anonymous structs?
John McCall129e2df2009-11-30 22:42:35 +00001609 if (FieldDecl *FD = R.getAsSingle<FieldDecl>())
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001610 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
John McCall5b3f9132009-11-22 01:44:31 +00001611 return BuildAnonymousStructUnionMemberReference(Loc, FD);
Sebastian Redlcd965b92009-01-18 18:53:16 +00001612
John McCallaa81e162009-12-01 22:10:20 +00001613 // If this is known to be an instance access, go ahead and build a
1614 // 'this' expression now.
John McCallea1471e2010-05-20 01:18:31 +00001615 DeclContext *DC = getFunctionLevelDeclContext();
1616 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(Context);
John McCallaa81e162009-12-01 22:10:20 +00001617 Expr *This = 0; // null signifies implicit access
1618 if (IsKnownInstance) {
Douglas Gregor828a1972010-01-07 23:12:05 +00001619 SourceLocation Loc = R.getNameLoc();
1620 if (SS.getRange().isValid())
1621 Loc = SS.getRange().getBegin();
1622 This = new (Context) CXXThisExpr(Loc, ThisType, /*isImplicit=*/true);
Douglas Gregor88a35142008-12-22 05:46:06 +00001623 }
1624
John McCall9ae2f072010-08-23 23:25:46 +00001625 return BuildMemberReferenceExpr(This, ThisType,
John McCallaa81e162009-12-01 22:10:20 +00001626 /*OpLoc*/ SourceLocation(),
1627 /*IsArrow*/ true,
John McCallc2233c52010-01-15 08:34:02 +00001628 SS,
1629 /*FirstQualifierInScope*/ 0,
1630 R, TemplateArgs);
John McCallba135432009-11-21 08:51:07 +00001631}
1632
John McCallf7a1a742009-11-24 19:00:30 +00001633bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00001634 const LookupResult &R,
1635 bool HasTrailingLParen) {
John McCallba135432009-11-21 08:51:07 +00001636 // Only when used directly as the postfix-expression of a call.
1637 if (!HasTrailingLParen)
1638 return false;
1639
1640 // Never if a scope specifier was provided.
John McCallf7a1a742009-11-24 19:00:30 +00001641 if (SS.isSet())
John McCallba135432009-11-21 08:51:07 +00001642 return false;
1643
1644 // Only in C++ or ObjC++.
John McCall5b3f9132009-11-22 01:44:31 +00001645 if (!getLangOptions().CPlusPlus)
John McCallba135432009-11-21 08:51:07 +00001646 return false;
1647
1648 // Turn off ADL when we find certain kinds of declarations during
1649 // normal lookup:
1650 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
1651 NamedDecl *D = *I;
1652
1653 // C++0x [basic.lookup.argdep]p3:
1654 // -- a declaration of a class member
1655 // Since using decls preserve this property, we check this on the
1656 // original decl.
John McCall3b4294e2009-12-16 12:17:52 +00001657 if (D->isCXXClassMember())
John McCallba135432009-11-21 08:51:07 +00001658 return false;
1659
1660 // C++0x [basic.lookup.argdep]p3:
1661 // -- a block-scope function declaration that is not a
1662 // using-declaration
1663 // NOTE: we also trigger this for function templates (in fact, we
1664 // don't check the decl type at all, since all other decl types
1665 // turn off ADL anyway).
1666 if (isa<UsingShadowDecl>(D))
1667 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1668 else if (D->getDeclContext()->isFunctionOrMethod())
1669 return false;
1670
1671 // C++0x [basic.lookup.argdep]p3:
1672 // -- a declaration that is neither a function or a function
1673 // template
1674 // And also for builtin functions.
1675 if (isa<FunctionDecl>(D)) {
1676 FunctionDecl *FDecl = cast<FunctionDecl>(D);
1677
1678 // But also builtin functions.
1679 if (FDecl->getBuiltinID() && FDecl->isImplicit())
1680 return false;
1681 } else if (!isa<FunctionTemplateDecl>(D))
1682 return false;
1683 }
1684
1685 return true;
1686}
1687
1688
John McCallba135432009-11-21 08:51:07 +00001689/// Diagnoses obvious problems with the use of the given declaration
1690/// as an expression. This is only actually called for lookups that
1691/// were not overloaded, and it doesn't promise that the declaration
1692/// will in fact be used.
1693static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
1694 if (isa<TypedefDecl>(D)) {
1695 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
1696 return true;
1697 }
1698
1699 if (isa<ObjCInterfaceDecl>(D)) {
1700 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
1701 return true;
1702 }
1703
1704 if (isa<NamespaceDecl>(D)) {
1705 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
1706 return true;
1707 }
1708
1709 return false;
1710}
1711
1712Sema::OwningExprResult
John McCallf7a1a742009-11-24 19:00:30 +00001713Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00001714 LookupResult &R,
1715 bool NeedsADL) {
John McCallfead20c2009-12-08 22:45:53 +00001716 // If this is a single, fully-resolved result and we don't need ADL,
1717 // just build an ordinary singleton decl ref.
Douglas Gregor86b8e092010-01-29 17:15:43 +00001718 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
Abramo Bagnara25777432010-08-11 22:01:17 +00001719 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
1720 R.getFoundDecl());
John McCallba135432009-11-21 08:51:07 +00001721
1722 // We only need to check the declaration if there's exactly one
1723 // result, because in the overloaded case the results can only be
1724 // functions and function templates.
John McCall5b3f9132009-11-22 01:44:31 +00001725 if (R.isSingleResult() &&
1726 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCallba135432009-11-21 08:51:07 +00001727 return ExprError();
1728
John McCallc373d482010-01-27 01:50:18 +00001729 // Otherwise, just build an unresolved lookup expression. Suppress
1730 // any lookup-related diagnostics; we'll hash these out later, when
1731 // we've picked a target.
1732 R.suppressDiagnostics();
1733
John McCallf7a1a742009-11-24 19:00:30 +00001734 bool Dependent
1735 = UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(), 0);
John McCallba135432009-11-21 08:51:07 +00001736 UnresolvedLookupExpr *ULE
John McCallc373d482010-01-27 01:50:18 +00001737 = UnresolvedLookupExpr::Create(Context, Dependent, R.getNamingClass(),
John McCallf7a1a742009-11-24 19:00:30 +00001738 (NestedNameSpecifier*) SS.getScopeRep(),
Abramo Bagnara25777432010-08-11 22:01:17 +00001739 SS.getRange(), R.getLookupNameInfo(),
Douglas Gregor5a84dec2010-05-23 18:57:34 +00001740 NeedsADL, R.isOverloadedResult(),
1741 R.begin(), R.end());
John McCallba135432009-11-21 08:51:07 +00001742
1743 return Owned(ULE);
1744}
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001745
John McCallba135432009-11-21 08:51:07 +00001746
1747/// \brief Complete semantic analysis for a reference to the given declaration.
1748Sema::OwningExprResult
John McCallf7a1a742009-11-24 19:00:30 +00001749Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00001750 const DeclarationNameInfo &NameInfo,
1751 NamedDecl *D) {
John McCallba135432009-11-21 08:51:07 +00001752 assert(D && "Cannot refer to a NULL declaration");
John McCall7453ed42009-11-22 00:44:51 +00001753 assert(!isa<FunctionTemplateDecl>(D) &&
1754 "Cannot refer unambiguously to a function template");
John McCallba135432009-11-21 08:51:07 +00001755
Abramo Bagnara25777432010-08-11 22:01:17 +00001756 SourceLocation Loc = NameInfo.getLoc();
John McCallba135432009-11-21 08:51:07 +00001757 if (CheckDeclInExpr(*this, Loc, D))
1758 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001759
Douglas Gregor9af2f522009-12-01 16:58:18 +00001760 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
1761 // Specifically diagnose references to class templates that are missing
1762 // a template argument list.
1763 Diag(Loc, diag::err_template_decl_ref)
1764 << Template << SS.getRange();
1765 Diag(Template->getLocation(), diag::note_template_decl_here);
1766 return ExprError();
1767 }
1768
1769 // Make sure that we're referring to a value.
1770 ValueDecl *VD = dyn_cast<ValueDecl>(D);
1771 if (!VD) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001772 Diag(Loc, diag::err_ref_non_value)
Douglas Gregor9af2f522009-12-01 16:58:18 +00001773 << D << SS.getRange();
John McCall87cf6702009-12-18 18:35:10 +00001774 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregor9af2f522009-12-01 16:58:18 +00001775 return ExprError();
1776 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001777
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001778 // Check whether this declaration can be used. Note that we suppress
1779 // this check when we're going to perform argument-dependent lookup
1780 // on this function name, because this might not be the function
1781 // that overload resolution actually selects.
John McCallba135432009-11-21 08:51:07 +00001782 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001783 return ExprError();
1784
Steve Naroffdd972f22008-09-05 22:11:13 +00001785 // Only create DeclRefExpr's for valid Decl's.
1786 if (VD->isInvalidDecl())
Sebastian Redlcd965b92009-01-18 18:53:16 +00001787 return ExprError();
1788
Chris Lattner639e2d32008-10-20 05:16:36 +00001789 // If the identifier reference is inside a block, and it refers to a value
1790 // that is outside the block, create a BlockDeclRefExpr instead of a
1791 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
1792 // the block is formed.
Steve Naroffdd972f22008-09-05 22:11:13 +00001793 //
Chris Lattner639e2d32008-10-20 05:16:36 +00001794 // We do not do this for things like enum constants, global variables, etc,
1795 // as they do not get snapshotted.
1796 //
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001797 if (getCurBlock() &&
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00001798 ShouldSnapshotBlockValueReference(*this, getCurBlock(), VD)) {
Mike Stump0d6fd572010-01-05 02:56:35 +00001799 if (VD->getType().getTypePtr()->isVariablyModifiedType()) {
1800 Diag(Loc, diag::err_ref_vm_type);
1801 Diag(D->getLocation(), diag::note_declared_at);
1802 return ExprError();
1803 }
1804
Fariborz Jahanian8596bbe2010-03-16 23:39:51 +00001805 if (VD->getType()->isArrayType()) {
Mike Stump28497342010-01-05 03:10:36 +00001806 Diag(Loc, diag::err_ref_array_type);
1807 Diag(D->getLocation(), diag::note_declared_at);
1808 return ExprError();
1809 }
1810
Douglas Gregore0762c92009-06-19 23:52:42 +00001811 MarkDeclarationReferenced(Loc, VD);
Eli Friedman5fdeae12009-03-22 23:00:19 +00001812 QualType ExprTy = VD->getType().getNonReferenceType();
Steve Naroff090276f2008-10-10 01:28:17 +00001813 // The BlocksAttr indicates the variable is bound by-reference.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001814 if (VD->getAttr<BlocksAttr>())
Eli Friedman5fdeae12009-03-22 23:00:19 +00001815 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, true));
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00001816 // This is to record that a 'const' was actually synthesize and added.
1817 bool constAdded = !ExprTy.isConstQualified();
Steve Naroff090276f2008-10-10 01:28:17 +00001818 // Variable will be bound by-copy, make it const within the closure.
Mike Stump1eb44332009-09-09 15:08:12 +00001819
Eli Friedman5fdeae12009-03-22 23:00:19 +00001820 ExprTy.addConst();
Fariborz Jahanian52bc56a2010-07-12 17:26:57 +00001821 QualType T = VD->getType();
Fariborz Jahanian59da45a2010-06-04 21:35:44 +00001822 BlockDeclRefExpr *BDRE = new (Context) BlockDeclRefExpr(VD,
1823 ExprTy, Loc, false,
Fariborz Jahanian84ca0082010-07-12 18:12:03 +00001824 constAdded);
Fariborz Jahanian833f42e2010-07-09 22:21:32 +00001825 if (getLangOptions().CPlusPlus) {
1826 if (!T->isDependentType() && !T->isReferenceType()) {
1827 Expr *E = new (Context)
1828 DeclRefExpr(const_cast<ValueDecl*>(BDRE->getDecl()), T,
1829 SourceLocation());
Fariborz Jahanian59da45a2010-06-04 21:35:44 +00001830
Fariborz Jahanian833f42e2010-07-09 22:21:32 +00001831 OwningExprResult Res = PerformCopyInitialization(
1832 InitializedEntity::InitializeBlock(VD->getLocation(),
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00001833 T, false),
Fariborz Jahanian833f42e2010-07-09 22:21:32 +00001834 SourceLocation(),
1835 Owned(E));
1836 if (!Res.isInvalid()) {
John McCall9ae2f072010-08-23 23:25:46 +00001837 Res = MaybeCreateCXXExprWithTemporaries(Res.get());
Fariborz Jahanian833f42e2010-07-09 22:21:32 +00001838 Expr *Init = Res.takeAs<Expr>();
1839 BDRE->setCopyConstructorExpr(Init);
1840 }
Fariborz Jahanian59da45a2010-06-04 21:35:44 +00001841 }
1842 }
1843 return Owned(BDRE);
Steve Naroff090276f2008-10-10 01:28:17 +00001844 }
1845 // If this reference is not in a block or if the referenced variable is
1846 // within the block, create a normal DeclRefExpr.
Douglas Gregor898574e2008-12-05 23:32:09 +00001847
Abramo Bagnara25777432010-08-11 22:01:17 +00001848 return BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(),
1849 NameInfo, &SS);
Reid Spencer5f016e22007-07-11 17:01:13 +00001850}
1851
Sebastian Redlcd965b92009-01-18 18:53:16 +00001852Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
1853 tok::TokenKind Kind) {
Chris Lattnerd9f69102008-08-10 01:53:14 +00001854 PredefinedExpr::IdentType IT;
Sebastian Redlcd965b92009-01-18 18:53:16 +00001855
Reid Spencer5f016e22007-07-11 17:01:13 +00001856 switch (Kind) {
Chris Lattner1423ea42008-01-12 18:39:25 +00001857 default: assert(0 && "Unknown simple primary expr!");
Chris Lattnerd9f69102008-08-10 01:53:14 +00001858 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
1859 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
1860 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00001861 }
Chris Lattner1423ea42008-01-12 18:39:25 +00001862
Chris Lattnerfa28b302008-01-12 08:14:25 +00001863 // Pre-defined identifiers are of type char[x], where x is the length of the
1864 // string.
Mike Stump1eb44332009-09-09 15:08:12 +00001865
Anders Carlsson3a082d82009-09-08 18:24:21 +00001866 Decl *currentDecl = getCurFunctionOrMethodDecl();
Fariborz Jahanianeb024ac2010-07-23 21:53:24 +00001867 if (!currentDecl && getCurBlock())
1868 currentDecl = getCurBlock()->TheDecl;
Anders Carlsson3a082d82009-09-08 18:24:21 +00001869 if (!currentDecl) {
Chris Lattnerb0da9232008-12-12 05:05:20 +00001870 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson3a082d82009-09-08 18:24:21 +00001871 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerb0da9232008-12-12 05:05:20 +00001872 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001873
Anders Carlsson773f3972009-09-11 01:22:35 +00001874 QualType ResTy;
1875 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
1876 ResTy = Context.DependentTy;
1877 } else {
Anders Carlsson848fa642010-02-11 18:20:28 +00001878 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001879
Anders Carlsson773f3972009-09-11 01:22:35 +00001880 llvm::APInt LengthI(32, Length + 1);
John McCall0953e762009-09-24 19:53:00 +00001881 ResTy = Context.CharTy.withConst();
Anders Carlsson773f3972009-09-11 01:22:35 +00001882 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
1883 }
Steve Naroff6ece14c2009-01-21 00:14:39 +00001884 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Reid Spencer5f016e22007-07-11 17:01:13 +00001885}
1886
Sebastian Redlcd965b92009-01-18 18:53:16 +00001887Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001888 llvm::SmallString<16> CharBuffer;
Douglas Gregor453091c2010-03-16 22:30:13 +00001889 bool Invalid = false;
1890 llvm::StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
1891 if (Invalid)
1892 return ExprError();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001893
Benjamin Kramerddeea562010-02-27 13:44:12 +00001894 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
1895 PP);
Reid Spencer5f016e22007-07-11 17:01:13 +00001896 if (Literal.hadError())
Sebastian Redlcd965b92009-01-18 18:53:16 +00001897 return ExprError();
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00001898
Chris Lattnere8337df2009-12-30 21:19:39 +00001899 QualType Ty;
1900 if (!getLangOptions().CPlusPlus)
1901 Ty = Context.IntTy; // 'x' and L'x' -> int in C.
1902 else if (Literal.isWide())
1903 Ty = Context.WCharTy; // L'x' -> wchar_t in C++.
Eli Friedman136b0cd2010-02-03 18:21:45 +00001904 else if (Literal.isMultiChar())
1905 Ty = Context.IntTy; // 'wxyz' -> int in C++.
Chris Lattnere8337df2009-12-30 21:19:39 +00001906 else
1907 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00001908
Sebastian Redle91b3bc2009-01-20 22:23:13 +00001909 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
1910 Literal.isWide(),
Chris Lattnere8337df2009-12-30 21:19:39 +00001911 Ty, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00001912}
1913
Sebastian Redlcd965b92009-01-18 18:53:16 +00001914Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
1915 // Fast path for a single digit (which is quite common). A single digit
Reid Spencer5f016e22007-07-11 17:01:13 +00001916 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
1917 if (Tok.getLength() == 1) {
Chris Lattner7216dc92009-01-26 22:36:52 +00001918 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattner0c21e842009-01-16 07:10:29 +00001919 unsigned IntSize = Context.Target.getIntWidth();
Steve Naroff6ece14c2009-01-21 00:14:39 +00001920 return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
Steve Naroff0a473932009-01-20 19:53:53 +00001921 Context.IntTy, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00001922 }
Ted Kremenek28396602009-01-13 23:19:12 +00001923
Reid Spencer5f016e22007-07-11 17:01:13 +00001924 llvm::SmallString<512> IntegerBuffer;
Chris Lattner2a299042008-09-30 20:53:45 +00001925 // Add padding so that NumericLiteralParser can overread by one character.
1926 IntegerBuffer.resize(Tok.getLength()+1);
Reid Spencer5f016e22007-07-11 17:01:13 +00001927 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd965b92009-01-18 18:53:16 +00001928
Reid Spencer5f016e22007-07-11 17:01:13 +00001929 // Get the spelling of the token, which eliminates trigraphs, etc.
Douglas Gregor453091c2010-03-16 22:30:13 +00001930 bool Invalid = false;
1931 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
1932 if (Invalid)
1933 return ExprError();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001934
Mike Stump1eb44332009-09-09 15:08:12 +00001935 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Reid Spencer5f016e22007-07-11 17:01:13 +00001936 Tok.getLocation(), PP);
1937 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +00001938 return ExprError();
1939
Chris Lattner5d661452007-08-26 03:42:43 +00001940 Expr *Res;
Sebastian Redlcd965b92009-01-18 18:53:16 +00001941
Chris Lattner5d661452007-08-26 03:42:43 +00001942 if (Literal.isFloatingLiteral()) {
Chris Lattner525a0502007-09-22 18:29:59 +00001943 QualType Ty;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001944 if (Literal.isFloat)
Chris Lattner525a0502007-09-22 18:29:59 +00001945 Ty = Context.FloatTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001946 else if (!Literal.isLong)
Chris Lattner525a0502007-09-22 18:29:59 +00001947 Ty = Context.DoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001948 else
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001949 Ty = Context.LongDoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001950
1951 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
1952
John McCall94c939d2009-12-24 09:08:04 +00001953 using llvm::APFloat;
1954 APFloat Val(Format);
1955
1956 APFloat::opStatus result = Literal.GetFloatValue(Val);
John McCall9f2df882009-12-24 11:09:08 +00001957
1958 // Overflow is always an error, but underflow is only an error if
1959 // we underflowed to zero (APFloat reports denormals as underflow).
1960 if ((result & APFloat::opOverflow) ||
1961 ((result & APFloat::opUnderflow) && Val.isZero())) {
John McCall94c939d2009-12-24 09:08:04 +00001962 unsigned diagnostic;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001963 llvm::SmallString<20> buffer;
John McCall94c939d2009-12-24 09:08:04 +00001964 if (result & APFloat::opOverflow) {
John McCall2a0d7572010-02-26 23:35:57 +00001965 diagnostic = diag::warn_float_overflow;
John McCall94c939d2009-12-24 09:08:04 +00001966 APFloat::getLargest(Format).toString(buffer);
1967 } else {
John McCall2a0d7572010-02-26 23:35:57 +00001968 diagnostic = diag::warn_float_underflow;
John McCall94c939d2009-12-24 09:08:04 +00001969 APFloat::getSmallest(Format).toString(buffer);
1970 }
1971
1972 Diag(Tok.getLocation(), diagnostic)
1973 << Ty
1974 << llvm::StringRef(buffer.data(), buffer.size());
1975 }
1976
1977 bool isExact = (result == APFloat::opOK);
Chris Lattner001d64d2009-06-29 17:34:55 +00001978 Res = new (Context) FloatingLiteral(Val, isExact, Ty, Tok.getLocation());
Sebastian Redlcd965b92009-01-18 18:53:16 +00001979
Chris Lattner5d661452007-08-26 03:42:43 +00001980 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00001981 return ExprError();
Chris Lattner5d661452007-08-26 03:42:43 +00001982 } else {
Chris Lattnerf0467b32008-04-02 04:24:33 +00001983 QualType Ty;
Reid Spencer5f016e22007-07-11 17:01:13 +00001984
Neil Boothb9449512007-08-29 22:00:19 +00001985 // long long is a C99 feature.
1986 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth79859c32007-08-29 22:13:52 +00001987 Literal.isLongLong)
Neil Boothb9449512007-08-29 22:00:19 +00001988 Diag(Tok.getLocation(), diag::ext_longlong);
1989
Reid Spencer5f016e22007-07-11 17:01:13 +00001990 // Get the value in the widest-possible width.
Chris Lattner98be4942008-03-05 18:54:05 +00001991 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlcd965b92009-01-18 18:53:16 +00001992
Reid Spencer5f016e22007-07-11 17:01:13 +00001993 if (Literal.GetIntegerValue(ResultVal)) {
1994 // If this value didn't fit into uintmax_t, warn and force to ull.
1995 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattnerf0467b32008-04-02 04:24:33 +00001996 Ty = Context.UnsignedLongLongTy;
1997 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner98be4942008-03-05 18:54:05 +00001998 "long long is not intmax_t?");
Reid Spencer5f016e22007-07-11 17:01:13 +00001999 } else {
2000 // If this value fits into a ULL, try to figure out what else it fits into
2001 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd965b92009-01-18 18:53:16 +00002002
Reid Spencer5f016e22007-07-11 17:01:13 +00002003 // Octal, Hexadecimal, and integers with a U suffix are allowed to
2004 // be an unsigned int.
2005 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2006
2007 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002008 unsigned Width = 0;
Chris Lattner97c51562007-08-23 21:58:08 +00002009 if (!Literal.isLong && !Literal.isLongLong) {
2010 // Are int/unsigned possibilities?
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002011 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002012
Reid Spencer5f016e22007-07-11 17:01:13 +00002013 // Does it fit in a unsigned int?
2014 if (ResultVal.isIntN(IntSize)) {
2015 // Does it fit in a signed int?
2016 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002017 Ty = Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002018 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002019 Ty = Context.UnsignedIntTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002020 Width = IntSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002021 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002022 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002023
Reid Spencer5f016e22007-07-11 17:01:13 +00002024 // Are long/unsigned long possibilities?
Chris Lattnerf0467b32008-04-02 04:24:33 +00002025 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002026 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002027
Reid Spencer5f016e22007-07-11 17:01:13 +00002028 // Does it fit in a unsigned long?
2029 if (ResultVal.isIntN(LongSize)) {
2030 // Does it fit in a signed long?
2031 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002032 Ty = Context.LongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002033 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002034 Ty = Context.UnsignedLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002035 Width = LongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002036 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002037 }
2038
Reid Spencer5f016e22007-07-11 17:01:13 +00002039 // Finally, check long long if needed.
Chris Lattnerf0467b32008-04-02 04:24:33 +00002040 if (Ty.isNull()) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002041 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002042
Reid Spencer5f016e22007-07-11 17:01:13 +00002043 // Does it fit in a unsigned long long?
2044 if (ResultVal.isIntN(LongLongSize)) {
2045 // Does it fit in a signed long long?
2046 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002047 Ty = Context.LongLongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002048 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002049 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002050 Width = LongLongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002051 }
2052 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002053
Reid Spencer5f016e22007-07-11 17:01:13 +00002054 // If we still couldn't decide a type, we probably have something that
2055 // does not fit in a signed long long, but has no U suffix.
Chris Lattnerf0467b32008-04-02 04:24:33 +00002056 if (Ty.isNull()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002057 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattnerf0467b32008-04-02 04:24:33 +00002058 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002059 Width = Context.Target.getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +00002060 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002061
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002062 if (ResultVal.getBitWidth() != Width)
2063 ResultVal.trunc(Width);
Reid Spencer5f016e22007-07-11 17:01:13 +00002064 }
Sebastian Redle91b3bc2009-01-20 22:23:13 +00002065 Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00002066 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002067
Chris Lattner5d661452007-08-26 03:42:43 +00002068 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
2069 if (Literal.isImaginary)
Mike Stump1eb44332009-09-09 15:08:12 +00002070 Res = new (Context) ImaginaryLiteral(Res,
Steve Naroff6ece14c2009-01-21 00:14:39 +00002071 Context.getComplexType(Res->getType()));
Sebastian Redlcd965b92009-01-18 18:53:16 +00002072
2073 return Owned(Res);
Reid Spencer5f016e22007-07-11 17:01:13 +00002074}
2075
Sebastian Redlcd965b92009-01-18 18:53:16 +00002076Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
John McCall9ae2f072010-08-23 23:25:46 +00002077 SourceLocation R, Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00002078 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff6ece14c2009-01-21 00:14:39 +00002079 return Owned(new (Context) ParenExpr(L, R, E));
Reid Spencer5f016e22007-07-11 17:01:13 +00002080}
2081
2082/// The UsualUnaryConversions() function is *not* called by this routine.
2083/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl28507842009-02-26 14:39:58 +00002084bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Sebastian Redl05189992008-11-11 17:56:53 +00002085 SourceLocation OpLoc,
2086 const SourceRange &ExprRange,
2087 bool isSizeof) {
Sebastian Redl28507842009-02-26 14:39:58 +00002088 if (exprType->isDependentType())
2089 return false;
2090
Sebastian Redl5d484e82009-11-23 17:18:46 +00002091 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2092 // the result is the size of the referenced type."
2093 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2094 // result shall be the alignment of the referenced type."
2095 if (const ReferenceType *Ref = exprType->getAs<ReferenceType>())
2096 exprType = Ref->getPointeeType();
2097
Reid Spencer5f016e22007-07-11 17:01:13 +00002098 // C99 6.5.3.4p1:
John McCall5ab75172009-11-04 07:28:41 +00002099 if (exprType->isFunctionType()) {
Chris Lattner1efaa952009-04-24 00:30:45 +00002100 // alignof(function) is allowed as an extension.
Chris Lattner01072922009-01-24 19:46:37 +00002101 if (isSizeof)
2102 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
2103 return false;
2104 }
Mike Stump1eb44332009-09-09 15:08:12 +00002105
Chris Lattner1efaa952009-04-24 00:30:45 +00002106 // Allow sizeof(void)/alignof(void) as an extension.
Chris Lattner01072922009-01-24 19:46:37 +00002107 if (exprType->isVoidType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002108 Diag(OpLoc, diag::ext_sizeof_void_type)
2109 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattner01072922009-01-24 19:46:37 +00002110 return false;
2111 }
Mike Stump1eb44332009-09-09 15:08:12 +00002112
Chris Lattner1efaa952009-04-24 00:30:45 +00002113 if (RequireCompleteType(OpLoc, exprType,
Douglas Gregor5cc07df2009-12-15 16:44:32 +00002114 PDiag(diag::err_sizeof_alignof_incomplete_type)
2115 << int(!isSizeof) << ExprRange))
Chris Lattner1efaa952009-04-24 00:30:45 +00002116 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002117
Chris Lattner1efaa952009-04-24 00:30:45 +00002118 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
John McCallc12c5bb2010-05-15 11:32:37 +00002119 if (LangOpts.ObjCNonFragileABI && exprType->isObjCObjectType()) {
Chris Lattner1efaa952009-04-24 00:30:45 +00002120 Diag(OpLoc, diag::err_sizeof_nonfragile_interface)
Chris Lattner5cb10d32009-04-24 22:30:50 +00002121 << exprType << isSizeof << ExprRange;
2122 return true;
Chris Lattnerca790922009-04-21 19:55:16 +00002123 }
Mike Stump1eb44332009-09-09 15:08:12 +00002124
Douglas Gregor9ba6af82010-05-23 19:43:23 +00002125 if (Context.hasSameUnqualifiedType(exprType, Context.OverloadTy)) {
2126 Diag(OpLoc, diag::err_sizeof_alignof_overloaded_function_type)
2127 << !isSizeof << ExprRange;
2128 return true;
2129 }
2130
Chris Lattner1efaa952009-04-24 00:30:45 +00002131 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002132}
2133
Chris Lattner31e21e02009-01-24 20:17:12 +00002134bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
2135 const SourceRange &ExprRange) {
2136 E = E->IgnoreParens();
Sebastian Redl28507842009-02-26 14:39:58 +00002137
Mike Stump1eb44332009-09-09 15:08:12 +00002138 // alignof decl is always ok.
Chris Lattner31e21e02009-01-24 20:17:12 +00002139 if (isa<DeclRefExpr>(E))
2140 return false;
Sebastian Redl28507842009-02-26 14:39:58 +00002141
2142 // Cannot know anything else if the expression is dependent.
2143 if (E->isTypeDependent())
2144 return false;
2145
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002146 if (E->getBitField()) {
2147 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
2148 return true;
Chris Lattner31e21e02009-01-24 20:17:12 +00002149 }
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002150
2151 // Alignment of a field access is always okay, so long as it isn't a
2152 // bit-field.
2153 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump8e1fab22009-07-22 18:58:19 +00002154 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002155 return false;
2156
Chris Lattner31e21e02009-01-24 20:17:12 +00002157 return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
2158}
2159
Douglas Gregorba498172009-03-13 21:01:28 +00002160/// \brief Build a sizeof or alignof expression given a type operand.
Mike Stump1eb44332009-09-09 15:08:12 +00002161Action::OwningExprResult
John McCalla93c9342009-12-07 02:54:59 +00002162Sema::CreateSizeOfAlignOfExpr(TypeSourceInfo *TInfo,
John McCall5ab75172009-11-04 07:28:41 +00002163 SourceLocation OpLoc,
Douglas Gregorba498172009-03-13 21:01:28 +00002164 bool isSizeOf, SourceRange R) {
John McCalla93c9342009-12-07 02:54:59 +00002165 if (!TInfo)
Douglas Gregorba498172009-03-13 21:01:28 +00002166 return ExprError();
2167
John McCalla93c9342009-12-07 02:54:59 +00002168 QualType T = TInfo->getType();
John McCall5ab75172009-11-04 07:28:41 +00002169
Douglas Gregorba498172009-03-13 21:01:28 +00002170 if (!T->isDependentType() &&
2171 CheckSizeOfAlignOfOperand(T, OpLoc, R, isSizeOf))
2172 return ExprError();
2173
2174 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
John McCalla93c9342009-12-07 02:54:59 +00002175 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, TInfo,
Douglas Gregorba498172009-03-13 21:01:28 +00002176 Context.getSizeType(), OpLoc,
2177 R.getEnd()));
2178}
2179
2180/// \brief Build a sizeof or alignof expression given an expression
2181/// operand.
Mike Stump1eb44332009-09-09 15:08:12 +00002182Action::OwningExprResult
2183Sema::CreateSizeOfAlignOfExpr(Expr *E, SourceLocation OpLoc,
Douglas Gregorba498172009-03-13 21:01:28 +00002184 bool isSizeOf, SourceRange R) {
2185 // Verify that the operand is valid.
2186 bool isInvalid = false;
2187 if (E->isTypeDependent()) {
2188 // Delay type-checking for type-dependent expressions.
2189 } else if (!isSizeOf) {
2190 isInvalid = CheckAlignOfExpr(E, OpLoc, R);
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002191 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Douglas Gregorba498172009-03-13 21:01:28 +00002192 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
2193 isInvalid = true;
2194 } else {
2195 isInvalid = CheckSizeOfAlignOfOperand(E->getType(), OpLoc, R, true);
2196 }
2197
2198 if (isInvalid)
2199 return ExprError();
2200
2201 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
2202 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, E,
2203 Context.getSizeType(), OpLoc,
2204 R.getEnd()));
2205}
2206
Sebastian Redl05189992008-11-11 17:56:53 +00002207/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
2208/// the same for @c alignof and @c __alignof
2209/// Note that the ArgRange is invalid if isType is false.
Sebastian Redl0eb23302009-01-19 00:08:26 +00002210Action::OwningExprResult
Sebastian Redl05189992008-11-11 17:56:53 +00002211Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
2212 void *TyOrEx, const SourceRange &ArgRange) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002213 // If error parsing type, ignore.
Sebastian Redl0eb23302009-01-19 00:08:26 +00002214 if (TyOrEx == 0) return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00002215
Sebastian Redl05189992008-11-11 17:56:53 +00002216 if (isType) {
John McCalla93c9342009-12-07 02:54:59 +00002217 TypeSourceInfo *TInfo;
2218 (void) GetTypeFromParser(TyOrEx, &TInfo);
2219 return CreateSizeOfAlignOfExpr(TInfo, OpLoc, isSizeof, ArgRange);
Mike Stump1eb44332009-09-09 15:08:12 +00002220 }
Sebastian Redl05189992008-11-11 17:56:53 +00002221
Douglas Gregorba498172009-03-13 21:01:28 +00002222 Expr *ArgEx = (Expr *)TyOrEx;
2223 Action::OwningExprResult Result
2224 = CreateSizeOfAlignOfExpr(ArgEx, OpLoc, isSizeof, ArgEx->getSourceRange());
2225
2226 if (Result.isInvalid())
2227 DeleteExpr(ArgEx);
2228
2229 return move(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00002230}
2231
Chris Lattnerba27e2a2009-02-17 08:12:06 +00002232QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc, bool isReal) {
Sebastian Redl28507842009-02-26 14:39:58 +00002233 if (V->isTypeDependent())
2234 return Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00002235
Chris Lattnercc26ed72007-08-26 05:39:26 +00002236 // These operators return the element type of a complex type.
John McCall183700f2009-09-21 23:43:11 +00002237 if (const ComplexType *CT = V->getType()->getAs<ComplexType>())
Chris Lattnerdbb36972007-08-24 21:16:53 +00002238 return CT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00002239
Chris Lattnercc26ed72007-08-26 05:39:26 +00002240 // Otherwise they pass through real integer and floating point types here.
2241 if (V->getType()->isArithmeticType())
2242 return V->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002243
Chris Lattnercc26ed72007-08-26 05:39:26 +00002244 // Reject anything else.
Chris Lattnerba27e2a2009-02-17 08:12:06 +00002245 Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
2246 << (isReal ? "__real" : "__imag");
Chris Lattnercc26ed72007-08-26 05:39:26 +00002247 return QualType();
Chris Lattnerdbb36972007-08-24 21:16:53 +00002248}
2249
2250
Reid Spencer5f016e22007-07-11 17:01:13 +00002251
Sebastian Redl0eb23302009-01-19 00:08:26 +00002252Action::OwningExprResult
2253Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall9ae2f072010-08-23 23:25:46 +00002254 tok::TokenKind Kind, Expr *Input) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002255 UnaryOperator::Opcode Opc;
2256 switch (Kind) {
2257 default: assert(0 && "Unknown unary op!");
2258 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
2259 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
2260 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002261
John McCall9ae2f072010-08-23 23:25:46 +00002262 return BuildUnaryOp(S, OpLoc, Opc, Input);
Reid Spencer5f016e22007-07-11 17:01:13 +00002263}
2264
Sebastian Redl0eb23302009-01-19 00:08:26 +00002265Action::OwningExprResult
John McCall9ae2f072010-08-23 23:25:46 +00002266Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
2267 Expr *Idx, SourceLocation RLoc) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00002268 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall9ae2f072010-08-23 23:25:46 +00002269 OwningExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
2270 if (Result.isInvalid()) return ExprError();
2271 Base = Result.take();
Nate Begeman2ef13e52009-08-10 23:49:36 +00002272
John McCall9ae2f072010-08-23 23:25:46 +00002273 Expr *LHSExp = Base, *RHSExp = Idx;
Mike Stump1eb44332009-09-09 15:08:12 +00002274
Douglas Gregor337c6b92008-11-19 17:17:41 +00002275 if (getLangOptions().CPlusPlus &&
Douglas Gregor3384c9c2009-05-19 00:01:19 +00002276 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
Douglas Gregor3384c9c2009-05-19 00:01:19 +00002277 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
2278 Context.DependentTy, RLoc));
2279 }
2280
Mike Stump1eb44332009-09-09 15:08:12 +00002281 if (getLangOptions().CPlusPlus &&
Sebastian Redl0eb23302009-01-19 00:08:26 +00002282 (LHSExp->getType()->isRecordType() ||
Eli Friedman03f332a2008-12-15 22:34:21 +00002283 LHSExp->getType()->isEnumeralType() ||
2284 RHSExp->getType()->isRecordType() ||
2285 RHSExp->getType()->isEnumeralType())) {
John McCall9ae2f072010-08-23 23:25:46 +00002286 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
Douglas Gregor337c6b92008-11-19 17:17:41 +00002287 }
2288
John McCall9ae2f072010-08-23 23:25:46 +00002289 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00002290}
2291
2292
2293Action::OwningExprResult
John McCall9ae2f072010-08-23 23:25:46 +00002294Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
2295 Expr *Idx, SourceLocation RLoc) {
2296 Expr *LHSExp = Base;
2297 Expr *RHSExp = Idx;
Sebastian Redlf322ed62009-10-29 20:17:01 +00002298
Chris Lattner12d9ff62007-07-16 00:14:47 +00002299 // Perform default conversions.
Douglas Gregora873dfc2010-02-03 00:27:59 +00002300 if (!LHSExp->getType()->getAs<VectorType>())
2301 DefaultFunctionArrayLvalueConversion(LHSExp);
2302 DefaultFunctionArrayLvalueConversion(RHSExp);
Sebastian Redl0eb23302009-01-19 00:08:26 +00002303
Chris Lattner12d9ff62007-07-16 00:14:47 +00002304 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002305
Reid Spencer5f016e22007-07-11 17:01:13 +00002306 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002307 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stumpeed9cac2009-02-19 03:04:26 +00002308 // in the subscript position. As a result, we need to derive the array base
Reid Spencer5f016e22007-07-11 17:01:13 +00002309 // and index from the expression types.
Chris Lattner12d9ff62007-07-16 00:14:47 +00002310 Expr *BaseExpr, *IndexExpr;
2311 QualType ResultType;
Sebastian Redl28507842009-02-26 14:39:58 +00002312 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
2313 BaseExpr = LHSExp;
2314 IndexExpr = RHSExp;
2315 ResultType = Context.DependentTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00002316 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner12d9ff62007-07-16 00:14:47 +00002317 BaseExpr = LHSExp;
2318 IndexExpr = RHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00002319 ResultType = PTy->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002320 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattner7a2e0472007-07-16 00:23:25 +00002321 // Handle the uncommon case of "123[Ptr]".
Chris Lattner12d9ff62007-07-16 00:14:47 +00002322 BaseExpr = RHSExp;
2323 IndexExpr = LHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00002324 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00002325 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00002326 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00002327 BaseExpr = LHSExp;
2328 IndexExpr = RHSExp;
2329 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00002330 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00002331 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00002332 // Handle the uncommon case of "123[Ptr]".
2333 BaseExpr = RHSExp;
2334 IndexExpr = LHSExp;
2335 ResultType = PTy->getPointeeType();
John McCall183700f2009-09-21 23:43:11 +00002336 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattnerc8629632007-07-31 19:29:30 +00002337 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner12d9ff62007-07-16 00:14:47 +00002338 IndexExpr = RHSExp;
Nate Begeman334a8022009-01-18 00:45:31 +00002339
Chris Lattner12d9ff62007-07-16 00:14:47 +00002340 // FIXME: need to deal with const...
2341 ResultType = VTy->getElementType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00002342 } else if (LHSTy->isArrayType()) {
2343 // If we see an array that wasn't promoted by
Douglas Gregora873dfc2010-02-03 00:27:59 +00002344 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedman7c32f8e2009-04-25 23:46:54 +00002345 // wasn't promoted because of the C90 rule that doesn't
2346 // allow promoting non-lvalue arrays. Warn, then
2347 // force the promotion here.
2348 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
2349 LHSExp->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00002350 ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
2351 CastExpr::CK_ArrayToPointerDecay);
Eli Friedman7c32f8e2009-04-25 23:46:54 +00002352 LHSTy = LHSExp->getType();
2353
2354 BaseExpr = LHSExp;
2355 IndexExpr = RHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00002356 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00002357 } else if (RHSTy->isArrayType()) {
2358 // Same as previous, except for 123[f().a] case
2359 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
2360 RHSExp->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00002361 ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
2362 CastExpr::CK_ArrayToPointerDecay);
Eli Friedman7c32f8e2009-04-25 23:46:54 +00002363 RHSTy = RHSExp->getType();
2364
2365 BaseExpr = RHSExp;
2366 IndexExpr = LHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00002367 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002368 } else {
Chris Lattner338395d2009-04-25 22:50:55 +00002369 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
2370 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00002371 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002372 // C99 6.5.2.1p1
Douglas Gregorf6094622010-07-23 15:58:24 +00002373 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner338395d2009-04-25 22:50:55 +00002374 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
2375 << IndexExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00002376
Daniel Dunbar7e88a602009-09-17 06:31:17 +00002377 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinig0f9a5b52009-09-14 20:14:57 +00002378 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
2379 && !IndexExpr->isTypeDependent())
Sam Weinig76e2b712009-09-14 01:58:58 +00002380 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
2381
Douglas Gregore7450f52009-03-24 19:52:54 +00002382 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump1eb44332009-09-09 15:08:12 +00002383 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
2384 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregore7450f52009-03-24 19:52:54 +00002385 // incomplete types are not object types.
2386 if (ResultType->isFunctionType()) {
2387 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
2388 << ResultType << BaseExpr->getSourceRange();
2389 return ExprError();
2390 }
Mike Stump1eb44332009-09-09 15:08:12 +00002391
Douglas Gregore7450f52009-03-24 19:52:54 +00002392 if (!ResultType->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00002393 RequireCompleteType(LLoc, ResultType,
Anders Carlssonb7906612009-08-26 23:45:07 +00002394 PDiag(diag::err_subscript_incomplete_type)
2395 << BaseExpr->getSourceRange()))
Douglas Gregore7450f52009-03-24 19:52:54 +00002396 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00002397
Chris Lattner1efaa952009-04-24 00:30:45 +00002398 // Diagnose bad cases where we step over interface counts.
John McCallc12c5bb2010-05-15 11:32:37 +00002399 if (ResultType->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner1efaa952009-04-24 00:30:45 +00002400 Diag(LLoc, diag::err_subscript_nonfragile_interface)
2401 << ResultType << BaseExpr->getSourceRange();
2402 return ExprError();
2403 }
Mike Stump1eb44332009-09-09 15:08:12 +00002404
Mike Stumpeed9cac2009-02-19 03:04:26 +00002405 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
Steve Naroff6ece14c2009-01-21 00:14:39 +00002406 ResultType, RLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00002407}
2408
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002409QualType Sema::
Nate Begeman213541a2008-04-18 23:10:10 +00002410CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00002411 const IdentifierInfo *CompName,
Anders Carlsson8f28f992009-08-26 18:25:21 +00002412 SourceLocation CompLoc) {
Daniel Dunbar2ad32892009-10-18 02:09:38 +00002413 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
2414 // see FIXME there.
2415 //
2416 // FIXME: This logic can be greatly simplified by splitting it along
2417 // halving/not halving and reworking the component checking.
John McCall183700f2009-09-21 23:43:11 +00002418 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
Nate Begeman8a997642008-05-09 06:41:27 +00002419
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002420 // The vector accessor can't exceed the number of elements.
Daniel Dunbare013d682009-10-18 20:26:12 +00002421 const char *compStr = CompName->getNameStart();
Nate Begeman353417a2009-01-18 01:47:54 +00002422
Mike Stumpeed9cac2009-02-19 03:04:26 +00002423 // This flag determines whether or not the component is one of the four
Nate Begeman353417a2009-01-18 01:47:54 +00002424 // special names that indicate a subset of exactly half the elements are
2425 // to be selected.
2426 bool HalvingSwizzle = false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00002427
Nate Begeman353417a2009-01-18 01:47:54 +00002428 // This flag determines whether or not CompName has an 's' char prefix,
2429 // indicating that it is a string of hex values to be used as vector indices.
Nate Begeman131f4652009-06-25 21:06:09 +00002430 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
Nate Begeman8a997642008-05-09 06:41:27 +00002431
2432 // Check that we've found one of the special components, or that the component
2433 // names must come from the same set.
Mike Stumpeed9cac2009-02-19 03:04:26 +00002434 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begeman353417a2009-01-18 01:47:54 +00002435 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
2436 HalvingSwizzle = true;
Nate Begeman8a997642008-05-09 06:41:27 +00002437 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner88dca042007-08-02 22:33:49 +00002438 do
2439 compStr++;
2440 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
Nate Begeman353417a2009-01-18 01:47:54 +00002441 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
Chris Lattner88dca042007-08-02 22:33:49 +00002442 do
2443 compStr++;
Nate Begeman353417a2009-01-18 01:47:54 +00002444 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
Chris Lattner88dca042007-08-02 22:33:49 +00002445 }
Nate Begeman353417a2009-01-18 01:47:54 +00002446
Mike Stumpeed9cac2009-02-19 03:04:26 +00002447 if (!HalvingSwizzle && *compStr) {
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002448 // We didn't get to the end of the string. This means the component names
2449 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002450 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
Benjamin Kramer476d8b82010-08-11 14:47:12 +00002451 << llvm::StringRef(compStr, 1) << SourceRange(CompLoc);
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002452 return QualType();
2453 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00002454
Nate Begeman353417a2009-01-18 01:47:54 +00002455 // Ensure no component accessor exceeds the width of the vector type it
2456 // operates on.
2457 if (!HalvingSwizzle) {
Daniel Dunbare013d682009-10-18 20:26:12 +00002458 compStr = CompName->getNameStart();
Nate Begeman353417a2009-01-18 01:47:54 +00002459
2460 if (HexSwizzle)
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002461 compStr++;
Nate Begeman353417a2009-01-18 01:47:54 +00002462
2463 while (*compStr) {
2464 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
2465 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
2466 << baseType << SourceRange(CompLoc);
2467 return QualType();
2468 }
2469 }
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002470 }
Nate Begeman8a997642008-05-09 06:41:27 +00002471
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002472 // The component accessor looks fine - now we need to compute the actual type.
Mike Stumpeed9cac2009-02-19 03:04:26 +00002473 // The vector type is implied by the component accessor. For example,
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002474 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman353417a2009-01-18 01:47:54 +00002475 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begeman8a997642008-05-09 06:41:27 +00002476 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begeman0479a0b2009-12-15 18:13:04 +00002477 unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2
Anders Carlsson8f28f992009-08-26 18:25:21 +00002478 : CompName->getLength();
Nate Begeman353417a2009-01-18 01:47:54 +00002479 if (HexSwizzle)
2480 CompSize--;
2481
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002482 if (CompSize == 1)
2483 return vecType->getElementType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00002484
Nate Begeman213541a2008-04-18 23:10:10 +00002485 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stumpeed9cac2009-02-19 03:04:26 +00002486 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begeman213541a2008-04-18 23:10:10 +00002487 // diagostics look bad. We want extended vector types to appear built-in.
2488 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
2489 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
2490 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroffbea0b342007-07-29 16:33:31 +00002491 }
2492 return VT; // should never get here (a typedef type should always be found).
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002493}
2494
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002495static Decl *FindGetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
Anders Carlsson8f28f992009-08-26 18:25:21 +00002496 IdentifierInfo *Member,
Douglas Gregor6ab35242009-04-09 21:40:53 +00002497 const Selector &Sel,
2498 ASTContext &Context) {
Mike Stump1eb44332009-09-09 15:08:12 +00002499
Anders Carlsson8f28f992009-08-26 18:25:21 +00002500 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002501 return PD;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002502 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002503 return OMD;
Mike Stump1eb44332009-09-09 15:08:12 +00002504
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002505 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
2506 E = PDecl->protocol_end(); I != E; ++I) {
Mike Stump1eb44332009-09-09 15:08:12 +00002507 if (Decl *D = FindGetterNameDeclFromProtocolList(*I, Member, Sel,
Douglas Gregor6ab35242009-04-09 21:40:53 +00002508 Context))
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002509 return D;
2510 }
2511 return 0;
2512}
2513
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002514static Decl *FindGetterNameDecl(const ObjCObjectPointerType *QIdTy,
Anders Carlsson8f28f992009-08-26 18:25:21 +00002515 IdentifierInfo *Member,
Douglas Gregor6ab35242009-04-09 21:40:53 +00002516 const Selector &Sel,
2517 ASTContext &Context) {
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002518 // Check protocols on qualified interfaces.
2519 Decl *GDecl = 0;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002520 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002521 E = QIdTy->qual_end(); I != E; ++I) {
Anders Carlsson8f28f992009-08-26 18:25:21 +00002522 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002523 GDecl = PD;
2524 break;
2525 }
2526 // Also must look for a getter name which uses property syntax.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002527 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002528 GDecl = OMD;
2529 break;
2530 }
2531 }
2532 if (!GDecl) {
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002533 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002534 E = QIdTy->qual_end(); I != E; ++I) {
2535 // Search in the protocol-qualifier list of current protocol.
Douglas Gregor6ab35242009-04-09 21:40:53 +00002536 GDecl = FindGetterNameDeclFromProtocolList(*I, Member, Sel, Context);
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002537 if (GDecl)
2538 return GDecl;
2539 }
2540 }
2541 return GDecl;
2542}
Chris Lattner76a642f2009-02-15 22:43:40 +00002543
John McCall129e2df2009-11-30 22:42:35 +00002544Sema::OwningExprResult
John McCall9ae2f072010-08-23 23:25:46 +00002545Sema::ActOnDependentMemberExpr(Expr *BaseExpr, QualType BaseType,
John McCallaa81e162009-12-01 22:10:20 +00002546 bool IsArrow, SourceLocation OpLoc,
John McCall129e2df2009-11-30 22:42:35 +00002547 const CXXScopeSpec &SS,
2548 NamedDecl *FirstQualifierInScope,
Abramo Bagnara25777432010-08-11 22:01:17 +00002549 const DeclarationNameInfo &NameInfo,
John McCall129e2df2009-11-30 22:42:35 +00002550 const TemplateArgumentListInfo *TemplateArgs) {
John McCall129e2df2009-11-30 22:42:35 +00002551 // Even in dependent contexts, try to diagnose base expressions with
2552 // obviously wrong types, e.g.:
2553 //
2554 // T* t;
2555 // t.f;
2556 //
2557 // In Obj-C++, however, the above expression is valid, since it could be
2558 // accessing the 'f' property if T is an Obj-C interface. The extra check
2559 // allows this, while still reporting an error if T is a struct pointer.
2560 if (!IsArrow) {
John McCallaa81e162009-12-01 22:10:20 +00002561 const PointerType *PT = BaseType->getAs<PointerType>();
John McCall129e2df2009-11-30 22:42:35 +00002562 if (PT && (!getLangOptions().ObjC1 ||
2563 PT->getPointeeType()->isRecordType())) {
John McCallaa81e162009-12-01 22:10:20 +00002564 assert(BaseExpr && "cannot happen with implicit member accesses");
Abramo Bagnara25777432010-08-11 22:01:17 +00002565 Diag(NameInfo.getLoc(), diag::err_typecheck_member_reference_struct_union)
John McCallaa81e162009-12-01 22:10:20 +00002566 << BaseType << BaseExpr->getSourceRange();
John McCall129e2df2009-11-30 22:42:35 +00002567 return ExprError();
2568 }
2569 }
2570
Abramo Bagnara25777432010-08-11 22:01:17 +00002571 assert(BaseType->isDependentType() ||
2572 NameInfo.getName().isDependentName() ||
Douglas Gregor01e56ae2010-04-12 20:54:26 +00002573 isDependentScopeSpecifier(SS));
John McCall129e2df2009-11-30 22:42:35 +00002574
2575 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
2576 // must have pointer type, and the accessed type is the pointee.
John McCallaa81e162009-12-01 22:10:20 +00002577 return Owned(CXXDependentScopeMemberExpr::Create(Context, BaseExpr, BaseType,
John McCall129e2df2009-11-30 22:42:35 +00002578 IsArrow, OpLoc,
John McCall9ae2f072010-08-23 23:25:46 +00002579 SS.getScopeRep(),
John McCall129e2df2009-11-30 22:42:35 +00002580 SS.getRange(),
2581 FirstQualifierInScope,
Abramo Bagnara25777432010-08-11 22:01:17 +00002582 NameInfo, TemplateArgs));
John McCall129e2df2009-11-30 22:42:35 +00002583}
2584
2585/// We know that the given qualified member reference points only to
2586/// declarations which do not belong to the static type of the base
2587/// expression. Diagnose the problem.
2588static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
2589 Expr *BaseExpr,
2590 QualType BaseType,
John McCall2f841ba2009-12-02 03:53:29 +00002591 const CXXScopeSpec &SS,
John McCall129e2df2009-11-30 22:42:35 +00002592 const LookupResult &R) {
John McCall2f841ba2009-12-02 03:53:29 +00002593 // If this is an implicit member access, use a different set of
2594 // diagnostics.
2595 if (!BaseExpr)
2596 return DiagnoseInstanceReference(SemaRef, SS, R);
John McCall129e2df2009-11-30 22:42:35 +00002597
John McCall110acc12010-04-27 01:43:38 +00002598 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_of_unrelated)
2599 << SS.getRange() << R.getRepresentativeDecl() << BaseType;
John McCall129e2df2009-11-30 22:42:35 +00002600}
2601
2602// Check whether the declarations we found through a nested-name
2603// specifier in a member expression are actually members of the base
2604// type. The restriction here is:
2605//
2606// C++ [expr.ref]p2:
2607// ... In these cases, the id-expression shall name a
2608// member of the class or of one of its base classes.
2609//
2610// So it's perfectly legitimate for the nested-name specifier to name
2611// an unrelated class, and for us to find an overload set including
2612// decls from classes which are not superclasses, as long as the decl
2613// we actually pick through overload resolution is from a superclass.
2614bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
2615 QualType BaseType,
John McCall2f841ba2009-12-02 03:53:29 +00002616 const CXXScopeSpec &SS,
John McCall129e2df2009-11-30 22:42:35 +00002617 const LookupResult &R) {
John McCallaa81e162009-12-01 22:10:20 +00002618 const RecordType *BaseRT = BaseType->getAs<RecordType>();
2619 if (!BaseRT) {
2620 // We can't check this yet because the base type is still
2621 // dependent.
2622 assert(BaseType->isDependentType());
2623 return false;
2624 }
2625 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall129e2df2009-11-30 22:42:35 +00002626
2627 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
John McCallaa81e162009-12-01 22:10:20 +00002628 // If this is an implicit member reference and we find a
2629 // non-instance member, it's not an error.
John McCall161755a2010-04-06 21:38:20 +00002630 if (!BaseExpr && !(*I)->isCXXInstanceMember())
John McCallaa81e162009-12-01 22:10:20 +00002631 return false;
John McCall129e2df2009-11-30 22:42:35 +00002632
John McCallaa81e162009-12-01 22:10:20 +00002633 // Note that we use the DC of the decl, not the underlying decl.
Eli Friedman02463762010-07-27 20:51:02 +00002634 DeclContext *DC = (*I)->getDeclContext();
2635 while (DC->isTransparentContext())
2636 DC = DC->getParent();
John McCallaa81e162009-12-01 22:10:20 +00002637
Douglas Gregor9d4bb942010-07-28 22:27:52 +00002638 if (!DC->isRecord())
2639 continue;
2640
John McCallaa81e162009-12-01 22:10:20 +00002641 llvm::SmallPtrSet<CXXRecordDecl*,4> MemberRecord;
Eli Friedman02463762010-07-27 20:51:02 +00002642 MemberRecord.insert(cast<CXXRecordDecl>(DC)->getCanonicalDecl());
John McCallaa81e162009-12-01 22:10:20 +00002643
2644 if (!IsProvablyNotDerivedFrom(*this, BaseRecord, MemberRecord))
2645 return false;
2646 }
2647
John McCall2f841ba2009-12-02 03:53:29 +00002648 DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS, R);
John McCallaa81e162009-12-01 22:10:20 +00002649 return true;
2650}
2651
2652static bool
2653LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
2654 SourceRange BaseRange, const RecordType *RTy,
John McCallad00b772010-06-16 08:42:20 +00002655 SourceLocation OpLoc, CXXScopeSpec &SS,
2656 bool HasTemplateArgs) {
John McCallaa81e162009-12-01 22:10:20 +00002657 RecordDecl *RDecl = RTy->getDecl();
2658 if (SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002659 SemaRef.PDiag(diag::err_typecheck_incomplete_tag)
John McCallaa81e162009-12-01 22:10:20 +00002660 << BaseRange))
2661 return true;
2662
John McCallad00b772010-06-16 08:42:20 +00002663 if (HasTemplateArgs) {
2664 // LookupTemplateName doesn't expect these both to exist simultaneously.
2665 QualType ObjectType = SS.isSet() ? QualType() : QualType(RTy, 0);
2666
2667 bool MOUS;
2668 SemaRef.LookupTemplateName(R, 0, SS, ObjectType, false, MOUS);
2669 return false;
2670 }
2671
John McCallaa81e162009-12-01 22:10:20 +00002672 DeclContext *DC = RDecl;
2673 if (SS.isSet()) {
2674 // If the member name was a qualified-id, look into the
2675 // nested-name-specifier.
2676 DC = SemaRef.computeDeclContext(SS, false);
2677
John McCall77bb1aa2010-05-01 00:40:08 +00002678 if (SemaRef.RequireCompleteDeclContext(SS, DC)) {
John McCall2f841ba2009-12-02 03:53:29 +00002679 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
2680 << SS.getRange() << DC;
2681 return true;
2682 }
2683
John McCallaa81e162009-12-01 22:10:20 +00002684 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002685
John McCallaa81e162009-12-01 22:10:20 +00002686 if (!isa<TypeDecl>(DC)) {
2687 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
2688 << DC << SS.getRange();
2689 return true;
John McCall129e2df2009-11-30 22:42:35 +00002690 }
2691 }
2692
John McCallaa81e162009-12-01 22:10:20 +00002693 // The record definition is complete, now look up the member.
2694 SemaRef.LookupQualifiedName(R, DC);
John McCall129e2df2009-11-30 22:42:35 +00002695
Douglas Gregor2dcc0112009-12-31 07:42:17 +00002696 if (!R.empty())
2697 return false;
2698
2699 // We didn't find anything with the given name, so try to correct
2700 // for typos.
2701 DeclarationName Name = R.getLookupName();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00002702 if (SemaRef.CorrectTypo(R, 0, &SS, DC, false, Sema::CTC_MemberLookup) &&
Douglas Gregoraaf87162010-04-14 20:04:41 +00002703 !R.empty() &&
Douglas Gregor2dcc0112009-12-31 07:42:17 +00002704 (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin()))) {
2705 SemaRef.Diag(R.getNameLoc(), diag::err_no_member_suggest)
2706 << Name << DC << R.getLookupName() << SS.getRange()
Douglas Gregor849b2432010-03-31 17:46:05 +00002707 << FixItHint::CreateReplacement(R.getNameLoc(),
2708 R.getLookupName().getAsString());
Douglas Gregor67dd1d42010-01-07 00:17:44 +00002709 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
2710 SemaRef.Diag(ND->getLocation(), diag::note_previous_decl)
2711 << ND->getDeclName();
Douglas Gregor2dcc0112009-12-31 07:42:17 +00002712 return false;
2713 } else {
2714 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00002715 R.setLookupName(Name);
Douglas Gregor2dcc0112009-12-31 07:42:17 +00002716 }
2717
John McCall129e2df2009-11-30 22:42:35 +00002718 return false;
2719}
2720
2721Sema::OwningExprResult
John McCall9ae2f072010-08-23 23:25:46 +00002722Sema::BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
John McCall129e2df2009-11-30 22:42:35 +00002723 SourceLocation OpLoc, bool IsArrow,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00002724 CXXScopeSpec &SS,
John McCall129e2df2009-11-30 22:42:35 +00002725 NamedDecl *FirstQualifierInScope,
Abramo Bagnara25777432010-08-11 22:01:17 +00002726 const DeclarationNameInfo &NameInfo,
John McCall129e2df2009-11-30 22:42:35 +00002727 const TemplateArgumentListInfo *TemplateArgs) {
John McCall2f841ba2009-12-02 03:53:29 +00002728 if (BaseType->isDependentType() ||
2729 (SS.isSet() && isDependentScopeSpecifier(SS)))
John McCall9ae2f072010-08-23 23:25:46 +00002730 return ActOnDependentMemberExpr(Base, BaseType,
John McCall129e2df2009-11-30 22:42:35 +00002731 IsArrow, OpLoc,
2732 SS, FirstQualifierInScope,
Abramo Bagnara25777432010-08-11 22:01:17 +00002733 NameInfo, TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00002734
Abramo Bagnara25777432010-08-11 22:01:17 +00002735 LookupResult R(*this, NameInfo, LookupMemberName);
John McCall129e2df2009-11-30 22:42:35 +00002736
John McCallaa81e162009-12-01 22:10:20 +00002737 // Implicit member accesses.
2738 if (!Base) {
2739 QualType RecordTy = BaseType;
2740 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
2741 if (LookupMemberExprInRecord(*this, R, SourceRange(),
2742 RecordTy->getAs<RecordType>(),
John McCallad00b772010-06-16 08:42:20 +00002743 OpLoc, SS, TemplateArgs != 0))
John McCallaa81e162009-12-01 22:10:20 +00002744 return ExprError();
2745
2746 // Explicit member accesses.
2747 } else {
2748 OwningExprResult Result =
2749 LookupMemberExpr(R, Base, IsArrow, OpLoc,
John McCalld226f652010-08-21 09:40:31 +00002750 SS, /*ObjCImpDecl*/ 0, TemplateArgs != 0);
John McCallaa81e162009-12-01 22:10:20 +00002751
2752 if (Result.isInvalid()) {
2753 Owned(Base);
2754 return ExprError();
2755 }
2756
2757 if (Result.get())
2758 return move(Result);
Sebastian Redlf3e63372010-05-07 09:25:11 +00002759
2760 // LookupMemberExpr can modify Base, and thus change BaseType
2761 BaseType = Base->getType();
John McCall129e2df2009-11-30 22:42:35 +00002762 }
2763
John McCall9ae2f072010-08-23 23:25:46 +00002764 return BuildMemberReferenceExpr(Base, BaseType,
John McCallc2233c52010-01-15 08:34:02 +00002765 OpLoc, IsArrow, SS, FirstQualifierInScope,
2766 R, TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00002767}
2768
2769Sema::OwningExprResult
John McCall9ae2f072010-08-23 23:25:46 +00002770Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType BaseExprType,
John McCallaa81e162009-12-01 22:10:20 +00002771 SourceLocation OpLoc, bool IsArrow,
2772 const CXXScopeSpec &SS,
John McCallc2233c52010-01-15 08:34:02 +00002773 NamedDecl *FirstQualifierInScope,
John McCall129e2df2009-11-30 22:42:35 +00002774 LookupResult &R,
Douglas Gregor06a9f362010-05-01 20:49:11 +00002775 const TemplateArgumentListInfo *TemplateArgs,
2776 bool SuppressQualifierCheck) {
John McCallaa81e162009-12-01 22:10:20 +00002777 QualType BaseType = BaseExprType;
John McCall129e2df2009-11-30 22:42:35 +00002778 if (IsArrow) {
2779 assert(BaseType->isPointerType());
2780 BaseType = BaseType->getAs<PointerType>()->getPointeeType();
2781 }
John McCall161755a2010-04-06 21:38:20 +00002782 R.setBaseObjectType(BaseType);
John McCall129e2df2009-11-30 22:42:35 +00002783
John McCall9ae2f072010-08-23 23:25:46 +00002784 NestedNameSpecifier *Qualifier = SS.getScopeRep();
Abramo Bagnara25777432010-08-11 22:01:17 +00002785 const DeclarationNameInfo &MemberNameInfo = R.getLookupNameInfo();
2786 DeclarationName MemberName = MemberNameInfo.getName();
2787 SourceLocation MemberLoc = MemberNameInfo.getLoc();
John McCall129e2df2009-11-30 22:42:35 +00002788
2789 if (R.isAmbiguous())
Douglas Gregorfe85ced2009-08-06 03:17:00 +00002790 return ExprError();
2791
John McCall129e2df2009-11-30 22:42:35 +00002792 if (R.empty()) {
2793 // Rederive where we looked up.
2794 DeclContext *DC = (SS.isSet()
2795 ? computeDeclContext(SS, false)
2796 : BaseType->getAs<RecordType>()->getDecl());
Nate Begeman2ef13e52009-08-10 23:49:36 +00002797
John McCall129e2df2009-11-30 22:42:35 +00002798 Diag(R.getNameLoc(), diag::err_no_member)
John McCallaa81e162009-12-01 22:10:20 +00002799 << MemberName << DC
2800 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
John McCall129e2df2009-11-30 22:42:35 +00002801 return ExprError();
2802 }
2803
John McCallc2233c52010-01-15 08:34:02 +00002804 // Diagnose lookups that find only declarations from a non-base
2805 // type. This is possible for either qualified lookups (which may
2806 // have been qualified with an unrelated type) or implicit member
2807 // expressions (which were found with unqualified lookup and thus
2808 // may have come from an enclosing scope). Note that it's okay for
2809 // lookup to find declarations from a non-base type as long as those
2810 // aren't the ones picked by overload resolution.
2811 if ((SS.isSet() || !BaseExpr ||
2812 (isa<CXXThisExpr>(BaseExpr) &&
2813 cast<CXXThisExpr>(BaseExpr)->isImplicit())) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00002814 !SuppressQualifierCheck &&
John McCallc2233c52010-01-15 08:34:02 +00002815 CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
John McCall129e2df2009-11-30 22:42:35 +00002816 return ExprError();
2817
2818 // Construct an unresolved result if we in fact got an unresolved
2819 // result.
2820 if (R.isOverloadedResult() || R.isUnresolvableResult()) {
John McCallaa81e162009-12-01 22:10:20 +00002821 bool Dependent =
John McCall410a3f32009-12-19 02:05:44 +00002822 BaseExprType->isDependentType() ||
John McCallaa81e162009-12-01 22:10:20 +00002823 R.isUnresolvableResult() ||
John McCall7bb12da2010-02-02 06:20:04 +00002824 OverloadExpr::ComputeDependence(R.begin(), R.end(), TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00002825
John McCallc373d482010-01-27 01:50:18 +00002826 // Suppress any lookup-related diagnostics; we'll do these when we
2827 // pick a member.
2828 R.suppressDiagnostics();
2829
John McCall129e2df2009-11-30 22:42:35 +00002830 UnresolvedMemberExpr *MemExpr
2831 = UnresolvedMemberExpr::Create(Context, Dependent,
2832 R.isUnresolvableResult(),
John McCallaa81e162009-12-01 22:10:20 +00002833 BaseExpr, BaseExprType,
2834 IsArrow, OpLoc,
John McCall129e2df2009-11-30 22:42:35 +00002835 Qualifier, SS.getRange(),
Abramo Bagnara25777432010-08-11 22:01:17 +00002836 MemberNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +00002837 TemplateArgs, R.begin(), R.end());
John McCall129e2df2009-11-30 22:42:35 +00002838
2839 return Owned(MemExpr);
2840 }
2841
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002842 assert(R.isSingleResult());
John McCall161755a2010-04-06 21:38:20 +00002843 DeclAccessPair FoundDecl = R.begin().getPair();
John McCall129e2df2009-11-30 22:42:35 +00002844 NamedDecl *MemberDecl = R.getFoundDecl();
2845
2846 // FIXME: diagnose the presence of template arguments now.
2847
2848 // If the decl being referenced had an error, return an error for this
2849 // sub-expr without emitting another error, in order to avoid cascading
2850 // error cases.
2851 if (MemberDecl->isInvalidDecl())
2852 return ExprError();
2853
John McCallaa81e162009-12-01 22:10:20 +00002854 // Handle the implicit-member-access case.
2855 if (!BaseExpr) {
2856 // If this is not an instance member, convert to a non-member access.
John McCall161755a2010-04-06 21:38:20 +00002857 if (!MemberDecl->isCXXInstanceMember())
Abramo Bagnara25777432010-08-11 22:01:17 +00002858 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), MemberDecl);
John McCallaa81e162009-12-01 22:10:20 +00002859
Douglas Gregor828a1972010-01-07 23:12:05 +00002860 SourceLocation Loc = R.getNameLoc();
2861 if (SS.getRange().isValid())
2862 Loc = SS.getRange().getBegin();
2863 BaseExpr = new (Context) CXXThisExpr(Loc, BaseExprType,/*isImplicit=*/true);
John McCallaa81e162009-12-01 22:10:20 +00002864 }
2865
John McCall129e2df2009-11-30 22:42:35 +00002866 bool ShouldCheckUse = true;
2867 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
2868 // Don't diagnose the use of a virtual member function unless it's
2869 // explicitly qualified.
2870 if (MD->isVirtual() && !SS.isSet())
2871 ShouldCheckUse = false;
2872 }
2873
2874 // Check the use of this member.
2875 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc)) {
2876 Owned(BaseExpr);
2877 return ExprError();
2878 }
2879
2880 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
2881 // We may have found a field within an anonymous union or struct
2882 // (C++ [class.union]).
Eli Friedman16c53782009-12-04 07:18:51 +00002883 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion() &&
2884 !BaseType->getAs<RecordType>()->getDecl()->isAnonymousStructOrUnion())
John McCall129e2df2009-11-30 22:42:35 +00002885 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
2886 BaseExpr, OpLoc);
2887
2888 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
2889 QualType MemberType = FD->getType();
2890 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>())
2891 MemberType = Ref->getPointeeType();
2892 else {
2893 Qualifiers BaseQuals = BaseType.getQualifiers();
2894 BaseQuals.removeObjCGCAttr();
2895 if (FD->isMutable()) BaseQuals.removeConst();
2896
2897 Qualifiers MemberQuals
2898 = Context.getCanonicalType(MemberType).getQualifiers();
2899
2900 Qualifiers Combined = BaseQuals + MemberQuals;
2901 if (Combined != MemberQuals)
2902 MemberType = Context.getQualifiedType(MemberType, Combined);
2903 }
2904
2905 MarkDeclarationReferenced(MemberLoc, FD);
John McCall6bb80172010-03-30 21:47:33 +00002906 if (PerformObjectMemberConversion(BaseExpr, Qualifier, FoundDecl, FD))
John McCall129e2df2009-11-30 22:42:35 +00002907 return ExprError();
2908 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00002909 FD, FoundDecl, MemberNameInfo,
2910 MemberType));
John McCall129e2df2009-11-30 22:42:35 +00002911 }
2912
2913 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
2914 MarkDeclarationReferenced(MemberLoc, Var);
2915 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00002916 Var, FoundDecl, MemberNameInfo,
John McCall129e2df2009-11-30 22:42:35 +00002917 Var->getType().getNonReferenceType()));
2918 }
2919
2920 if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl)) {
2921 MarkDeclarationReferenced(MemberLoc, MemberDecl);
2922 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00002923 MemberFn, FoundDecl, MemberNameInfo,
John McCall129e2df2009-11-30 22:42:35 +00002924 MemberFn->getType()));
2925 }
2926
2927 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
2928 MarkDeclarationReferenced(MemberLoc, MemberDecl);
2929 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00002930 Enum, FoundDecl, MemberNameInfo,
2931 Enum->getType()));
John McCall129e2df2009-11-30 22:42:35 +00002932 }
2933
2934 Owned(BaseExpr);
2935
Douglas Gregorb0fd4832010-04-25 20:55:08 +00002936 // We found something that we didn't expect. Complain.
John McCall129e2df2009-11-30 22:42:35 +00002937 if (isa<TypeDecl>(MemberDecl))
Abramo Bagnara25777432010-08-11 22:01:17 +00002938 Diag(MemberLoc, diag::err_typecheck_member_reference_type)
Douglas Gregorb0fd4832010-04-25 20:55:08 +00002939 << MemberName << BaseType << int(IsArrow);
2940 else
2941 Diag(MemberLoc, diag::err_typecheck_member_reference_unknown)
2942 << MemberName << BaseType << int(IsArrow);
John McCall129e2df2009-11-30 22:42:35 +00002943
Douglas Gregorb0fd4832010-04-25 20:55:08 +00002944 Diag(MemberDecl->getLocation(), diag::note_member_declared_here)
2945 << MemberName;
Douglas Gregor2b147f02010-04-25 21:15:30 +00002946 R.suppressDiagnostics();
Douglas Gregorb0fd4832010-04-25 20:55:08 +00002947 return ExprError();
John McCall129e2df2009-11-30 22:42:35 +00002948}
2949
2950/// Look up the given member of the given non-type-dependent
2951/// expression. This can return in one of two ways:
2952/// * If it returns a sentinel null-but-valid result, the caller will
2953/// assume that lookup was performed and the results written into
2954/// the provided structure. It will take over from there.
2955/// * Otherwise, the returned expression will be produced in place of
2956/// an ordinary member expression.
2957///
2958/// The ObjCImpDecl bit is a gross hack that will need to be properly
2959/// fixed for ObjC++.
2960Sema::OwningExprResult
2961Sema::LookupMemberExpr(LookupResult &R, Expr *&BaseExpr,
John McCall812c1542009-12-07 22:46:59 +00002962 bool &IsArrow, SourceLocation OpLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00002963 CXXScopeSpec &SS,
John McCalld226f652010-08-21 09:40:31 +00002964 Decl *ObjCImpDecl, bool HasTemplateArgs) {
Douglas Gregora71d8192009-09-04 17:36:40 +00002965 assert(BaseExpr && "no base expression");
Mike Stump1eb44332009-09-09 15:08:12 +00002966
Steve Naroff3cc4af82007-12-16 21:42:28 +00002967 // Perform default conversions.
2968 DefaultFunctionArrayConversion(BaseExpr);
Sebastian Redl0eb23302009-01-19 00:08:26 +00002969
Steve Naroffdfa6aae2007-07-26 03:11:44 +00002970 QualType BaseType = BaseExpr->getType();
John McCall129e2df2009-11-30 22:42:35 +00002971 assert(!BaseType->isDependentType());
2972
2973 DeclarationName MemberName = R.getLookupName();
2974 SourceLocation MemberLoc = R.getNameLoc();
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00002975
2976 // If the user is trying to apply -> or . to a function pointer
John McCall129e2df2009-11-30 22:42:35 +00002977 // type, it's probably because they forgot parentheses to call that
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00002978 // function. Suggest the addition of those parentheses, build the
2979 // call, and continue on.
2980 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
2981 if (const FunctionProtoType *Fun
2982 = Ptr->getPointeeType()->getAs<FunctionProtoType>()) {
2983 QualType ResultTy = Fun->getResultType();
2984 if (Fun->getNumArgs() == 0 &&
John McCall129e2df2009-11-30 22:42:35 +00002985 ((!IsArrow && ResultTy->isRecordType()) ||
2986 (IsArrow && ResultTy->isPointerType() &&
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00002987 ResultTy->getAs<PointerType>()->getPointeeType()
2988 ->isRecordType()))) {
2989 SourceLocation Loc = PP.getLocForEndOfToken(BaseExpr->getLocEnd());
2990 Diag(Loc, diag::err_member_reference_needs_call)
2991 << QualType(Fun, 0)
Douglas Gregor849b2432010-03-31 17:46:05 +00002992 << FixItHint::CreateInsertion(Loc, "()");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002993
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00002994 OwningExprResult NewBase
John McCall9ae2f072010-08-23 23:25:46 +00002995 = ActOnCallExpr(0, BaseExpr, Loc,
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00002996 MultiExprArg(*this, 0, 0), 0, Loc);
Douglas Gregorf918b832010-06-21 22:46:46 +00002997 BaseExpr = 0;
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00002998 if (NewBase.isInvalid())
John McCall129e2df2009-11-30 22:42:35 +00002999 return ExprError();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003000
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00003001 BaseExpr = NewBase.takeAs<Expr>();
3002 DefaultFunctionArrayConversion(BaseExpr);
3003 BaseType = BaseExpr->getType();
3004 }
3005 }
3006 }
3007
David Chisnall0f436562009-08-17 16:35:33 +00003008 // If this is an Objective-C pseudo-builtin and a definition is provided then
3009 // use that.
3010 if (BaseType->isObjCIdType()) {
Fariborz Jahanian6d910f02009-12-07 20:09:25 +00003011 if (IsArrow) {
3012 // Handle the following exceptional case PObj->isa.
3013 if (const ObjCObjectPointerType *OPT =
3014 BaseType->getAs<ObjCObjectPointerType>()) {
John McCallc12c5bb2010-05-15 11:32:37 +00003015 if (OPT->getObjectType()->isObjCId() &&
Fariborz Jahanian6d910f02009-12-07 20:09:25 +00003016 MemberName.getAsIdentifierInfo()->isStr("isa"))
Fariborz Jahanian83dc3252009-12-09 19:05:56 +00003017 return Owned(new (Context) ObjCIsaExpr(BaseExpr, true, MemberLoc,
3018 Context.getObjCClassType()));
Fariborz Jahanian6d910f02009-12-07 20:09:25 +00003019 }
3020 }
David Chisnall0f436562009-08-17 16:35:33 +00003021 // We have an 'id' type. Rather than fall through, we check if this
3022 // is a reference to 'isa'.
3023 if (BaseType != Context.ObjCIdRedefinitionType) {
3024 BaseType = Context.ObjCIdRedefinitionType;
Eli Friedman73c39ab2009-10-20 08:27:19 +00003025 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
David Chisnall0f436562009-08-17 16:35:33 +00003026 }
David Chisnall0f436562009-08-17 16:35:33 +00003027 }
John McCall129e2df2009-11-30 22:42:35 +00003028
Fariborz Jahanian369a3bd2009-11-25 23:07:42 +00003029 // If this is an Objective-C pseudo-builtin and a definition is provided then
3030 // use that.
3031 if (Context.isObjCSelType(BaseType)) {
3032 // We have an 'SEL' type. Rather than fall through, we check if this
3033 // is a reference to 'sel_id'.
3034 if (BaseType != Context.ObjCSelRedefinitionType) {
3035 BaseType = Context.ObjCSelRedefinitionType;
3036 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
3037 }
3038 }
John McCall129e2df2009-11-30 22:42:35 +00003039
Steve Naroffdfa6aae2007-07-26 03:11:44 +00003040 assert(!BaseType.isNull() && "no type for member expression");
Sebastian Redl0eb23302009-01-19 00:08:26 +00003041
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003042 // Handle properties on ObjC 'Class' types.
John McCall129e2df2009-11-30 22:42:35 +00003043 if (!IsArrow && BaseType->isObjCClassType()) {
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003044 // Also must look for a getter name which uses property syntax.
3045 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
3046 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
3047 if (ObjCMethodDecl *MD = getCurMethodDecl()) {
3048 ObjCInterfaceDecl *IFace = MD->getClassInterface();
3049 ObjCMethodDecl *Getter;
3050 // FIXME: need to also look locally in the implementation.
3051 if ((Getter = IFace->lookupClassMethod(Sel))) {
3052 // Check the use of this method.
3053 if (DiagnoseUseOfDecl(Getter, MemberLoc))
3054 return ExprError();
3055 }
3056 // If we found a getter then this may be a valid dot-reference, we
3057 // will look for the matching setter, in case it is needed.
3058 Selector SetterSel =
3059 SelectorTable::constructSetterName(PP.getIdentifierTable(),
3060 PP.getSelectorTable(), Member);
3061 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
3062 if (!Setter) {
3063 // If this reference is in an @implementation, also check for 'private'
3064 // methods.
Steve Naroffd789d3d2009-10-01 23:46:04 +00003065 Setter = IFace->lookupPrivateInstanceMethod(SetterSel);
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003066 }
3067 // Look through local category implementations associated with the class.
3068 if (!Setter)
3069 Setter = IFace->getCategoryClassMethod(SetterSel);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003070
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003071 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
3072 return ExprError();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003073
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003074 if (Getter || Setter) {
3075 QualType PType;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003076
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003077 if (Getter)
Douglas Gregor5291c3c2010-07-13 08:18:22 +00003078 PType = Getter->getSendResultType();
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003079 else
3080 // Get the expression type from Setter's incoming parameter.
3081 PType = (*(Setter->param_end() -1))->getType();
3082 // FIXME: we must check that the setter has property type.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003083 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter,
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003084 PType,
3085 Setter, MemberLoc, BaseExpr));
3086 }
3087 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
3088 << MemberName << BaseType);
3089 }
3090 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003091
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003092 if (BaseType->isObjCClassType() &&
3093 BaseType != Context.ObjCClassRedefinitionType) {
3094 BaseType = Context.ObjCClassRedefinitionType;
Eli Friedman73c39ab2009-10-20 08:27:19 +00003095 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003096 }
Mike Stump1eb44332009-09-09 15:08:12 +00003097
John McCall129e2df2009-11-30 22:42:35 +00003098 if (IsArrow) {
3099 if (const PointerType *PT = BaseType->getAs<PointerType>())
Steve Naroffdfa6aae2007-07-26 03:11:44 +00003100 BaseType = PT->getPointeeType();
Steve Naroff14108da2009-07-10 23:34:53 +00003101 else if (BaseType->isObjCObjectPointerType())
3102 ;
John McCall812c1542009-12-07 22:46:59 +00003103 else if (BaseType->isRecordType()) {
3104 // Recover from arrow accesses to records, e.g.:
3105 // struct MyRecord foo;
3106 // foo->bar
3107 // This is actually well-formed in C++ if MyRecord has an
3108 // overloaded operator->, but that should have been dealt with
3109 // by now.
3110 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
3111 << BaseType << int(IsArrow) << BaseExpr->getSourceRange()
Douglas Gregor849b2432010-03-31 17:46:05 +00003112 << FixItHint::CreateReplacement(OpLoc, ".");
John McCall812c1542009-12-07 22:46:59 +00003113 IsArrow = false;
3114 } else {
John McCall129e2df2009-11-30 22:42:35 +00003115 Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
3116 << BaseType << BaseExpr->getSourceRange();
3117 return ExprError();
Anders Carlsson4ef27702009-05-16 20:31:20 +00003118 }
John McCall812c1542009-12-07 22:46:59 +00003119 } else {
3120 // Recover from dot accesses to pointers, e.g.:
3121 // type *foo;
3122 // foo.bar
3123 // This is actually well-formed in two cases:
3124 // - 'type' is an Objective C type
3125 // - 'bar' is a pseudo-destructor name which happens to refer to
3126 // the appropriate pointer type
3127 if (MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
3128 const PointerType *PT = BaseType->getAs<PointerType>();
3129 if (PT && PT->getPointeeType()->isRecordType()) {
3130 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
3131 << BaseType << int(IsArrow) << BaseExpr->getSourceRange()
Douglas Gregor849b2432010-03-31 17:46:05 +00003132 << FixItHint::CreateReplacement(OpLoc, "->");
John McCall812c1542009-12-07 22:46:59 +00003133 BaseType = PT->getPointeeType();
3134 IsArrow = true;
3135 }
3136 }
John McCall129e2df2009-11-30 22:42:35 +00003137 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003138
John McCallc12c5bb2010-05-15 11:32:37 +00003139 // Handle field access to simple records.
Ted Kremenek6217b802009-07-29 21:53:49 +00003140 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
John McCallaa81e162009-12-01 22:10:20 +00003141 if (LookupMemberExprInRecord(*this, R, BaseExpr->getSourceRange(),
John McCallad00b772010-06-16 08:42:20 +00003142 RTy, OpLoc, SS, HasTemplateArgs))
Douglas Gregor4ec339f2009-01-19 19:26:10 +00003143 return ExprError();
John McCall129e2df2009-11-30 22:42:35 +00003144 return Owned((Expr*) 0);
Chris Lattnerfb173ec2008-07-21 04:28:12 +00003145 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00003146
Chris Lattnera38e6b12008-07-21 04:59:05 +00003147 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
3148 // (*Obj).ivar.
John McCall129e2df2009-11-30 22:42:35 +00003149 if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
John McCallc12c5bb2010-05-15 11:32:37 +00003150 (!IsArrow && BaseType->isObjCObjectType())) {
John McCall183700f2009-09-21 23:43:11 +00003151 const ObjCObjectPointerType *OPT = BaseType->getAs<ObjCObjectPointerType>();
John McCallc12c5bb2010-05-15 11:32:37 +00003152 ObjCInterfaceDecl *IDecl =
3153 OPT ? OPT->getInterfaceDecl()
3154 : BaseType->getAs<ObjCObjectType>()->getInterface();
3155 if (IDecl) {
Anders Carlsson8f28f992009-08-26 18:25:21 +00003156 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
3157
Steve Naroffc70e8d92009-07-16 00:25:06 +00003158 ObjCInterfaceDecl *ClassDeclared;
Anders Carlsson8f28f992009-08-26 18:25:21 +00003159 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
Mike Stump1eb44332009-09-09 15:08:12 +00003160
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003161 if (!IV) {
3162 // Attempt to correct for typos in ivar names.
3163 LookupResult Res(*this, R.getLookupName(), R.getNameLoc(),
3164 LookupMemberName);
Douglas Gregoraaf87162010-04-14 20:04:41 +00003165 if (CorrectTypo(Res, 0, 0, IDecl, false, CTC_MemberLookup) &&
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003166 (IV = Res.getAsSingle<ObjCIvarDecl>())) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003167 Diag(R.getNameLoc(),
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003168 diag::err_typecheck_member_reference_ivar_suggest)
3169 << IDecl->getDeclName() << MemberName << IV->getDeclName()
Douglas Gregor849b2432010-03-31 17:46:05 +00003170 << FixItHint::CreateReplacement(R.getNameLoc(),
3171 IV->getNameAsString());
Douglas Gregor67dd1d42010-01-07 00:17:44 +00003172 Diag(IV->getLocation(), diag::note_previous_decl)
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003173 << IV->getDeclName();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00003174 } else {
3175 Res.clear();
3176 Res.setLookupName(Member);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003177 }
3178 }
3179
Steve Naroffc70e8d92009-07-16 00:25:06 +00003180 if (IV) {
3181 // If the decl being referenced had an error, return an error for this
3182 // sub-expr without emitting another error, in order to avoid cascading
3183 // error cases.
3184 if (IV->isInvalidDecl())
3185 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003186
Steve Naroffc70e8d92009-07-16 00:25:06 +00003187 // Check whether we can reference this field.
3188 if (DiagnoseUseOfDecl(IV, MemberLoc))
3189 return ExprError();
3190 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
3191 IV->getAccessControl() != ObjCIvarDecl::Package) {
3192 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
3193 if (ObjCMethodDecl *MD = getCurMethodDecl())
3194 ClassOfMethodDecl = MD->getClassInterface();
3195 else if (ObjCImpDecl && getCurFunctionDecl()) {
3196 // Case of a c-function declared inside an objc implementation.
3197 // FIXME: For a c-style function nested inside an objc implementation
3198 // class, there is no implementation context available, so we pass
3199 // down the context as argument to this routine. Ideally, this context
3200 // need be passed down in the AST node and somehow calculated from the
3201 // AST for a function decl.
Mike Stump1eb44332009-09-09 15:08:12 +00003202 if (ObjCImplementationDecl *IMPD =
John McCalld226f652010-08-21 09:40:31 +00003203 dyn_cast<ObjCImplementationDecl>(ObjCImpDecl))
Steve Naroffc70e8d92009-07-16 00:25:06 +00003204 ClassOfMethodDecl = IMPD->getClassInterface();
3205 else if (ObjCCategoryImplDecl* CatImplClass =
John McCalld226f652010-08-21 09:40:31 +00003206 dyn_cast<ObjCCategoryImplDecl>(ObjCImpDecl))
Steve Naroffc70e8d92009-07-16 00:25:06 +00003207 ClassOfMethodDecl = CatImplClass->getClassInterface();
3208 }
Mike Stump1eb44332009-09-09 15:08:12 +00003209
3210 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
3211 if (ClassDeclared != IDecl ||
Steve Naroffc70e8d92009-07-16 00:25:06 +00003212 ClassOfMethodDecl != ClassDeclared)
Mike Stump1eb44332009-09-09 15:08:12 +00003213 Diag(MemberLoc, diag::error_private_ivar_access)
Steve Naroffc70e8d92009-07-16 00:25:06 +00003214 << IV->getDeclName();
Mike Stumpac5fc7c2009-08-04 21:02:39 +00003215 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
3216 // @protected
Mike Stump1eb44332009-09-09 15:08:12 +00003217 Diag(MemberLoc, diag::error_protected_ivar_access)
Steve Naroffc70e8d92009-07-16 00:25:06 +00003218 << IV->getDeclName();
Steve Naroffb06d8752009-03-04 18:34:24 +00003219 }
Steve Naroffc70e8d92009-07-16 00:25:06 +00003220
3221 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
3222 MemberLoc, BaseExpr,
John McCall129e2df2009-11-30 22:42:35 +00003223 IsArrow));
Fariborz Jahanian935fd762009-03-03 01:21:12 +00003224 }
Steve Naroffc70e8d92009-07-16 00:25:06 +00003225 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
Anders Carlsson8f28f992009-08-26 18:25:21 +00003226 << IDecl->getDeclName() << MemberName
Steve Naroffc70e8d92009-07-16 00:25:06 +00003227 << BaseExpr->getSourceRange());
Fariborz Jahanianaaa63a72008-12-13 22:20:28 +00003228 }
Chris Lattnerfb173ec2008-07-21 04:28:12 +00003229 }
Steve Naroffde2e22d2009-07-15 18:40:39 +00003230 // Handle properties on 'id' and qualified "id".
John McCall129e2df2009-11-30 22:42:35 +00003231 if (!IsArrow && (BaseType->isObjCIdType() ||
3232 BaseType->isObjCQualifiedIdType())) {
John McCall183700f2009-09-21 23:43:11 +00003233 const ObjCObjectPointerType *QIdTy = BaseType->getAs<ObjCObjectPointerType>();
Anders Carlsson8f28f992009-08-26 18:25:21 +00003234 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Mike Stump1eb44332009-09-09 15:08:12 +00003235
Steve Naroff14108da2009-07-10 23:34:53 +00003236 // Check protocols on qualified interfaces.
Anders Carlsson8f28f992009-08-26 18:25:21 +00003237 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Steve Naroff14108da2009-07-10 23:34:53 +00003238 if (Decl *PMDecl = FindGetterNameDecl(QIdTy, Member, Sel, Context)) {
3239 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
3240 // Check the use of this declaration
3241 if (DiagnoseUseOfDecl(PD, MemberLoc))
3242 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003243
Steve Naroff14108da2009-07-10 23:34:53 +00003244 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
3245 MemberLoc, BaseExpr));
3246 }
3247 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
3248 // Check the use of this method.
3249 if (DiagnoseUseOfDecl(OMD, MemberLoc))
3250 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003251
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00003252 return Owned(ObjCMessageExpr::Create(Context,
Douglas Gregor5291c3c2010-07-13 08:18:22 +00003253 OMD->getSendResultType(),
Douglas Gregor04badcf2010-04-21 00:45:42 +00003254 OpLoc, BaseExpr, Sel,
3255 OMD, NULL, 0, MemberLoc));
Steve Naroff14108da2009-07-10 23:34:53 +00003256 }
3257 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00003258
Steve Naroff14108da2009-07-10 23:34:53 +00003259 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlsson8f28f992009-08-26 18:25:21 +00003260 << MemberName << BaseType);
Steve Naroff14108da2009-07-10 23:34:53 +00003261 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00003262
Chris Lattnera38e6b12008-07-21 04:59:05 +00003263 // Handle Objective-C property access, which is "Obj.property" where Obj is a
3264 // pointer to a (potentially qualified) interface type.
Chris Lattner7f816522010-04-11 07:45:24 +00003265 if (!IsArrow)
3266 if (const ObjCObjectPointerType *OPT =
3267 BaseType->getAsObjCInterfacePointerType())
Chris Lattnerb9d4fc12010-04-11 07:51:10 +00003268 return HandleExprPropertyRefExpr(OPT, BaseExpr, MemberName, MemberLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00003269
Steve Narofff242b1b2009-07-24 17:54:45 +00003270 // Handle the following exceptional case (*Obj).isa.
John McCall129e2df2009-11-30 22:42:35 +00003271 if (!IsArrow &&
John McCallc12c5bb2010-05-15 11:32:37 +00003272 BaseType->isObjCObjectType() &&
3273 BaseType->getAs<ObjCObjectType>()->isObjCId() &&
Anders Carlsson8f28f992009-08-26 18:25:21 +00003274 MemberName.getAsIdentifierInfo()->isStr("isa"))
Steve Narofff242b1b2009-07-24 17:54:45 +00003275 return Owned(new (Context) ObjCIsaExpr(BaseExpr, false, MemberLoc,
Fariborz Jahanian83dc3252009-12-09 19:05:56 +00003276 Context.getObjCClassType()));
Steve Narofff242b1b2009-07-24 17:54:45 +00003277
Chris Lattnerfb173ec2008-07-21 04:28:12 +00003278 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner73525de2009-02-16 21:11:58 +00003279 if (BaseType->isExtVectorType()) {
Anders Carlsson8f28f992009-08-26 18:25:21 +00003280 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Chris Lattnerfb173ec2008-07-21 04:28:12 +00003281 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
3282 if (ret.isNull())
Sebastian Redl0eb23302009-01-19 00:08:26 +00003283 return ExprError();
Anders Carlsson8f28f992009-08-26 18:25:21 +00003284 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, *Member,
Steve Naroff6ece14c2009-01-21 00:14:39 +00003285 MemberLoc));
Chris Lattnerfb173ec2008-07-21 04:28:12 +00003286 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003287
Douglas Gregor214f31a2009-03-27 06:00:30 +00003288 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
3289 << BaseType << BaseExpr->getSourceRange();
3290
Douglas Gregor214f31a2009-03-27 06:00:30 +00003291 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00003292}
3293
John McCall129e2df2009-11-30 22:42:35 +00003294/// The main callback when the parser finds something like
3295/// expression . [nested-name-specifier] identifier
3296/// expression -> [nested-name-specifier] identifier
3297/// where 'identifier' encompasses a fairly broad spectrum of
3298/// possibilities, including destructor and operator references.
3299///
3300/// \param OpKind either tok::arrow or tok::period
3301/// \param HasTrailingLParen whether the next token is '(', which
3302/// is used to diagnose mis-uses of special members that can
3303/// only be called
3304/// \param ObjCImpDecl the current ObjC @implementation decl;
3305/// this is an ugly hack around the fact that ObjC @implementations
3306/// aren't properly put in the context chain
John McCall9ae2f072010-08-23 23:25:46 +00003307Sema::OwningExprResult Sema::ActOnMemberAccessExpr(Scope *S, Expr *Base,
John McCall129e2df2009-11-30 22:42:35 +00003308 SourceLocation OpLoc,
3309 tok::TokenKind OpKind,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003310 CXXScopeSpec &SS,
John McCall129e2df2009-11-30 22:42:35 +00003311 UnqualifiedId &Id,
John McCalld226f652010-08-21 09:40:31 +00003312 Decl *ObjCImpDecl,
John McCall129e2df2009-11-30 22:42:35 +00003313 bool HasTrailingLParen) {
3314 if (SS.isSet() && SS.isInvalid())
3315 return ExprError();
3316
3317 TemplateArgumentListInfo TemplateArgsBuffer;
3318
3319 // Decompose the name into its component parts.
Abramo Bagnara25777432010-08-11 22:01:17 +00003320 DeclarationNameInfo NameInfo;
John McCall129e2df2009-11-30 22:42:35 +00003321 const TemplateArgumentListInfo *TemplateArgs;
3322 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer,
Abramo Bagnara25777432010-08-11 22:01:17 +00003323 NameInfo, TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00003324
Abramo Bagnara25777432010-08-11 22:01:17 +00003325 DeclarationName Name = NameInfo.getName();
John McCall129e2df2009-11-30 22:42:35 +00003326 bool IsArrow = (OpKind == tok::arrow);
3327
3328 NamedDecl *FirstQualifierInScope
3329 = (!SS.isSet() ? 0 : FindFirstQualifierInScope(S,
3330 static_cast<NestedNameSpecifier*>(SS.getScopeRep())));
3331
3332 // This is a postfix expression, so get rid of ParenListExprs.
John McCall9ae2f072010-08-23 23:25:46 +00003333 OwningExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
3334 if (Result.isInvalid()) return ExprError();
3335 Base = Result.take();
John McCall129e2df2009-11-30 22:42:35 +00003336
Douglas Gregor01e56ae2010-04-12 20:54:26 +00003337 if (Base->getType()->isDependentType() || Name.isDependentName() ||
3338 isDependentScopeSpecifier(SS)) {
John McCall9ae2f072010-08-23 23:25:46 +00003339 Result = ActOnDependentMemberExpr(Base, Base->getType(),
John McCall129e2df2009-11-30 22:42:35 +00003340 IsArrow, OpLoc,
3341 SS, FirstQualifierInScope,
Abramo Bagnara25777432010-08-11 22:01:17 +00003342 NameInfo, TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00003343 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +00003344 LookupResult R(*this, NameInfo, LookupMemberName);
John McCallad00b772010-06-16 08:42:20 +00003345 Result = LookupMemberExpr(R, Base, IsArrow, OpLoc,
3346 SS, ObjCImpDecl, TemplateArgs != 0);
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00003347
John McCallad00b772010-06-16 08:42:20 +00003348 if (Result.isInvalid()) {
3349 Owned(Base);
3350 return ExprError();
3351 }
John McCall129e2df2009-11-30 22:42:35 +00003352
John McCallad00b772010-06-16 08:42:20 +00003353 if (Result.get()) {
3354 // The only way a reference to a destructor can be used is to
3355 // immediately call it, which falls into this case. If the
3356 // next token is not a '(', produce a diagnostic and build the
3357 // call now.
3358 if (!HasTrailingLParen &&
3359 Id.getKind() == UnqualifiedId::IK_DestructorName)
John McCall9ae2f072010-08-23 23:25:46 +00003360 return DiagnoseDtorReference(NameInfo.getLoc(), Result.get());
John McCall129e2df2009-11-30 22:42:35 +00003361
John McCallad00b772010-06-16 08:42:20 +00003362 return move(Result);
John McCall129e2df2009-11-30 22:42:35 +00003363 }
3364
John McCall9ae2f072010-08-23 23:25:46 +00003365 Result = BuildMemberReferenceExpr(Base, Base->getType(),
John McCallc2233c52010-01-15 08:34:02 +00003366 OpLoc, IsArrow, SS, FirstQualifierInScope,
3367 R, TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00003368 }
3369
3370 return move(Result);
Anders Carlsson8f28f992009-08-26 18:25:21 +00003371}
3372
Anders Carlsson56c5e332009-08-25 03:49:14 +00003373Sema::OwningExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
3374 FunctionDecl *FD,
3375 ParmVarDecl *Param) {
3376 if (Param->hasUnparsedDefaultArg()) {
3377 Diag (CallLoc,
3378 diag::err_use_of_default_argument_to_function_declared_later) <<
3379 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00003380 Diag(UnparsedDefaultArgLocs[Param],
Anders Carlsson56c5e332009-08-25 03:49:14 +00003381 diag::note_default_argument_declared_here);
3382 } else {
3383 if (Param->hasUninstantiatedDefaultArg()) {
3384 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
3385
3386 // Instantiate the expression.
Douglas Gregor525f96c2010-02-05 07:33:43 +00003387 MultiLevelTemplateArgumentList ArgList
3388 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
Anders Carlsson25cae7f2009-09-05 05:14:19 +00003389
Douglas Gregor24bae922010-07-08 18:37:38 +00003390 std::pair<const TemplateArgument *, unsigned> Innermost
3391 = ArgList.getInnermost();
3392 InstantiatingTemplate Inst(*this, CallLoc, Param, Innermost.first,
3393 Innermost.second);
Anders Carlsson56c5e332009-08-25 03:49:14 +00003394
John McCallce3ff2b2009-08-25 22:02:44 +00003395 OwningExprResult Result = SubstExpr(UninstExpr, ArgList);
Mike Stump1eb44332009-09-09 15:08:12 +00003396 if (Result.isInvalid())
Anders Carlsson56c5e332009-08-25 03:49:14 +00003397 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003398
Douglas Gregor65222e82009-12-23 18:19:08 +00003399 // Check the expression as an initializer for the parameter.
3400 InitializedEntity Entity
3401 = InitializedEntity::InitializeParameter(Param);
3402 InitializationKind Kind
3403 = InitializationKind::CreateCopy(Param->getLocation(),
3404 /*FIXME:EqualLoc*/UninstExpr->getSourceRange().getBegin());
3405 Expr *ResultE = Result.takeAs<Expr>();
3406
3407 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003408 Result = InitSeq.Perform(*this, Entity, Kind,
John McCallca0408f2010-08-23 06:44:23 +00003409 MultiExprArg(*this, &ResultE, 1));
Douglas Gregor65222e82009-12-23 18:19:08 +00003410 if (Result.isInvalid())
Anders Carlsson56c5e332009-08-25 03:49:14 +00003411 return ExprError();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003412
Douglas Gregor65222e82009-12-23 18:19:08 +00003413 // Build the default argument expression.
Douglas Gregor036aed12009-12-23 23:03:06 +00003414 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param,
Douglas Gregor65222e82009-12-23 18:19:08 +00003415 Result.takeAs<Expr>()));
Anders Carlsson56c5e332009-08-25 03:49:14 +00003416 }
Mike Stump1eb44332009-09-09 15:08:12 +00003417
Anders Carlsson56c5e332009-08-25 03:49:14 +00003418 // If the default expression creates temporaries, we need to
3419 // push them to the current stack of expression temporaries so they'll
3420 // be properly destroyed.
Douglas Gregor65222e82009-12-23 18:19:08 +00003421 // FIXME: We should really be rebuilding the default argument with new
3422 // bound temporaries; see the comment in PR5810.
Anders Carlsson337cba42009-12-15 19:16:31 +00003423 for (unsigned i = 0, e = Param->getNumDefaultArgTemporaries(); i != e; ++i)
3424 ExprTemporaries.push_back(Param->getDefaultArgTemporary(i));
Anders Carlsson56c5e332009-08-25 03:49:14 +00003425 }
3426
3427 // We already type-checked the argument, so we know it works.
Douglas Gregor036aed12009-12-23 23:03:06 +00003428 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson56c5e332009-08-25 03:49:14 +00003429}
3430
Douglas Gregor88a35142008-12-22 05:46:06 +00003431/// ConvertArgumentsForCall - Converts the arguments specified in
3432/// Args/NumArgs to the parameter types of the function FDecl with
3433/// function prototype Proto. Call is the call expression itself, and
3434/// Fn is the function expression. For a C++ member function, this
3435/// routine does not attempt to convert the object argument. Returns
3436/// true if the call is ill-formed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003437bool
3438Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor88a35142008-12-22 05:46:06 +00003439 FunctionDecl *FDecl,
Douglas Gregor72564e72009-02-26 23:50:07 +00003440 const FunctionProtoType *Proto,
Douglas Gregor88a35142008-12-22 05:46:06 +00003441 Expr **Args, unsigned NumArgs,
3442 SourceLocation RParenLoc) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00003443 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor88a35142008-12-22 05:46:06 +00003444 // assignment, to the types of the corresponding parameter, ...
3445 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor3fd56d72009-01-23 21:30:56 +00003446 bool Invalid = false;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003447
Douglas Gregor88a35142008-12-22 05:46:06 +00003448 // If too few arguments are available (and we don't have default
3449 // arguments for the remaining parameters), don't make the call.
3450 if (NumArgs < NumArgsInProto) {
3451 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
3452 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00003453 << Fn->getType()->isBlockPointerType()
Eric Christopherd77b9a22010-04-16 04:48:22 +00003454 << NumArgsInProto << NumArgs << Fn->getSourceRange();
Ted Kremenek8189cde2009-02-07 01:47:29 +00003455 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor88a35142008-12-22 05:46:06 +00003456 }
3457
3458 // If too many are passed and not variadic, error on the extras and drop
3459 // them.
3460 if (NumArgs > NumArgsInProto) {
3461 if (!Proto->isVariadic()) {
3462 Diag(Args[NumArgsInProto]->getLocStart(),
3463 diag::err_typecheck_call_too_many_args)
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00003464 << Fn->getType()->isBlockPointerType()
Eric Christopherccfa9632010-04-16 04:56:46 +00003465 << NumArgsInProto << NumArgs << Fn->getSourceRange()
Douglas Gregor88a35142008-12-22 05:46:06 +00003466 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3467 Args[NumArgs-1]->getLocEnd());
3468 // This deletes the extra arguments.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003469 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003470 return true;
Douglas Gregor88a35142008-12-22 05:46:06 +00003471 }
Douglas Gregor88a35142008-12-22 05:46:06 +00003472 }
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003473 llvm::SmallVector<Expr *, 8> AllArgs;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003474 VariadicCallType CallType =
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00003475 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
3476 if (Fn->getType()->isBlockPointerType())
3477 CallType = VariadicBlock; // Block
3478 else if (isa<MemberExpr>(Fn))
3479 CallType = VariadicMethod;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003480 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00003481 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003482 if (Invalid)
3483 return true;
3484 unsigned TotalNumArgs = AllArgs.size();
3485 for (unsigned i = 0; i < TotalNumArgs; ++i)
3486 Call->setArg(i, AllArgs[i]);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003487
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003488 return false;
3489}
Mike Stumpeed9cac2009-02-19 03:04:26 +00003490
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003491bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
3492 FunctionDecl *FDecl,
3493 const FunctionProtoType *Proto,
3494 unsigned FirstProtoArg,
3495 Expr **Args, unsigned NumArgs,
3496 llvm::SmallVector<Expr *, 8> &AllArgs,
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00003497 VariadicCallType CallType) {
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003498 unsigned NumArgsInProto = Proto->getNumArgs();
3499 unsigned NumArgsToCheck = NumArgs;
3500 bool Invalid = false;
3501 if (NumArgs != NumArgsInProto)
3502 // Use default arguments for missing arguments
3503 NumArgsToCheck = NumArgsInProto;
3504 unsigned ArgIx = 0;
Douglas Gregor88a35142008-12-22 05:46:06 +00003505 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003506 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor88a35142008-12-22 05:46:06 +00003507 QualType ProtoArgType = Proto->getArgType(i);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003508
Douglas Gregor88a35142008-12-22 05:46:06 +00003509 Expr *Arg;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003510 if (ArgIx < NumArgs) {
3511 Arg = Args[ArgIx++];
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003512
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003513 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3514 ProtoArgType,
Anders Carlssonb7906612009-08-26 23:45:07 +00003515 PDiag(diag::err_call_incomplete_argument)
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003516 << Arg->getSourceRange()))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003517 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003518
Douglas Gregora188ff22009-12-22 16:09:06 +00003519 // Pass the argument
3520 ParmVarDecl *Param = 0;
3521 if (FDecl && i < FDecl->getNumParams())
3522 Param = FDecl->getParamDecl(i);
Douglas Gregoraa037312009-12-22 07:24:36 +00003523
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003524
Douglas Gregora188ff22009-12-22 16:09:06 +00003525 InitializedEntity Entity =
3526 Param? InitializedEntity::InitializeParameter(Param)
3527 : InitializedEntity::InitializeParameter(ProtoArgType);
3528 OwningExprResult ArgE = PerformCopyInitialization(Entity,
3529 SourceLocation(),
3530 Owned(Arg));
3531 if (ArgE.isInvalid())
3532 return true;
3533
3534 Arg = ArgE.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00003535 } else {
Anders Carlssoned961f92009-08-25 02:29:20 +00003536 ParmVarDecl *Param = FDecl->getParamDecl(i);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003537
Mike Stump1eb44332009-09-09 15:08:12 +00003538 OwningExprResult ArgExpr =
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003539 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson56c5e332009-08-25 03:49:14 +00003540 if (ArgExpr.isInvalid())
3541 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003542
Anders Carlsson56c5e332009-08-25 03:49:14 +00003543 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00003544 }
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003545 AllArgs.push_back(Arg);
Douglas Gregor88a35142008-12-22 05:46:06 +00003546 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003547
Douglas Gregor88a35142008-12-22 05:46:06 +00003548 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00003549 if (CallType != VariadicDoesNotApply) {
Douglas Gregor88a35142008-12-22 05:46:06 +00003550 // Promote the arguments (C99 6.5.2.2p7).
Chris Lattner40378332010-05-16 04:01:30 +00003551 for (unsigned i = ArgIx; i != NumArgs; ++i) {
Douglas Gregor88a35142008-12-22 05:46:06 +00003552 Expr *Arg = Args[i];
Chris Lattner40378332010-05-16 04:01:30 +00003553 Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType, FDecl);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003554 AllArgs.push_back(Arg);
Douglas Gregor88a35142008-12-22 05:46:06 +00003555 }
3556 }
Douglas Gregor3fd56d72009-01-23 21:30:56 +00003557 return Invalid;
Douglas Gregor88a35142008-12-22 05:46:06 +00003558}
3559
Steve Narofff69936d2007-09-16 03:34:24 +00003560/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Reid Spencer5f016e22007-07-11 17:01:13 +00003561/// This provides the location of the left/right parens and a list of comma
3562/// locations.
Sebastian Redl0eb23302009-01-19 00:08:26 +00003563Action::OwningExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003564Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
Sebastian Redl0eb23302009-01-19 00:08:26 +00003565 MultiExprArg args,
Douglas Gregor88a35142008-12-22 05:46:06 +00003566 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Sebastian Redl0eb23302009-01-19 00:08:26 +00003567 unsigned NumArgs = args.size();
Nate Begeman2ef13e52009-08-10 23:49:36 +00003568
3569 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall9ae2f072010-08-23 23:25:46 +00003570 OwningExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
3571 if (Result.isInvalid()) return ExprError();
3572 Fn = Result.take();
Mike Stump1eb44332009-09-09 15:08:12 +00003573
John McCall9ae2f072010-08-23 23:25:46 +00003574 Expr **Args = args.release();
Mike Stump1eb44332009-09-09 15:08:12 +00003575
Douglas Gregor88a35142008-12-22 05:46:06 +00003576 if (getLangOptions().CPlusPlus) {
Douglas Gregora71d8192009-09-04 17:36:40 +00003577 // If this is a pseudo-destructor expression, build the call immediately.
3578 if (isa<CXXPseudoDestructorExpr>(Fn)) {
3579 if (NumArgs > 0) {
3580 // Pseudo-destructor calls should not have any arguments.
3581 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Douglas Gregor849b2432010-03-31 17:46:05 +00003582 << FixItHint::CreateRemoval(
Douglas Gregora71d8192009-09-04 17:36:40 +00003583 SourceRange(Args[0]->getLocStart(),
3584 Args[NumArgs-1]->getLocEnd()));
Mike Stump1eb44332009-09-09 15:08:12 +00003585
Douglas Gregora71d8192009-09-04 17:36:40 +00003586 NumArgs = 0;
3587 }
Mike Stump1eb44332009-09-09 15:08:12 +00003588
Douglas Gregora71d8192009-09-04 17:36:40 +00003589 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
3590 RParenLoc));
3591 }
Mike Stump1eb44332009-09-09 15:08:12 +00003592
Douglas Gregor17330012009-02-04 15:01:18 +00003593 // Determine whether this is a dependent call inside a C++ template,
Mike Stumpeed9cac2009-02-19 03:04:26 +00003594 // in which case we won't do any semantic analysis now.
Mike Stump390b4cc2009-05-16 07:39:55 +00003595 // FIXME: Will need to cache the results of name lookup (including ADL) in
3596 // Fn.
Douglas Gregor17330012009-02-04 15:01:18 +00003597 bool Dependent = false;
3598 if (Fn->isTypeDependent())
3599 Dependent = true;
3600 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
3601 Dependent = true;
3602
3603 if (Dependent)
Ted Kremenek668bf912009-02-09 20:51:47 +00003604 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
Douglas Gregor17330012009-02-04 15:01:18 +00003605 Context.DependentTy, RParenLoc));
3606
3607 // Determine whether this is a call to an object (C++ [over.call.object]).
3608 if (Fn->getType()->isRecordType())
3609 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
3610 CommaLocs, RParenLoc));
3611
John McCall129e2df2009-11-30 22:42:35 +00003612 Expr *NakedFn = Fn->IgnoreParens();
3613
3614 // Determine whether this is a call to an unresolved member function.
3615 if (UnresolvedMemberExpr *MemE = dyn_cast<UnresolvedMemberExpr>(NakedFn)) {
3616 // If lookup was unresolved but not dependent (i.e. didn't find
3617 // an unresolved using declaration), it has to be an overloaded
3618 // function set, which means it must contain either multiple
3619 // declarations (all methods or method templates) or a single
3620 // method template.
3621 assert((MemE->getNumDecls() > 1) ||
Douglas Gregor2b147f02010-04-25 21:15:30 +00003622 isa<FunctionTemplateDecl>(
3623 (*MemE->decls_begin())->getUnderlyingDecl()));
Douglas Gregor958aeb02009-12-01 03:34:29 +00003624 (void)MemE;
John McCall129e2df2009-11-30 22:42:35 +00003625
John McCallaa81e162009-12-01 22:10:20 +00003626 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
3627 CommaLocs, RParenLoc);
John McCall129e2df2009-11-30 22:42:35 +00003628 }
3629
Douglas Gregorfa047642009-02-04 00:32:51 +00003630 // Determine whether this is a call to a member function.
John McCall129e2df2009-11-30 22:42:35 +00003631 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(NakedFn)) {
Douglas Gregore53060f2009-06-25 22:08:12 +00003632 NamedDecl *MemDecl = MemExpr->getMemberDecl();
John McCall129e2df2009-11-30 22:42:35 +00003633 if (isa<CXXMethodDecl>(MemDecl))
John McCallaa81e162009-12-01 22:10:20 +00003634 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
3635 CommaLocs, RParenLoc);
Douglas Gregore53060f2009-06-25 22:08:12 +00003636 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003637
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003638 // Determine whether this is a call to a pointer-to-member function.
John McCall129e2df2009-11-30 22:42:35 +00003639 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(NakedFn)) {
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003640 if (BO->getOpcode() == BinaryOperator::PtrMemD ||
3641 BO->getOpcode() == BinaryOperator::PtrMemI) {
Douglas Gregor5f970ee2010-05-04 18:18:31 +00003642 if (const FunctionProtoType *FPT
3643 = BO->getType()->getAs<FunctionProtoType>()) {
Douglas Gregor5291c3c2010-07-13 08:18:22 +00003644 QualType ResultTy = FPT->getCallResultType(Context);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003645
John McCall9ae2f072010-08-23 23:25:46 +00003646 CXXMemberCallExpr *TheCall
3647 = new (Context) CXXMemberCallExpr(Context, BO, Args,
3648 NumArgs, ResultTy,
3649 RParenLoc);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003650
3651 if (CheckCallReturnType(FPT->getResultType(),
3652 BO->getRHS()->getSourceRange().getBegin(),
John McCall9ae2f072010-08-23 23:25:46 +00003653 TheCall, 0))
Fariborz Jahanian5de24502009-10-28 16:49:46 +00003654 return ExprError();
Anders Carlsson8d6d90d2009-10-15 00:41:48 +00003655
John McCall9ae2f072010-08-23 23:25:46 +00003656 if (ConvertArgumentsForCall(TheCall, BO, 0, FPT, Args, NumArgs,
Fariborz Jahanian5de24502009-10-28 16:49:46 +00003657 RParenLoc))
3658 return ExprError();
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003659
John McCall9ae2f072010-08-23 23:25:46 +00003660 return MaybeBindToTemporary(TheCall);
Fariborz Jahanian5de24502009-10-28 16:49:46 +00003661 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003662 return ExprError(Diag(Fn->getLocStart(),
Fariborz Jahanian5de24502009-10-28 16:49:46 +00003663 diag::err_typecheck_call_not_function)
3664 << Fn->getType() << Fn->getSourceRange());
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003665 }
3666 }
Douglas Gregor88a35142008-12-22 05:46:06 +00003667 }
3668
Douglas Gregorfa047642009-02-04 00:32:51 +00003669 // If we're directly calling a function, get the appropriate declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003670 // Also, in C++, keep track of whether we should perform argument-dependent
Douglas Gregor6db8ed42009-06-30 23:57:56 +00003671 // lookup and whether there were any explicitly-specified template arguments.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003672
Eli Friedmanefa42f72009-12-26 03:35:45 +00003673 Expr *NakedFn = Fn->IgnoreParens();
John McCall3b4294e2009-12-16 12:17:52 +00003674 if (isa<UnresolvedLookupExpr>(NakedFn)) {
3675 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(NakedFn);
Douglas Gregor1aae80b2010-04-14 20:27:54 +00003676 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs,
John McCall3b4294e2009-12-16 12:17:52 +00003677 CommaLocs, RParenLoc);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003678 }
Chris Lattner04421082008-04-08 04:40:51 +00003679
John McCall3b4294e2009-12-16 12:17:52 +00003680 NamedDecl *NDecl = 0;
3681 if (isa<DeclRefExpr>(NakedFn))
3682 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
3683
John McCallaa81e162009-12-01 22:10:20 +00003684 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc);
3685}
3686
John McCall3b4294e2009-12-16 12:17:52 +00003687/// BuildResolvedCallExpr - Build a call to a resolved expression,
3688/// i.e. an expression not of \p OverloadTy. The expression should
John McCallaa81e162009-12-01 22:10:20 +00003689/// unary-convert to an expression of function-pointer or
3690/// block-pointer type.
3691///
3692/// \param NDecl the declaration being called, if available
3693Sema::OwningExprResult
3694Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
3695 SourceLocation LParenLoc,
3696 Expr **Args, unsigned NumArgs,
3697 SourceLocation RParenLoc) {
3698 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
3699
Chris Lattner04421082008-04-08 04:40:51 +00003700 // Promote the function operand.
3701 UsualUnaryConversions(Fn);
3702
Chris Lattner925e60d2007-12-28 05:29:59 +00003703 // Make the call expr early, before semantic checks. This guarantees cleanup
3704 // of arguments and function on error.
John McCall9ae2f072010-08-23 23:25:46 +00003705 CallExpr *TheCall = new (Context) CallExpr(Context, Fn,
3706 Args, NumArgs,
3707 Context.BoolTy,
3708 RParenLoc);
Sebastian Redl0eb23302009-01-19 00:08:26 +00003709
Steve Naroffdd972f22008-09-05 22:11:13 +00003710 const FunctionType *FuncT;
3711 if (!Fn->getType()->isBlockPointerType()) {
3712 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
3713 // have type pointer to function".
Ted Kremenek6217b802009-07-29 21:53:49 +00003714 const PointerType *PT = Fn->getType()->getAs<PointerType>();
Steve Naroffdd972f22008-09-05 22:11:13 +00003715 if (PT == 0)
Sebastian Redl0eb23302009-01-19 00:08:26 +00003716 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3717 << Fn->getType() << Fn->getSourceRange());
John McCall183700f2009-09-21 23:43:11 +00003718 FuncT = PT->getPointeeType()->getAs<FunctionType>();
Steve Naroffdd972f22008-09-05 22:11:13 +00003719 } else { // This is a block call.
Ted Kremenek6217b802009-07-29 21:53:49 +00003720 FuncT = Fn->getType()->getAs<BlockPointerType>()->getPointeeType()->
John McCall183700f2009-09-21 23:43:11 +00003721 getAs<FunctionType>();
Steve Naroffdd972f22008-09-05 22:11:13 +00003722 }
Chris Lattner925e60d2007-12-28 05:29:59 +00003723 if (FuncT == 0)
Sebastian Redl0eb23302009-01-19 00:08:26 +00003724 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3725 << Fn->getType() << Fn->getSourceRange());
3726
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003727 // Check for a valid return type
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003728 if (CheckCallReturnType(FuncT->getResultType(),
John McCall9ae2f072010-08-23 23:25:46 +00003729 Fn->getSourceRange().getBegin(), TheCall,
Anders Carlsson8c8d9192009-10-09 23:51:55 +00003730 FDecl))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003731 return ExprError();
3732
Chris Lattner925e60d2007-12-28 05:29:59 +00003733 // We know the result type of the call, set it.
Douglas Gregor5291c3c2010-07-13 08:18:22 +00003734 TheCall->setType(FuncT->getCallResultType(Context));
Sebastian Redl0eb23302009-01-19 00:08:26 +00003735
Douglas Gregor72564e72009-02-26 23:50:07 +00003736 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
John McCall9ae2f072010-08-23 23:25:46 +00003737 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00003738 RParenLoc))
Sebastian Redl0eb23302009-01-19 00:08:26 +00003739 return ExprError();
Chris Lattner925e60d2007-12-28 05:29:59 +00003740 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00003741 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redl0eb23302009-01-19 00:08:26 +00003742
Douglas Gregor74734d52009-04-02 15:37:10 +00003743 if (FDecl) {
3744 // Check if we have too few/too many template arguments, based
3745 // on our knowledge of the function definition.
3746 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00003747 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00003748 const FunctionProtoType *Proto =
John McCall183700f2009-09-21 23:43:11 +00003749 Def->getType()->getAs<FunctionProtoType>();
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00003750 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size())) {
3751 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
3752 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
3753 }
3754 }
Douglas Gregor74734d52009-04-02 15:37:10 +00003755 }
3756
Steve Naroffb291ab62007-08-28 23:30:39 +00003757 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner925e60d2007-12-28 05:29:59 +00003758 for (unsigned i = 0; i != NumArgs; i++) {
3759 Expr *Arg = Args[i];
3760 DefaultArgumentPromotion(Arg);
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003761 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3762 Arg->getType(),
Anders Carlssonb7906612009-08-26 23:45:07 +00003763 PDiag(diag::err_call_incomplete_argument)
3764 << Arg->getSourceRange()))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003765 return ExprError();
Chris Lattner925e60d2007-12-28 05:29:59 +00003766 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +00003767 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003768 }
Chris Lattner925e60d2007-12-28 05:29:59 +00003769
Douglas Gregor88a35142008-12-22 05:46:06 +00003770 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3771 if (!Method->isStatic())
Sebastian Redl0eb23302009-01-19 00:08:26 +00003772 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
3773 << Fn->getSourceRange());
Douglas Gregor88a35142008-12-22 05:46:06 +00003774
Fariborz Jahaniandaf04152009-05-15 20:33:25 +00003775 // Check for sentinels
3776 if (NDecl)
3777 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00003778
Chris Lattner59907c42007-08-10 20:18:51 +00003779 // Do special checking on direct calls to functions.
Anders Carlssond406bf02009-08-16 01:56:34 +00003780 if (FDecl) {
John McCall9ae2f072010-08-23 23:25:46 +00003781 if (CheckFunctionCall(FDecl, TheCall))
Anders Carlssond406bf02009-08-16 01:56:34 +00003782 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003783
Douglas Gregor7814e6d2009-09-12 00:22:50 +00003784 if (unsigned BuiltinID = FDecl->getBuiltinID())
John McCall9ae2f072010-08-23 23:25:46 +00003785 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
Anders Carlssond406bf02009-08-16 01:56:34 +00003786 } else if (NDecl) {
John McCall9ae2f072010-08-23 23:25:46 +00003787 if (CheckBlockCall(NDecl, TheCall))
Anders Carlssond406bf02009-08-16 01:56:34 +00003788 return ExprError();
3789 }
Chris Lattner59907c42007-08-10 20:18:51 +00003790
John McCall9ae2f072010-08-23 23:25:46 +00003791 return MaybeBindToTemporary(TheCall);
Reid Spencer5f016e22007-07-11 17:01:13 +00003792}
3793
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003794Action::OwningExprResult
3795Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
John McCall9ae2f072010-08-23 23:25:46 +00003796 SourceLocation RParenLoc, Expr *InitExpr) {
Steve Narofff69936d2007-09-16 03:34:24 +00003797 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroffaff1edd2007-07-19 21:32:11 +00003798 // FIXME: put back this assert when initializers are worked out.
Steve Narofff69936d2007-09-16 03:34:24 +00003799 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCall42f56b52010-01-18 19:35:47 +00003800
3801 TypeSourceInfo *TInfo;
3802 QualType literalType = GetTypeFromParser(Ty, &TInfo);
3803 if (!TInfo)
3804 TInfo = Context.getTrivialTypeSourceInfo(literalType);
3805
John McCall9ae2f072010-08-23 23:25:46 +00003806 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
John McCall42f56b52010-01-18 19:35:47 +00003807}
3808
3809Action::OwningExprResult
3810Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
John McCall9ae2f072010-08-23 23:25:46 +00003811 SourceLocation RParenLoc, Expr *literalExpr) {
John McCall42f56b52010-01-18 19:35:47 +00003812 QualType literalType = TInfo->getType();
Anders Carlssond35c8322007-12-05 07:24:19 +00003813
Eli Friedman6223c222008-05-20 05:22:08 +00003814 if (literalType->isArrayType()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003815 if (literalType->isVariableArrayType())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003816 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
3817 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor690dc7f2009-05-21 23:48:18 +00003818 } else if (!literalType->isDependentType() &&
3819 RequireCompleteType(LParenLoc, literalType,
Anders Carlssonb7906612009-08-26 23:45:07 +00003820 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump1eb44332009-09-09 15:08:12 +00003821 << SourceRange(LParenLoc,
Anders Carlssonb7906612009-08-26 23:45:07 +00003822 literalExpr->getSourceRange().getEnd())))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003823 return ExprError();
Eli Friedman6223c222008-05-20 05:22:08 +00003824
Douglas Gregor99a2e602009-12-16 01:38:02 +00003825 InitializedEntity Entity
Douglas Gregord6542d82009-12-22 15:35:07 +00003826 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor99a2e602009-12-16 01:38:02 +00003827 InitializationKind Kind
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003828 = InitializationKind::CreateCast(SourceRange(LParenLoc, RParenLoc),
Douglas Gregor99a2e602009-12-16 01:38:02 +00003829 /*IsCStyleCast=*/true);
Eli Friedman08544622009-12-22 02:35:53 +00003830 InitializationSequence InitSeq(*this, Entity, Kind, &literalExpr, 1);
3831 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCallca0408f2010-08-23 06:44:23 +00003832 MultiExprArg(*this, &literalExpr, 1),
Eli Friedman08544622009-12-22 02:35:53 +00003833 &literalType);
3834 if (Result.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003835 return ExprError();
John McCall9ae2f072010-08-23 23:25:46 +00003836 literalExpr = Result.get();
Steve Naroffe9b12192008-01-14 18:19:28 +00003837
Chris Lattner371f2582008-12-04 23:50:19 +00003838 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffe9b12192008-01-14 18:19:28 +00003839 if (isFileScope) { // 6.5.2.5p3
Steve Naroffd0091aa2008-01-10 22:15:12 +00003840 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003841 return ExprError();
Steve Naroffd0091aa2008-01-10 22:15:12 +00003842 }
Eli Friedman08544622009-12-22 02:35:53 +00003843
John McCall1d7d8d62010-01-19 22:33:45 +00003844 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
Steve Naroff6ece14c2009-01-21 00:14:39 +00003845 literalExpr, isFileScope));
Steve Naroff4aa88f82007-07-19 01:06:55 +00003846}
3847
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003848Action::OwningExprResult
3849Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003850 SourceLocation RBraceLoc) {
3851 unsigned NumInit = initlist.size();
John McCall9ae2f072010-08-23 23:25:46 +00003852 Expr **InitList = initlist.release();
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00003853
Steve Naroff08d92e42007-09-15 18:49:24 +00003854 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stumpeed9cac2009-02-19 03:04:26 +00003855 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003856
Ted Kremenek709210f2010-04-13 23:39:13 +00003857 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList,
3858 NumInit, RBraceLoc);
Chris Lattnerf0467b32008-04-02 04:24:33 +00003859 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003860 return Owned(E);
Steve Naroff4aa88f82007-07-19 01:06:55 +00003861}
3862
Anders Carlsson82debc72009-10-18 18:12:03 +00003863static CastExpr::CastKind getScalarCastKind(ASTContext &Context,
3864 QualType SrcTy, QualType DestTy) {
Douglas Gregora4923eb2009-11-16 21:35:15 +00003865 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
Anders Carlsson82debc72009-10-18 18:12:03 +00003866 return CastExpr::CK_NoOp;
3867
3868 if (SrcTy->hasPointerRepresentation()) {
3869 if (DestTy->hasPointerRepresentation())
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003870 return DestTy->isObjCObjectPointerType() ?
3871 CastExpr::CK_AnyPointerToObjCPointerCast :
Fariborz Jahaniana7fa7cd2009-12-15 21:34:52 +00003872 CastExpr::CK_BitCast;
Anders Carlsson82debc72009-10-18 18:12:03 +00003873 if (DestTy->isIntegerType())
3874 return CastExpr::CK_PointerToIntegral;
3875 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003876
Anders Carlsson82debc72009-10-18 18:12:03 +00003877 if (SrcTy->isIntegerType()) {
3878 if (DestTy->isIntegerType())
3879 return CastExpr::CK_IntegralCast;
3880 if (DestTy->hasPointerRepresentation())
3881 return CastExpr::CK_IntegralToPointer;
3882 if (DestTy->isRealFloatingType())
3883 return CastExpr::CK_IntegralToFloating;
3884 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003885
Anders Carlsson82debc72009-10-18 18:12:03 +00003886 if (SrcTy->isRealFloatingType()) {
3887 if (DestTy->isRealFloatingType())
3888 return CastExpr::CK_FloatingCast;
3889 if (DestTy->isIntegerType())
3890 return CastExpr::CK_FloatingToIntegral;
3891 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003892
Anders Carlsson82debc72009-10-18 18:12:03 +00003893 // FIXME: Assert here.
3894 // assert(false && "Unhandled cast combination!");
3895 return CastExpr::CK_Unknown;
3896}
3897
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003898/// CheckCastTypes - Check type constraints for casting between types.
Sebastian Redlef0cb8e2009-07-29 13:50:23 +00003899bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr,
Mike Stump1eb44332009-09-09 15:08:12 +00003900 CastExpr::CastKind& Kind,
John McCallf871d0c2010-08-07 06:22:56 +00003901 CXXCastPath &BasePath,
Fariborz Jahaniane9f42082009-08-26 18:55:36 +00003902 bool FunctionalStyle) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00003903 if (getLangOptions().CPlusPlus)
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00003904 return CXXCheckCStyleCast(TyR, castType, castExpr, Kind, BasePath,
3905 FunctionalStyle);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00003906
Douglas Gregora873dfc2010-02-03 00:27:59 +00003907 DefaultFunctionArrayLvalueConversion(castExpr);
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003908
3909 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
3910 // type needs to be scalar.
3911 if (castType->isVoidType()) {
3912 // Cast to void allows any expr type.
Anders Carlssonebeaf202009-10-16 02:35:04 +00003913 Kind = CastExpr::CK_ToVoid;
3914 return false;
3915 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003916
Eli Friedman8d438082010-07-17 20:43:49 +00003917 if (RequireCompleteType(TyR.getBegin(), castType,
3918 diag::err_typecheck_cast_to_incomplete))
3919 return true;
3920
Anders Carlssonebeaf202009-10-16 02:35:04 +00003921 if (!castType->isScalarType() && !castType->isVectorType()) {
Douglas Gregora4923eb2009-11-16 21:35:15 +00003922 if (Context.hasSameUnqualifiedType(castType, castExpr->getType()) &&
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003923 (castType->isStructureType() || castType->isUnionType())) {
3924 // GCC struct/union extension: allow cast to self.
Eli Friedmanb1d796d2009-03-23 00:24:07 +00003925 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003926 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
3927 << castType << castExpr->getSourceRange();
Anders Carlsson4d8673b2009-08-07 23:22:37 +00003928 Kind = CastExpr::CK_NoOp;
Anders Carlssonc3516322009-10-16 02:48:28 +00003929 return false;
3930 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003931
Anders Carlssonc3516322009-10-16 02:48:28 +00003932 if (castType->isUnionType()) {
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003933 // GCC cast to union extension
Ted Kremenek6217b802009-07-29 21:53:49 +00003934 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003935 RecordDecl::field_iterator Field, FieldEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003936 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003937 Field != FieldEnd; ++Field) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003938 if (Context.hasSameUnqualifiedType(Field->getType(),
Douglas Gregora4923eb2009-11-16 21:35:15 +00003939 castExpr->getType())) {
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003940 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
3941 << castExpr->getSourceRange();
3942 break;
3943 }
3944 }
3945 if (Field == FieldEnd)
3946 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
3947 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlsson4d8673b2009-08-07 23:22:37 +00003948 Kind = CastExpr::CK_ToUnion;
Anders Carlssonc3516322009-10-16 02:48:28 +00003949 return false;
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003950 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003951
Anders Carlssonc3516322009-10-16 02:48:28 +00003952 // Reject any other conversions to non-scalar types.
3953 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
3954 << castType << castExpr->getSourceRange();
3955 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003956
3957 if (!castExpr->getType()->isScalarType() &&
Anders Carlssonc3516322009-10-16 02:48:28 +00003958 !castExpr->getType()->isVectorType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003959 return Diag(castExpr->getLocStart(),
3960 diag::err_typecheck_expect_scalar_operand)
Chris Lattnerd1625842008-11-24 06:25:27 +00003961 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlssonc3516322009-10-16 02:48:28 +00003962 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003963
3964 if (castType->isExtVectorType())
Anders Carlsson16a89042009-10-16 05:23:41 +00003965 return CheckExtVectorCast(TyR, castType, castExpr, Kind);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003966
Anders Carlssonc3516322009-10-16 02:48:28 +00003967 if (castType->isVectorType())
3968 return CheckVectorCast(TyR, castType, castExpr->getType(), Kind);
3969 if (castExpr->getType()->isVectorType())
3970 return CheckVectorCast(TyR, castExpr->getType(), castType, Kind);
3971
Anders Carlsson16a89042009-10-16 05:23:41 +00003972 if (isa<ObjCSelectorExpr>(castExpr))
3973 return Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003974
Anders Carlssonc3516322009-10-16 02:48:28 +00003975 if (!castType->isArithmeticType()) {
Eli Friedman41826bb2009-05-01 02:23:58 +00003976 QualType castExprType = castExpr->getType();
Douglas Gregor9d3347a2010-06-16 00:35:25 +00003977 if (!castExprType->isIntegralType(Context) &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003978 castExprType->isArithmeticType())
Eli Friedman41826bb2009-05-01 02:23:58 +00003979 return Diag(castExpr->getLocStart(),
3980 diag::err_cast_pointer_from_non_pointer_int)
3981 << castExprType << castExpr->getSourceRange();
3982 } else if (!castExpr->getType()->isArithmeticType()) {
Douglas Gregor9d3347a2010-06-16 00:35:25 +00003983 if (!castType->isIntegralType(Context) && castType->isArithmeticType())
Eli Friedman41826bb2009-05-01 02:23:58 +00003984 return Diag(castExpr->getLocStart(),
3985 diag::err_cast_pointer_to_non_pointer_int)
3986 << castType << castExpr->getSourceRange();
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003987 }
Anders Carlsson82debc72009-10-18 18:12:03 +00003988
3989 Kind = getScalarCastKind(Context, castExpr->getType(), castType);
John McCallb7f4ffe2010-08-12 21:44:57 +00003990
3991 if (Kind == CastExpr::CK_Unknown || Kind == CastExpr::CK_BitCast)
3992 CheckCastAlign(castExpr, castType, TyR);
3993
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003994 return false;
3995}
3996
Anders Carlssonc3516322009-10-16 02:48:28 +00003997bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
3998 CastExpr::CastKind &Kind) {
Anders Carlssona64db8f2007-11-27 05:51:55 +00003999 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00004000
Anders Carlssona64db8f2007-11-27 05:51:55 +00004001 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner98be4942008-03-05 18:54:05 +00004002 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssona64db8f2007-11-27 05:51:55 +00004003 return Diag(R.getBegin(),
Mike Stumpeed9cac2009-02-19 03:04:26 +00004004 Ty->isVectorType() ?
Anders Carlssona64db8f2007-11-27 05:51:55 +00004005 diag::err_invalid_conversion_between_vectors :
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004006 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00004007 << VectorTy << Ty << R;
Anders Carlssona64db8f2007-11-27 05:51:55 +00004008 } else
4009 return Diag(R.getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004010 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattnerd1625842008-11-24 06:25:27 +00004011 << VectorTy << Ty << R;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004012
Anders Carlssonc3516322009-10-16 02:48:28 +00004013 Kind = CastExpr::CK_BitCast;
Anders Carlssona64db8f2007-11-27 05:51:55 +00004014 return false;
4015}
4016
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004017bool Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *&CastExpr,
Anders Carlsson16a89042009-10-16 05:23:41 +00004018 CastExpr::CastKind &Kind) {
Nate Begeman58d29a42009-06-26 00:50:28 +00004019 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004020
Anders Carlsson16a89042009-10-16 05:23:41 +00004021 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004022
Nate Begeman9b10da62009-06-27 22:05:55 +00004023 // If SrcTy is a VectorType, the total size must match to explicitly cast to
4024 // an ExtVectorType.
Nate Begeman58d29a42009-06-26 00:50:28 +00004025 if (SrcTy->isVectorType()) {
4026 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
4027 return Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
4028 << DestTy << SrcTy << R;
Anders Carlsson16a89042009-10-16 05:23:41 +00004029 Kind = CastExpr::CK_BitCast;
Nate Begeman58d29a42009-06-26 00:50:28 +00004030 return false;
4031 }
4032
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004033 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begeman58d29a42009-06-26 00:50:28 +00004034 // conversion will take place first from scalar to elt type, and then
4035 // splat from elt type to vector.
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004036 if (SrcTy->isPointerType())
4037 return Diag(R.getBegin(),
4038 diag::err_invalid_conversion_between_vector_and_scalar)
4039 << DestTy << SrcTy << R;
Eli Friedman73c39ab2009-10-20 08:27:19 +00004040
4041 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
4042 ImpCastExprToType(CastExpr, DestElemTy,
4043 getScalarCastKind(Context, SrcTy, DestElemTy));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004044
Anders Carlsson16a89042009-10-16 05:23:41 +00004045 Kind = CastExpr::CK_VectorSplat;
Nate Begeman58d29a42009-06-26 00:50:28 +00004046 return false;
4047}
4048
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004049Action::OwningExprResult
Nate Begeman2ef13e52009-08-10 23:49:36 +00004050Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, TypeTy *Ty,
John McCall9ae2f072010-08-23 23:25:46 +00004051 SourceLocation RParenLoc, Expr *castExpr) {
4052 assert((Ty != 0) && (castExpr != 0) &&
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004053 "ActOnCastExpr(): missing type or expr");
Steve Naroff16beff82007-07-16 23:25:18 +00004054
John McCall9d125032010-01-15 18:39:57 +00004055 TypeSourceInfo *castTInfo;
4056 QualType castType = GetTypeFromParser(Ty, &castTInfo);
4057 if (!castTInfo)
John McCall42f56b52010-01-18 19:35:47 +00004058 castTInfo = Context.getTrivialTypeSourceInfo(castType);
Mike Stump1eb44332009-09-09 15:08:12 +00004059
Nate Begeman2ef13e52009-08-10 23:49:36 +00004060 // If the Expr being casted is a ParenListExpr, handle it specially.
4061 if (isa<ParenListExpr>(castExpr))
John McCall9ae2f072010-08-23 23:25:46 +00004062 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, castExpr,
John McCall42f56b52010-01-18 19:35:47 +00004063 castTInfo);
John McCallb042fdf2010-01-15 18:56:44 +00004064
John McCall9ae2f072010-08-23 23:25:46 +00004065 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, castExpr);
John McCallb042fdf2010-01-15 18:56:44 +00004066}
4067
4068Action::OwningExprResult
4069Sema::BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty,
John McCall9ae2f072010-08-23 23:25:46 +00004070 SourceLocation RParenLoc, Expr *castExpr) {
John McCallb042fdf2010-01-15 18:56:44 +00004071 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
John McCallf871d0c2010-08-07 06:22:56 +00004072 CXXCastPath BasePath;
John McCallb042fdf2010-01-15 18:56:44 +00004073 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), Ty->getType(), castExpr,
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00004074 Kind, BasePath))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004075 return ExprError();
Anders Carlsson0aebc812009-09-09 21:33:21 +00004076
John McCallf871d0c2010-08-07 06:22:56 +00004077 return Owned(CStyleCastExpr::Create(Context,
Douglas Gregor63982352010-07-13 18:40:04 +00004078 Ty->getType().getNonLValueExprType(Context),
John McCallf871d0c2010-08-07 06:22:56 +00004079 Kind, castExpr, &BasePath, Ty,
4080 LParenLoc, RParenLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00004081}
4082
Nate Begeman2ef13e52009-08-10 23:49:36 +00004083/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
4084/// of comma binary operators.
John McCall9ae2f072010-08-23 23:25:46 +00004085OwningExprResult
4086Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *expr) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00004087 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
4088 if (!E)
4089 return Owned(expr);
Mike Stump1eb44332009-09-09 15:08:12 +00004090
John McCallca0408f2010-08-23 06:44:23 +00004091 OwningExprResult Result(E->getExpr(0));
Mike Stump1eb44332009-09-09 15:08:12 +00004092
Nate Begeman2ef13e52009-08-10 23:49:36 +00004093 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
John McCall9ae2f072010-08-23 23:25:46 +00004094 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
4095 E->getExpr(i));
Mike Stump1eb44332009-09-09 15:08:12 +00004096
John McCall9ae2f072010-08-23 23:25:46 +00004097 if (Result.isInvalid()) return ExprError();
4098
4099 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
Nate Begeman2ef13e52009-08-10 23:49:36 +00004100}
4101
4102Action::OwningExprResult
4103Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
John McCall9ae2f072010-08-23 23:25:46 +00004104 SourceLocation RParenLoc, Expr *Op,
John McCall42f56b52010-01-18 19:35:47 +00004105 TypeSourceInfo *TInfo) {
John McCall9ae2f072010-08-23 23:25:46 +00004106 ParenListExpr *PE = cast<ParenListExpr>(Op);
John McCall42f56b52010-01-18 19:35:47 +00004107 QualType Ty = TInfo->getType();
John Thompson8bb59a82010-06-30 22:55:51 +00004108 bool isAltiVecLiteral = false;
Mike Stump1eb44332009-09-09 15:08:12 +00004109
John Thompson8bb59a82010-06-30 22:55:51 +00004110 // Check for an altivec literal,
4111 // i.e. all the elements are integer constants.
Nate Begeman2ef13e52009-08-10 23:49:36 +00004112 if (getLangOptions().AltiVec && Ty->isVectorType()) {
4113 if (PE->getNumExprs() == 0) {
4114 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
4115 return ExprError();
4116 }
John Thompson8bb59a82010-06-30 22:55:51 +00004117 if (PE->getNumExprs() == 1) {
4118 if (!PE->getExpr(0)->getType()->isVectorType())
4119 isAltiVecLiteral = true;
4120 }
4121 else
4122 isAltiVecLiteral = true;
4123 }
Nate Begeman2ef13e52009-08-10 23:49:36 +00004124
John Thompson8bb59a82010-06-30 22:55:51 +00004125 // If this is an altivec initializer, '(' type ')' '(' init, ..., init ')'
4126 // then handle it as such.
4127 if (isAltiVecLiteral) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00004128 llvm::SmallVector<Expr *, 8> initExprs;
4129 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
4130 initExprs.push_back(PE->getExpr(i));
4131
4132 // FIXME: This means that pretty-printing the final AST will produce curly
4133 // braces instead of the original commas.
Ted Kremenek709210f2010-04-13 23:39:13 +00004134 InitListExpr *E = new (Context) InitListExpr(Context, LParenLoc,
4135 &initExprs[0],
Nate Begeman2ef13e52009-08-10 23:49:36 +00004136 initExprs.size(), RParenLoc);
4137 E->setType(Ty);
John McCall9ae2f072010-08-23 23:25:46 +00004138 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, E);
Nate Begeman2ef13e52009-08-10 23:49:36 +00004139 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00004140 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
Nate Begeman2ef13e52009-08-10 23:49:36 +00004141 // sequence of BinOp comma operators.
John McCall9ae2f072010-08-23 23:25:46 +00004142 OwningExprResult Result = MaybeConvertParenListExprToParenExpr(S, Op);
4143 if (Result.isInvalid()) return ExprError();
4144 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Result.take());
Nate Begeman2ef13e52009-08-10 23:49:36 +00004145 }
4146}
4147
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00004148Action::OwningExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
Nate Begeman2ef13e52009-08-10 23:49:36 +00004149 SourceLocation R,
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00004150 MultiExprArg Val,
4151 TypeTy *TypeOfCast) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00004152 unsigned nexprs = Val.size();
4153 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00004154 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
4155 Expr *expr;
4156 if (nexprs == 1 && TypeOfCast && !TypeIsVectorType(TypeOfCast))
4157 expr = new (Context) ParenExpr(L, R, exprs[0]);
4158 else
4159 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
Nate Begeman2ef13e52009-08-10 23:49:36 +00004160 return Owned(expr);
4161}
4162
Sebastian Redl28507842009-02-26 14:39:58 +00004163/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
4164/// In that case, lhs = cond.
Chris Lattnera119a3b2009-02-18 04:38:20 +00004165/// C99 6.5.15
4166QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
4167 SourceLocation QuestionLoc) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004168 // C++ is sufficiently different to merit its own checker.
4169 if (getLangOptions().CPlusPlus)
4170 return CXXCheckConditionalOperands(Cond, LHS, RHS, QuestionLoc);
4171
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004172 UsualUnaryConversions(Cond);
4173 UsualUnaryConversions(LHS);
4174 UsualUnaryConversions(RHS);
4175 QualType CondTy = Cond->getType();
4176 QualType LHSTy = LHS->getType();
4177 QualType RHSTy = RHS->getType();
Steve Naroffc80b4ee2007-07-16 21:54:35 +00004178
Reid Spencer5f016e22007-07-11 17:01:13 +00004179 // first, check the condition.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004180 if (!CondTy->isScalarType()) { // C99 6.5.15p2
4181 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4182 << CondTy;
4183 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00004184 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004185
Chris Lattner70d67a92008-01-06 22:42:25 +00004186 // Now check the two expressions.
Nate Begeman2ef13e52009-08-10 23:49:36 +00004187 if (LHSTy->isVectorType() || RHSTy->isVectorType())
4188 return CheckVectorOperands(QuestionLoc, LHS, RHS);
Douglas Gregor898574e2008-12-05 23:32:09 +00004189
Chris Lattner70d67a92008-01-06 22:42:25 +00004190 // If both operands have arithmetic type, do the usual arithmetic conversions
4191 // to find a common type: C99 6.5.15p3,5.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004192 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
4193 UsualArithmeticConversions(LHS, RHS);
4194 return LHS->getType();
Steve Naroffa4332e22007-07-17 00:58:39 +00004195 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004196
Chris Lattner70d67a92008-01-06 22:42:25 +00004197 // If both operands are the same structure or union type, the result is that
4198 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00004199 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
4200 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattnera21ddb32007-11-26 01:40:58 +00004201 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stumpeed9cac2009-02-19 03:04:26 +00004202 // "If both the operands have structure or union type, the result has
Chris Lattner70d67a92008-01-06 22:42:25 +00004203 // that type." This implies that CV qualifiers are dropped.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004204 return LHSTy.getUnqualifiedType();
Eli Friedmanb1d796d2009-03-23 00:24:07 +00004205 // FIXME: Type of conditional expression must be complete in C mode.
Reid Spencer5f016e22007-07-11 17:01:13 +00004206 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004207
Chris Lattner70d67a92008-01-06 22:42:25 +00004208 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffe701c0a2008-05-12 21:44:38 +00004209 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004210 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
4211 if (!LHSTy->isVoidType())
4212 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
4213 << RHS->getSourceRange();
4214 if (!RHSTy->isVoidType())
4215 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
4216 << LHS->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00004217 ImpCastExprToType(LHS, Context.VoidTy, CastExpr::CK_ToVoid);
4218 ImpCastExprToType(RHS, Context.VoidTy, CastExpr::CK_ToVoid);
Eli Friedman0e724012008-06-04 19:47:51 +00004219 return Context.VoidTy;
Steve Naroffe701c0a2008-05-12 21:44:38 +00004220 }
Steve Naroffb6d54e52008-01-08 01:11:38 +00004221 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
4222 // the type of the other operand."
Steve Naroff58f9f2c2009-07-14 18:25:06 +00004223 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
Douglas Gregorce940492009-09-25 04:25:58 +00004224 RHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004225 // promote the null to a pointer.
4226 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_Unknown);
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004227 return LHSTy;
Steve Naroffb6d54e52008-01-08 01:11:38 +00004228 }
Steve Naroff58f9f2c2009-07-14 18:25:06 +00004229 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
Douglas Gregorce940492009-09-25 04:25:58 +00004230 LHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004231 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_Unknown);
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004232 return RHSTy;
Steve Naroffb6d54e52008-01-08 01:11:38 +00004233 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004234
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004235 // All objective-c pointer type analysis is done here.
4236 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
4237 QuestionLoc);
4238 if (!compositeType.isNull())
4239 return compositeType;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004240
4241
Steve Naroff7154a772009-07-01 14:36:47 +00004242 // Handle block pointer types.
4243 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
4244 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
4245 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
4246 QualType destType = Context.getPointerType(Context.VoidTy);
Eli Friedman73c39ab2009-10-20 08:27:19 +00004247 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
4248 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00004249 return destType;
4250 }
4251 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004252 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Steve Naroff7154a772009-07-01 14:36:47 +00004253 return QualType();
Mike Stumpdd3e1662009-05-07 03:14:14 +00004254 }
Steve Naroff7154a772009-07-01 14:36:47 +00004255 // We have 2 block pointer types.
4256 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4257 // Two identical block pointer types are always compatible.
Mike Stumpdd3e1662009-05-07 03:14:14 +00004258 return LHSTy;
4259 }
Steve Naroff7154a772009-07-01 14:36:47 +00004260 // The block pointer types aren't identical, continue checking.
Ted Kremenek6217b802009-07-29 21:53:49 +00004261 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
4262 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004263
Steve Naroff7154a772009-07-01 14:36:47 +00004264 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
4265 rhptee.getUnqualifiedType())) {
Mike Stumpdd3e1662009-05-07 03:14:14 +00004266 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004267 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stumpdd3e1662009-05-07 03:14:14 +00004268 // In this situation, we assume void* type. No especially good
4269 // reason, but this is what gcc does, and we do have to pick
4270 // to get a consistent AST.
4271 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Eli Friedman73c39ab2009-10-20 08:27:19 +00004272 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
4273 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
Mike Stumpdd3e1662009-05-07 03:14:14 +00004274 return incompatTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00004275 }
Steve Naroff7154a772009-07-01 14:36:47 +00004276 // The block pointer types are compatible.
Eli Friedman73c39ab2009-10-20 08:27:19 +00004277 ImpCastExprToType(LHS, LHSTy, CastExpr::CK_BitCast);
4278 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
Steve Naroff91588042009-04-08 17:05:15 +00004279 return LHSTy;
4280 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004281
Steve Naroff7154a772009-07-01 14:36:47 +00004282 // Check constraints for C object pointers types (C99 6.5.15p3,6).
4283 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
4284 // get the "pointed to" types
Ted Kremenek6217b802009-07-29 21:53:49 +00004285 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4286 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff7154a772009-07-01 14:36:47 +00004287
4288 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
4289 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
4290 // Figure out necessary qualifiers (C99 6.5.15p6)
John McCall0953e762009-09-24 19:53:00 +00004291 QualType destPointee
4292 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
Steve Naroff7154a772009-07-01 14:36:47 +00004293 QualType destType = Context.getPointerType(destPointee);
Eli Friedman73c39ab2009-10-20 08:27:19 +00004294 // Add qualifiers if necessary.
4295 ImpCastExprToType(LHS, destType, CastExpr::CK_NoOp);
4296 // Promote to void*.
4297 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00004298 return destType;
4299 }
4300 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
John McCall0953e762009-09-24 19:53:00 +00004301 QualType destPointee
4302 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
Steve Naroff7154a772009-07-01 14:36:47 +00004303 QualType destType = Context.getPointerType(destPointee);
Eli Friedman73c39ab2009-10-20 08:27:19 +00004304 // Add qualifiers if necessary.
Eli Friedman16fea9b2009-11-17 01:22:05 +00004305 ImpCastExprToType(RHS, destType, CastExpr::CK_NoOp);
Eli Friedman73c39ab2009-10-20 08:27:19 +00004306 // Promote to void*.
Eli Friedman16fea9b2009-11-17 01:22:05 +00004307 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00004308 return destType;
4309 }
4310
4311 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4312 // Two identical pointer types are always compatible.
4313 return LHSTy;
4314 }
4315 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
4316 rhptee.getUnqualifiedType())) {
4317 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
4318 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
4319 // In this situation, we assume void* type. No especially good
4320 // reason, but this is what gcc does, and we do have to pick
4321 // to get a consistent AST.
4322 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Eli Friedman73c39ab2009-10-20 08:27:19 +00004323 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
4324 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00004325 return incompatTy;
4326 }
4327 // The pointer types are compatible.
4328 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
4329 // differently qualified versions of compatible types, the result type is
4330 // a pointer to an appropriately qualified version of the *composite*
4331 // type.
4332 // FIXME: Need to calculate the composite type.
4333 // FIXME: Need to add qualifiers
Eli Friedman73c39ab2009-10-20 08:27:19 +00004334 ImpCastExprToType(LHS, LHSTy, CastExpr::CK_BitCast);
4335 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00004336 return LHSTy;
4337 }
Mike Stump1eb44332009-09-09 15:08:12 +00004338
Steve Naroff7154a772009-07-01 14:36:47 +00004339 // GCC compatibility: soften pointer/integer mismatch.
4340 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
4341 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4342 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00004343 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_IntegralToPointer);
Steve Naroff7154a772009-07-01 14:36:47 +00004344 return RHSTy;
4345 }
4346 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
4347 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4348 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00004349 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_IntegralToPointer);
Steve Naroff7154a772009-07-01 14:36:47 +00004350 return LHSTy;
4351 }
Daniel Dunbar5e155f02008-09-11 23:12:46 +00004352
Chris Lattner70d67a92008-01-06 22:42:25 +00004353 // Otherwise, the operands are not compatible.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004354 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
4355 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00004356 return QualType();
4357}
4358
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004359/// FindCompositeObjCPointerType - Helper method to find composite type of
4360/// two objective-c pointer types of the two input expressions.
4361QualType Sema::FindCompositeObjCPointerType(Expr *&LHS, Expr *&RHS,
4362 SourceLocation QuestionLoc) {
4363 QualType LHSTy = LHS->getType();
4364 QualType RHSTy = RHS->getType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004365
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004366 // Handle things like Class and struct objc_class*. Here we case the result
4367 // to the pseudo-builtin, because that will be implicitly cast back to the
4368 // redefinition type if an attempt is made to access its fields.
4369 if (LHSTy->isObjCClassType() &&
4370 (RHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
4371 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
4372 return LHSTy;
4373 }
4374 if (RHSTy->isObjCClassType() &&
4375 (LHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
4376 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
4377 return RHSTy;
4378 }
4379 // And the same for struct objc_object* / id
4380 if (LHSTy->isObjCIdType() &&
4381 (RHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
4382 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
4383 return LHSTy;
4384 }
4385 if (RHSTy->isObjCIdType() &&
4386 (LHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
4387 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
4388 return RHSTy;
4389 }
4390 // And the same for struct objc_selector* / SEL
4391 if (Context.isObjCSelType(LHSTy) &&
4392 (RHSTy.getDesugaredType() == Context.ObjCSelRedefinitionType)) {
4393 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
4394 return LHSTy;
4395 }
4396 if (Context.isObjCSelType(RHSTy) &&
4397 (LHSTy.getDesugaredType() == Context.ObjCSelRedefinitionType)) {
4398 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
4399 return RHSTy;
4400 }
4401 // Check constraints for Objective-C object pointers types.
4402 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004403
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004404 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4405 // Two identical object pointer types are always compatible.
4406 return LHSTy;
4407 }
4408 const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>();
4409 const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>();
4410 QualType compositeType = LHSTy;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004411
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004412 // If both operands are interfaces and either operand can be
4413 // assigned to the other, use that type as the composite
4414 // type. This allows
4415 // xxx ? (A*) a : (B*) b
4416 // where B is a subclass of A.
4417 //
4418 // Additionally, as for assignment, if either type is 'id'
4419 // allow silent coercion. Finally, if the types are
4420 // incompatible then make sure to use 'id' as the composite
4421 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004422
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004423 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
4424 // It could return the composite type.
4425 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
4426 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
4427 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
4428 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
4429 } else if ((LHSTy->isObjCQualifiedIdType() ||
4430 RHSTy->isObjCQualifiedIdType()) &&
4431 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
4432 // Need to handle "id<xx>" explicitly.
4433 // GCC allows qualified id and any Objective-C type to devolve to
4434 // id. Currently localizing to here until clear this should be
4435 // part of ObjCQualifiedIdTypesAreCompatible.
4436 compositeType = Context.getObjCIdType();
4437 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
4438 compositeType = Context.getObjCIdType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004439 } else if (!(compositeType =
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004440 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
4441 ;
4442 else {
4443 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
4444 << LHSTy << RHSTy
4445 << LHS->getSourceRange() << RHS->getSourceRange();
4446 QualType incompatTy = Context.getObjCIdType();
4447 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
4448 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
4449 return incompatTy;
4450 }
4451 // The object pointer types are compatible.
4452 ImpCastExprToType(LHS, compositeType, CastExpr::CK_BitCast);
4453 ImpCastExprToType(RHS, compositeType, CastExpr::CK_BitCast);
4454 return compositeType;
4455 }
4456 // Check Objective-C object pointer types and 'void *'
4457 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
4458 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4459 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4460 QualType destPointee
4461 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4462 QualType destType = Context.getPointerType(destPointee);
4463 // Add qualifiers if necessary.
4464 ImpCastExprToType(LHS, destType, CastExpr::CK_NoOp);
4465 // Promote to void*.
4466 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
4467 return destType;
4468 }
4469 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
4470 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4471 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4472 QualType destPointee
4473 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4474 QualType destType = Context.getPointerType(destPointee);
4475 // Add qualifiers if necessary.
4476 ImpCastExprToType(RHS, destType, CastExpr::CK_NoOp);
4477 // Promote to void*.
4478 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
4479 return destType;
4480 }
4481 return QualType();
4482}
4483
Steve Narofff69936d2007-09-16 03:34:24 +00004484/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Reid Spencer5f016e22007-07-11 17:01:13 +00004485/// in the case of a the GNU conditional expr extension.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004486Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
4487 SourceLocation ColonLoc,
John McCall9ae2f072010-08-23 23:25:46 +00004488 Expr *CondExpr, Expr *LHSExpr,
4489 Expr *RHSExpr) {
Chris Lattnera21ddb32007-11-26 01:40:58 +00004490 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
4491 // was the condition.
4492 bool isLHSNull = LHSExpr == 0;
4493 if (isLHSNull)
4494 LHSExpr = CondExpr;
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004495
4496 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
Chris Lattner26824902007-07-16 21:39:03 +00004497 RHSExpr, QuestionLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00004498 if (result.isNull())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004499 return ExprError();
4500
Douglas Gregor47e1f7c2009-08-26 14:37:04 +00004501 return Owned(new (Context) ConditionalOperator(CondExpr, QuestionLoc,
Steve Naroff6ece14c2009-01-21 00:14:39 +00004502 isLHSNull ? 0 : LHSExpr,
Douglas Gregor47e1f7c2009-08-26 14:37:04 +00004503 ColonLoc, RHSExpr, result));
Reid Spencer5f016e22007-07-11 17:01:13 +00004504}
4505
Reid Spencer5f016e22007-07-11 17:01:13 +00004506// CheckPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stumpeed9cac2009-02-19 03:04:26 +00004507// being closely modeled after the C99 spec:-). The odd characteristic of this
Reid Spencer5f016e22007-07-11 17:01:13 +00004508// routine is it effectively iqnores the qualifiers on the top level pointee.
4509// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
4510// FIXME: add a couple examples in this comment.
Mike Stumpeed9cac2009-02-19 03:04:26 +00004511Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00004512Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
4513 QualType lhptee, rhptee;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004514
David Chisnall0f436562009-08-17 16:35:33 +00004515 if ((lhsType->isObjCClassType() &&
4516 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
4517 (rhsType->isObjCClassType() &&
4518 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
4519 return Compatible;
4520 }
4521
Reid Spencer5f016e22007-07-11 17:01:13 +00004522 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenek6217b802009-07-29 21:53:49 +00004523 lhptee = lhsType->getAs<PointerType>()->getPointeeType();
4524 rhptee = rhsType->getAs<PointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004525
Reid Spencer5f016e22007-07-11 17:01:13 +00004526 // make sure we operate on the canonical type
Chris Lattnerb77792e2008-07-26 22:17:49 +00004527 lhptee = Context.getCanonicalType(lhptee);
4528 rhptee = Context.getCanonicalType(rhptee);
Reid Spencer5f016e22007-07-11 17:01:13 +00004529
Chris Lattner5cf216b2008-01-04 18:04:52 +00004530 AssignConvertType ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004531
4532 // C99 6.5.16.1p1: This following citation is common to constraints
4533 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
4534 // qualifiers of the type *pointed to* by the right;
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00004535 // FIXME: Handle ExtQualType
Douglas Gregor98cd5992008-10-21 23:43:52 +00004536 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner5cf216b2008-01-04 18:04:52 +00004537 ConvTy = CompatiblePointerDiscardsQualifiers;
Reid Spencer5f016e22007-07-11 17:01:13 +00004538
Mike Stumpeed9cac2009-02-19 03:04:26 +00004539 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
4540 // incomplete type and the other is a pointer to a qualified or unqualified
Reid Spencer5f016e22007-07-11 17:01:13 +00004541 // version of void...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00004542 if (lhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00004543 if (rhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00004544 return ConvTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004545
Chris Lattnerbfe639e2008-01-03 22:56:36 +00004546 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00004547 assert(rhptee->isFunctionType());
4548 return FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00004549 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004550
Chris Lattnerbfe639e2008-01-03 22:56:36 +00004551 if (rhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00004552 if (lhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00004553 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00004554
4555 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00004556 assert(lhptee->isFunctionType());
4557 return FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00004558 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004559 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Reid Spencer5f016e22007-07-11 17:01:13 +00004560 // unqualified versions of compatible types, ...
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004561 lhptee = lhptee.getUnqualifiedType();
4562 rhptee = rhptee.getUnqualifiedType();
4563 if (!Context.typesAreCompatible(lhptee, rhptee)) {
4564 // Check if the pointee types are compatible ignoring the sign.
4565 // We explicitly check for char so that we catch "char" vs
4566 // "unsigned char" on systems where "char" is unsigned.
Chris Lattner6a2b9262009-10-17 20:33:28 +00004567 if (lhptee->isCharType())
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004568 lhptee = Context.UnsignedCharTy;
Douglas Gregorf6094622010-07-23 15:58:24 +00004569 else if (lhptee->hasSignedIntegerRepresentation())
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004570 lhptee = Context.getCorrespondingUnsignedType(lhptee);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004571
Chris Lattner6a2b9262009-10-17 20:33:28 +00004572 if (rhptee->isCharType())
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004573 rhptee = Context.UnsignedCharTy;
Douglas Gregorf6094622010-07-23 15:58:24 +00004574 else if (rhptee->hasSignedIntegerRepresentation())
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004575 rhptee = Context.getCorrespondingUnsignedType(rhptee);
Chris Lattner6a2b9262009-10-17 20:33:28 +00004576
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004577 if (lhptee == rhptee) {
4578 // Types are compatible ignoring the sign. Qualifier incompatibility
4579 // takes priority over sign incompatibility because the sign
4580 // warning can be disabled.
4581 if (ConvTy != Compatible)
4582 return ConvTy;
4583 return IncompatiblePointerSign;
4584 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004585
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00004586 // If we are a multi-level pointer, it's possible that our issue is simply
4587 // one of qualification - e.g. char ** -> const char ** is not allowed. If
4588 // the eventual target type is the same and the pointers have the same
4589 // level of indirection, this must be the issue.
4590 if (lhptee->isPointerType() && rhptee->isPointerType()) {
4591 do {
4592 lhptee = lhptee->getAs<PointerType>()->getPointeeType();
4593 rhptee = rhptee->getAs<PointerType>()->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004594
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00004595 lhptee = Context.getCanonicalType(lhptee);
4596 rhptee = Context.getCanonicalType(rhptee);
4597 } while (lhptee->isPointerType() && rhptee->isPointerType());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004598
Douglas Gregora4923eb2009-11-16 21:35:15 +00004599 if (Context.hasSameUnqualifiedType(lhptee, rhptee))
Sean Huntc9132b62009-11-08 07:46:34 +00004600 return IncompatibleNestedPointerQualifiers;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00004601 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004602
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004603 // General pointer incompatibility takes priority over qualifiers.
Mike Stump1eb44332009-09-09 15:08:12 +00004604 return IncompatiblePointer;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004605 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00004606 return ConvTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00004607}
4608
Steve Naroff1c7d0672008-09-04 15:10:53 +00004609/// CheckBlockPointerTypesForAssignment - This routine determines whether two
4610/// block pointer types are compatible or whether a block and normal pointer
4611/// are compatible. It is more restrict than comparing two function pointer
4612// types.
Mike Stumpeed9cac2009-02-19 03:04:26 +00004613Sema::AssignConvertType
4614Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
Steve Naroff1c7d0672008-09-04 15:10:53 +00004615 QualType rhsType) {
4616 QualType lhptee, rhptee;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004617
Steve Naroff1c7d0672008-09-04 15:10:53 +00004618 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenek6217b802009-07-29 21:53:49 +00004619 lhptee = lhsType->getAs<BlockPointerType>()->getPointeeType();
4620 rhptee = rhsType->getAs<BlockPointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004621
Steve Naroff1c7d0672008-09-04 15:10:53 +00004622 // make sure we operate on the canonical type
4623 lhptee = Context.getCanonicalType(lhptee);
4624 rhptee = Context.getCanonicalType(rhptee);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004625
Steve Naroff1c7d0672008-09-04 15:10:53 +00004626 AssignConvertType ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004627
Steve Naroff1c7d0672008-09-04 15:10:53 +00004628 // For blocks we enforce that qualifiers are identical.
Douglas Gregora4923eb2009-11-16 21:35:15 +00004629 if (lhptee.getLocalCVRQualifiers() != rhptee.getLocalCVRQualifiers())
Steve Naroff1c7d0672008-09-04 15:10:53 +00004630 ConvTy = CompatiblePointerDiscardsQualifiers;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004631
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004632 if (!getLangOptions().CPlusPlus) {
4633 if (!Context.typesAreBlockPointerCompatible(lhsType, rhsType))
4634 return IncompatibleBlockPointer;
4635 }
4636 else if (!Context.typesAreCompatible(lhptee, rhptee))
Mike Stumpeed9cac2009-02-19 03:04:26 +00004637 return IncompatibleBlockPointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00004638 return ConvTy;
4639}
4640
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00004641/// CheckObjCPointerTypesForAssignment - Compares two objective-c pointer types
4642/// for assignment compatibility.
4643Sema::AssignConvertType
4644Sema::CheckObjCPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00004645 if (lhsType->isObjCBuiltinType()) {
4646 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian528adb12010-03-24 21:00:27 +00004647 if (lhsType->isObjCClassType() && !rhsType->isObjCBuiltinType() &&
4648 !rhsType->isObjCQualifiedClassType())
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00004649 return IncompatiblePointer;
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00004650 return Compatible;
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00004651 }
4652 if (rhsType->isObjCBuiltinType()) {
4653 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian528adb12010-03-24 21:00:27 +00004654 if (rhsType->isObjCClassType() && !lhsType->isObjCBuiltinType() &&
4655 !lhsType->isObjCQualifiedClassType())
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00004656 return IncompatiblePointer;
4657 return Compatible;
4658 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004659 QualType lhptee =
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00004660 lhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004661 QualType rhptee =
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00004662 rhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
4663 // make sure we operate on the canonical type
4664 lhptee = Context.getCanonicalType(lhptee);
4665 rhptee = Context.getCanonicalType(rhptee);
4666 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
4667 return CompatiblePointerDiscardsQualifiers;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004668
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00004669 if (Context.typesAreCompatible(lhsType, rhsType))
4670 return Compatible;
4671 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
4672 return IncompatibleObjCQualifiedId;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004673 return IncompatiblePointer;
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00004674}
4675
Mike Stumpeed9cac2009-02-19 03:04:26 +00004676/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
4677/// has code to accommodate several GCC extensions when type checking
Reid Spencer5f016e22007-07-11 17:01:13 +00004678/// pointers. Here are some objectionable examples that GCC considers warnings:
4679///
4680/// int a, *pint;
4681/// short *pshort;
4682/// struct foo *pfoo;
4683///
4684/// pint = pshort; // warning: assignment from incompatible pointer type
4685/// a = pint; // warning: assignment makes integer from pointer without a cast
4686/// pint = a; // warning: assignment makes pointer from integer without a cast
4687/// pint = pfoo; // warning: assignment from incompatible pointer type
4688///
4689/// As a result, the code for dealing with pointers is more complex than the
Mike Stumpeed9cac2009-02-19 03:04:26 +00004690/// C99 spec dictates.
Reid Spencer5f016e22007-07-11 17:01:13 +00004691///
Chris Lattner5cf216b2008-01-04 18:04:52 +00004692Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00004693Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattnerfc144e22008-01-04 23:18:45 +00004694 // Get canonical types. We're not formatting these types, just comparing
4695 // them.
Chris Lattnerb77792e2008-07-26 22:17:49 +00004696 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
4697 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedmanf8f873d2008-05-30 18:07:22 +00004698
4699 if (lhsType == rhsType)
Chris Lattnerd2656dd2008-01-07 17:51:46 +00004700 return Compatible; // Common case: fast path an exact match.
Steve Naroff700204c2007-07-24 21:46:40 +00004701
David Chisnall0f436562009-08-17 16:35:33 +00004702 if ((lhsType->isObjCClassType() &&
4703 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
4704 (rhsType->isObjCClassType() &&
4705 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
4706 return Compatible;
4707 }
4708
Douglas Gregor9d293df2008-10-28 00:22:11 +00004709 // If the left-hand side is a reference type, then we are in a
4710 // (rare!) case where we've allowed the use of references in C,
4711 // e.g., as a parameter type in a built-in function. In this case,
4712 // just make sure that the type referenced is compatible with the
4713 // right-hand side type. The caller is responsible for adjusting
4714 // lhsType so that the resulting expression does not have reference
4715 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00004716 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
Douglas Gregor9d293df2008-10-28 00:22:11 +00004717 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlsson793680e2007-10-12 23:56:29 +00004718 return Compatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00004719 return Incompatible;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00004720 }
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004721 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
4722 // to the same ExtVector type.
4723 if (lhsType->isExtVectorType()) {
4724 if (rhsType->isExtVectorType())
4725 return lhsType == rhsType ? Compatible : Incompatible;
Douglas Gregor00619622010-06-22 23:41:02 +00004726 if (rhsType->isArithmeticType())
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004727 return Compatible;
4728 }
Mike Stump1eb44332009-09-09 15:08:12 +00004729
Nate Begemanbe2341d2008-07-14 18:02:46 +00004730 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Douglas Gregor255210e2010-08-06 10:14:59 +00004731 if (lhsType->isVectorType() && rhsType->isVectorType()) {
4732 // If we are allowing lax vector conversions, and LHS and RHS are both
4733 // vectors, the total size only needs to be the same. This is a bitcast;
4734 // no bits are changed but the result type is different.
4735 if (getLangOptions().LaxVectorConversions &&
4736 (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType)))
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00004737 return IncompatibleVectors;
Douglas Gregor255210e2010-08-06 10:14:59 +00004738
4739 // Allow assignments of an AltiVec vector type to an equivalent GCC
4740 // vector type and vice versa
4741 if (Context.areCompatibleVectorTypes(lhsType, rhsType))
4742 return Compatible;
Chris Lattnere8b3e962008-01-04 23:32:24 +00004743 }
4744 return Incompatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004745 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00004746
Douglas Gregor88623ad2010-05-23 21:53:47 +00004747 if (lhsType->isArithmeticType() && rhsType->isArithmeticType() &&
4748 !(getLangOptions().CPlusPlus && lhsType->isEnumeralType()))
Reid Spencer5f016e22007-07-11 17:01:13 +00004749 return Compatible;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00004750
Chris Lattner78eca282008-04-07 06:49:41 +00004751 if (isa<PointerType>(lhsType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00004752 if (rhsType->isIntegerType())
Chris Lattnerb7b61152008-01-04 18:22:42 +00004753 return IntToPointer;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00004754
Chris Lattner78eca282008-04-07 06:49:41 +00004755 if (isa<PointerType>(rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00004756 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004757
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004758 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff14108da2009-07-10 23:34:53 +00004759 if (isa<ObjCObjectPointerType>(rhsType)) {
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004760 if (lhsType->isVoidPointerType()) // an exception to the rule.
4761 return Compatible;
4762 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00004763 }
Ted Kremenek6217b802009-07-29 21:53:49 +00004764 if (rhsType->getAs<BlockPointerType>()) {
4765 if (lhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00004766 return Compatible;
Steve Naroffb4406862008-09-29 18:10:17 +00004767
4768 // Treat block pointers as objects.
Steve Naroff14108da2009-07-10 23:34:53 +00004769 if (getLangOptions().ObjC1 && lhsType->isObjCIdType())
Steve Naroffb4406862008-09-29 18:10:17 +00004770 return Compatible;
4771 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00004772 return Incompatible;
4773 }
4774
4775 if (isa<BlockPointerType>(lhsType)) {
4776 if (rhsType->isIntegerType())
Eli Friedmand8f4f432009-02-25 04:20:42 +00004777 return IntToBlockPointer;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004778
Steve Naroffb4406862008-09-29 18:10:17 +00004779 // Treat block pointers as objects.
Steve Naroff14108da2009-07-10 23:34:53 +00004780 if (getLangOptions().ObjC1 && rhsType->isObjCIdType())
Steve Naroffb4406862008-09-29 18:10:17 +00004781 return Compatible;
4782
Steve Naroff1c7d0672008-09-04 15:10:53 +00004783 if (rhsType->isBlockPointerType())
4784 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004785
Ted Kremenek6217b802009-07-29 21:53:49 +00004786 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff1c7d0672008-09-04 15:10:53 +00004787 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00004788 return Compatible;
Steve Naroff1c7d0672008-09-04 15:10:53 +00004789 }
Chris Lattnerfc144e22008-01-04 23:18:45 +00004790 return Incompatible;
4791 }
4792
Steve Naroff14108da2009-07-10 23:34:53 +00004793 if (isa<ObjCObjectPointerType>(lhsType)) {
4794 if (rhsType->isIntegerType())
4795 return IntToPointer;
Mike Stump1eb44332009-09-09 15:08:12 +00004796
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004797 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff14108da2009-07-10 23:34:53 +00004798 if (isa<PointerType>(rhsType)) {
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004799 if (rhsType->isVoidPointerType()) // an exception to the rule.
4800 return Compatible;
4801 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00004802 }
4803 if (rhsType->isObjCObjectPointerType()) {
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00004804 return CheckObjCPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff14108da2009-07-10 23:34:53 +00004805 }
Ted Kremenek6217b802009-07-29 21:53:49 +00004806 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00004807 if (RHSPT->getPointeeType()->isVoidType())
4808 return Compatible;
4809 }
4810 // Treat block pointers as objects.
4811 if (rhsType->isBlockPointerType())
4812 return Compatible;
4813 return Incompatible;
4814 }
Chris Lattner78eca282008-04-07 06:49:41 +00004815 if (isa<PointerType>(rhsType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00004816 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedmanf8f873d2008-05-30 18:07:22 +00004817 if (lhsType == Context.BoolTy)
4818 return Compatible;
4819
4820 if (lhsType->isIntegerType())
Chris Lattnerb7b61152008-01-04 18:22:42 +00004821 return PointerToInt;
Reid Spencer5f016e22007-07-11 17:01:13 +00004822
Mike Stumpeed9cac2009-02-19 03:04:26 +00004823 if (isa<PointerType>(lhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00004824 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004825
4826 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenek6217b802009-07-29 21:53:49 +00004827 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00004828 return Compatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00004829 return Incompatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00004830 }
Steve Naroff14108da2009-07-10 23:34:53 +00004831 if (isa<ObjCObjectPointerType>(rhsType)) {
4832 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
4833 if (lhsType == Context.BoolTy)
4834 return Compatible;
4835
4836 if (lhsType->isIntegerType())
4837 return PointerToInt;
4838
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004839 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff14108da2009-07-10 23:34:53 +00004840 if (isa<PointerType>(lhsType)) {
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004841 if (lhsType->isVoidPointerType()) // an exception to the rule.
4842 return Compatible;
4843 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00004844 }
4845 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenek6217b802009-07-29 21:53:49 +00004846 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Steve Naroff14108da2009-07-10 23:34:53 +00004847 return Compatible;
4848 return Incompatible;
4849 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00004850
Chris Lattnerfc144e22008-01-04 23:18:45 +00004851 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner78eca282008-04-07 06:49:41 +00004852 if (Context.typesAreCompatible(lhsType, rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00004853 return Compatible;
Reid Spencer5f016e22007-07-11 17:01:13 +00004854 }
4855 return Incompatible;
4856}
4857
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004858/// \brief Constructs a transparent union from an expression that is
4859/// used to initialize the transparent union.
Mike Stump1eb44332009-09-09 15:08:12 +00004860static void ConstructTransparentUnion(ASTContext &C, Expr *&E,
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004861 QualType UnionType, FieldDecl *Field) {
4862 // Build an initializer list that designates the appropriate member
4863 // of the transparent union.
Ted Kremenek709210f2010-04-13 23:39:13 +00004864 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
Ted Kremenekba7bc552010-02-19 01:50:18 +00004865 &E, 1,
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004866 SourceLocation());
4867 Initializer->setType(UnionType);
4868 Initializer->setInitializedFieldInUnion(Field);
4869
4870 // Build a compound literal constructing a value of the transparent
4871 // union type from this initializer list.
John McCall42f56b52010-01-18 19:35:47 +00004872 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John McCall1d7d8d62010-01-19 22:33:45 +00004873 E = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
John McCall42f56b52010-01-18 19:35:47 +00004874 Initializer, false);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004875}
4876
4877Sema::AssignConvertType
4878Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) {
4879 QualType FromType = rExpr->getType();
4880
Mike Stump1eb44332009-09-09 15:08:12 +00004881 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004882 // transparent_union GCC extension.
4883 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00004884 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004885 return Incompatible;
4886
4887 // The field to initialize within the transparent union.
4888 RecordDecl *UD = UT->getDecl();
4889 FieldDecl *InitField = 0;
4890 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004891 for (RecordDecl::field_iterator it = UD->field_begin(),
4892 itend = UD->field_end();
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004893 it != itend; ++it) {
4894 if (it->getType()->isPointerType()) {
4895 // If the transparent union contains a pointer type, we allow:
4896 // 1) void pointer
4897 // 2) null pointer constant
4898 if (FromType->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +00004899 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004900 ImpCastExprToType(rExpr, it->getType(), CastExpr::CK_BitCast);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004901 InitField = *it;
4902 break;
4903 }
Mike Stump1eb44332009-09-09 15:08:12 +00004904
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004905 if (rExpr->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00004906 Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004907 ImpCastExprToType(rExpr, it->getType(), CastExpr::CK_IntegralToPointer);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004908 InitField = *it;
4909 break;
4910 }
4911 }
4912
4913 if (CheckAssignmentConstraints(it->getType(), rExpr->getType())
4914 == Compatible) {
4915 InitField = *it;
4916 break;
4917 }
4918 }
4919
4920 if (!InitField)
4921 return Incompatible;
4922
4923 ConstructTransparentUnion(Context, rExpr, ArgType, InitField);
4924 return Compatible;
4925}
4926
Chris Lattner5cf216b2008-01-04 18:04:52 +00004927Sema::AssignConvertType
Steve Naroff90045e82007-07-13 23:32:42 +00004928Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00004929 if (getLangOptions().CPlusPlus) {
4930 if (!lhsType->isRecordType()) {
4931 // C++ 5.17p3: If the left operand is not of class type, the
4932 // expression is implicitly converted (C++ 4) to the
4933 // cv-unqualified type of the left operand.
Douglas Gregor45920e82008-12-19 17:40:08 +00004934 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
Douglas Gregor68647482009-12-16 03:45:30 +00004935 AA_Assigning))
Douglas Gregor98cd5992008-10-21 23:43:52 +00004936 return Incompatible;
Chris Lattner2c4463f2009-04-12 09:02:39 +00004937 return Compatible;
Douglas Gregor98cd5992008-10-21 23:43:52 +00004938 }
4939
4940 // FIXME: Currently, we fall through and treat C++ classes like C
4941 // structures.
4942 }
4943
Steve Naroff529a4ad2007-11-27 17:58:44 +00004944 // C99 6.5.16.1p1: the left operand is a pointer and the right is
4945 // a null pointer constant.
Mike Stump1eb44332009-09-09 15:08:12 +00004946 if ((lhsType->isPointerType() ||
4947 lhsType->isObjCObjectPointerType() ||
Mike Stumpeed9cac2009-02-19 03:04:26 +00004948 lhsType->isBlockPointerType())
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004949 && rExpr->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00004950 Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004951 ImpCastExprToType(rExpr, lhsType, CastExpr::CK_Unknown);
Steve Naroff529a4ad2007-11-27 17:58:44 +00004952 return Compatible;
4953 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004954
Chris Lattner943140e2007-10-16 02:55:40 +00004955 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroff90045e82007-07-13 23:32:42 +00004956 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregor02a24ee2009-11-03 16:56:39 +00004957 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Nick Lewyckyc133e9e2010-08-05 06:27:49 +00004958 // expressions that suppress this implicit conversion (&, sizeof).
Chris Lattner943140e2007-10-16 02:55:40 +00004959 //
Mike Stumpeed9cac2009-02-19 03:04:26 +00004960 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner943140e2007-10-16 02:55:40 +00004961 if (!lhsType->isReferenceType())
Douglas Gregora873dfc2010-02-03 00:27:59 +00004962 DefaultFunctionArrayLvalueConversion(rExpr);
Steve Narofff1120de2007-08-24 22:33:52 +00004963
Chris Lattner5cf216b2008-01-04 18:04:52 +00004964 Sema::AssignConvertType result =
4965 CheckAssignmentConstraints(lhsType, rExpr->getType());
Mike Stumpeed9cac2009-02-19 03:04:26 +00004966
Steve Narofff1120de2007-08-24 22:33:52 +00004967 // C99 6.5.16.1p2: The value of the right operand is converted to the
4968 // type of the assignment expression.
Douglas Gregor9d293df2008-10-28 00:22:11 +00004969 // CheckAssignmentConstraints allows the left-hand side to be a reference,
4970 // so that we can use references in built-in functions even in C.
4971 // The getNonReferenceType() call makes sure that the resulting expression
4972 // does not have reference type.
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004973 if (result != Incompatible && rExpr->getType() != lhsType)
Douglas Gregor63982352010-07-13 18:40:04 +00004974 ImpCastExprToType(rExpr, lhsType.getNonLValueExprType(Context),
Eli Friedman73c39ab2009-10-20 08:27:19 +00004975 CastExpr::CK_Unknown);
Steve Narofff1120de2007-08-24 22:33:52 +00004976 return result;
Steve Naroff90045e82007-07-13 23:32:42 +00004977}
4978
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004979QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004980 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattner22caddc2008-11-23 09:13:29 +00004981 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004982 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerca5eede2007-12-12 05:47:28 +00004983 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00004984}
4985
Chris Lattner7ef655a2010-01-12 21:23:57 +00004986QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00004987 // For conversion purposes, we ignore any qualifiers.
Nate Begeman1330b0e2008-04-04 01:30:25 +00004988 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +00004989 QualType lhsType =
4990 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
4991 QualType rhsType =
4992 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004993
Nate Begemanbe2341d2008-07-14 18:02:46 +00004994 // If the vector types are identical, return.
Nate Begeman1330b0e2008-04-04 01:30:25 +00004995 if (lhsType == rhsType)
Reid Spencer5f016e22007-07-11 17:01:13 +00004996 return lhsType;
Nate Begeman4119d1a2007-12-30 02:59:45 +00004997
Nate Begemanbe2341d2008-07-14 18:02:46 +00004998 // Handle the case of a vector & extvector type of the same size and element
4999 // type. It would be nice if we only had one vector type someday.
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00005000 if (getLangOptions().LaxVectorConversions) {
5001 // FIXME: Should we warn here?
John McCall183700f2009-09-21 23:43:11 +00005002 if (const VectorType *LV = lhsType->getAs<VectorType>()) {
5003 if (const VectorType *RV = rhsType->getAs<VectorType>())
Nate Begemanbe2341d2008-07-14 18:02:46 +00005004 if (LV->getElementType() == RV->getElementType() &&
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00005005 LV->getNumElements() == RV->getNumElements()) {
Douglas Gregor26bcf672010-05-19 03:21:00 +00005006 if (lhsType->isExtVectorType()) {
5007 ImpCastExprToType(rex, lhsType, CastExpr::CK_BitCast);
5008 return lhsType;
5009 }
5010
5011 ImpCastExprToType(lex, rhsType, CastExpr::CK_BitCast);
5012 return rhsType;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00005013 }
5014 }
5015 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005016
Douglas Gregor255210e2010-08-06 10:14:59 +00005017 // Handle the case of equivalent AltiVec and GCC vector types
5018 if (lhsType->isVectorType() && rhsType->isVectorType() &&
5019 Context.areCompatibleVectorTypes(lhsType, rhsType)) {
5020 ImpCastExprToType(lex, rhsType, CastExpr::CK_BitCast);
5021 return rhsType;
5022 }
5023
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005024 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
5025 // swap back (so that we don't reverse the inputs to a subtract, for instance.
5026 bool swapped = false;
5027 if (rhsType->isExtVectorType()) {
5028 swapped = true;
5029 std::swap(rex, lex);
5030 std::swap(rhsType, lhsType);
5031 }
Mike Stump1eb44332009-09-09 15:08:12 +00005032
Nate Begemandde25982009-06-28 19:12:57 +00005033 // Handle the case of an ext vector and scalar.
John McCall183700f2009-09-21 23:43:11 +00005034 if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) {
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005035 QualType EltTy = LV->getElementType();
Douglas Gregor9d3347a2010-06-16 00:35:25 +00005036 if (EltTy->isIntegralType(Context) && rhsType->isIntegralType(Context)) {
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005037 if (Context.getIntegerTypeOrder(EltTy, rhsType) >= 0) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00005038 ImpCastExprToType(rex, lhsType, CastExpr::CK_IntegralCast);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005039 if (swapped) std::swap(rex, lex);
5040 return lhsType;
5041 }
5042 }
5043 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
5044 rhsType->isRealFloatingType()) {
5045 if (Context.getFloatingTypeOrder(EltTy, rhsType) >= 0) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00005046 ImpCastExprToType(rex, lhsType, CastExpr::CK_FloatingCast);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005047 if (swapped) std::swap(rex, lex);
5048 return lhsType;
5049 }
Nate Begeman4119d1a2007-12-30 02:59:45 +00005050 }
5051 }
Mike Stump1eb44332009-09-09 15:08:12 +00005052
Nate Begemandde25982009-06-28 19:12:57 +00005053 // Vectors of different size or scalar and non-ext-vector are errors.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00005054 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattnerd1625842008-11-24 06:25:27 +00005055 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00005056 << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00005057 return QualType();
Sebastian Redl22460502009-02-07 00:15:38 +00005058}
5059
Chris Lattner7ef655a2010-01-12 21:23:57 +00005060QualType Sema::CheckMultiplyDivideOperands(
5061 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign, bool isDiv) {
Daniel Dunbar69d1d002009-01-05 22:42:10 +00005062 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005063 return CheckVectorOperands(Loc, lex, rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005064
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00005065 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005066
Chris Lattner7ef655a2010-01-12 21:23:57 +00005067 if (!lex->getType()->isArithmeticType() ||
5068 !rex->getType()->isArithmeticType())
5069 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005070
Chris Lattner7ef655a2010-01-12 21:23:57 +00005071 // Check for division by zero.
5072 if (isDiv &&
5073 rex->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005074 DiagRuntimeBehavior(Loc, PDiag(diag::warn_division_by_zero)
Chris Lattnercb329c52010-01-12 21:30:55 +00005075 << rex->getSourceRange());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005076
Chris Lattner7ef655a2010-01-12 21:23:57 +00005077 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00005078}
5079
Chris Lattner7ef655a2010-01-12 21:23:57 +00005080QualType Sema::CheckRemainderOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00005081 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Daniel Dunbar523aa602009-01-05 22:55:36 +00005082 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
Douglas Gregorf6094622010-07-23 15:58:24 +00005083 if (lex->getType()->hasIntegerRepresentation() &&
5084 rex->getType()->hasIntegerRepresentation())
Daniel Dunbar523aa602009-01-05 22:55:36 +00005085 return CheckVectorOperands(Loc, lex, rex);
5086 return InvalidOperands(Loc, lex, rex);
5087 }
Steve Naroff90045e82007-07-13 23:32:42 +00005088
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00005089 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005090
Chris Lattner7ef655a2010-01-12 21:23:57 +00005091 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
5092 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005093
Chris Lattner7ef655a2010-01-12 21:23:57 +00005094 // Check for remainder by zero.
5095 if (rex->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
Chris Lattnercb329c52010-01-12 21:30:55 +00005096 DiagRuntimeBehavior(Loc, PDiag(diag::warn_remainder_by_zero)
5097 << rex->getSourceRange());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005098
Chris Lattner7ef655a2010-01-12 21:23:57 +00005099 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00005100}
5101
Chris Lattner7ef655a2010-01-12 21:23:57 +00005102QualType Sema::CheckAdditionOperands( // C99 6.5.6
Mike Stump1eb44332009-09-09 15:08:12 +00005103 Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00005104 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
5105 QualType compType = CheckVectorOperands(Loc, lex, rex);
5106 if (CompLHSTy) *CompLHSTy = compType;
5107 return compType;
5108 }
Steve Naroff49b45262007-07-13 16:58:59 +00005109
Eli Friedmanab3a8522009-03-28 01:22:36 +00005110 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Eli Friedmand72d16e2008-05-18 18:08:51 +00005111
Reid Spencer5f016e22007-07-11 17:01:13 +00005112 // handle the common case first (both operands are arithmetic).
Eli Friedmanab3a8522009-03-28 01:22:36 +00005113 if (lex->getType()->isArithmeticType() &&
5114 rex->getType()->isArithmeticType()) {
5115 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00005116 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00005117 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005118
Eli Friedmand72d16e2008-05-18 18:08:51 +00005119 // Put any potential pointer into PExp
5120 Expr* PExp = lex, *IExp = rex;
Steve Naroff58f9f2c2009-07-14 18:25:06 +00005121 if (IExp->getType()->isAnyPointerType())
Eli Friedmand72d16e2008-05-18 18:08:51 +00005122 std::swap(PExp, IExp);
5123
Steve Naroff58f9f2c2009-07-14 18:25:06 +00005124 if (PExp->getType()->isAnyPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00005125
Eli Friedmand72d16e2008-05-18 18:08:51 +00005126 if (IExp->getType()->isIntegerType()) {
Steve Naroff760e3c42009-07-13 21:20:41 +00005127 QualType PointeeTy = PExp->getType()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00005128
Chris Lattnerb5f15622009-04-24 23:50:08 +00005129 // Check for arithmetic on pointers to incomplete types.
5130 if (PointeeTy->isVoidType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +00005131 if (getLangOptions().CPlusPlus) {
5132 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005133 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor4ec339f2009-01-19 19:26:10 +00005134 return QualType();
Eli Friedmand72d16e2008-05-18 18:08:51 +00005135 }
Douglas Gregore7450f52009-03-24 19:52:54 +00005136
5137 // GNU extension: arithmetic on pointer to void
5138 Diag(Loc, diag::ext_gnu_void_ptr)
5139 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerb5f15622009-04-24 23:50:08 +00005140 } else if (PointeeTy->isFunctionType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +00005141 if (getLangOptions().CPlusPlus) {
5142 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
5143 << lex->getType() << lex->getSourceRange();
5144 return QualType();
5145 }
5146
5147 // GNU extension: arithmetic on pointer to function
5148 Diag(Loc, diag::ext_gnu_ptr_func_arith)
5149 << lex->getType() << lex->getSourceRange();
Steve Naroff9deaeca2009-07-13 21:32:29 +00005150 } else {
Steve Naroff760e3c42009-07-13 21:20:41 +00005151 // Check if we require a complete type.
Mike Stump1eb44332009-09-09 15:08:12 +00005152 if (((PExp->getType()->isPointerType() &&
Steve Naroff9deaeca2009-07-13 21:32:29 +00005153 !PExp->getType()->isDependentType()) ||
Steve Naroff760e3c42009-07-13 21:20:41 +00005154 PExp->getType()->isObjCObjectPointerType()) &&
5155 RequireCompleteType(Loc, PointeeTy,
Mike Stump1eb44332009-09-09 15:08:12 +00005156 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
5157 << PExp->getSourceRange()
Anders Carlssond497ba72009-08-26 22:59:12 +00005158 << PExp->getType()))
Steve Naroff760e3c42009-07-13 21:20:41 +00005159 return QualType();
5160 }
Chris Lattnerb5f15622009-04-24 23:50:08 +00005161 // Diagnose bad cases where we step over interface counts.
John McCallc12c5bb2010-05-15 11:32:37 +00005162 if (PointeeTy->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattnerb5f15622009-04-24 23:50:08 +00005163 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
5164 << PointeeTy << PExp->getSourceRange();
5165 return QualType();
5166 }
Mike Stump1eb44332009-09-09 15:08:12 +00005167
Eli Friedmanab3a8522009-03-28 01:22:36 +00005168 if (CompLHSTy) {
Eli Friedman04e83572009-08-20 04:21:42 +00005169 QualType LHSTy = Context.isPromotableBitField(lex);
5170 if (LHSTy.isNull()) {
5171 LHSTy = lex->getType();
5172 if (LHSTy->isPromotableIntegerType())
5173 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregor2d833e32009-05-02 00:36:19 +00005174 }
Eli Friedmanab3a8522009-03-28 01:22:36 +00005175 *CompLHSTy = LHSTy;
5176 }
Eli Friedmand72d16e2008-05-18 18:08:51 +00005177 return PExp->getType();
5178 }
5179 }
5180
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005181 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00005182}
5183
Chris Lattnereca7be62008-04-07 05:30:13 +00005184// C99 6.5.6
5185QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Eli Friedmanab3a8522009-03-28 01:22:36 +00005186 SourceLocation Loc, QualType* CompLHSTy) {
5187 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
5188 QualType compType = CheckVectorOperands(Loc, lex, rex);
5189 if (CompLHSTy) *CompLHSTy = compType;
5190 return compType;
5191 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005192
Eli Friedmanab3a8522009-03-28 01:22:36 +00005193 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005194
Chris Lattner6e4ab612007-12-09 21:53:25 +00005195 // Enforce type constraints: C99 6.5.6p3.
Mike Stumpeed9cac2009-02-19 03:04:26 +00005196
Chris Lattner6e4ab612007-12-09 21:53:25 +00005197 // Handle the common case first (both operands are arithmetic).
Mike Stumpaf199f32009-05-07 18:43:07 +00005198 if (lex->getType()->isArithmeticType()
5199 && rex->getType()->isArithmeticType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00005200 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00005201 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00005202 }
Mike Stump1eb44332009-09-09 15:08:12 +00005203
Chris Lattner6e4ab612007-12-09 21:53:25 +00005204 // Either ptr - int or ptr - ptr.
Steve Naroff58f9f2c2009-07-14 18:25:06 +00005205 if (lex->getType()->isAnyPointerType()) {
Steve Naroff430ee5a2009-07-13 17:19:15 +00005206 QualType lpointee = lex->getType()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005207
Douglas Gregore7450f52009-03-24 19:52:54 +00005208 // The LHS must be an completely-defined object type.
Douglas Gregorc983b862009-01-23 00:36:41 +00005209
Douglas Gregore7450f52009-03-24 19:52:54 +00005210 bool ComplainAboutVoid = false;
5211 Expr *ComplainAboutFunc = 0;
5212 if (lpointee->isVoidType()) {
5213 if (getLangOptions().CPlusPlus) {
5214 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
5215 << lex->getSourceRange() << rex->getSourceRange();
5216 return QualType();
5217 }
5218
5219 // GNU C extension: arithmetic on pointer to void
5220 ComplainAboutVoid = true;
5221 } else if (lpointee->isFunctionType()) {
5222 if (getLangOptions().CPlusPlus) {
5223 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattnerd1625842008-11-24 06:25:27 +00005224 << lex->getType() << lex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00005225 return QualType();
5226 }
Douglas Gregore7450f52009-03-24 19:52:54 +00005227
5228 // GNU C extension: arithmetic on pointer to function
5229 ComplainAboutFunc = lex;
5230 } else if (!lpointee->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00005231 RequireCompleteType(Loc, lpointee,
Anders Carlssond497ba72009-08-26 22:59:12 +00005232 PDiag(diag::err_typecheck_sub_ptr_object)
Mike Stump1eb44332009-09-09 15:08:12 +00005233 << lex->getSourceRange()
Anders Carlssond497ba72009-08-26 22:59:12 +00005234 << lex->getType()))
Douglas Gregore7450f52009-03-24 19:52:54 +00005235 return QualType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00005236
Chris Lattnerb5f15622009-04-24 23:50:08 +00005237 // Diagnose bad cases where we step over interface counts.
John McCallc12c5bb2010-05-15 11:32:37 +00005238 if (lpointee->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattnerb5f15622009-04-24 23:50:08 +00005239 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
5240 << lpointee << lex->getSourceRange();
5241 return QualType();
5242 }
Mike Stump1eb44332009-09-09 15:08:12 +00005243
Chris Lattner6e4ab612007-12-09 21:53:25 +00005244 // The result type of a pointer-int computation is the pointer type.
Douglas Gregore7450f52009-03-24 19:52:54 +00005245 if (rex->getType()->isIntegerType()) {
5246 if (ComplainAboutVoid)
5247 Diag(Loc, diag::ext_gnu_void_ptr)
5248 << lex->getSourceRange() << rex->getSourceRange();
5249 if (ComplainAboutFunc)
5250 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump1eb44332009-09-09 15:08:12 +00005251 << ComplainAboutFunc->getType()
Douglas Gregore7450f52009-03-24 19:52:54 +00005252 << ComplainAboutFunc->getSourceRange();
5253
Eli Friedmanab3a8522009-03-28 01:22:36 +00005254 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00005255 return lex->getType();
Douglas Gregore7450f52009-03-24 19:52:54 +00005256 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005257
Chris Lattner6e4ab612007-12-09 21:53:25 +00005258 // Handle pointer-pointer subtractions.
Ted Kremenek6217b802009-07-29 21:53:49 +00005259 if (const PointerType *RHSPTy = rex->getType()->getAs<PointerType>()) {
Eli Friedman8e54ad02008-02-08 01:19:44 +00005260 QualType rpointee = RHSPTy->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005261
Douglas Gregore7450f52009-03-24 19:52:54 +00005262 // RHS must be a completely-type object type.
5263 // Handle the GNU void* extension.
5264 if (rpointee->isVoidType()) {
5265 if (getLangOptions().CPlusPlus) {
5266 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
5267 << lex->getSourceRange() << rex->getSourceRange();
5268 return QualType();
5269 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005270
Douglas Gregore7450f52009-03-24 19:52:54 +00005271 ComplainAboutVoid = true;
5272 } else if (rpointee->isFunctionType()) {
5273 if (getLangOptions().CPlusPlus) {
5274 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattnerd1625842008-11-24 06:25:27 +00005275 << rex->getType() << rex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00005276 return QualType();
5277 }
Douglas Gregore7450f52009-03-24 19:52:54 +00005278
5279 // GNU extension: arithmetic on pointer to function
5280 if (!ComplainAboutFunc)
5281 ComplainAboutFunc = rex;
5282 } else if (!rpointee->isDependentType() &&
5283 RequireCompleteType(Loc, rpointee,
Anders Carlssond497ba72009-08-26 22:59:12 +00005284 PDiag(diag::err_typecheck_sub_ptr_object)
5285 << rex->getSourceRange()
5286 << rex->getType()))
Douglas Gregore7450f52009-03-24 19:52:54 +00005287 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005288
Eli Friedman88d936b2009-05-16 13:54:38 +00005289 if (getLangOptions().CPlusPlus) {
5290 // Pointee types must be the same: C++ [expr.add]
5291 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
5292 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
5293 << lex->getType() << rex->getType()
5294 << lex->getSourceRange() << rex->getSourceRange();
5295 return QualType();
5296 }
5297 } else {
5298 // Pointee types must be compatible C99 6.5.6p3
5299 if (!Context.typesAreCompatible(
5300 Context.getCanonicalType(lpointee).getUnqualifiedType(),
5301 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
5302 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
5303 << lex->getType() << rex->getType()
5304 << lex->getSourceRange() << rex->getSourceRange();
5305 return QualType();
5306 }
Chris Lattner6e4ab612007-12-09 21:53:25 +00005307 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005308
Douglas Gregore7450f52009-03-24 19:52:54 +00005309 if (ComplainAboutVoid)
5310 Diag(Loc, diag::ext_gnu_void_ptr)
5311 << lex->getSourceRange() << rex->getSourceRange();
5312 if (ComplainAboutFunc)
5313 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump1eb44332009-09-09 15:08:12 +00005314 << ComplainAboutFunc->getType()
Douglas Gregore7450f52009-03-24 19:52:54 +00005315 << ComplainAboutFunc->getSourceRange();
Eli Friedmanab3a8522009-03-28 01:22:36 +00005316
5317 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00005318 return Context.getPointerDiffType();
5319 }
5320 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005321
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005322 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00005323}
5324
Chris Lattnereca7be62008-04-07 05:30:13 +00005325// C99 6.5.7
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005326QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnereca7be62008-04-07 05:30:13 +00005327 bool isCompAssign) {
Chris Lattnerca5eede2007-12-12 05:47:28 +00005328 // C99 6.5.7p2: Each of the operands shall have integer type.
Douglas Gregorf6094622010-07-23 15:58:24 +00005329 if (!lex->getType()->hasIntegerRepresentation() ||
5330 !rex->getType()->hasIntegerRepresentation())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005331 return InvalidOperands(Loc, lex, rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005332
Nate Begeman2207d792009-10-25 02:26:48 +00005333 // Vector shifts promote their scalar inputs to vector type.
5334 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
5335 return CheckVectorOperands(Loc, lex, rex);
5336
Chris Lattnerca5eede2007-12-12 05:47:28 +00005337 // Shifts don't perform usual arithmetic conversions, they just do integer
5338 // promotions on each operand. C99 6.5.7p3
Eli Friedman04e83572009-08-20 04:21:42 +00005339 QualType LHSTy = Context.isPromotableBitField(lex);
5340 if (LHSTy.isNull()) {
5341 LHSTy = lex->getType();
5342 if (LHSTy->isPromotableIntegerType())
5343 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregor2d833e32009-05-02 00:36:19 +00005344 }
Chris Lattner1dcf2c82007-12-13 07:28:16 +00005345 if (!isCompAssign)
Eli Friedman73c39ab2009-10-20 08:27:19 +00005346 ImpCastExprToType(lex, LHSTy, CastExpr::CK_IntegralCast);
Eli Friedmanab3a8522009-03-28 01:22:36 +00005347
Chris Lattnerca5eede2007-12-12 05:47:28 +00005348 UsualUnaryConversions(rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005349
Ryan Flynnd0439682009-08-07 16:20:20 +00005350 // Sanity-check shift operands
5351 llvm::APSInt Right;
5352 // Check right/shifter operand
Daniel Dunbar3f180c62009-09-17 06:31:27 +00005353 if (!rex->isValueDependent() &&
5354 rex->isIntegerConstantExpr(Right, Context)) {
Ryan Flynn8045c732009-08-08 19:18:23 +00005355 if (Right.isNegative())
Ryan Flynnd0439682009-08-07 16:20:20 +00005356 Diag(Loc, diag::warn_shift_negative) << rex->getSourceRange();
5357 else {
5358 llvm::APInt LeftBits(Right.getBitWidth(),
5359 Context.getTypeSize(lex->getType()));
5360 if (Right.uge(LeftBits))
5361 Diag(Loc, diag::warn_shift_gt_typewidth) << rex->getSourceRange();
5362 }
5363 }
5364
Chris Lattnerca5eede2007-12-12 05:47:28 +00005365 // "The type of the result is that of the promoted left operand."
Eli Friedmanab3a8522009-03-28 01:22:36 +00005366 return LHSTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00005367}
5368
Chandler Carruth99919472010-07-10 12:30:03 +00005369static bool IsWithinTemplateSpecialization(Decl *D) {
5370 if (DeclContext *DC = D->getDeclContext()) {
5371 if (isa<ClassTemplateSpecializationDecl>(DC))
5372 return true;
5373 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
5374 return FD->isFunctionTemplateSpecialization();
5375 }
5376 return false;
5377}
5378
Douglas Gregor0c6db942009-05-04 06:07:12 +00005379// C99 6.5.8, C++ [expr.rel]
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005380QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Douglas Gregora86b8322009-04-06 18:45:53 +00005381 unsigned OpaqueOpc, bool isRelational) {
5382 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)OpaqueOpc;
5383
Chris Lattner02dd4b12009-12-05 05:40:13 +00005384 // Handle vector comparisons separately.
Nate Begemanbe2341d2008-07-14 18:02:46 +00005385 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005386 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005387
Steve Naroffc80b4ee2007-07-16 21:54:35 +00005388 QualType lType = lex->getType();
5389 QualType rType = rex->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005390
Douglas Gregor8eee1192010-06-22 22:12:46 +00005391 if (!lType->hasFloatingRepresentation() &&
5392 !(lType->isBlockPointerType() && isRelational)) {
Chris Lattner55660a72009-03-08 19:39:53 +00005393 // For non-floating point types, check for self-comparisons of the form
5394 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
5395 // often indicate logic errors in the program.
Chandler Carruth64d092c2010-07-12 06:23:38 +00005396 //
5397 // NOTE: Don't warn about comparison expressions resulting from macro
5398 // expansion. Also don't warn about comparisons which are only self
5399 // comparisons within a template specialization. The warnings should catch
5400 // obvious cases in the definition of the template anyways. The idea is to
5401 // warn when the typed comparison operator will always evaluate to the same
5402 // result.
Chris Lattner55660a72009-03-08 19:39:53 +00005403 Expr *LHSStripped = lex->IgnoreParens();
5404 Expr *RHSStripped = rex->IgnoreParens();
Chandler Carruth99919472010-07-10 12:30:03 +00005405 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
Douglas Gregord64fdd02010-06-08 19:50:34 +00005406 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
Chandler Carruth64d092c2010-07-12 06:23:38 +00005407 if (DRL->getDecl() == DRR->getDecl() && !Loc.isMacroID() &&
Chandler Carruth99919472010-07-10 12:30:03 +00005408 !IsWithinTemplateSpecialization(DRL->getDecl())) {
Douglas Gregord64fdd02010-06-08 19:50:34 +00005409 DiagRuntimeBehavior(Loc, PDiag(diag::warn_comparison_always)
5410 << 0 // self-
5411 << (Opc == BinaryOperator::EQ
5412 || Opc == BinaryOperator::LE
5413 || Opc == BinaryOperator::GE));
5414 } else if (lType->isArrayType() && rType->isArrayType() &&
5415 !DRL->getDecl()->getType()->isReferenceType() &&
5416 !DRR->getDecl()->getType()->isReferenceType()) {
5417 // what is it always going to eval to?
5418 char always_evals_to;
5419 switch(Opc) {
5420 case BinaryOperator::EQ: // e.g. array1 == array2
5421 always_evals_to = 0; // false
5422 break;
5423 case BinaryOperator::NE: // e.g. array1 != array2
5424 always_evals_to = 1; // true
5425 break;
5426 default:
5427 // best we can say is 'a constant'
5428 always_evals_to = 2; // e.g. array1 <= array2
5429 break;
5430 }
5431 DiagRuntimeBehavior(Loc, PDiag(diag::warn_comparison_always)
5432 << 1 // array
5433 << always_evals_to);
5434 }
5435 }
Chandler Carruth99919472010-07-10 12:30:03 +00005436 }
Mike Stump1eb44332009-09-09 15:08:12 +00005437
Chris Lattner55660a72009-03-08 19:39:53 +00005438 if (isa<CastExpr>(LHSStripped))
5439 LHSStripped = LHSStripped->IgnoreParenCasts();
5440 if (isa<CastExpr>(RHSStripped))
5441 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00005442
Chris Lattner55660a72009-03-08 19:39:53 +00005443 // Warn about comparisons against a string constant (unless the other
5444 // operand is null), the user probably wants strcmp.
Douglas Gregora86b8322009-04-06 18:45:53 +00005445 Expr *literalString = 0;
5446 Expr *literalStringStripped = 0;
Chris Lattner55660a72009-03-08 19:39:53 +00005447 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005448 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00005449 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregora86b8322009-04-06 18:45:53 +00005450 literalString = lex;
5451 literalStringStripped = LHSStripped;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00005452 } else if ((isa<StringLiteral>(RHSStripped) ||
5453 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005454 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00005455 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregora86b8322009-04-06 18:45:53 +00005456 literalString = rex;
5457 literalStringStripped = RHSStripped;
5458 }
5459
5460 if (literalString) {
5461 std::string resultComparison;
5462 switch (Opc) {
5463 case BinaryOperator::LT: resultComparison = ") < 0"; break;
5464 case BinaryOperator::GT: resultComparison = ") > 0"; break;
5465 case BinaryOperator::LE: resultComparison = ") <= 0"; break;
5466 case BinaryOperator::GE: resultComparison = ") >= 0"; break;
5467 case BinaryOperator::EQ: resultComparison = ") == 0"; break;
5468 case BinaryOperator::NE: resultComparison = ") != 0"; break;
5469 default: assert(false && "Invalid comparison operator");
5470 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005471
Douglas Gregord1e4d9b2010-01-12 23:18:54 +00005472 DiagRuntimeBehavior(Loc,
5473 PDiag(diag::warn_stringcompare)
5474 << isa<ObjCEncodeExpr>(literalStringStripped)
Ted Kremenek03a4bee2010-04-09 20:26:53 +00005475 << literalString->getSourceRange());
Douglas Gregora86b8322009-04-06 18:45:53 +00005476 }
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00005477 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005478
Douglas Gregord64fdd02010-06-08 19:50:34 +00005479 // C99 6.5.8p3 / C99 6.5.9p4
5480 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
5481 UsualArithmeticConversions(lex, rex);
5482 else {
5483 UsualUnaryConversions(lex);
5484 UsualUnaryConversions(rex);
5485 }
5486
5487 lType = lex->getType();
5488 rType = rex->getType();
5489
Douglas Gregor447b69e2008-11-19 03:25:36 +00005490 // The result of comparisons is 'bool' in C++, 'int' in C.
Chris Lattner02dd4b12009-12-05 05:40:13 +00005491 QualType ResultTy = getLangOptions().CPlusPlus ? Context.BoolTy:Context.IntTy;
Douglas Gregor447b69e2008-11-19 03:25:36 +00005492
Chris Lattnera5937dd2007-08-26 01:18:55 +00005493 if (isRelational) {
5494 if (lType->isRealType() && rType->isRealType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00005495 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00005496 } else {
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00005497 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor8eee1192010-06-22 22:12:46 +00005498 if (lType->hasFloatingRepresentation())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005499 CheckFloatComparison(Loc,lex,rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005500
Chris Lattnera5937dd2007-08-26 01:18:55 +00005501 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00005502 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00005503 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005504
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005505 bool LHSIsNull = lex->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00005506 Expr::NPC_ValueDependentIsNull);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005507 bool RHSIsNull = rex->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00005508 Expr::NPC_ValueDependentIsNull);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005509
Douglas Gregor6e5122c2010-06-15 21:38:40 +00005510 // All of the following pointer-related warnings are GCC extensions, except
5511 // when handling null pointer constants.
Steve Naroff77878cc2007-08-27 04:08:11 +00005512 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00005513 QualType LCanPointeeTy =
Ted Kremenek6217b802009-07-29 21:53:49 +00005514 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattnerbc896f52008-04-03 05:07:25 +00005515 QualType RCanPointeeTy =
Ted Kremenek6217b802009-07-29 21:53:49 +00005516 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stumpeed9cac2009-02-19 03:04:26 +00005517
Douglas Gregor0c6db942009-05-04 06:07:12 +00005518 if (getLangOptions().CPlusPlus) {
Eli Friedman3075e762009-08-23 00:27:47 +00005519 if (LCanPointeeTy == RCanPointeeTy)
5520 return ResultTy;
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00005521 if (!isRelational &&
5522 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
5523 // Valid unless comparison between non-null pointer and function pointer
5524 // This is a gcc extension compatibility comparison.
Douglas Gregor6e5122c2010-06-15 21:38:40 +00005525 // In a SFINAE context, we treat this as a hard error to maintain
5526 // conformance with the C++ standard.
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00005527 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
5528 && !LHSIsNull && !RHSIsNull) {
Douglas Gregor6e5122c2010-06-15 21:38:40 +00005529 Diag(Loc,
5530 isSFINAEContext()?
5531 diag::err_typecheck_comparison_of_fptr_to_void
5532 : diag::ext_typecheck_comparison_of_fptr_to_void)
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00005533 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor6e5122c2010-06-15 21:38:40 +00005534
5535 if (isSFINAEContext())
5536 return QualType();
5537
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00005538 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
5539 return ResultTy;
5540 }
5541 }
Douglas Gregor0c6db942009-05-04 06:07:12 +00005542 // C++ [expr.rel]p2:
5543 // [...] Pointer conversions (4.10) and qualification
5544 // conversions (4.4) are performed on pointer operands (or on
5545 // a pointer operand and a null pointer constant) to bring
5546 // them to their composite pointer type. [...]
5547 //
Douglas Gregor20b3e992009-08-24 17:42:35 +00005548 // C++ [expr.eq]p1 uses the same notion for (in)equality
Douglas Gregor0c6db942009-05-04 06:07:12 +00005549 // comparisons of pointers.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00005550 bool NonStandardCompositeType = false;
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00005551 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00005552 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregor0c6db942009-05-04 06:07:12 +00005553 if (T.isNull()) {
5554 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
5555 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5556 return QualType();
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00005557 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005558 Diag(Loc,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00005559 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005560 << lType << rType << T
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00005561 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor0c6db942009-05-04 06:07:12 +00005562 }
5563
Eli Friedman73c39ab2009-10-20 08:27:19 +00005564 ImpCastExprToType(lex, T, CastExpr::CK_BitCast);
5565 ImpCastExprToType(rex, T, CastExpr::CK_BitCast);
Douglas Gregor0c6db942009-05-04 06:07:12 +00005566 return ResultTy;
5567 }
Eli Friedman3075e762009-08-23 00:27:47 +00005568 // C99 6.5.9p2 and C99 6.5.8p2
5569 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
5570 RCanPointeeTy.getUnqualifiedType())) {
5571 // Valid unless a relational comparison of function pointers
5572 if (isRelational && LCanPointeeTy->isFunctionType()) {
5573 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
5574 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5575 }
5576 } else if (!isRelational &&
5577 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
5578 // Valid unless comparison between non-null pointer and function pointer
5579 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
5580 && !LHSIsNull && !RHSIsNull) {
5581 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
5582 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5583 }
5584 } else {
5585 // Invalid
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00005586 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattnerd1625842008-11-24 06:25:27 +00005587 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00005588 }
Eli Friedman3075e762009-08-23 00:27:47 +00005589 if (LCanPointeeTy != RCanPointeeTy)
Eli Friedman73c39ab2009-10-20 08:27:19 +00005590 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005591 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00005592 }
Mike Stump1eb44332009-09-09 15:08:12 +00005593
Sebastian Redl6e8ed162009-05-10 18:38:11 +00005594 if (getLangOptions().CPlusPlus) {
Mike Stump1eb44332009-09-09 15:08:12 +00005595 // Comparison of pointers with null pointer constants and equality
Douglas Gregor20b3e992009-08-24 17:42:35 +00005596 // comparisons of member pointers to null pointer constants.
Mike Stump1eb44332009-09-09 15:08:12 +00005597 if (RHSIsNull &&
Douglas Gregor20b3e992009-08-24 17:42:35 +00005598 (lType->isPointerType() ||
5599 (!isRelational && lType->isMemberPointerType()))) {
Douglas Gregor443c2122010-08-07 13:36:37 +00005600 ImpCastExprToType(rex, lType,
5601 lType->isMemberPointerType()
5602 ? CastExpr::CK_NullToMemberPointer
5603 : CastExpr::CK_IntegralToPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00005604 return ResultTy;
5605 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00005606 if (LHSIsNull &&
5607 (rType->isPointerType() ||
5608 (!isRelational && rType->isMemberPointerType()))) {
Douglas Gregor443c2122010-08-07 13:36:37 +00005609 ImpCastExprToType(lex, rType,
5610 rType->isMemberPointerType()
5611 ? CastExpr::CK_NullToMemberPointer
5612 : CastExpr::CK_IntegralToPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00005613 return ResultTy;
5614 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00005615
5616 // Comparison of member pointers.
Mike Stump1eb44332009-09-09 15:08:12 +00005617 if (!isRelational &&
Douglas Gregor20b3e992009-08-24 17:42:35 +00005618 lType->isMemberPointerType() && rType->isMemberPointerType()) {
5619 // C++ [expr.eq]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00005620 // In addition, pointers to members can be compared, or a pointer to
5621 // member and a null pointer constant. Pointer to member conversions
5622 // (4.11) and qualification conversions (4.4) are performed to bring
5623 // them to a common type. If one operand is a null pointer constant,
5624 // the common type is the type of the other operand. Otherwise, the
5625 // common type is a pointer to member type similar (4.4) to the type
5626 // of one of the operands, with a cv-qualification signature (4.4)
5627 // that is the union of the cv-qualification signatures of the operand
Douglas Gregor20b3e992009-08-24 17:42:35 +00005628 // types.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00005629 bool NonStandardCompositeType = false;
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00005630 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00005631 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregor20b3e992009-08-24 17:42:35 +00005632 if (T.isNull()) {
5633 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00005634 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor20b3e992009-08-24 17:42:35 +00005635 return QualType();
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00005636 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005637 Diag(Loc,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00005638 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005639 << lType << rType << T
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00005640 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor20b3e992009-08-24 17:42:35 +00005641 }
Mike Stump1eb44332009-09-09 15:08:12 +00005642
Eli Friedman73c39ab2009-10-20 08:27:19 +00005643 ImpCastExprToType(lex, T, CastExpr::CK_BitCast);
5644 ImpCastExprToType(rex, T, CastExpr::CK_BitCast);
Douglas Gregor20b3e992009-08-24 17:42:35 +00005645 return ResultTy;
5646 }
Mike Stump1eb44332009-09-09 15:08:12 +00005647
Douglas Gregor20b3e992009-08-24 17:42:35 +00005648 // Comparison of nullptr_t with itself.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00005649 if (lType->isNullPtrType() && rType->isNullPtrType())
5650 return ResultTy;
5651 }
Mike Stump1eb44332009-09-09 15:08:12 +00005652
Steve Naroff1c7d0672008-09-04 15:10:53 +00005653 // Handle block pointer types.
Mike Stumpdd3e1662009-05-07 03:14:14 +00005654 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00005655 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
5656 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005657
Steve Naroff1c7d0672008-09-04 15:10:53 +00005658 if (!LHSIsNull && !RHSIsNull &&
Eli Friedman26784c12009-06-08 05:08:54 +00005659 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00005660 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattnerd1625842008-11-24 06:25:27 +00005661 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff1c7d0672008-09-04 15:10:53 +00005662 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00005663 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005664 return ResultTy;
Steve Naroff1c7d0672008-09-04 15:10:53 +00005665 }
Steve Naroff59f53942008-09-28 01:11:11 +00005666 // Allow block pointers to be compared with null pointer constants.
Mike Stumpdd3e1662009-05-07 03:14:14 +00005667 if (!isRelational
5668 && ((lType->isBlockPointerType() && rType->isPointerType())
5669 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Naroff59f53942008-09-28 01:11:11 +00005670 if (!LHSIsNull && !RHSIsNull) {
Ted Kremenek6217b802009-07-29 21:53:49 +00005671 if (!((rType->isPointerType() && rType->getAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00005672 ->getPointeeType()->isVoidType())
Ted Kremenek6217b802009-07-29 21:53:49 +00005673 || (lType->isPointerType() && lType->getAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00005674 ->getPointeeType()->isVoidType())))
5675 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
5676 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff59f53942008-09-28 01:11:11 +00005677 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00005678 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005679 return ResultTy;
Steve Naroff59f53942008-09-28 01:11:11 +00005680 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00005681
Steve Naroff14108da2009-07-10 23:34:53 +00005682 if ((lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType())) {
Steve Naroffa5ad8632008-10-27 10:33:19 +00005683 if (lType->isPointerType() || rType->isPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00005684 const PointerType *LPT = lType->getAs<PointerType>();
5685 const PointerType *RPT = rType->getAs<PointerType>();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005686 bool LPtrToVoid = LPT ?
Steve Naroffa8069f12008-11-17 19:49:16 +00005687 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005688 bool RPtrToVoid = RPT ?
Steve Naroffa8069f12008-11-17 19:49:16 +00005689 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005690
Steve Naroffa8069f12008-11-17 19:49:16 +00005691 if (!LPtrToVoid && !RPtrToVoid &&
5692 !Context.typesAreCompatible(lType, rType)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00005693 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattnerd1625842008-11-24 06:25:27 +00005694 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroffa5ad8632008-10-27 10:33:19 +00005695 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00005696 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005697 return ResultTy;
Steve Naroff87f3b932008-10-20 18:19:10 +00005698 }
Steve Naroff14108da2009-07-10 23:34:53 +00005699 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00005700 if (!Context.areComparableObjCPointerTypes(lType, rType))
Steve Naroff14108da2009-07-10 23:34:53 +00005701 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
5702 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00005703 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005704 return ResultTy;
Steve Naroff20373222008-06-03 14:04:54 +00005705 }
Fariborz Jahanian7359f042007-12-20 01:06:58 +00005706 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00005707 if ((lType->isAnyPointerType() && rType->isIntegerType()) ||
5708 (lType->isIntegerType() && rType->isAnyPointerType())) {
Chris Lattner06c0f5b2009-08-23 00:03:44 +00005709 unsigned DiagID = 0;
Douglas Gregor6e5122c2010-06-15 21:38:40 +00005710 bool isError = false;
5711 if ((LHSIsNull && lType->isIntegerType()) ||
5712 (RHSIsNull && rType->isIntegerType())) {
5713 if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattner06c0f5b2009-08-23 00:03:44 +00005714 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
Douglas Gregor6e5122c2010-06-15 21:38:40 +00005715 } else if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattner06c0f5b2009-08-23 00:03:44 +00005716 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
Douglas Gregor6e5122c2010-06-15 21:38:40 +00005717 else if (getLangOptions().CPlusPlus) {
5718 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
5719 isError = true;
5720 } else
Chris Lattner06c0f5b2009-08-23 00:03:44 +00005721 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump1eb44332009-09-09 15:08:12 +00005722
Chris Lattner06c0f5b2009-08-23 00:03:44 +00005723 if (DiagID) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00005724 Diag(Loc, DiagID)
Chris Lattner149f1382009-06-30 06:24:05 +00005725 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor6e5122c2010-06-15 21:38:40 +00005726 if (isError)
5727 return QualType();
Chris Lattner6365e3e2009-08-22 18:58:31 +00005728 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00005729
5730 if (lType->isIntegerType())
5731 ImpCastExprToType(lex, rType, CastExpr::CK_IntegralToPointer);
Chris Lattner06c0f5b2009-08-23 00:03:44 +00005732 else
Douglas Gregor6e5122c2010-06-15 21:38:40 +00005733 ImpCastExprToType(rex, lType, CastExpr::CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005734 return ResultTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00005735 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00005736
Steve Naroff39218df2008-09-04 16:56:14 +00005737 // Handle block pointers.
Mike Stumpaf199f32009-05-07 18:43:07 +00005738 if (!isRelational && RHSIsNull
5739 && lType->isBlockPointerType() && rType->isIntegerType()) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00005740 ImpCastExprToType(rex, lType, CastExpr::CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005741 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00005742 }
Mike Stumpaf199f32009-05-07 18:43:07 +00005743 if (!isRelational && LHSIsNull
5744 && lType->isIntegerType() && rType->isBlockPointerType()) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00005745 ImpCastExprToType(lex, rType, CastExpr::CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005746 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00005747 }
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005748 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00005749}
5750
Nate Begemanbe2341d2008-07-14 18:02:46 +00005751/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stumpeed9cac2009-02-19 03:04:26 +00005752/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begemanbe2341d2008-07-14 18:02:46 +00005753/// like a scalar comparison, a vector comparison produces a vector of integer
5754/// types.
5755QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005756 SourceLocation Loc,
Nate Begemanbe2341d2008-07-14 18:02:46 +00005757 bool isRelational) {
5758 // Check to make sure we're operating on vectors of the same type and width,
5759 // Allowing one side to be a scalar of element type.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005760 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanbe2341d2008-07-14 18:02:46 +00005761 if (vType.isNull())
5762 return vType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005763
Nate Begemanbe2341d2008-07-14 18:02:46 +00005764 QualType lType = lex->getType();
5765 QualType rType = rex->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005766
Nate Begemanbe2341d2008-07-14 18:02:46 +00005767 // For non-floating point types, check for self-comparisons of the form
5768 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
5769 // often indicate logic errors in the program.
Douglas Gregor8eee1192010-06-22 22:12:46 +00005770 if (!lType->hasFloatingRepresentation()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00005771 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
5772 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
5773 if (DRL->getDecl() == DRR->getDecl())
Douglas Gregord64fdd02010-06-08 19:50:34 +00005774 DiagRuntimeBehavior(Loc,
5775 PDiag(diag::warn_comparison_always)
5776 << 0 // self-
5777 << 2 // "a constant"
5778 );
Nate Begemanbe2341d2008-07-14 18:02:46 +00005779 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005780
Nate Begemanbe2341d2008-07-14 18:02:46 +00005781 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor8eee1192010-06-22 22:12:46 +00005782 if (!isRelational && lType->hasFloatingRepresentation()) {
5783 assert (rType->hasFloatingRepresentation());
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005784 CheckFloatComparison(Loc,lex,rex);
Nate Begemanbe2341d2008-07-14 18:02:46 +00005785 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005786
Nate Begemanbe2341d2008-07-14 18:02:46 +00005787 // Return the type for the comparison, which is the same as vector type for
5788 // integer vectors, or an integer type of identical size and number of
5789 // elements for floating point vectors.
Douglas Gregorf6094622010-07-23 15:58:24 +00005790 if (lType->hasIntegerRepresentation())
Nate Begemanbe2341d2008-07-14 18:02:46 +00005791 return lType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005792
John McCall183700f2009-09-21 23:43:11 +00005793 const VectorType *VTy = lType->getAs<VectorType>();
Nate Begemanbe2341d2008-07-14 18:02:46 +00005794 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman59b5da62009-01-18 03:20:47 +00005795 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanbe2341d2008-07-14 18:02:46 +00005796 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattnerd013aa12009-03-31 07:46:52 +00005797 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman59b5da62009-01-18 03:20:47 +00005798 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
5799
Mike Stumpeed9cac2009-02-19 03:04:26 +00005800 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman59b5da62009-01-18 03:20:47 +00005801 "Unhandled vector element size in vector compare");
Nate Begemanbe2341d2008-07-14 18:02:46 +00005802 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
5803}
5804
Reid Spencer5f016e22007-07-11 17:01:13 +00005805inline QualType Sema::CheckBitwiseOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00005806 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Douglas Gregorf6094622010-07-23 15:58:24 +00005807 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
5808 if (lex->getType()->hasIntegerRepresentation() &&
5809 rex->getType()->hasIntegerRepresentation())
5810 return CheckVectorOperands(Loc, lex, rex);
5811
5812 return InvalidOperands(Loc, lex, rex);
5813 }
Steve Naroff90045e82007-07-13 23:32:42 +00005814
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00005815 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005816
Steve Naroffa4332e22007-07-17 00:58:39 +00005817 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00005818 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005819 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00005820}
5821
5822inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Chris Lattner90a8f272010-07-13 19:41:32 +00005823 Expr *&lex, Expr *&rex, SourceLocation Loc, unsigned Opc) {
5824
5825 // Diagnose cases where the user write a logical and/or but probably meant a
5826 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
5827 // is a constant.
5828 if (lex->getType()->isIntegerType() && !lex->getType()->isBooleanType() &&
Eli Friedman787b0942010-07-27 19:14:53 +00005829 rex->getType()->isIntegerType() && !rex->isValueDependent() &&
Chris Lattner23ef3e42010-07-15 00:26:43 +00005830 // Don't warn in macros.
Chris Lattnerb7690b42010-07-24 01:10:11 +00005831 !Loc.isMacroID()) {
5832 // If the RHS can be constant folded, and if it constant folds to something
5833 // that isn't 0 or 1 (which indicate a potential logical operation that
5834 // happened to fold to true/false) then warn.
5835 Expr::EvalResult Result;
5836 if (rex->Evaluate(Result, Context) && !Result.HasSideEffects &&
5837 Result.Val.getInt() != 0 && Result.Val.getInt() != 1) {
5838 Diag(Loc, diag::warn_logical_instead_of_bitwise)
5839 << rex->getSourceRange()
5840 << (Opc == BinaryOperator::LAnd ? "&&" : "||")
5841 << (Opc == BinaryOperator::LAnd ? "&" : "|");
5842 }
5843 }
Chris Lattner90a8f272010-07-13 19:41:32 +00005844
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005845 if (!Context.getLangOptions().CPlusPlus) {
5846 UsualUnaryConversions(lex);
5847 UsualUnaryConversions(rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005848
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005849 if (!lex->getType()->isScalarType() || !rex->getType()->isScalarType())
5850 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005851
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005852 return Context.IntTy;
Anders Carlsson04905012009-10-16 01:44:21 +00005853 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005854
John McCall75f7c0f2010-06-04 00:29:51 +00005855 // The following is safe because we only use this method for
5856 // non-overloadable operands.
5857
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005858 // C++ [expr.log.and]p1
5859 // C++ [expr.log.or]p1
John McCall75f7c0f2010-06-04 00:29:51 +00005860 // The operands are both contextually converted to type bool.
5861 if (PerformContextuallyConvertToBool(lex) ||
5862 PerformContextuallyConvertToBool(rex))
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005863 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005864
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005865 // C++ [expr.log.and]p2
5866 // C++ [expr.log.or]p2
5867 // The result is a bool.
5868 return Context.BoolTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00005869}
5870
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00005871/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
5872/// is a read-only property; return true if so. A readonly property expression
5873/// depends on various declarations and thus must be treated specially.
5874///
Mike Stump1eb44332009-09-09 15:08:12 +00005875static bool IsReadonlyProperty(Expr *E, Sema &S) {
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00005876 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
5877 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
5878 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
5879 QualType BaseType = PropExpr->getBase()->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00005880 if (const ObjCObjectPointerType *OPT =
Steve Naroff14108da2009-07-10 23:34:53 +00005881 BaseType->getAsObjCInterfacePointerType())
5882 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
5883 if (S.isPropertyReadonly(PDecl, IFace))
5884 return true;
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00005885 }
5886 }
5887 return false;
5888}
5889
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005890/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
5891/// emit an error and return true. If so, return false.
5892static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbar44e35f72009-04-15 00:08:05 +00005893 SourceLocation OrigLoc = Loc;
Mike Stump1eb44332009-09-09 15:08:12 +00005894 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbar44e35f72009-04-15 00:08:05 +00005895 &Loc);
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00005896 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
5897 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005898 if (IsLV == Expr::MLV_Valid)
5899 return false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005900
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005901 unsigned Diag = 0;
5902 bool NeedType = false;
5903 switch (IsLV) { // C99 6.5.16p2
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005904 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005905 case Expr::MLV_ArrayType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005906 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
5907 NeedType = true;
5908 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005909 case Expr::MLV_NotObjectType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005910 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
5911 NeedType = true;
5912 break;
Chris Lattnerca354fa2008-11-17 19:51:54 +00005913 case Expr::MLV_LValueCast:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005914 Diag = diag::err_typecheck_lvalue_casts_not_supported;
5915 break;
Douglas Gregore873fb72010-02-16 21:39:57 +00005916 case Expr::MLV_Valid:
5917 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner5cf216b2008-01-04 18:04:52 +00005918 case Expr::MLV_InvalidExpression:
Douglas Gregore873fb72010-02-16 21:39:57 +00005919 case Expr::MLV_MemberFunction:
5920 case Expr::MLV_ClassTemporary:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005921 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
5922 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00005923 case Expr::MLV_IncompleteType:
5924 case Expr::MLV_IncompleteVoidType:
Douglas Gregor86447ec2009-03-09 16:13:40 +00005925 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00005926 S.PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
Anders Carlssonb7906612009-08-26 23:45:07 +00005927 << E->getSourceRange());
Chris Lattner5cf216b2008-01-04 18:04:52 +00005928 case Expr::MLV_DuplicateVectorComponents:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005929 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
5930 break;
Steve Naroff4f6a7d72008-09-26 14:41:28 +00005931 case Expr::MLV_NotBlockQualified:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005932 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
5933 break;
Fariborz Jahanian5daf5702008-11-22 18:39:36 +00005934 case Expr::MLV_ReadonlyProperty:
5935 Diag = diag::error_readonly_property_assignment;
5936 break;
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00005937 case Expr::MLV_NoSetterProperty:
5938 Diag = diag::error_nosetter_property_assignment;
5939 break;
Fariborz Jahanian2514a302009-12-15 23:59:41 +00005940 case Expr::MLV_SubObjCPropertySetting:
5941 Diag = diag::error_no_subobject_property_setting;
5942 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00005943 }
Steve Naroffd1861fd2007-07-31 12:34:36 +00005944
Daniel Dunbar44e35f72009-04-15 00:08:05 +00005945 SourceRange Assign;
5946 if (Loc != OrigLoc)
5947 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005948 if (NeedType)
Daniel Dunbar44e35f72009-04-15 00:08:05 +00005949 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005950 else
Mike Stump1eb44332009-09-09 15:08:12 +00005951 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005952 return true;
5953}
5954
5955
5956
5957// C99 6.5.16.1
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005958QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
5959 SourceLocation Loc,
5960 QualType CompoundType) {
5961 // Verify that LHS is a modifiable lvalue, and emit error if not.
5962 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005963 return QualType();
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005964
5965 QualType LHSType = LHS->getType();
5966 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Chris Lattner5cf216b2008-01-04 18:04:52 +00005967 AssignConvertType ConvTy;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005968 if (CompoundType.isNull()) {
Fariborz Jahaniane2a901a2010-06-07 22:02:01 +00005969 QualType LHSTy(LHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00005970 // Simple assignment "x = y".
Fariborz Jahaniane2a901a2010-06-07 22:02:01 +00005971 if (const ObjCImplicitSetterGetterRefExpr *OISGE =
5972 dyn_cast<ObjCImplicitSetterGetterRefExpr>(LHS)) {
5973 // If using property-dot syntax notation for assignment, and there is a
5974 // setter, RHS expression is being passed to the setter argument. So,
5975 // type conversion (and comparison) is RHS to setter's argument type.
5976 if (const ObjCMethodDecl *SetterMD = OISGE->getSetterMethod()) {
5977 ObjCMethodDecl::param_iterator P = SetterMD->param_begin();
5978 LHSTy = (*P)->getType();
5979 }
5980 }
5981
5982 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00005983 // Special case of NSObject attributes on c-style pointer types.
5984 if (ConvTy == IncompatiblePointer &&
5985 ((Context.isObjCNSObjectType(LHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00005986 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00005987 (Context.isObjCNSObjectType(RHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00005988 LHSType->isObjCObjectPointerType())))
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00005989 ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005990
Chris Lattner2c156472008-08-21 18:04:13 +00005991 // If the RHS is a unary plus or minus, check to see if they = and + are
5992 // right next to each other. If so, the user may have typo'd "x =+ 4"
5993 // instead of "x += 4".
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005994 Expr *RHSCheck = RHS;
Chris Lattner2c156472008-08-21 18:04:13 +00005995 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
5996 RHSCheck = ICE->getSubExpr();
5997 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
5998 if ((UO->getOpcode() == UnaryOperator::Plus ||
5999 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006000 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner2c156472008-08-21 18:04:13 +00006001 // Only if the two operators are exactly adjacent.
Chris Lattner399bd1b2009-03-08 06:51:10 +00006002 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
6003 // And there is a space or other character before the subexpr of the
6004 // unary +/-. We don't want to warn on "x=-1".
Chris Lattner3e872092009-03-09 07:11:10 +00006005 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
6006 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00006007 Diag(Loc, diag::warn_not_compound_assign)
6008 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
6009 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner399bd1b2009-03-08 06:51:10 +00006010 }
Chris Lattner2c156472008-08-21 18:04:13 +00006011 }
6012 } else {
6013 // Compound assignment "x += y"
Eli Friedman623712b2009-05-16 05:56:02 +00006014 ConvTy = CheckAssignmentConstraints(LHSType, RHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00006015 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00006016
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006017 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
Douglas Gregor68647482009-12-16 03:45:30 +00006018 RHS, AA_Assigning))
Chris Lattner5cf216b2008-01-04 18:04:52 +00006019 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006020
Chris Lattner8b5dec32010-07-07 06:14:23 +00006021
6022 // Check to see if the destination operand is a dereferenced null pointer. If
6023 // so, and if not volatile-qualified, this is undefined behavior that the
6024 // optimizer will delete, so warn about it. People sometimes try to use this
6025 // to get a deterministic trap and are surprised by clang's behavior. This
6026 // only handles the pattern "*null = whatever", which is a very syntactic
6027 // check.
6028 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS->IgnoreParenCasts()))
6029 if (UO->getOpcode() == UnaryOperator::Deref &&
6030 UO->getSubExpr()->IgnoreParenCasts()->
6031 isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) &&
6032 !UO->getType().isVolatileQualified()) {
6033 Diag(UO->getOperatorLoc(), diag::warn_indirection_through_null)
6034 << UO->getSubExpr()->getSourceRange();
6035 Diag(UO->getOperatorLoc(), diag::note_indirection_through_null);
6036 }
6037
Reid Spencer5f016e22007-07-11 17:01:13 +00006038 // C99 6.5.16p3: The type of an assignment expression is the type of the
6039 // left operand unless the left operand has qualified type, in which case
Mike Stumpeed9cac2009-02-19 03:04:26 +00006040 // it is the unqualified version of the type of the left operand.
Reid Spencer5f016e22007-07-11 17:01:13 +00006041 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
6042 // is converted to the type of the assignment expression (above).
Chris Lattner73d0d4f2007-08-30 17:45:32 +00006043 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregor2d833e32009-05-02 00:36:19 +00006044 // operand.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006045 return LHSType.getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +00006046}
6047
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006048// C99 6.5.17
6049QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
Argyrios Kyrtzidis25973452010-06-30 10:53:14 +00006050 DiagnoseUnusedExprResult(LHS);
6051
Chris Lattner53fcaa92008-07-25 20:54:07 +00006052 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Douglas Gregora873dfc2010-02-03 00:27:59 +00006053 // C++ does not perform this conversion (C++ [expr.comma]p1).
6054 if (!getLangOptions().CPlusPlus)
6055 DefaultFunctionArrayLvalueConversion(RHS);
Eli Friedmanb1d796d2009-03-23 00:24:07 +00006056
6057 // FIXME: Check that RHS type is complete in C mode (it's legal for it to be
6058 // incomplete in C++).
6059
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006060 return RHS->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00006061}
6062
Steve Naroff49b45262007-07-13 16:58:59 +00006063/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
6064/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00006065QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00006066 bool isInc, bool isPrefix) {
Sebastian Redl28507842009-02-26 14:39:58 +00006067 if (Op->isTypeDependent())
6068 return Context.DependentTy;
6069
Chris Lattner3528d352008-11-21 07:05:48 +00006070 QualType ResType = Op->getType();
6071 assert(!ResType.isNull() && "no type for increment/decrement expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00006072
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00006073 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
6074 // Decrement of bool is not allowed.
6075 if (!isInc) {
6076 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
6077 return QualType();
6078 }
6079 // Increment of bool sets it to true, but is deprecated.
6080 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
6081 } else if (ResType->isRealType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00006082 // OK!
Steve Naroff58f9f2c2009-07-14 18:25:06 +00006083 } else if (ResType->isAnyPointerType()) {
6084 QualType PointeeTy = ResType->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00006085
Chris Lattner3528d352008-11-21 07:05:48 +00006086 // C99 6.5.2.4p2, 6.5.6p2
Steve Naroff14108da2009-07-10 23:34:53 +00006087 if (PointeeTy->isVoidType()) {
Douglas Gregorc983b862009-01-23 00:36:41 +00006088 if (getLangOptions().CPlusPlus) {
6089 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
6090 << Op->getSourceRange();
6091 return QualType();
6092 }
6093
6094 // Pointer to void is a GNU extension in C.
Chris Lattner3528d352008-11-21 07:05:48 +00006095 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Steve Naroff14108da2009-07-10 23:34:53 +00006096 } else if (PointeeTy->isFunctionType()) {
Douglas Gregorc983b862009-01-23 00:36:41 +00006097 if (getLangOptions().CPlusPlus) {
6098 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
6099 << Op->getType() << Op->getSourceRange();
6100 return QualType();
6101 }
6102
6103 Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattnerd1625842008-11-24 06:25:27 +00006104 << ResType << Op->getSourceRange();
Steve Naroff14108da2009-07-10 23:34:53 +00006105 } else if (RequireCompleteType(OpLoc, PointeeTy,
Anders Carlssond497ba72009-08-26 22:59:12 +00006106 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
Mike Stump1eb44332009-09-09 15:08:12 +00006107 << Op->getSourceRange()
Anders Carlssond497ba72009-08-26 22:59:12 +00006108 << ResType))
Douglas Gregor4ec339f2009-01-19 19:26:10 +00006109 return QualType();
Fariborz Jahanian9f8a04f2009-07-16 17:59:14 +00006110 // Diagnose bad cases where we step over interface counts.
John McCallc12c5bb2010-05-15 11:32:37 +00006111 else if (PointeeTy->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Fariborz Jahanian9f8a04f2009-07-16 17:59:14 +00006112 Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
6113 << PointeeTy << Op->getSourceRange();
6114 return QualType();
6115 }
Eli Friedman5b088a12010-01-03 00:20:48 +00006116 } else if (ResType->isAnyComplexType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00006117 // C99 does not support ++/-- on complex types, we allow as an extension.
6118 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00006119 << ResType << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00006120 } else {
6121 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Douglas Gregor5cc07df2009-12-15 16:44:32 +00006122 << ResType << int(isInc) << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00006123 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00006124 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006125 // At this point, we know we have a real, complex or pointer type.
Steve Naroffdd10e022007-08-23 21:37:33 +00006126 // Now make sure the operand is a modifiable lvalue.
Chris Lattner3528d352008-11-21 07:05:48 +00006127 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Reid Spencer5f016e22007-07-11 17:01:13 +00006128 return QualType();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00006129 // In C++, a prefix increment is the same type as the operand. Otherwise
6130 // (in C or with postfix), the increment is the unqualified type of the
6131 // operand.
6132 return isPrefix && getLangOptions().CPlusPlus
6133 ? ResType : ResType.getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +00006134}
6135
Anders Carlsson369dee42008-02-01 07:15:58 +00006136/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Reid Spencer5f016e22007-07-11 17:01:13 +00006137/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00006138/// where the declaration is needed for type checking. We only need to
6139/// handle cases when the expression references a function designator
6140/// or is an lvalue. Here are some examples:
6141/// - &(x) => x
6142/// - &*****f => f for f a function designator.
6143/// - &s.xx => s
6144/// - &s.zz[1].yy -> s, if zz is an array
6145/// - *(x + 1) -> x, if x is an array
6146/// - &"123"[2] -> 0
6147/// - & __real__ x -> x
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006148static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00006149 switch (E->getStmtClass()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00006150 case Stmt::DeclRefExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00006151 return cast<DeclRefExpr>(E)->getDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00006152 case Stmt::MemberExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00006153 // If this is an arrow operator, the address is an offset from
6154 // the base's value, so the object the base refers to is
6155 // irrelevant.
Chris Lattnerf0467b32008-04-02 04:24:33 +00006156 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnerf82228f2007-11-16 17:46:48 +00006157 return 0;
Eli Friedman23d58ce2009-04-20 08:23:18 +00006158 // Otherwise, the expression refers to a part of the base
Chris Lattnerf0467b32008-04-02 04:24:33 +00006159 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson369dee42008-02-01 07:15:58 +00006160 case Stmt::ArraySubscriptExprClass: {
Mike Stump390b4cc2009-05-16 07:39:55 +00006161 // FIXME: This code shouldn't be necessary! We should catch the implicit
6162 // promotion of register arrays earlier.
Eli Friedman23d58ce2009-04-20 08:23:18 +00006163 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
6164 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
6165 if (ICE->getSubExpr()->getType()->isArrayType())
6166 return getPrimaryDecl(ICE->getSubExpr());
6167 }
6168 return 0;
Anders Carlsson369dee42008-02-01 07:15:58 +00006169 }
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00006170 case Stmt::UnaryOperatorClass: {
6171 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006172
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00006173 switch(UO->getOpcode()) {
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00006174 case UnaryOperator::Real:
6175 case UnaryOperator::Imag:
6176 case UnaryOperator::Extension:
6177 return getPrimaryDecl(UO->getSubExpr());
6178 default:
6179 return 0;
6180 }
6181 }
Reid Spencer5f016e22007-07-11 17:01:13 +00006182 case Stmt::ParenExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00006183 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnerf82228f2007-11-16 17:46:48 +00006184 case Stmt::ImplicitCastExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00006185 // If the result of an implicit cast is an l-value, we care about
6186 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattnerf0467b32008-04-02 04:24:33 +00006187 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Reid Spencer5f016e22007-07-11 17:01:13 +00006188 default:
6189 return 0;
6190 }
6191}
6192
6193/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stumpeed9cac2009-02-19 03:04:26 +00006194/// designator or an lvalue designating an object. If it is an lvalue, the
Reid Spencer5f016e22007-07-11 17:01:13 +00006195/// object cannot be declared with storage class register or be a bit field.
Mike Stumpeed9cac2009-02-19 03:04:26 +00006196/// Note: The usual conversions are *not* applied to the operand of the &
Reid Spencer5f016e22007-07-11 17:01:13 +00006197/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stumpeed9cac2009-02-19 03:04:26 +00006198/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregor904eed32008-11-10 20:40:00 +00006199/// we allow the '&' but retain the overloaded-function type.
Reid Spencer5f016e22007-07-11 17:01:13 +00006200QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Eli Friedman23d58ce2009-04-20 08:23:18 +00006201 // Make sure to ignore parentheses in subsequent checks
6202 op = op->IgnoreParens();
6203
Douglas Gregor9103bb22008-12-17 22:52:20 +00006204 if (op->isTypeDependent())
6205 return Context.DependentTy;
6206
Steve Naroff08f19672008-01-13 17:10:08 +00006207 if (getLangOptions().C99) {
6208 // Implement C99-only parts of addressof rules.
6209 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
6210 if (uOp->getOpcode() == UnaryOperator::Deref)
6211 // Per C99 6.5.3.2, the address of a deref always returns a valid result
6212 // (assuming the deref expression is valid).
6213 return uOp->getSubExpr()->getType();
6214 }
6215 // Technically, there should be a check for array subscript
6216 // expressions here, but the result of one is always an lvalue anyway.
6217 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006218 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner28be73f2008-07-26 21:30:36 +00006219 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes6b6609f2008-12-16 22:59:47 +00006220
Sebastian Redle27d87f2010-01-11 15:56:56 +00006221 MemberExpr *ME = dyn_cast<MemberExpr>(op);
6222 if (lval == Expr::LV_MemberFunction && ME &&
6223 isa<CXXMethodDecl>(ME->getMemberDecl())) {
6224 ValueDecl *dcl = cast<MemberExpr>(op)->getMemberDecl();
6225 // &f where f is a member of the current object, or &o.f, or &p->f
6226 // All these are not allowed, and we need to catch them before the dcl
6227 // branch of the if, below.
6228 Diag(OpLoc, diag::err_unqualified_pointer_member_function)
6229 << dcl;
6230 // FIXME: Improve this diagnostic and provide a fixit.
6231
6232 // Now recover by acting as if the function had been accessed qualified.
6233 return Context.getMemberPointerType(op->getType(),
6234 Context.getTypeDeclType(cast<RecordDecl>(dcl->getDeclContext()))
6235 .getTypePtr());
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00006236 }
6237
6238 if (lval == Expr::LV_ClassTemporary) {
Douglas Gregore873fb72010-02-16 21:39:57 +00006239 Diag(OpLoc, isSFINAEContext()? diag::err_typecheck_addrof_class_temporary
6240 : diag::ext_typecheck_addrof_class_temporary)
6241 << op->getType() << op->getSourceRange();
6242 if (isSFINAEContext())
6243 return QualType();
Chris Lattnerc721ae82010-07-05 19:36:34 +00006244 } else if (isa<ObjCSelectorExpr>(op))
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00006245 return Context.getPointerType(op->getType());
Chris Lattnerc721ae82010-07-05 19:36:34 +00006246 else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedman441cf102009-05-16 23:27:50 +00006247 // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00006248 // The operand must be either an l-value or a function designator
Eli Friedman441cf102009-05-16 23:27:50 +00006249 if (!op->getType()->isFunctionType()) {
Chris Lattnerf82228f2007-11-16 17:46:48 +00006250 // FIXME: emit more specific diag...
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00006251 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
6252 << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00006253 return QualType();
6254 }
Douglas Gregor33bbbc52009-05-02 02:18:30 +00006255 } else if (op->getBitField()) { // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00006256 // The operand cannot be a bit-field
6257 Diag(OpLoc, diag::err_typecheck_address_of)
6258 << "bit-field" << op->getSourceRange();
Douglas Gregor86f19402008-12-20 23:49:58 +00006259 return QualType();
Anders Carlsson09380262010-01-31 17:18:49 +00006260 } else if (op->refersToVectorElement()) {
Eli Friedman23d58ce2009-04-20 08:23:18 +00006261 // The operand cannot be an element of a vector
Chris Lattnerd3a94e22008-11-20 06:06:08 +00006262 Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemanb104b1f2009-02-15 22:45:20 +00006263 << "vector element" << op->getSourceRange();
Steve Naroffbcb2b612008-02-29 23:30:25 +00006264 return QualType();
Fariborz Jahanian0337f212009-07-07 18:50:52 +00006265 } else if (isa<ObjCPropertyRefExpr>(op)) {
6266 // cannot take address of a property expression.
6267 Diag(OpLoc, diag::err_typecheck_address_of)
6268 << "property expression" << op->getSourceRange();
6269 return QualType();
Anders Carlsson1d524c32009-09-14 23:15:26 +00006270 } else if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(op)) {
6271 // FIXME: Can LHS ever be null here?
Anders Carlsson474e1022009-09-15 16:03:44 +00006272 if (!CheckAddressOfOperand(CO->getTrueExpr(), OpLoc).isNull())
6273 return CheckAddressOfOperand(CO->getFalseExpr(), OpLoc);
Eli Friedmanfb3bb312010-08-24 05:23:20 +00006274 } else if (isa<OverloadExpr>(op)) {
John McCallba135432009-11-21 08:51:07 +00006275 return Context.OverloadTy;
Steve Naroffbcb2b612008-02-29 23:30:25 +00006276 } else if (dcl) { // C99 6.5.3.2p1
Mike Stumpeed9cac2009-02-19 03:04:26 +00006277 // We have an lvalue with a decl. Make sure the decl is not declared
Reid Spencer5f016e22007-07-11 17:01:13 +00006278 // with the register storage-class specifier.
6279 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
6280 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00006281 Diag(OpLoc, diag::err_typecheck_address_of)
6282 << "register variable" << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00006283 return QualType();
6284 }
John McCallba135432009-11-21 08:51:07 +00006285 } else if (isa<FunctionTemplateDecl>(dcl)) {
Douglas Gregor904eed32008-11-10 20:40:00 +00006286 return Context.OverloadTy;
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00006287 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(dcl)) {
Douglas Gregor29882052008-12-10 21:26:49 +00006288 // Okay: we can take the address of a field.
Sebastian Redlebc07d52009-02-03 20:19:35 +00006289 // Could be a pointer to member, though, if there is an explicit
6290 // scope qualifier for the class.
Douglas Gregora2813ce2009-10-23 18:54:35 +00006291 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redlebc07d52009-02-03 20:19:35 +00006292 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00006293 if (Ctx && Ctx->isRecord()) {
6294 if (FD->getType()->isReferenceType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00006295 Diag(OpLoc,
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00006296 diag::err_cannot_form_pointer_to_member_of_reference_type)
6297 << FD->getDeclName() << FD->getType();
6298 return QualType();
6299 }
Mike Stump1eb44332009-09-09 15:08:12 +00006300
Sebastian Redlebc07d52009-02-03 20:19:35 +00006301 return Context.getMemberPointerType(op->getType(),
6302 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00006303 }
Sebastian Redlebc07d52009-02-03 20:19:35 +00006304 }
Anders Carlsson196f7d02009-05-16 21:43:42 +00006305 } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(dcl)) {
Nuno Lopes6fea8d22008-12-16 22:58:26 +00006306 // Okay: we can take the address of a function.
Sebastian Redl33b399a2009-02-04 21:23:32 +00006307 // As above.
Douglas Gregora2813ce2009-10-23 18:54:35 +00006308 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier() &&
6309 MD->isInstance())
Anders Carlsson196f7d02009-05-16 21:43:42 +00006310 return Context.getMemberPointerType(op->getType(),
6311 Context.getTypeDeclType(MD->getParent()).getTypePtr());
6312 } else if (!isa<FunctionDecl>(dcl))
Reid Spencer5f016e22007-07-11 17:01:13 +00006313 assert(0 && "Unknown/unexpected decl type");
Reid Spencer5f016e22007-07-11 17:01:13 +00006314 }
Sebastian Redl33b399a2009-02-04 21:23:32 +00006315
Eli Friedman441cf102009-05-16 23:27:50 +00006316 if (lval == Expr::LV_IncompleteVoidType) {
6317 // Taking the address of a void variable is technically illegal, but we
6318 // allow it in cases which are otherwise valid.
6319 // Example: "extern void x; void* y = &x;".
6320 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
6321 }
6322
Reid Spencer5f016e22007-07-11 17:01:13 +00006323 // If the operand has type "type", the result has type "pointer to type".
Douglas Gregor8f70ddb2010-07-29 16:05:45 +00006324 if (op->getType()->isObjCObjectType())
6325 return Context.getObjCObjectPointerType(op->getType());
Reid Spencer5f016e22007-07-11 17:01:13 +00006326 return Context.getPointerType(op->getType());
6327}
6328
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00006329/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
Chris Lattner22caddc2008-11-23 09:13:29 +00006330QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
Sebastian Redl28507842009-02-26 14:39:58 +00006331 if (Op->isTypeDependent())
6332 return Context.DependentTy;
6333
Chris Lattner22caddc2008-11-23 09:13:29 +00006334 UsualUnaryConversions(Op);
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00006335 QualType OpTy = Op->getType();
6336 QualType Result;
6337
6338 // Note that per both C89 and C99, indirection is always legal, even if OpTy
6339 // is an incomplete type or void. It would be possible to warn about
6340 // dereferencing a void pointer, but it's completely well-defined, and such a
6341 // warning is unlikely to catch any mistakes.
6342 if (const PointerType *PT = OpTy->getAs<PointerType>())
6343 Result = PT->getPointeeType();
6344 else if (const ObjCObjectPointerType *OPT =
6345 OpTy->getAs<ObjCObjectPointerType>())
6346 Result = OPT->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006347
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00006348 if (Result.isNull()) {
6349 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
6350 << OpTy << Op->getSourceRange();
6351 return QualType();
6352 }
6353
6354 return Result;
Reid Spencer5f016e22007-07-11 17:01:13 +00006355}
6356
6357static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
6358 tok::TokenKind Kind) {
6359 BinaryOperator::Opcode Opc;
6360 switch (Kind) {
6361 default: assert(0 && "Unknown binop!");
Sebastian Redl22460502009-02-07 00:15:38 +00006362 case tok::periodstar: Opc = BinaryOperator::PtrMemD; break;
6363 case tok::arrowstar: Opc = BinaryOperator::PtrMemI; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00006364 case tok::star: Opc = BinaryOperator::Mul; break;
6365 case tok::slash: Opc = BinaryOperator::Div; break;
6366 case tok::percent: Opc = BinaryOperator::Rem; break;
6367 case tok::plus: Opc = BinaryOperator::Add; break;
6368 case tok::minus: Opc = BinaryOperator::Sub; break;
6369 case tok::lessless: Opc = BinaryOperator::Shl; break;
6370 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
6371 case tok::lessequal: Opc = BinaryOperator::LE; break;
6372 case tok::less: Opc = BinaryOperator::LT; break;
6373 case tok::greaterequal: Opc = BinaryOperator::GE; break;
6374 case tok::greater: Opc = BinaryOperator::GT; break;
6375 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
6376 case tok::equalequal: Opc = BinaryOperator::EQ; break;
6377 case tok::amp: Opc = BinaryOperator::And; break;
6378 case tok::caret: Opc = BinaryOperator::Xor; break;
6379 case tok::pipe: Opc = BinaryOperator::Or; break;
6380 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
6381 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
6382 case tok::equal: Opc = BinaryOperator::Assign; break;
6383 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
6384 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
6385 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
6386 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
6387 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
6388 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
6389 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
6390 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
6391 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
6392 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
6393 case tok::comma: Opc = BinaryOperator::Comma; break;
6394 }
6395 return Opc;
6396}
6397
6398static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
6399 tok::TokenKind Kind) {
6400 UnaryOperator::Opcode Opc;
6401 switch (Kind) {
6402 default: assert(0 && "Unknown unary op!");
6403 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
6404 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
6405 case tok::amp: Opc = UnaryOperator::AddrOf; break;
6406 case tok::star: Opc = UnaryOperator::Deref; break;
6407 case tok::plus: Opc = UnaryOperator::Plus; break;
6408 case tok::minus: Opc = UnaryOperator::Minus; break;
6409 case tok::tilde: Opc = UnaryOperator::Not; break;
6410 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00006411 case tok::kw___real: Opc = UnaryOperator::Real; break;
6412 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
6413 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
6414 }
6415 return Opc;
6416}
6417
Douglas Gregoreaebc752008-11-06 23:29:22 +00006418/// CreateBuiltinBinOp - Creates a new built-in binary operation with
6419/// operator @p Opc at location @c TokLoc. This routine only supports
6420/// built-in operations; ActOnBinOp handles overloaded operators.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00006421Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
6422 unsigned Op,
6423 Expr *lhs, Expr *rhs) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00006424 QualType ResultTy; // Result type of the binary operator.
Douglas Gregoreaebc752008-11-06 23:29:22 +00006425 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
Eli Friedmanab3a8522009-03-28 01:22:36 +00006426 // The following two variables are used for compound assignment operators
6427 QualType CompLHSTy; // Type of LHS after promotions for computation
6428 QualType CompResultTy; // Type of computation result
Douglas Gregoreaebc752008-11-06 23:29:22 +00006429
6430 switch (Opc) {
Douglas Gregoreaebc752008-11-06 23:29:22 +00006431 case BinaryOperator::Assign:
6432 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
6433 break;
Sebastian Redl22460502009-02-07 00:15:38 +00006434 case BinaryOperator::PtrMemD:
6435 case BinaryOperator::PtrMemI:
6436 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
6437 Opc == BinaryOperator::PtrMemI);
6438 break;
6439 case BinaryOperator::Mul:
Douglas Gregoreaebc752008-11-06 23:29:22 +00006440 case BinaryOperator::Div:
Chris Lattner7ef655a2010-01-12 21:23:57 +00006441 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, false,
6442 Opc == BinaryOperator::Div);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006443 break;
6444 case BinaryOperator::Rem:
6445 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
6446 break;
6447 case BinaryOperator::Add:
6448 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
6449 break;
6450 case BinaryOperator::Sub:
6451 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
6452 break;
Sebastian Redl22460502009-02-07 00:15:38 +00006453 case BinaryOperator::Shl:
Douglas Gregoreaebc752008-11-06 23:29:22 +00006454 case BinaryOperator::Shr:
6455 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
6456 break;
6457 case BinaryOperator::LE:
6458 case BinaryOperator::LT:
6459 case BinaryOperator::GE:
6460 case BinaryOperator::GT:
Douglas Gregora86b8322009-04-06 18:45:53 +00006461 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006462 break;
6463 case BinaryOperator::EQ:
6464 case BinaryOperator::NE:
Douglas Gregora86b8322009-04-06 18:45:53 +00006465 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006466 break;
6467 case BinaryOperator::And:
6468 case BinaryOperator::Xor:
6469 case BinaryOperator::Or:
6470 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
6471 break;
6472 case BinaryOperator::LAnd:
6473 case BinaryOperator::LOr:
Chris Lattner90a8f272010-07-13 19:41:32 +00006474 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc, Opc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006475 break;
6476 case BinaryOperator::MulAssign:
6477 case BinaryOperator::DivAssign:
Chris Lattner7ef655a2010-01-12 21:23:57 +00006478 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true,
6479 Opc == BinaryOperator::DivAssign);
Eli Friedmanab3a8522009-03-28 01:22:36 +00006480 CompLHSTy = CompResultTy;
6481 if (!CompResultTy.isNull())
6482 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006483 break;
6484 case BinaryOperator::RemAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00006485 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
6486 CompLHSTy = CompResultTy;
6487 if (!CompResultTy.isNull())
6488 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006489 break;
6490 case BinaryOperator::AddAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00006491 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
6492 if (!CompResultTy.isNull())
6493 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006494 break;
6495 case BinaryOperator::SubAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00006496 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
6497 if (!CompResultTy.isNull())
6498 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006499 break;
6500 case BinaryOperator::ShlAssign:
6501 case BinaryOperator::ShrAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00006502 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
6503 CompLHSTy = CompResultTy;
6504 if (!CompResultTy.isNull())
6505 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006506 break;
6507 case BinaryOperator::AndAssign:
6508 case BinaryOperator::XorAssign:
6509 case BinaryOperator::OrAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00006510 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
6511 CompLHSTy = CompResultTy;
6512 if (!CompResultTy.isNull())
6513 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006514 break;
6515 case BinaryOperator::Comma:
6516 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
6517 break;
6518 }
6519 if (ResultTy.isNull())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00006520 return ExprError();
Fariborz Jahanian57dae1a2010-08-16 21:51:12 +00006521 if (ResultTy->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
6522 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign)
6523 Diag(OpLoc, diag::err_assignment_requires_nonfragile_object)
6524 << ResultTy;
6525 }
Eli Friedmanab3a8522009-03-28 01:22:36 +00006526 if (CompResultTy.isNull())
Steve Naroff6ece14c2009-01-21 00:14:39 +00006527 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
6528 else
6529 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
Eli Friedmanab3a8522009-03-28 01:22:36 +00006530 CompLHSTy, CompResultTy,
6531 OpLoc));
Douglas Gregoreaebc752008-11-06 23:29:22 +00006532}
6533
Sebastian Redlaee3c932009-10-27 12:10:02 +00006534/// SuggestParentheses - Emit a diagnostic together with a fixit hint that wraps
6535/// ParenRange in parentheses.
Sebastian Redl6b169ac2009-10-26 17:01:32 +00006536static void SuggestParentheses(Sema &Self, SourceLocation Loc,
6537 const PartialDiagnostic &PD,
Douglas Gregor55b38842010-04-14 16:09:52 +00006538 const PartialDiagnostic &FirstNote,
6539 SourceRange FirstParenRange,
6540 const PartialDiagnostic &SecondNote,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00006541 SourceRange SecondParenRange) {
Douglas Gregor55b38842010-04-14 16:09:52 +00006542 Self.Diag(Loc, PD);
6543
6544 if (!FirstNote.getDiagID())
6545 return;
6546
6547 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(FirstParenRange.getEnd());
6548 if (!FirstParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
6549 // We can't display the parentheses, so just return.
Sebastian Redl6b169ac2009-10-26 17:01:32 +00006550 return;
6551 }
6552
Douglas Gregor55b38842010-04-14 16:09:52 +00006553 Self.Diag(Loc, FirstNote)
6554 << FixItHint::CreateInsertion(FirstParenRange.getBegin(), "(")
Douglas Gregor849b2432010-03-31 17:46:05 +00006555 << FixItHint::CreateInsertion(EndLoc, ")");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006556
Douglas Gregor55b38842010-04-14 16:09:52 +00006557 if (!SecondNote.getDiagID())
Douglas Gregor827feec2010-01-08 00:20:23 +00006558 return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006559
Douglas Gregor827feec2010-01-08 00:20:23 +00006560 EndLoc = Self.PP.getLocForEndOfToken(SecondParenRange.getEnd());
6561 if (!SecondParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
6562 // We can't display the parentheses, so just dig the
6563 // warning/error and return.
Douglas Gregor55b38842010-04-14 16:09:52 +00006564 Self.Diag(Loc, SecondNote);
Douglas Gregor827feec2010-01-08 00:20:23 +00006565 return;
6566 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006567
Douglas Gregor55b38842010-04-14 16:09:52 +00006568 Self.Diag(Loc, SecondNote)
Douglas Gregor849b2432010-03-31 17:46:05 +00006569 << FixItHint::CreateInsertion(SecondParenRange.getBegin(), "(")
6570 << FixItHint::CreateInsertion(EndLoc, ")");
Sebastian Redl6b169ac2009-10-26 17:01:32 +00006571}
6572
Sebastian Redlaee3c932009-10-27 12:10:02 +00006573/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
6574/// operators are mixed in a way that suggests that the programmer forgot that
6575/// comparison operators have higher precedence. The most typical example of
6576/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006577static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperator::Opcode Opc,
6578 SourceLocation OpLoc,Expr *lhs,Expr *rhs){
Sebastian Redlaee3c932009-10-27 12:10:02 +00006579 typedef BinaryOperator BinOp;
6580 BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1),
6581 rhsopc = static_cast<BinOp::Opcode>(-1);
6582 if (BinOp *BO = dyn_cast<BinOp>(lhs))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006583 lhsopc = BO->getOpcode();
Sebastian Redlaee3c932009-10-27 12:10:02 +00006584 if (BinOp *BO = dyn_cast<BinOp>(rhs))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006585 rhsopc = BO->getOpcode();
6586
6587 // Subs are not binary operators.
6588 if (lhsopc == -1 && rhsopc == -1)
6589 return;
6590
6591 // Bitwise operations are sometimes used as eager logical ops.
6592 // Don't diagnose this.
Sebastian Redlaee3c932009-10-27 12:10:02 +00006593 if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) &&
6594 (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc)))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006595 return;
6596
Sebastian Redlaee3c932009-10-27 12:10:02 +00006597 if (BinOp::isComparisonOp(lhsopc))
Sebastian Redl6b169ac2009-10-26 17:01:32 +00006598 SuggestParentheses(Self, OpLoc,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00006599 Self.PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redlaee3c932009-10-27 12:10:02 +00006600 << SourceRange(lhs->getLocStart(), OpLoc)
6601 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(lhsopc),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00006602 Self.PDiag(diag::note_precedence_bitwise_first)
Douglas Gregor827feec2010-01-08 00:20:23 +00006603 << BinOp::getOpcodeStr(Opc),
Douglas Gregor55b38842010-04-14 16:09:52 +00006604 SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(), rhs->getLocEnd()),
6605 Self.PDiag(diag::note_precedence_bitwise_silence)
6606 << BinOp::getOpcodeStr(lhsopc),
6607 lhs->getSourceRange());
Sebastian Redlaee3c932009-10-27 12:10:02 +00006608 else if (BinOp::isComparisonOp(rhsopc))
Sebastian Redl6b169ac2009-10-26 17:01:32 +00006609 SuggestParentheses(Self, OpLoc,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00006610 Self.PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redlaee3c932009-10-27 12:10:02 +00006611 << SourceRange(OpLoc, rhs->getLocEnd())
6612 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(rhsopc),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00006613 Self.PDiag(diag::note_precedence_bitwise_first)
Douglas Gregor827feec2010-01-08 00:20:23 +00006614 << BinOp::getOpcodeStr(Opc),
Douglas Gregor55b38842010-04-14 16:09:52 +00006615 SourceRange(lhs->getLocEnd(), cast<BinOp>(rhs)->getLHS()->getLocStart()),
6616 Self.PDiag(diag::note_precedence_bitwise_silence)
6617 << BinOp::getOpcodeStr(rhsopc),
6618 rhs->getSourceRange());
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006619}
6620
6621/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
6622/// precedence. This currently diagnoses only "arg1 'bitwise' arg2 'eq' arg3".
6623/// But it could also warn about arg1 && arg2 || arg3, as GCC 4.3+ does.
6624static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperator::Opcode Opc,
6625 SourceLocation OpLoc, Expr *lhs, Expr *rhs){
Sebastian Redlaee3c932009-10-27 12:10:02 +00006626 if (BinaryOperator::isBitwiseOp(Opc))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006627 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs);
6628}
6629
Reid Spencer5f016e22007-07-11 17:01:13 +00006630// Binary Operators. 'Tok' is the token for the operator.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00006631Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
6632 tok::TokenKind Kind,
John McCall9ae2f072010-08-23 23:25:46 +00006633 Expr *lhs, Expr *rhs) {
Reid Spencer5f016e22007-07-11 17:01:13 +00006634 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
Steve Narofff69936d2007-09-16 03:34:24 +00006635 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
6636 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00006637
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006638 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
6639 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs);
6640
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006641 return BuildBinOp(S, TokLoc, Opc, lhs, rhs);
6642}
6643
6644Action::OwningExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
6645 BinaryOperator::Opcode Opc,
6646 Expr *lhs, Expr *rhs) {
Douglas Gregor063daf62009-03-13 18:40:31 +00006647 if (getLangOptions().CPlusPlus &&
Mike Stump1eb44332009-09-09 15:08:12 +00006648 (lhs->getType()->isOverloadableType() ||
Douglas Gregor063daf62009-03-13 18:40:31 +00006649 rhs->getType()->isOverloadableType())) {
6650 // Find all of the overloaded operators visible from this
6651 // point. We perform both an operator-name lookup from the local
6652 // scope and an argument-dependent lookup based on the types of
6653 // the arguments.
John McCall6e266892010-01-26 03:27:55 +00006654 UnresolvedSet<16> Functions;
Douglas Gregor063daf62009-03-13 18:40:31 +00006655 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
John McCall6e266892010-01-26 03:27:55 +00006656 if (S && OverOp != OO_None)
6657 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
6658 Functions);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006659
Douglas Gregor063daf62009-03-13 18:40:31 +00006660 // Build the (potentially-overloaded, potentially-dependent)
6661 // binary operation.
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006662 return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs);
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00006663 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006664
Douglas Gregoreaebc752008-11-06 23:29:22 +00006665 // Build a built-in binary operation.
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006666 return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs);
Reid Spencer5f016e22007-07-11 17:01:13 +00006667}
6668
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006669Action::OwningExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00006670 unsigned OpcIn,
John McCall9ae2f072010-08-23 23:25:46 +00006671 Expr *Input) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006672 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor74253732008-11-19 15:42:04 +00006673
Reid Spencer5f016e22007-07-11 17:01:13 +00006674 QualType resultType;
6675 switch (Opc) {
Reid Spencer5f016e22007-07-11 17:01:13 +00006676 case UnaryOperator::PreInc:
6677 case UnaryOperator::PreDec:
Eli Friedmande99a452009-07-22 22:25:00 +00006678 case UnaryOperator::PostInc:
6679 case UnaryOperator::PostDec:
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00006680 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
Eli Friedmande99a452009-07-22 22:25:00 +00006681 Opc == UnaryOperator::PreInc ||
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00006682 Opc == UnaryOperator::PostInc,
6683 Opc == UnaryOperator::PreInc ||
6684 Opc == UnaryOperator::PreDec);
Reid Spencer5f016e22007-07-11 17:01:13 +00006685 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006686 case UnaryOperator::AddrOf:
Reid Spencer5f016e22007-07-11 17:01:13 +00006687 resultType = CheckAddressOfOperand(Input, OpLoc);
6688 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006689 case UnaryOperator::Deref:
Douglas Gregora873dfc2010-02-03 00:27:59 +00006690 DefaultFunctionArrayLvalueConversion(Input);
Reid Spencer5f016e22007-07-11 17:01:13 +00006691 resultType = CheckIndirectionOperand(Input, OpLoc);
6692 break;
6693 case UnaryOperator::Plus:
6694 case UnaryOperator::Minus:
Steve Naroffc80b4ee2007-07-16 21:54:35 +00006695 UsualUnaryConversions(Input);
6696 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00006697 if (resultType->isDependentType())
6698 break;
Douglas Gregor00619622010-06-22 23:41:02 +00006699 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
6700 resultType->isVectorType())
Douglas Gregor74253732008-11-19 15:42:04 +00006701 break;
6702 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
6703 resultType->isEnumeralType())
6704 break;
6705 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
6706 Opc == UnaryOperator::Plus &&
6707 resultType->isPointerType())
6708 break;
6709
Sebastian Redl0eb23302009-01-19 00:08:26 +00006710 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
6711 << resultType << Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00006712 case UnaryOperator::Not: // bitwise complement
Steve Naroffc80b4ee2007-07-16 21:54:35 +00006713 UsualUnaryConversions(Input);
6714 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00006715 if (resultType->isDependentType())
6716 break;
Chris Lattner02a65142008-07-25 23:52:49 +00006717 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
6718 if (resultType->isComplexType() || resultType->isComplexIntegerType())
6719 // C99 does not support '~' for complex conjugation.
Chris Lattnerd3a94e22008-11-20 06:06:08 +00006720 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00006721 << resultType << Input->getSourceRange();
Douglas Gregorf6094622010-07-23 15:58:24 +00006722 else if (!resultType->hasIntegerRepresentation())
Sebastian Redl0eb23302009-01-19 00:08:26 +00006723 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
6724 << resultType << Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00006725 break;
6726 case UnaryOperator::LNot: // logical negation
6727 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Douglas Gregora873dfc2010-02-03 00:27:59 +00006728 DefaultFunctionArrayLvalueConversion(Input);
Steve Naroffc80b4ee2007-07-16 21:54:35 +00006729 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00006730 if (resultType->isDependentType())
6731 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00006732 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redl0eb23302009-01-19 00:08:26 +00006733 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
6734 << resultType << Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00006735 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl0eb23302009-01-19 00:08:26 +00006736 // In C++, it's bool. C++ 5.3.1p8
6737 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00006738 break;
Chris Lattnerdbb36972007-08-24 21:16:53 +00006739 case UnaryOperator::Real:
Chris Lattnerdbb36972007-08-24 21:16:53 +00006740 case UnaryOperator::Imag:
Chris Lattnerba27e2a2009-02-17 08:12:06 +00006741 resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real);
Chris Lattnerdbb36972007-08-24 21:16:53 +00006742 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00006743 case UnaryOperator::Extension:
Reid Spencer5f016e22007-07-11 17:01:13 +00006744 resultType = Input->getType();
6745 break;
6746 }
6747 if (resultType.isNull())
Sebastian Redl0eb23302009-01-19 00:08:26 +00006748 return ExprError();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006749
Steve Naroff6ece14c2009-01-21 00:14:39 +00006750 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00006751}
6752
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006753Action::OwningExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
6754 UnaryOperator::Opcode Opc,
John McCall9ae2f072010-08-23 23:25:46 +00006755 Expr *Input) {
Anders Carlssona8a1e3d2009-11-14 21:26:41 +00006756 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
6757 Opc != UnaryOperator::Extension) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006758 // Find all of the overloaded operators visible from this
6759 // point. We perform both an operator-name lookup from the local
6760 // scope and an argument-dependent lookup based on the types of
6761 // the arguments.
John McCall6e266892010-01-26 03:27:55 +00006762 UnresolvedSet<16> Functions;
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006763 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall6e266892010-01-26 03:27:55 +00006764 if (S && OverOp != OO_None)
6765 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
6766 Functions);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006767
John McCall9ae2f072010-08-23 23:25:46 +00006768 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006769 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006770
John McCall9ae2f072010-08-23 23:25:46 +00006771 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006772}
6773
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006774// Unary Operators. 'Tok' is the token for the operator.
6775Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall9ae2f072010-08-23 23:25:46 +00006776 tok::TokenKind Op, Expr *Input) {
6777 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006778}
6779
Steve Naroff1b273c42007-09-16 14:56:35 +00006780/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Sebastian Redlf53597f2009-03-15 17:47:39 +00006781Sema::OwningExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
6782 SourceLocation LabLoc,
6783 IdentifierInfo *LabelII) {
Reid Spencer5f016e22007-07-11 17:01:13 +00006784 // Look up the record for this label identifier.
Chris Lattnerea29a3a2009-04-18 20:01:55 +00006785 LabelStmt *&LabelDecl = getLabelMap()[LabelII];
Mike Stumpeed9cac2009-02-19 03:04:26 +00006786
Daniel Dunbar0ffb1252008-08-04 16:51:22 +00006787 // If we haven't seen this label yet, create a forward reference. It
6788 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Steve Naroffcaaacec2009-03-13 15:38:40 +00006789 if (LabelDecl == 0)
Steve Naroff6ece14c2009-01-21 00:14:39 +00006790 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006791
Reid Spencer5f016e22007-07-11 17:01:13 +00006792 // Create the AST node. The address of a label always has type 'void*'.
Sebastian Redlf53597f2009-03-15 17:47:39 +00006793 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
6794 Context.getPointerType(Context.VoidTy)));
Reid Spencer5f016e22007-07-11 17:01:13 +00006795}
6796
Sebastian Redlf53597f2009-03-15 17:47:39 +00006797Sema::OwningExprResult
John McCall9ae2f072010-08-23 23:25:46 +00006798Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
Sebastian Redlf53597f2009-03-15 17:47:39 +00006799 SourceLocation RPLoc) { // "({..})"
Chris Lattnerab18c4c2007-07-24 16:58:17 +00006800 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
6801 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
6802
Douglas Gregordd8f5692010-03-10 04:54:39 +00006803 bool isFileScope
6804 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
Chris Lattner4a049f02009-04-25 19:11:05 +00006805 if (isFileScope)
Sebastian Redlf53597f2009-03-15 17:47:39 +00006806 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedmandca2b732009-01-24 23:09:00 +00006807
Chris Lattnerab18c4c2007-07-24 16:58:17 +00006808 // FIXME: there are a variety of strange constraints to enforce here, for
6809 // example, it is not possible to goto into a stmt expression apparently.
6810 // More semantic analysis is needed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00006811
Chris Lattnerab18c4c2007-07-24 16:58:17 +00006812 // If there are sub stmts in the compound stmt, take the type of the last one
6813 // as the type of the stmtexpr.
6814 QualType Ty = Context.VoidTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006815
Chris Lattner611b2ec2008-07-26 19:51:01 +00006816 if (!Compound->body_empty()) {
6817 Stmt *LastStmt = Compound->body_back();
6818 // If LastStmt is a label, skip down through into the body.
6819 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
6820 LastStmt = Label->getSubStmt();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006821
Chris Lattner611b2ec2008-07-26 19:51:01 +00006822 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattnerab18c4c2007-07-24 16:58:17 +00006823 Ty = LastExpr->getType();
Chris Lattner611b2ec2008-07-26 19:51:01 +00006824 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006825
Eli Friedmanb1d796d2009-03-23 00:24:07 +00006826 // FIXME: Check that expression type is complete/non-abstract; statement
6827 // expressions are not lvalues.
6828
Sebastian Redlf53597f2009-03-15 17:47:39 +00006829 return Owned(new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc));
Chris Lattnerab18c4c2007-07-24 16:58:17 +00006830}
Steve Naroffd34e9152007-08-01 22:05:33 +00006831
Douglas Gregor8ecdb652010-04-28 22:16:22 +00006832Sema::OwningExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
6833 TypeSourceInfo *TInfo,
Sebastian Redlf53597f2009-03-15 17:47:39 +00006834 OffsetOfComponent *CompPtr,
6835 unsigned NumComponents,
Douglas Gregor8ecdb652010-04-28 22:16:22 +00006836 SourceLocation RParenLoc) {
6837 QualType ArgTy = TInfo->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00006838 bool Dependent = ArgTy->isDependentType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00006839 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00006840
Chris Lattner73d0d4f2007-08-30 17:45:32 +00006841 // We must have at least one component that refers to the type, and the first
6842 // one is known to be a field designator. Verify that the ArgTy represents
6843 // a struct/union/class.
Sebastian Redl28507842009-02-26 14:39:58 +00006844 if (!Dependent && !ArgTy->isRecordType())
Douglas Gregor8ecdb652010-04-28 22:16:22 +00006845 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
6846 << ArgTy << TypeRange);
6847
6848 // Type must be complete per C99 7.17p3 because a declaring a variable
6849 // with an incomplete type would be ill-formed.
6850 if (!Dependent
6851 && RequireCompleteType(BuiltinLoc, ArgTy,
6852 PDiag(diag::err_offsetof_incomplete_type)
6853 << TypeRange))
6854 return ExprError();
6855
Chris Lattner9e2b75c2007-08-31 21:49:13 +00006856 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
6857 // GCC extension, diagnose them.
Eli Friedman35183ac2009-02-27 06:44:11 +00006858 // FIXME: This diagnostic isn't actually visible because the location is in
6859 // a system header!
Chris Lattner9e2b75c2007-08-31 21:49:13 +00006860 if (NumComponents != 1)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00006861 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
6862 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00006863
6864 bool DidWarnAboutNonPOD = false;
6865 QualType CurrentType = ArgTy;
6866 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
6867 llvm::SmallVector<OffsetOfNode, 4> Comps;
6868 llvm::SmallVector<Expr*, 4> Exprs;
6869 for (unsigned i = 0; i != NumComponents; ++i) {
6870 const OffsetOfComponent &OC = CompPtr[i];
6871 if (OC.isBrackets) {
6872 // Offset of an array sub-field. TODO: Should we allow vector elements?
6873 if (!CurrentType->isDependentType()) {
6874 const ArrayType *AT = Context.getAsArrayType(CurrentType);
6875 if(!AT)
6876 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
6877 << CurrentType);
6878 CurrentType = AT->getElementType();
6879 } else
6880 CurrentType = Context.DependentTy;
6881
6882 // The expression must be an integral expression.
6883 // FIXME: An integral constant expression?
6884 Expr *Idx = static_cast<Expr*>(OC.U.E);
6885 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
6886 !Idx->getType()->isIntegerType())
6887 return ExprError(Diag(Idx->getLocStart(),
6888 diag::err_typecheck_subscript_not_integer)
6889 << Idx->getSourceRange());
6890
6891 // Record this array index.
6892 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
6893 Exprs.push_back(Idx);
6894 continue;
6895 }
6896
6897 // Offset of a field.
6898 if (CurrentType->isDependentType()) {
6899 // We have the offset of a field, but we can't look into the dependent
6900 // type. Just record the identifier of the field.
6901 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
6902 CurrentType = Context.DependentTy;
6903 continue;
6904 }
6905
6906 // We need to have a complete type to look into.
6907 if (RequireCompleteType(OC.LocStart, CurrentType,
6908 diag::err_offsetof_incomplete_type))
6909 return ExprError();
6910
6911 // Look for the designated field.
6912 const RecordType *RC = CurrentType->getAs<RecordType>();
6913 if (!RC)
6914 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
6915 << CurrentType);
6916 RecordDecl *RD = RC->getDecl();
6917
6918 // C++ [lib.support.types]p5:
6919 // The macro offsetof accepts a restricted set of type arguments in this
6920 // International Standard. type shall be a POD structure or a POD union
6921 // (clause 9).
6922 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
6923 if (!CRD->isPOD() && !DidWarnAboutNonPOD &&
6924 DiagRuntimeBehavior(BuiltinLoc,
6925 PDiag(diag::warn_offsetof_non_pod_type)
6926 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
6927 << CurrentType))
6928 DidWarnAboutNonPOD = true;
6929 }
6930
6931 // Look for the field.
6932 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
6933 LookupQualifiedName(R, RD);
6934 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
6935 if (!MemberDecl)
6936 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
6937 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
6938 OC.LocEnd));
6939
Douglas Gregor9d5d60f2010-04-28 22:36:06 +00006940 // C99 7.17p3:
6941 // (If the specified member is a bit-field, the behavior is undefined.)
6942 //
6943 // We diagnose this as an error.
6944 if (MemberDecl->getBitWidth()) {
6945 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
6946 << MemberDecl->getDeclName()
6947 << SourceRange(BuiltinLoc, RParenLoc);
6948 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
6949 return ExprError();
6950 }
Eli Friedman19410a72010-08-05 10:11:36 +00006951
6952 RecordDecl *Parent = MemberDecl->getParent();
6953 bool AnonStructUnion = Parent->isAnonymousStructOrUnion();
6954 if (AnonStructUnion) {
6955 do {
6956 Parent = cast<RecordDecl>(Parent->getParent());
6957 } while (Parent->isAnonymousStructOrUnion());
6958 }
6959
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00006960 // If the member was found in a base class, introduce OffsetOfNodes for
6961 // the base class indirections.
6962 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
6963 /*DetectVirtual=*/false);
Eli Friedman19410a72010-08-05 10:11:36 +00006964 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00006965 CXXBasePath &Path = Paths.front();
6966 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
6967 B != BEnd; ++B)
6968 Comps.push_back(OffsetOfNode(B->Base));
6969 }
Eli Friedman19410a72010-08-05 10:11:36 +00006970
6971 if (AnonStructUnion) {
Douglas Gregor8ecdb652010-04-28 22:16:22 +00006972 llvm::SmallVector<FieldDecl*, 4> Path;
6973 BuildAnonymousStructUnionMemberPath(MemberDecl, Path);
6974 unsigned n = Path.size();
6975 for (int j = n - 1; j > -1; --j)
6976 Comps.push_back(OffsetOfNode(OC.LocStart, Path[j], OC.LocEnd));
6977 } else {
6978 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
6979 }
6980 CurrentType = MemberDecl->getType().getNonReferenceType();
6981 }
6982
6983 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
6984 TInfo, Comps.data(), Comps.size(),
6985 Exprs.data(), Exprs.size(), RParenLoc));
6986}
Mike Stumpeed9cac2009-02-19 03:04:26 +00006987
Douglas Gregor8ecdb652010-04-28 22:16:22 +00006988Sema::OwningExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
6989 SourceLocation BuiltinLoc,
6990 SourceLocation TypeLoc,
6991 TypeTy *argty,
6992 OffsetOfComponent *CompPtr,
6993 unsigned NumComponents,
6994 SourceLocation RPLoc) {
6995
6996 TypeSourceInfo *ArgTInfo;
6997 QualType ArgTy = GetTypeFromParser(argty, &ArgTInfo);
6998 if (ArgTy.isNull())
6999 return ExprError();
7000
Eli Friedman5a15dc12010-08-05 10:15:45 +00007001 if (!ArgTInfo)
7002 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
7003
7004 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
7005 RPLoc);
Chris Lattner73d0d4f2007-08-30 17:45:32 +00007006}
7007
7008
Sebastian Redlf53597f2009-03-15 17:47:39 +00007009Sema::OwningExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
7010 TypeTy *arg1,TypeTy *arg2,
7011 SourceLocation RPLoc) {
Abramo Bagnara3fcb73d2010-08-10 08:50:03 +00007012 TypeSourceInfo *argTInfo1;
7013 QualType argT1 = GetTypeFromParser(arg1, &argTInfo1);
7014 TypeSourceInfo *argTInfo2;
7015 QualType argT2 = GetTypeFromParser(arg2, &argTInfo2);
Mike Stumpeed9cac2009-02-19 03:04:26 +00007016
Steve Naroffd34e9152007-08-01 22:05:33 +00007017 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
Mike Stumpeed9cac2009-02-19 03:04:26 +00007018
Abramo Bagnara3fcb73d2010-08-10 08:50:03 +00007019 return BuildTypesCompatibleExpr(BuiltinLoc, argTInfo1, argTInfo2, RPLoc);
7020}
7021
7022Sema::OwningExprResult
7023Sema::BuildTypesCompatibleExpr(SourceLocation BuiltinLoc,
7024 TypeSourceInfo *argTInfo1,
7025 TypeSourceInfo *argTInfo2,
7026 SourceLocation RPLoc) {
Douglas Gregorc12a9c52009-05-19 22:28:02 +00007027 if (getLangOptions().CPlusPlus) {
7028 Diag(BuiltinLoc, diag::err_types_compatible_p_in_cplusplus)
7029 << SourceRange(BuiltinLoc, RPLoc);
7030 return ExprError();
7031 }
7032
Sebastian Redlf53597f2009-03-15 17:47:39 +00007033 return Owned(new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc,
Abramo Bagnara3fcb73d2010-08-10 08:50:03 +00007034 argTInfo1, argTInfo2, RPLoc));
Steve Naroffd34e9152007-08-01 22:05:33 +00007035}
7036
Abramo Bagnara3fcb73d2010-08-10 08:50:03 +00007037
Sebastian Redlf53597f2009-03-15 17:47:39 +00007038Sema::OwningExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
John McCall9ae2f072010-08-23 23:25:46 +00007039 Expr *CondExpr,
7040 Expr *LHSExpr, Expr *RHSExpr,
Sebastian Redlf53597f2009-03-15 17:47:39 +00007041 SourceLocation RPLoc) {
Steve Naroffd04fdd52007-08-03 21:21:27 +00007042 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
7043
Sebastian Redl28507842009-02-26 14:39:58 +00007044 QualType resType;
Douglas Gregorce940492009-09-25 04:25:58 +00007045 bool ValueDependent = false;
Douglas Gregorc9ecc572009-05-19 22:43:30 +00007046 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl28507842009-02-26 14:39:58 +00007047 resType = Context.DependentTy;
Douglas Gregorce940492009-09-25 04:25:58 +00007048 ValueDependent = true;
Sebastian Redl28507842009-02-26 14:39:58 +00007049 } else {
7050 // The conditional expression is required to be a constant expression.
7051 llvm::APSInt condEval(32);
7052 SourceLocation ExpLoc;
7053 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redlf53597f2009-03-15 17:47:39 +00007054 return ExprError(Diag(ExpLoc,
7055 diag::err_typecheck_choose_expr_requires_constant)
7056 << CondExpr->getSourceRange());
Steve Naroffd04fdd52007-08-03 21:21:27 +00007057
Sebastian Redl28507842009-02-26 14:39:58 +00007058 // If the condition is > zero, then the AST type is the same as the LSHExpr.
7059 resType = condEval.getZExtValue() ? LHSExpr->getType() : RHSExpr->getType();
Douglas Gregorce940492009-09-25 04:25:58 +00007060 ValueDependent = condEval.getZExtValue() ? LHSExpr->isValueDependent()
7061 : RHSExpr->isValueDependent();
Sebastian Redl28507842009-02-26 14:39:58 +00007062 }
7063
Sebastian Redlf53597f2009-03-15 17:47:39 +00007064 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
Douglas Gregorce940492009-09-25 04:25:58 +00007065 resType, RPLoc,
7066 resType->isDependentType(),
7067 ValueDependent));
Steve Naroffd04fdd52007-08-03 21:21:27 +00007068}
7069
Steve Naroff4eb206b2008-09-03 18:15:37 +00007070//===----------------------------------------------------------------------===//
7071// Clang Extensions.
7072//===----------------------------------------------------------------------===//
7073
7074/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff090276f2008-10-10 01:28:17 +00007075void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00007076 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
7077 PushBlockScope(BlockScope, Block);
7078 CurContext->addDecl(Block);
Fariborz Jahaniana729da22010-07-09 18:44:02 +00007079 if (BlockScope)
7080 PushDeclContext(BlockScope, Block);
7081 else
7082 CurContext = Block;
Steve Naroff090276f2008-10-10 01:28:17 +00007083}
7084
Mike Stump98eb8a72009-02-04 22:31:32 +00007085void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpaf199f32009-05-07 18:43:07 +00007086 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00007087 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007088
John McCallbf1a0282010-06-04 23:28:52 +00007089 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
John McCall82dc0092010-06-04 11:21:44 +00007090 CurBlock->TheDecl->setSignatureAsWritten(Sig);
John McCallbf1a0282010-06-04 23:28:52 +00007091 QualType T = Sig->getType();
Mike Stump98eb8a72009-02-04 22:31:32 +00007092
John McCallc71a4912010-06-04 19:02:56 +00007093 bool isVariadic;
John McCall82dc0092010-06-04 11:21:44 +00007094 QualType RetTy;
7095 if (const FunctionType *Fn = T->getAs<FunctionType>()) {
John McCallc71a4912010-06-04 19:02:56 +00007096 CurBlock->FunctionType = T;
John McCall82dc0092010-06-04 11:21:44 +00007097 RetTy = Fn->getResultType();
John McCallc71a4912010-06-04 19:02:56 +00007098 isVariadic =
John McCall82dc0092010-06-04 11:21:44 +00007099 !isa<FunctionProtoType>(Fn) || cast<FunctionProtoType>(Fn)->isVariadic();
7100 } else {
7101 RetTy = T;
John McCallc71a4912010-06-04 19:02:56 +00007102 isVariadic = false;
John McCall82dc0092010-06-04 11:21:44 +00007103 }
Mike Stump1eb44332009-09-09 15:08:12 +00007104
John McCallc71a4912010-06-04 19:02:56 +00007105 CurBlock->TheDecl->setIsVariadic(isVariadic);
Douglas Gregora873dfc2010-02-03 00:27:59 +00007106
John McCall82dc0092010-06-04 11:21:44 +00007107 // Don't allow returning an array by value.
7108 if (RetTy->isArrayType()) {
7109 Diag(ParamInfo.getSourceRange().getBegin(), diag::err_block_returns_array);
Mike Stump98eb8a72009-02-04 22:31:32 +00007110 return;
7111 }
7112
John McCall82dc0092010-06-04 11:21:44 +00007113 // Don't allow returning a objc interface by value.
7114 if (RetTy->isObjCObjectType()) {
7115 Diag(ParamInfo.getSourceRange().getBegin(),
7116 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
7117 return;
7118 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007119
John McCall82dc0092010-06-04 11:21:44 +00007120 // Context.DependentTy is used as a placeholder for a missing block
John McCallc71a4912010-06-04 19:02:56 +00007121 // return type. TODO: what should we do with declarators like:
7122 // ^ * { ... }
7123 // If the answer is "apply template argument deduction"....
John McCall82dc0092010-06-04 11:21:44 +00007124 if (RetTy != Context.DependentTy)
7125 CurBlock->ReturnType = RetTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007126
John McCall82dc0092010-06-04 11:21:44 +00007127 // Push block parameters from the declarator if we had them.
John McCallc71a4912010-06-04 19:02:56 +00007128 llvm::SmallVector<ParmVarDecl*, 8> Params;
John McCall82dc0092010-06-04 11:21:44 +00007129 if (isa<FunctionProtoType>(T)) {
7130 FunctionProtoTypeLoc TL = cast<FunctionProtoTypeLoc>(Sig->getTypeLoc());
7131 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
7132 ParmVarDecl *Param = TL.getArg(I);
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00007133 if (Param->getIdentifier() == 0 &&
7134 !Param->isImplicit() &&
7135 !Param->isInvalidDecl() &&
7136 !getLangOptions().CPlusPlus)
7137 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
John McCallc71a4912010-06-04 19:02:56 +00007138 Params.push_back(Param);
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00007139 }
John McCall82dc0092010-06-04 11:21:44 +00007140
7141 // Fake up parameter variables if we have a typedef, like
7142 // ^ fntype { ... }
7143 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
7144 for (FunctionProtoType::arg_type_iterator
7145 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
7146 ParmVarDecl *Param =
7147 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
7148 ParamInfo.getSourceRange().getBegin(),
7149 *I);
John McCallc71a4912010-06-04 19:02:56 +00007150 Params.push_back(Param);
John McCall82dc0092010-06-04 11:21:44 +00007151 }
Steve Naroff4eb206b2008-09-03 18:15:37 +00007152 }
John McCall82dc0092010-06-04 11:21:44 +00007153
John McCallc71a4912010-06-04 19:02:56 +00007154 // Set the parameters on the block decl.
7155 if (!Params.empty())
7156 CurBlock->TheDecl->setParams(Params.data(), Params.size());
John McCall82dc0092010-06-04 11:21:44 +00007157
7158 // Finally we can process decl attributes.
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00007159 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCall053f4bd2010-03-22 09:20:08 +00007160
John McCallc71a4912010-06-04 19:02:56 +00007161 if (!isVariadic && CurBlock->TheDecl->getAttr<SentinelAttr>()) {
John McCall82dc0092010-06-04 11:21:44 +00007162 Diag(ParamInfo.getAttributes()->getLoc(),
7163 diag::warn_attribute_sentinel_not_variadic) << 1;
7164 // FIXME: remove the attribute.
7165 }
7166
7167 // Put the parameter variables in scope. We can bail out immediately
7168 // if we don't have any.
John McCallc71a4912010-06-04 19:02:56 +00007169 if (Params.empty())
John McCall82dc0092010-06-04 11:21:44 +00007170 return;
7171
John McCall053f4bd2010-03-22 09:20:08 +00007172 bool ShouldCheckShadow =
7173 Diags.getDiagnosticLevel(diag::warn_decl_shadow) != Diagnostic::Ignored;
7174
Steve Naroff090276f2008-10-10 01:28:17 +00007175 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCall7a9813c2010-01-22 00:28:27 +00007176 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
7177 (*AI)->setOwningFunction(CurBlock->TheDecl);
7178
Steve Naroff090276f2008-10-10 01:28:17 +00007179 // If this has an identifier, add it to the scope stack.
John McCall053f4bd2010-03-22 09:20:08 +00007180 if ((*AI)->getIdentifier()) {
7181 if (ShouldCheckShadow)
7182 CheckShadow(CurBlock->TheScope, *AI);
7183
Steve Naroff090276f2008-10-10 01:28:17 +00007184 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCall053f4bd2010-03-22 09:20:08 +00007185 }
John McCall7a9813c2010-01-22 00:28:27 +00007186 }
Steve Naroff4eb206b2008-09-03 18:15:37 +00007187}
7188
7189/// ActOnBlockError - If there is an error parsing a block, this callback
7190/// is invoked to pop the information about the block from the action impl.
7191void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00007192 // Pop off CurBlock, handle nested blocks.
Chris Lattner5c59e2b2009-04-21 22:38:46 +00007193 PopDeclContext();
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00007194 PopFunctionOrBlockScope();
Steve Naroff4eb206b2008-09-03 18:15:37 +00007195 // FIXME: Delete the ParmVarDecl objects as well???
Steve Naroff4eb206b2008-09-03 18:15:37 +00007196}
7197
7198/// ActOnBlockStmtExpr - This is called when the body of a block statement
7199/// literal was successfully completed. ^(int x){...}
Sebastian Redlf53597f2009-03-15 17:47:39 +00007200Sema::OwningExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
John McCall9ae2f072010-08-23 23:25:46 +00007201 Stmt *Body, Scope *CurScope) {
Chris Lattner9af55002009-03-27 04:18:06 +00007202 // If blocks are disabled, emit an error.
7203 if (!LangOpts.Blocks)
7204 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump1eb44332009-09-09 15:08:12 +00007205
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00007206 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Fariborz Jahaniana729da22010-07-09 18:44:02 +00007207
Steve Naroff090276f2008-10-10 01:28:17 +00007208 PopDeclContext();
7209
Steve Naroff4eb206b2008-09-03 18:15:37 +00007210 QualType RetTy = Context.VoidTy;
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00007211 if (!BSI->ReturnType.isNull())
7212 RetTy = BSI->ReturnType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007213
Mike Stump56925862009-07-28 22:04:01 +00007214 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroff4eb206b2008-09-03 18:15:37 +00007215 QualType BlockTy;
John McCallc71a4912010-06-04 19:02:56 +00007216
7217 // If the user wrote a function type in some form, try to use that.
7218 if (!BSI->FunctionType.isNull()) {
7219 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
7220
7221 FunctionType::ExtInfo Ext = FTy->getExtInfo();
7222 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
7223
7224 // Turn protoless block types into nullary block types.
7225 if (isa<FunctionNoProtoType>(FTy)) {
7226 BlockTy = Context.getFunctionType(RetTy, 0, 0, false, 0,
7227 false, false, 0, 0, Ext);
7228
7229 // Otherwise, if we don't need to change anything about the function type,
7230 // preserve its sugar structure.
7231 } else if (FTy->getResultType() == RetTy &&
7232 (!NoReturn || FTy->getNoReturnAttr())) {
7233 BlockTy = BSI->FunctionType;
7234
7235 // Otherwise, make the minimal modifications to the function type.
7236 } else {
7237 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
7238 BlockTy = Context.getFunctionType(RetTy,
7239 FPT->arg_type_begin(),
7240 FPT->getNumArgs(),
7241 FPT->isVariadic(),
7242 /*quals*/ 0,
7243 FPT->hasExceptionSpec(),
7244 FPT->hasAnyExceptionSpec(),
7245 FPT->getNumExceptions(),
7246 FPT->exception_begin(),
7247 Ext);
7248 }
7249
7250 // If we don't have a function type, just build one from nothing.
7251 } else {
7252 BlockTy = Context.getFunctionType(RetTy, 0, 0, false, 0,
7253 false, false, 0, 0,
7254 FunctionType::ExtInfo(NoReturn, 0, CC_Default));
7255 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007256
Eli Friedmanb1d796d2009-03-23 00:24:07 +00007257 // FIXME: Check that return/parameter types are complete/non-abstract
John McCallc71a4912010-06-04 19:02:56 +00007258 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
7259 BSI->TheDecl->param_end());
Steve Naroff4eb206b2008-09-03 18:15:37 +00007260 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00007261
Chris Lattner17a78302009-04-19 05:28:12 +00007262 // If needed, diagnose invalid gotos and switches in the block.
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00007263 if (FunctionNeedsScopeChecking() && !hasAnyErrorsInThisFunction())
John McCall9ae2f072010-08-23 23:25:46 +00007264 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
Mike Stump1eb44332009-09-09 15:08:12 +00007265
John McCall9ae2f072010-08-23 23:25:46 +00007266 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
Mike Stumpa3899eb2010-01-19 23:08:01 +00007267
7268 bool Good = true;
7269 // Check goto/label use.
7270 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
7271 I = BSI->LabelMap.begin(), E = BSI->LabelMap.end(); I != E; ++I) {
7272 LabelStmt *L = I->second;
7273
7274 // Verify that we have no forward references left. If so, there was a goto
7275 // or address of a label taken, but no definition of it.
7276 if (L->getSubStmt() != 0)
7277 continue;
7278
7279 // Emit error.
7280 Diag(L->getIdentLoc(), diag::err_undeclared_label_use) << L->getName();
7281 Good = false;
7282 }
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00007283 if (!Good) {
7284 PopFunctionOrBlockScope();
Mike Stumpa3899eb2010-01-19 23:08:01 +00007285 return ExprError();
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00007286 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007287
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00007288 // Issue any analysis-based warnings.
Ted Kremenekd064fdc2010-03-23 00:13:23 +00007289 const sema::AnalysisBasedWarnings::Policy &WP =
7290 AnalysisWarnings.getDefaultPolicy();
7291 AnalysisWarnings.IssueWarnings(WP, BSI->TheDecl, BlockTy);
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00007292
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00007293 Expr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy,
7294 BSI->hasBlockDeclRefExprs);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007295 PopFunctionOrBlockScope();
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00007296 return Owned(Result);
Steve Naroff4eb206b2008-09-03 18:15:37 +00007297}
7298
Sebastian Redlf53597f2009-03-15 17:47:39 +00007299Sema::OwningExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
John McCall9ae2f072010-08-23 23:25:46 +00007300 Expr *expr, TypeTy *type,
Sebastian Redlf53597f2009-03-15 17:47:39 +00007301 SourceLocation RPLoc) {
Abramo Bagnara2cad9002010-08-10 10:06:15 +00007302 TypeSourceInfo *TInfo;
7303 QualType T = GetTypeFromParser(type, &TInfo);
John McCall9ae2f072010-08-23 23:25:46 +00007304 return BuildVAArgExpr(BuiltinLoc, expr, TInfo, RPLoc);
Abramo Bagnara2cad9002010-08-10 10:06:15 +00007305}
7306
7307Sema::OwningExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
John McCall9ae2f072010-08-23 23:25:46 +00007308 Expr *E, TypeSourceInfo *TInfo,
Abramo Bagnara2cad9002010-08-10 10:06:15 +00007309 SourceLocation RPLoc) {
Chris Lattner0d20b8a2009-04-05 15:49:53 +00007310 Expr *OrigExpr = E;
Mike Stump1eb44332009-09-09 15:08:12 +00007311
Anders Carlsson7c50aca2007-10-15 20:28:48 +00007312 InitBuiltinVaListType();
Eli Friedmanc34bcde2008-08-09 23:32:40 +00007313
7314 // Get the va_list type
7315 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedman5c091ba2009-05-16 12:46:54 +00007316 if (VaListType->isArrayType()) {
7317 // Deal with implicit array decay; for example, on x86-64,
7318 // va_list is an array, but it's supposed to decay to
7319 // a pointer for va_arg.
Eli Friedmanc34bcde2008-08-09 23:32:40 +00007320 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman5c091ba2009-05-16 12:46:54 +00007321 // Make sure the input expression also decays appropriately.
7322 UsualUnaryConversions(E);
7323 } else {
7324 // Otherwise, the va_list argument must be an l-value because
7325 // it is modified by va_arg.
Mike Stump1eb44332009-09-09 15:08:12 +00007326 if (!E->isTypeDependent() &&
Douglas Gregordd027302009-05-19 23:10:31 +00007327 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedman5c091ba2009-05-16 12:46:54 +00007328 return ExprError();
7329 }
Eli Friedmanc34bcde2008-08-09 23:32:40 +00007330
Douglas Gregordd027302009-05-19 23:10:31 +00007331 if (!E->isTypeDependent() &&
7332 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redlf53597f2009-03-15 17:47:39 +00007333 return ExprError(Diag(E->getLocStart(),
7334 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner0d20b8a2009-04-05 15:49:53 +00007335 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner9dc8f192009-04-05 00:59:53 +00007336 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007337
Eli Friedmanb1d796d2009-03-23 00:24:07 +00007338 // FIXME: Check that type is complete/non-abstract
Anders Carlsson7c50aca2007-10-15 20:28:48 +00007339 // FIXME: Warn if a non-POD type is passed in.
Mike Stumpeed9cac2009-02-19 03:04:26 +00007340
Abramo Bagnara2cad9002010-08-10 10:06:15 +00007341 QualType T = TInfo->getType().getNonLValueExprType(Context);
7342 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
Anders Carlsson7c50aca2007-10-15 20:28:48 +00007343}
7344
Sebastian Redlf53597f2009-03-15 17:47:39 +00007345Sema::OwningExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor2d8b2732008-11-29 04:51:27 +00007346 // The type of __null will be int or long, depending on the size of
7347 // pointers on the target.
7348 QualType Ty;
7349 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
7350 Ty = Context.IntTy;
7351 else
7352 Ty = Context.LongTy;
7353
Sebastian Redlf53597f2009-03-15 17:47:39 +00007354 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor2d8b2732008-11-29 04:51:27 +00007355}
7356
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00007357static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
Douglas Gregor849b2432010-03-31 17:46:05 +00007358 Expr *SrcExpr, FixItHint &Hint) {
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00007359 if (!SemaRef.getLangOptions().ObjC1)
7360 return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007361
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00007362 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
7363 if (!PT)
7364 return;
7365
7366 // Check if the destination is of type 'id'.
7367 if (!PT->isObjCIdType()) {
7368 // Check if the destination is the 'NSString' interface.
7369 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
7370 if (!ID || !ID->getIdentifier()->isStr("NSString"))
7371 return;
7372 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007373
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00007374 // Strip off any parens and casts.
7375 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
7376 if (!SL || SL->isWide())
7377 return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007378
Douglas Gregor849b2432010-03-31 17:46:05 +00007379 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00007380}
7381
Chris Lattner5cf216b2008-01-04 18:04:52 +00007382bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
7383 SourceLocation Loc,
7384 QualType DstType, QualType SrcType,
Douglas Gregora41a8c52010-04-22 00:20:18 +00007385 Expr *SrcExpr, AssignmentAction Action,
7386 bool *Complained) {
7387 if (Complained)
7388 *Complained = false;
7389
Chris Lattner5cf216b2008-01-04 18:04:52 +00007390 // Decode the result (notice that AST's are still created for extensions).
7391 bool isInvalid = false;
7392 unsigned DiagKind;
Douglas Gregor849b2432010-03-31 17:46:05 +00007393 FixItHint Hint;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007394
Chris Lattner5cf216b2008-01-04 18:04:52 +00007395 switch (ConvTy) {
7396 default: assert(0 && "Unknown conversion type");
7397 case Compatible: return false;
Chris Lattnerb7b61152008-01-04 18:22:42 +00007398 case PointerToInt:
Chris Lattner5cf216b2008-01-04 18:04:52 +00007399 DiagKind = diag::ext_typecheck_convert_pointer_int;
7400 break;
Chris Lattnerb7b61152008-01-04 18:22:42 +00007401 case IntToPointer:
7402 DiagKind = diag::ext_typecheck_convert_int_pointer;
7403 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00007404 case IncompatiblePointer:
Douglas Gregor849b2432010-03-31 17:46:05 +00007405 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
Chris Lattner5cf216b2008-01-04 18:04:52 +00007406 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
7407 break;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00007408 case IncompatiblePointerSign:
7409 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
7410 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00007411 case FunctionVoidPointer:
7412 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
7413 break;
7414 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor77a52232008-09-12 00:47:35 +00007415 // If the qualifiers lost were because we were applying the
7416 // (deprecated) C++ conversion from a string literal to a char*
7417 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
7418 // Ideally, this check would be performed in
7419 // CheckPointerTypesForAssignment. However, that would require a
7420 // bit of refactoring (so that the second argument is an
7421 // expression, rather than a type), which should be done as part
7422 // of a larger effort to fix CheckPointerTypesForAssignment for
7423 // C++ semantics.
7424 if (getLangOptions().CPlusPlus &&
7425 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
7426 return false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00007427 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
7428 break;
Sean Huntc9132b62009-11-08 07:46:34 +00007429 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanian3451e922009-11-09 22:16:37 +00007430 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00007431 break;
Steve Naroff1c7d0672008-09-04 15:10:53 +00007432 case IntToBlockPointer:
7433 DiagKind = diag::err_int_to_block_pointer;
7434 break;
7435 case IncompatibleBlockPointer:
Mike Stump25efa102009-04-21 22:51:42 +00007436 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00007437 break;
Steve Naroff39579072008-10-14 22:18:38 +00007438 case IncompatibleObjCQualifiedId:
Mike Stumpeed9cac2009-02-19 03:04:26 +00007439 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff39579072008-10-14 22:18:38 +00007440 // it can give a more specific diagnostic.
7441 DiagKind = diag::warn_incompatible_qualified_id;
7442 break;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00007443 case IncompatibleVectors:
7444 DiagKind = diag::warn_incompatible_vectors;
7445 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00007446 case Incompatible:
7447 DiagKind = diag::err_typecheck_convert_incompatible;
7448 isInvalid = true;
7449 break;
7450 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007451
Douglas Gregord4eea832010-04-09 00:35:39 +00007452 QualType FirstType, SecondType;
7453 switch (Action) {
7454 case AA_Assigning:
7455 case AA_Initializing:
7456 // The destination type comes first.
7457 FirstType = DstType;
7458 SecondType = SrcType;
7459 break;
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00007460
Douglas Gregord4eea832010-04-09 00:35:39 +00007461 case AA_Returning:
7462 case AA_Passing:
7463 case AA_Converting:
7464 case AA_Sending:
7465 case AA_Casting:
7466 // The source type comes first.
7467 FirstType = SrcType;
7468 SecondType = DstType;
7469 break;
7470 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00007471
Douglas Gregord4eea832010-04-09 00:35:39 +00007472 Diag(Loc, DiagKind) << FirstType << SecondType << Action
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00007473 << SrcExpr->getSourceRange() << Hint;
Douglas Gregora41a8c52010-04-22 00:20:18 +00007474 if (Complained)
7475 *Complained = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00007476 return isInvalid;
7477}
Anders Carlssone21555e2008-11-30 19:50:32 +00007478
Chris Lattner3bf68932009-04-25 21:59:05 +00007479bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedman3b5ccca2009-04-25 22:26:58 +00007480 llvm::APSInt ICEResult;
7481 if (E->isIntegerConstantExpr(ICEResult, Context)) {
7482 if (Result)
7483 *Result = ICEResult;
7484 return false;
7485 }
7486
Anders Carlssone21555e2008-11-30 19:50:32 +00007487 Expr::EvalResult EvalResult;
7488
Mike Stumpeed9cac2009-02-19 03:04:26 +00007489 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone21555e2008-11-30 19:50:32 +00007490 EvalResult.HasSideEffects) {
7491 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
7492
7493 if (EvalResult.Diag) {
7494 // We only show the note if it's not the usual "invalid subexpression"
7495 // or if it's actually in a subexpression.
7496 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
7497 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
7498 Diag(EvalResult.DiagLoc, EvalResult.Diag);
7499 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007500
Anders Carlssone21555e2008-11-30 19:50:32 +00007501 return true;
7502 }
7503
Eli Friedman3b5ccca2009-04-25 22:26:58 +00007504 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
7505 E->getSourceRange();
Anders Carlssone21555e2008-11-30 19:50:32 +00007506
Eli Friedman3b5ccca2009-04-25 22:26:58 +00007507 if (EvalResult.Diag &&
7508 Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
7509 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stumpeed9cac2009-02-19 03:04:26 +00007510
Anders Carlssone21555e2008-11-30 19:50:32 +00007511 if (Result)
7512 *Result = EvalResult.Val.getInt();
7513 return false;
7514}
Douglas Gregore0762c92009-06-19 23:52:42 +00007515
Douglas Gregor2afce722009-11-26 00:44:06 +00007516void
Mike Stump1eb44332009-09-09 15:08:12 +00007517Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregor2afce722009-11-26 00:44:06 +00007518 ExprEvalContexts.push_back(
7519 ExpressionEvaluationContextRecord(NewContext, ExprTemporaries.size()));
Douglas Gregorac7610d2009-06-22 20:57:11 +00007520}
7521
Mike Stump1eb44332009-09-09 15:08:12 +00007522void
Douglas Gregor2afce722009-11-26 00:44:06 +00007523Sema::PopExpressionEvaluationContext() {
7524 // Pop the current expression evaluation context off the stack.
7525 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
7526 ExprEvalContexts.pop_back();
Douglas Gregorac7610d2009-06-22 20:57:11 +00007527
Douglas Gregor06d33692009-12-12 07:57:52 +00007528 if (Rec.Context == PotentiallyPotentiallyEvaluated) {
7529 if (Rec.PotentiallyReferenced) {
7530 // Mark any remaining declarations in the current position of the stack
7531 // as "referenced". If they were not meant to be referenced, semantic
7532 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007533 for (PotentiallyReferencedDecls::iterator
Douglas Gregor06d33692009-12-12 07:57:52 +00007534 I = Rec.PotentiallyReferenced->begin(),
7535 IEnd = Rec.PotentiallyReferenced->end();
7536 I != IEnd; ++I)
7537 MarkDeclarationReferenced(I->first, I->second);
7538 }
7539
7540 if (Rec.PotentiallyDiagnosed) {
7541 // Emit any pending diagnostics.
7542 for (PotentiallyEmittedDiagnostics::iterator
7543 I = Rec.PotentiallyDiagnosed->begin(),
7544 IEnd = Rec.PotentiallyDiagnosed->end();
7545 I != IEnd; ++I)
7546 Diag(I->first, I->second);
7547 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007548 }
Douglas Gregor2afce722009-11-26 00:44:06 +00007549
7550 // When are coming out of an unevaluated context, clear out any
7551 // temporaries that we may have created as part of the evaluation of
7552 // the expression in that context: they aren't relevant because they
7553 // will never be constructed.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007554 if (Rec.Context == Unevaluated &&
Douglas Gregor2afce722009-11-26 00:44:06 +00007555 ExprTemporaries.size() > Rec.NumTemporaries)
7556 ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
7557 ExprTemporaries.end());
7558
7559 // Destroy the popped expression evaluation record.
7560 Rec.Destroy();
Douglas Gregorac7610d2009-06-22 20:57:11 +00007561}
Douglas Gregore0762c92009-06-19 23:52:42 +00007562
7563/// \brief Note that the given declaration was referenced in the source code.
7564///
7565/// This routine should be invoke whenever a given declaration is referenced
7566/// in the source code, and where that reference occurred. If this declaration
7567/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
7568/// C99 6.9p3), then the declaration will be marked as used.
7569///
7570/// \param Loc the location where the declaration was referenced.
7571///
7572/// \param D the declaration that has been referenced by the source code.
7573void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
7574 assert(D && "No declaration?");
Mike Stump1eb44332009-09-09 15:08:12 +00007575
Douglas Gregorc070cc62010-06-17 23:14:26 +00007576 if (D->isUsed(false))
Douglas Gregord7f37bf2009-06-22 23:06:13 +00007577 return;
Mike Stump1eb44332009-09-09 15:08:12 +00007578
Douglas Gregorb5352cf2009-10-08 21:35:42 +00007579 // Mark a parameter or variable declaration "used", regardless of whether we're in a
7580 // template or not. The reason for this is that unevaluated expressions
7581 // (e.g. (void)sizeof()) constitute a use for warning purposes (-Wunused-variables and
7582 // -Wunused-parameters)
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007583 if (isa<ParmVarDecl>(D) ||
Douglas Gregorfc2ca562010-04-07 20:29:57 +00007584 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod())) {
Douglas Gregore0762c92009-06-19 23:52:42 +00007585 D->setUsed(true);
Douglas Gregorfc2ca562010-04-07 20:29:57 +00007586 return;
7587 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00007588
Douglas Gregorfc2ca562010-04-07 20:29:57 +00007589 if (!isa<VarDecl>(D) && !isa<FunctionDecl>(D))
7590 return;
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00007591
Douglas Gregore0762c92009-06-19 23:52:42 +00007592 // Do not mark anything as "used" within a dependent context; wait for
7593 // an instantiation.
7594 if (CurContext->isDependentContext())
7595 return;
Mike Stump1eb44332009-09-09 15:08:12 +00007596
Douglas Gregor2afce722009-11-26 00:44:06 +00007597 switch (ExprEvalContexts.back().Context) {
Douglas Gregorac7610d2009-06-22 20:57:11 +00007598 case Unevaluated:
7599 // We are in an expression that is not potentially evaluated; do nothing.
7600 return;
Mike Stump1eb44332009-09-09 15:08:12 +00007601
Douglas Gregorac7610d2009-06-22 20:57:11 +00007602 case PotentiallyEvaluated:
7603 // We are in a potentially-evaluated expression, so this declaration is
7604 // "used"; handle this below.
7605 break;
Mike Stump1eb44332009-09-09 15:08:12 +00007606
Douglas Gregorac7610d2009-06-22 20:57:11 +00007607 case PotentiallyPotentiallyEvaluated:
7608 // We are in an expression that may be potentially evaluated; queue this
7609 // declaration reference until we know whether the expression is
7610 // potentially evaluated.
Douglas Gregor2afce722009-11-26 00:44:06 +00007611 ExprEvalContexts.back().addReferencedDecl(Loc, D);
Douglas Gregorac7610d2009-06-22 20:57:11 +00007612 return;
7613 }
Mike Stump1eb44332009-09-09 15:08:12 +00007614
Douglas Gregore0762c92009-06-19 23:52:42 +00007615 // Note that this declaration has been used.
Fariborz Jahanianb7f4cc02009-06-22 17:30:33 +00007616 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00007617 unsigned TypeQuals;
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00007618 if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) {
Chandler Carruth4e6fbce2010-08-23 07:55:51 +00007619 if (Constructor->getParent()->hasTrivialConstructor())
7620 return;
7621 if (!Constructor->isUsed(false))
7622 DefineImplicitDefaultConstructor(Loc, Constructor);
Mike Stump1eb44332009-09-09 15:08:12 +00007623 } else if (Constructor->isImplicit() &&
Douglas Gregor9e9199d2009-12-22 00:34:07 +00007624 Constructor->isCopyConstructor(TypeQuals)) {
Douglas Gregorc070cc62010-06-17 23:14:26 +00007625 if (!Constructor->isUsed(false))
Fariborz Jahanian485f0872009-06-22 23:34:40 +00007626 DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals);
7627 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007628
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007629 MarkVTableUsed(Loc, Constructor->getParent());
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007630 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Douglas Gregorc070cc62010-06-17 23:14:26 +00007631 if (Destructor->isImplicit() && !Destructor->isUsed(false))
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007632 DefineImplicitDestructor(Loc, Destructor);
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007633 if (Destructor->isVirtual())
7634 MarkVTableUsed(Loc, Destructor->getParent());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007635 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
7636 if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
7637 MethodDecl->getOverloadedOperator() == OO_Equal) {
Douglas Gregorc070cc62010-06-17 23:14:26 +00007638 if (!MethodDecl->isUsed(false))
Douglas Gregor39957dc2010-05-01 15:04:51 +00007639 DefineImplicitCopyAssignment(Loc, MethodDecl);
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007640 } else if (MethodDecl->isVirtual())
7641 MarkVTableUsed(Loc, MethodDecl->getParent());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007642 }
Fariborz Jahanianf5ed9e02009-06-24 22:09:44 +00007643 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Mike Stump1eb44332009-09-09 15:08:12 +00007644 // Implicit instantiation of function templates and member functions of
Douglas Gregor1637be72009-06-26 00:10:03 +00007645 // class templates.
Douglas Gregor6cfacfe2010-05-17 17:34:56 +00007646 if (Function->isImplicitlyInstantiable()) {
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00007647 bool AlreadyInstantiated = false;
7648 if (FunctionTemplateSpecializationInfo *SpecInfo
7649 = Function->getTemplateSpecializationInfo()) {
7650 if (SpecInfo->getPointOfInstantiation().isInvalid())
7651 SpecInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007652 else if (SpecInfo->getTemplateSpecializationKind()
Douglas Gregor3b846b62009-10-27 20:53:28 +00007653 == TSK_ImplicitInstantiation)
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00007654 AlreadyInstantiated = true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007655 } else if (MemberSpecializationInfo *MSInfo
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00007656 = Function->getMemberSpecializationInfo()) {
7657 if (MSInfo->getPointOfInstantiation().isInvalid())
7658 MSInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007659 else if (MSInfo->getTemplateSpecializationKind()
Douglas Gregor3b846b62009-10-27 20:53:28 +00007660 == TSK_ImplicitInstantiation)
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00007661 AlreadyInstantiated = true;
7662 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007663
Douglas Gregor60406be2010-01-16 22:29:39 +00007664 if (!AlreadyInstantiated) {
7665 if (isa<CXXRecordDecl>(Function->getDeclContext()) &&
7666 cast<CXXRecordDecl>(Function->getDeclContext())->isLocalClass())
7667 PendingLocalImplicitInstantiations.push_back(std::make_pair(Function,
7668 Loc));
7669 else
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007670 PendingImplicitInstantiations.push_back(std::make_pair(Function,
Douglas Gregor60406be2010-01-16 22:29:39 +00007671 Loc));
7672 }
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00007673 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007674
Douglas Gregore0762c92009-06-19 23:52:42 +00007675 // FIXME: keep track of references to static functions
Douglas Gregore0762c92009-06-19 23:52:42 +00007676 Function->setUsed(true);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007677
Douglas Gregore0762c92009-06-19 23:52:42 +00007678 return;
Douglas Gregord7f37bf2009-06-22 23:06:13 +00007679 }
Mike Stump1eb44332009-09-09 15:08:12 +00007680
Douglas Gregore0762c92009-06-19 23:52:42 +00007681 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00007682 // Implicit instantiation of static data members of class templates.
Mike Stump1eb44332009-09-09 15:08:12 +00007683 if (Var->isStaticDataMember() &&
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00007684 Var->getInstantiatedFromStaticDataMember()) {
7685 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
7686 assert(MSInfo && "Missing member specialization information?");
7687 if (MSInfo->getPointOfInstantiation().isInvalid() &&
7688 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
7689 MSInfo->setPointOfInstantiation(Loc);
7690 PendingImplicitInstantiations.push_back(std::make_pair(Var, Loc));
7691 }
7692 }
Mike Stump1eb44332009-09-09 15:08:12 +00007693
Douglas Gregore0762c92009-06-19 23:52:42 +00007694 // FIXME: keep track of references to static data?
Douglas Gregor7caa6822009-07-24 20:34:43 +00007695
Douglas Gregore0762c92009-06-19 23:52:42 +00007696 D->setUsed(true);
Douglas Gregor7caa6822009-07-24 20:34:43 +00007697 return;
Sam Weinigcce6ebc2009-09-11 03:29:30 +00007698 }
Douglas Gregore0762c92009-06-19 23:52:42 +00007699}
Anders Carlsson8c8d9192009-10-09 23:51:55 +00007700
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00007701namespace {
Chandler Carruthdfc35e32010-06-09 08:17:30 +00007702 // Mark all of the declarations referenced
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00007703 // FIXME: Not fully implemented yet! We need to have a better understanding
Chandler Carruthdfc35e32010-06-09 08:17:30 +00007704 // of when we're entering
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00007705 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
7706 Sema &S;
7707 SourceLocation Loc;
Chandler Carruthdfc35e32010-06-09 08:17:30 +00007708
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00007709 public:
7710 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
Chandler Carruthdfc35e32010-06-09 08:17:30 +00007711
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00007712 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
Chandler Carruthdfc35e32010-06-09 08:17:30 +00007713
7714 bool TraverseTemplateArgument(const TemplateArgument &Arg);
7715 bool TraverseRecordType(RecordType *T);
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00007716 };
7717}
7718
Chandler Carruthdfc35e32010-06-09 08:17:30 +00007719bool MarkReferencedDecls::TraverseTemplateArgument(
7720 const TemplateArgument &Arg) {
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00007721 if (Arg.getKind() == TemplateArgument::Declaration) {
7722 S.MarkDeclarationReferenced(Loc, Arg.getAsDecl());
7723 }
Chandler Carruthdfc35e32010-06-09 08:17:30 +00007724
7725 return Inherited::TraverseTemplateArgument(Arg);
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00007726}
7727
Chandler Carruthdfc35e32010-06-09 08:17:30 +00007728bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00007729 if (ClassTemplateSpecializationDecl *Spec
7730 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
7731 const TemplateArgumentList &Args = Spec->getTemplateArgs();
Chandler Carruthdfc35e32010-06-09 08:17:30 +00007732 return TraverseTemplateArguments(Args.getFlatArgumentList(),
7733 Args.flat_size());
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00007734 }
7735
Chandler Carruthe3e210c2010-06-10 10:31:57 +00007736 return true;
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00007737}
7738
7739void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
7740 MarkReferencedDecls Marker(*this, Loc);
Chandler Carruthdfc35e32010-06-09 08:17:30 +00007741 Marker.TraverseType(Context.getCanonicalType(T));
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00007742}
7743
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00007744/// \brief Emit a diagnostic that describes an effect on the run-time behavior
7745/// of the program being compiled.
7746///
7747/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007748/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00007749/// possibility that the code will actually be executable. Code in sizeof()
7750/// expressions, code used only during overload resolution, etc., are not
7751/// potentially evaluated. This routine will suppress such diagnostics or,
7752/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007753/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00007754/// later.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007755///
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00007756/// This routine should be used for all diagnostics that describe the run-time
7757/// behavior of a program, such as passing a non-POD value through an ellipsis.
7758/// Failure to do so will likely result in spurious diagnostics or failures
7759/// during overload resolution or within sizeof/alignof/typeof/typeid.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007760bool Sema::DiagRuntimeBehavior(SourceLocation Loc,
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00007761 const PartialDiagnostic &PD) {
7762 switch (ExprEvalContexts.back().Context ) {
7763 case Unevaluated:
7764 // The argument will never be evaluated, so don't complain.
7765 break;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007766
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00007767 case PotentiallyEvaluated:
7768 Diag(Loc, PD);
7769 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007770
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00007771 case PotentiallyPotentiallyEvaluated:
7772 ExprEvalContexts.back().addDiagnostic(Loc, PD);
7773 break;
7774 }
7775
7776 return false;
7777}
7778
Anders Carlsson8c8d9192009-10-09 23:51:55 +00007779bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
7780 CallExpr *CE, FunctionDecl *FD) {
7781 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
7782 return false;
7783
7784 PartialDiagnostic Note =
7785 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
7786 << FD->getDeclName() : PDiag();
7787 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007788
Anders Carlsson8c8d9192009-10-09 23:51:55 +00007789 if (RequireCompleteType(Loc, ReturnType,
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007790 FD ?
Anders Carlsson8c8d9192009-10-09 23:51:55 +00007791 PDiag(diag::err_call_function_incomplete_return)
7792 << CE->getSourceRange() << FD->getDeclName() :
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007793 PDiag(diag::err_call_incomplete_return)
Anders Carlsson8c8d9192009-10-09 23:51:55 +00007794 << CE->getSourceRange(),
7795 std::make_pair(NoteLoc, Note)))
7796 return true;
7797
7798 return false;
7799}
7800
John McCall5a881bb2009-10-12 21:59:07 +00007801// Diagnose the common s/=/==/ typo. Note that adding parentheses
7802// will prevent this condition from triggering, which is what we want.
7803void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
7804 SourceLocation Loc;
7805
John McCalla52ef082009-11-11 02:41:58 +00007806 unsigned diagnostic = diag::warn_condition_is_assignment;
7807
John McCall5a881bb2009-10-12 21:59:07 +00007808 if (isa<BinaryOperator>(E)) {
7809 BinaryOperator *Op = cast<BinaryOperator>(E);
7810 if (Op->getOpcode() != BinaryOperator::Assign)
7811 return;
7812
John McCallc8d8ac52009-11-12 00:06:05 +00007813 // Greylist some idioms by putting them into a warning subcategory.
7814 if (ObjCMessageExpr *ME
7815 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
7816 Selector Sel = ME->getSelector();
7817
John McCallc8d8ac52009-11-12 00:06:05 +00007818 // self = [<foo> init...]
7819 if (isSelfExpr(Op->getLHS())
7820 && Sel.getIdentifierInfoForSlot(0)->getName().startswith("init"))
7821 diagnostic = diag::warn_condition_is_idiomatic_assignment;
7822
7823 // <foo> = [<bar> nextObject]
7824 else if (Sel.isUnarySelector() &&
7825 Sel.getIdentifierInfoForSlot(0)->getName() == "nextObject")
7826 diagnostic = diag::warn_condition_is_idiomatic_assignment;
7827 }
John McCalla52ef082009-11-11 02:41:58 +00007828
John McCall5a881bb2009-10-12 21:59:07 +00007829 Loc = Op->getOperatorLoc();
7830 } else if (isa<CXXOperatorCallExpr>(E)) {
7831 CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(E);
7832 if (Op->getOperator() != OO_Equal)
7833 return;
7834
7835 Loc = Op->getOperatorLoc();
7836 } else {
7837 // Not an assignment.
7838 return;
7839 }
7840
John McCall5a881bb2009-10-12 21:59:07 +00007841 SourceLocation Open = E->getSourceRange().getBegin();
John McCall2d152152009-10-12 22:25:59 +00007842 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007843
Douglas Gregor55b38842010-04-14 16:09:52 +00007844 Diag(Loc, diagnostic) << E->getSourceRange();
Douglas Gregor827feec2010-01-08 00:20:23 +00007845 Diag(Loc, diag::note_condition_assign_to_comparison)
Douglas Gregor849b2432010-03-31 17:46:05 +00007846 << FixItHint::CreateReplacement(Loc, "==");
Douglas Gregor55b38842010-04-14 16:09:52 +00007847 Diag(Loc, diag::note_condition_assign_silence)
7848 << FixItHint::CreateInsertion(Open, "(")
7849 << FixItHint::CreateInsertion(Close, ")");
John McCall5a881bb2009-10-12 21:59:07 +00007850}
7851
7852bool Sema::CheckBooleanCondition(Expr *&E, SourceLocation Loc) {
7853 DiagnoseAssignmentAsCondition(E);
7854
7855 if (!E->isTypeDependent()) {
Douglas Gregora873dfc2010-02-03 00:27:59 +00007856 DefaultFunctionArrayLvalueConversion(E);
John McCall5a881bb2009-10-12 21:59:07 +00007857
7858 QualType T = E->getType();
7859
7860 if (getLangOptions().CPlusPlus) {
7861 if (CheckCXXBooleanCondition(E)) // C++ 6.4p4
7862 return true;
7863 } else if (!T->isScalarType()) { // C99 6.8.4.1p1
7864 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
7865 << T << E->getSourceRange();
7866 return true;
7867 }
7868 }
7869
7870 return false;
7871}
Douglas Gregor586596f2010-05-06 17:25:47 +00007872
7873Sema::OwningExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
John McCall9ae2f072010-08-23 23:25:46 +00007874 Expr *Sub) {
Douglas Gregoreecf38f2010-05-06 21:39:56 +00007875 if (!Sub)
Douglas Gregor586596f2010-05-06 17:25:47 +00007876 return ExprError();
7877
Douglas Gregorff331c12010-07-25 18:17:45 +00007878 if (CheckBooleanCondition(Sub, Loc))
Douglas Gregor586596f2010-05-06 17:25:47 +00007879 return ExprError();
Douglas Gregor586596f2010-05-06 17:25:47 +00007880
7881 return Owned(Sub);
7882}