blob: 73127df5ddc23d50f4e95fe318365c1b9706b518 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Douglas Gregor99a2e602009-12-16 01:38:02 +000015#include "SemaInit.h"
John McCall7d384dd2009-11-18 07:57:50 +000016#include "Lookup.h"
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000017#include "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"
Steve Naroff4eb206b2008-09-03 18:15:37 +000032#include "clang/Parse/DeclSpec.h"
Chris Lattner418f6c72008-10-26 23:43:26 +000033#include "clang/Parse/Designator.h"
Steve Naroff4eb206b2008-09-03 18:15:37 +000034#include "clang/Parse/Scope.h"
Douglas Gregor314b97f2009-11-10 19:49:08 +000035#include "clang/Parse/Template.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>()) {
62 Diag(Loc, diag::warn_unavailable) << D->getDeclName();
63 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
462
Douglas Gregora2813ce2009-10-23 18:54:35 +0000463/// BuildDeclRefExpr - Build a DeclRefExpr.
Anders Carlssone41590d2009-06-24 00:10:43 +0000464Sema::OwningExprResult
John McCalldbd872f2009-12-08 09:08:17 +0000465Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, SourceLocation Loc,
Sebastian Redlebc07d52009-02-03 20:19:35 +0000466 const CXXScopeSpec *SS) {
Anders Carlssone2bb2242009-06-26 19:16:07 +0000467 if (Context.getCanonicalType(Ty) == Context.UndeducedAutoTy) {
468 Diag(Loc,
Mike Stump1eb44332009-09-09 15:08:12 +0000469 diag::err_auto_variable_cannot_appear_in_own_initializer)
Anders Carlssone2bb2242009-06-26 19:16:07 +0000470 << D->getDeclName();
471 return ExprError();
472 }
Mike Stump1eb44332009-09-09 15:08:12 +0000473
Anders Carlssone41590d2009-06-24 00:10:43 +0000474 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Douglas Gregor15dedf02010-04-27 21:10:04 +0000475 if (isa<NonTypeTemplateParmDecl>(VD)) {
476 // Non-type template parameters can be referenced anywhere they are
477 // visible.
Douglas Gregor63982352010-07-13 18:40:04 +0000478 Ty = Ty.getNonLValueExprType(Context);
Douglas Gregor15dedf02010-04-27 21:10:04 +0000479 } else if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
Anders Carlssone41590d2009-06-24 00:10:43 +0000480 if (const FunctionDecl *FD = MD->getParent()->isLocalClass()) {
481 if (VD->hasLocalStorage() && VD->getDeclContext() != CurContext) {
Mike Stump1eb44332009-09-09 15:08:12 +0000482 Diag(Loc, diag::err_reference_to_local_var_in_enclosing_function)
Anders Carlssone41590d2009-06-24 00:10:43 +0000483 << D->getIdentifier() << FD->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +0000484 Diag(D->getLocation(), diag::note_local_variable_declared_here)
Anders Carlssone41590d2009-06-24 00:10:43 +0000485 << D->getIdentifier();
486 return ExprError();
487 }
488 }
489 }
490 }
Mike Stump1eb44332009-09-09 15:08:12 +0000491
Douglas Gregore0762c92009-06-19 23:52:42 +0000492 MarkDeclarationReferenced(Loc, D);
Mike Stump1eb44332009-09-09 15:08:12 +0000493
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000494 return Owned(DeclRefExpr::Create(Context,
495 SS? (NestedNameSpecifier *)SS->getScopeRep() : 0,
496 SS? SS->getRange() : SourceRange(),
Douglas Gregor0da76df2009-11-23 11:41:28 +0000497 D, Loc, Ty));
Douglas Gregor1a49af92009-01-06 05:10:23 +0000498}
499
Douglas Gregorffb4b6e2009-04-15 06:41:24 +0000500/// \brief Given a field that represents a member of an anonymous
501/// struct/union, build the path from that field's context to the
502/// actual member.
503///
504/// Construct the sequence of field member references we'll have to
505/// perform to get to the field in the anonymous union/struct. The
506/// list of members is built from the field outward, so traverse it
507/// backwards to go from an object in the current context to the field
508/// we found.
509///
510/// \returns The variable from which the field access should begin,
511/// for an anonymous struct/union that is not a member of another
512/// class. Otherwise, returns NULL.
513VarDecl *Sema::BuildAnonymousStructUnionMemberPath(FieldDecl *Field,
514 llvm::SmallVectorImpl<FieldDecl *> &Path) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000515 assert(Field->getDeclContext()->isRecord() &&
516 cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion()
517 && "Field must be stored inside an anonymous struct or union");
518
Douglas Gregorffb4b6e2009-04-15 06:41:24 +0000519 Path.push_back(Field);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000520 VarDecl *BaseObject = 0;
521 DeclContext *Ctx = Field->getDeclContext();
522 do {
523 RecordDecl *Record = cast<RecordDecl>(Ctx);
John McCallbc365c52010-05-21 01:17:40 +0000524 ValueDecl *AnonObject = Record->getAnonymousStructOrUnionObject();
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000525 if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject))
Douglas Gregorffb4b6e2009-04-15 06:41:24 +0000526 Path.push_back(AnonField);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000527 else {
528 BaseObject = cast<VarDecl>(AnonObject);
529 break;
530 }
531 Ctx = Ctx->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +0000532 } while (Ctx->isRecord() &&
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000533 cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion());
Douglas Gregorffb4b6e2009-04-15 06:41:24 +0000534
535 return BaseObject;
536}
537
538Sema::OwningExprResult
539Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
540 FieldDecl *Field,
541 Expr *BaseObjectExpr,
542 SourceLocation OpLoc) {
543 llvm::SmallVector<FieldDecl *, 4> AnonFields;
Mike Stump1eb44332009-09-09 15:08:12 +0000544 VarDecl *BaseObject = BuildAnonymousStructUnionMemberPath(Field,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +0000545 AnonFields);
546
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000547 // Build the expression that refers to the base object, from
548 // which we will build a sequence of member references to each
549 // of the anonymous union objects and, eventually, the field we
550 // found via name lookup.
551 bool BaseObjectIsPointer = false;
John McCall0953e762009-09-24 19:53:00 +0000552 Qualifiers BaseQuals;
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000553 if (BaseObject) {
554 // BaseObject is an anonymous struct/union variable (and is,
555 // therefore, not part of another non-anonymous record).
Ted Kremenek8189cde2009-02-07 01:47:29 +0000556 if (BaseObjectExpr) BaseObjectExpr->Destroy(Context);
Douglas Gregore0762c92009-06-19 23:52:42 +0000557 MarkDeclarationReferenced(Loc, BaseObject);
Steve Naroff6ece14c2009-01-21 00:14:39 +0000558 BaseObjectExpr = new (Context) DeclRefExpr(BaseObject,BaseObject->getType(),
Mike Stumpeed9cac2009-02-19 03:04:26 +0000559 SourceLocation());
John McCall0953e762009-09-24 19:53:00 +0000560 BaseQuals
561 = Context.getCanonicalType(BaseObject->getType()).getQualifiers();
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000562 } else if (BaseObjectExpr) {
563 // The caller provided the base object expression. Determine
564 // whether its a pointer and whether it adds any qualifiers to the
565 // anonymous struct/union fields we're looking into.
566 QualType ObjectType = BaseObjectExpr->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000567 if (const PointerType *ObjectPtr = ObjectType->getAs<PointerType>()) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000568 BaseObjectIsPointer = true;
569 ObjectType = ObjectPtr->getPointeeType();
570 }
John McCall0953e762009-09-24 19:53:00 +0000571 BaseQuals
572 = Context.getCanonicalType(ObjectType).getQualifiers();
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000573 } else {
574 // We've found a member of an anonymous struct/union that is
575 // inside a non-anonymous struct/union, so in a well-formed
576 // program our base object expression is "this".
John McCallea1471e2010-05-20 01:18:31 +0000577 DeclContext *DC = getFunctionLevelDeclContext();
578 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000579 if (!MD->isStatic()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000580 QualType AnonFieldType
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000581 = Context.getTagDeclType(
582 cast<RecordDecl>(AnonFields.back()->getDeclContext()));
583 QualType ThisType = Context.getTagDeclType(MD->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +0000584 if ((Context.getCanonicalType(AnonFieldType)
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000585 == Context.getCanonicalType(ThisType)) ||
586 IsDerivedFrom(ThisType, AnonFieldType)) {
587 // Our base object expression is "this".
Douglas Gregor8aa5f402009-12-24 20:23:34 +0000588 BaseObjectExpr = new (Context) CXXThisExpr(Loc,
Douglas Gregor828a1972010-01-07 23:12:05 +0000589 MD->getThisType(Context),
590 /*isImplicit=*/true);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000591 BaseObjectIsPointer = true;
592 }
593 } else {
Sebastian Redlcd965b92009-01-18 18:53:16 +0000594 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
595 << Field->getDeclName());
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000596 }
John McCall0953e762009-09-24 19:53:00 +0000597 BaseQuals = Qualifiers::fromCVRMask(MD->getTypeQualifiers());
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000598 }
599
Mike Stump1eb44332009-09-09 15:08:12 +0000600 if (!BaseObjectExpr)
Sebastian Redlcd965b92009-01-18 18:53:16 +0000601 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
602 << Field->getDeclName());
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000603 }
604
605 // Build the implicit member references to the field of the
606 // anonymous struct/union.
607 Expr *Result = BaseObjectExpr;
John McCall0953e762009-09-24 19:53:00 +0000608 Qualifiers ResultQuals = BaseQuals;
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000609 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
610 FI = AnonFields.rbegin(), FIEnd = AnonFields.rend();
611 FI != FIEnd; ++FI) {
612 QualType MemberType = (*FI)->getType();
John McCall0953e762009-09-24 19:53:00 +0000613 Qualifiers MemberTypeQuals =
614 Context.getCanonicalType(MemberType).getQualifiers();
615
616 // CVR attributes from the base are picked up by members,
617 // except that 'mutable' members don't pick up 'const'.
618 if ((*FI)->isMutable())
619 ResultQuals.removeConst();
620
621 // GC attributes are never picked up by members.
622 ResultQuals.removeObjCGCAttr();
623
624 // TR 18037 does not allow fields to be declared with address spaces.
625 assert(!MemberTypeQuals.hasAddressSpace());
626
627 Qualifiers NewQuals = ResultQuals + MemberTypeQuals;
628 if (NewQuals != MemberTypeQuals)
629 MemberType = Context.getQualifiedType(MemberType, NewQuals);
630
Douglas Gregore0762c92009-06-19 23:52:42 +0000631 MarkDeclarationReferenced(Loc, *FI);
John McCall6bb80172010-03-30 21:47:33 +0000632 PerformObjectMemberConversion(Result, /*FIXME:Qualifier=*/0, *FI, *FI);
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +0000633 // FIXME: Might this end up being a qualified name?
Steve Naroff6ece14c2009-01-21 00:14:39 +0000634 Result = new (Context) MemberExpr(Result, BaseObjectIsPointer, *FI,
635 OpLoc, MemberType);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000636 BaseObjectIsPointer = false;
John McCall0953e762009-09-24 19:53:00 +0000637 ResultQuals = NewQuals;
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000638 }
639
Sebastian Redlcd965b92009-01-18 18:53:16 +0000640 return Owned(Result);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000641}
642
John McCall129e2df2009-11-30 22:42:35 +0000643/// Decomposes the given name into a DeclarationName, its location, and
644/// possibly a list of template arguments.
645///
646/// If this produces template arguments, it is permitted to call
647/// DecomposeTemplateName.
648///
649/// This actually loses a lot of source location information for
650/// non-standard name kinds; we should consider preserving that in
651/// some way.
652static void DecomposeUnqualifiedId(Sema &SemaRef,
653 const UnqualifiedId &Id,
654 TemplateArgumentListInfo &Buffer,
655 DeclarationName &Name,
656 SourceLocation &NameLoc,
657 const TemplateArgumentListInfo *&TemplateArgs) {
658 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
659 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
660 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
661
662 ASTTemplateArgsPtr TemplateArgsPtr(SemaRef,
663 Id.TemplateId->getTemplateArgs(),
664 Id.TemplateId->NumArgs);
665 SemaRef.translateTemplateArguments(TemplateArgsPtr, Buffer);
666 TemplateArgsPtr.release();
667
668 TemplateName TName =
669 Sema::TemplateTy::make(Id.TemplateId->Template).getAsVal<TemplateName>();
670
671 Name = SemaRef.Context.getNameForTemplate(TName);
672 NameLoc = Id.TemplateId->TemplateNameLoc;
673 TemplateArgs = &Buffer;
674 } else {
675 Name = SemaRef.GetNameFromUnqualifiedId(Id);
676 NameLoc = Id.StartLocation;
677 TemplateArgs = 0;
678 }
679}
680
John McCall4c72d3e2010-02-08 19:26:07 +0000681/// Determines whether the given record is "fully-formed" at the given
682/// location, i.e. whether a qualified lookup into it is assured of
683/// getting consistent results already.
John McCall129e2df2009-11-30 22:42:35 +0000684static bool IsFullyFormedScope(Sema &SemaRef, CXXRecordDecl *Record) {
John McCall4c72d3e2010-02-08 19:26:07 +0000685 if (!Record->hasDefinition())
686 return false;
687
John McCall129e2df2009-11-30 22:42:35 +0000688 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
689 E = Record->bases_end(); I != E; ++I) {
690 CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
691 CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
692 if (!BaseRT) return false;
693
694 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall4c72d3e2010-02-08 19:26:07 +0000695 if (!BaseRecord->hasDefinition() ||
John McCall129e2df2009-11-30 22:42:35 +0000696 !IsFullyFormedScope(SemaRef, BaseRecord))
697 return false;
698 }
699
700 return true;
701}
702
John McCalle1599ce2009-11-30 23:50:49 +0000703/// Determines whether we can lookup this id-expression now or whether
704/// we have to wait until template instantiation is complete.
705static bool IsDependentIdExpression(Sema &SemaRef, const CXXScopeSpec &SS) {
John McCall129e2df2009-11-30 22:42:35 +0000706 DeclContext *DC = SemaRef.computeDeclContext(SS, false);
John McCall129e2df2009-11-30 22:42:35 +0000707
John McCalle1599ce2009-11-30 23:50:49 +0000708 // If the qualifier scope isn't computable, it's definitely dependent.
709 if (!DC) return true;
710
711 // If the qualifier scope doesn't name a record, we can always look into it.
712 if (!isa<CXXRecordDecl>(DC)) return false;
713
714 // We can't look into record types unless they're fully-formed.
715 if (!IsFullyFormedScope(SemaRef, cast<CXXRecordDecl>(DC))) return true;
716
John McCallaa81e162009-12-01 22:10:20 +0000717 return false;
718}
John McCalle1599ce2009-11-30 23:50:49 +0000719
John McCallaa81e162009-12-01 22:10:20 +0000720/// Determines if the given class is provably not derived from all of
721/// the prospective base classes.
722static bool IsProvablyNotDerivedFrom(Sema &SemaRef,
723 CXXRecordDecl *Record,
724 const llvm::SmallPtrSet<CXXRecordDecl*, 4> &Bases) {
John McCallb1b42562009-12-01 22:28:41 +0000725 if (Bases.count(Record->getCanonicalDecl()))
John McCallaa81e162009-12-01 22:10:20 +0000726 return false;
727
Douglas Gregor952b0172010-02-11 01:04:33 +0000728 RecordDecl *RD = Record->getDefinition();
John McCallb1b42562009-12-01 22:28:41 +0000729 if (!RD) return false;
730 Record = cast<CXXRecordDecl>(RD);
731
John McCallaa81e162009-12-01 22:10:20 +0000732 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
733 E = Record->bases_end(); I != E; ++I) {
734 CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
735 CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
736 if (!BaseRT) return false;
737
738 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCallaa81e162009-12-01 22:10:20 +0000739 if (!IsProvablyNotDerivedFrom(SemaRef, BaseRecord, Bases))
740 return false;
741 }
742
743 return true;
744}
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000745
John McCallaa81e162009-12-01 22:10:20 +0000746enum IMAKind {
747 /// The reference is definitely not an instance member access.
748 IMA_Static,
749
750 /// The reference may be an implicit instance member access.
751 IMA_Mixed,
752
753 /// The reference may be to an instance member, but it is invalid if
754 /// so, because the context is not an instance method.
755 IMA_Mixed_StaticContext,
756
757 /// The reference may be to an instance member, but it is invalid if
758 /// so, because the context is from an unrelated class.
759 IMA_Mixed_Unrelated,
760
761 /// The reference is definitely an implicit instance member access.
762 IMA_Instance,
763
764 /// The reference may be to an unresolved using declaration.
765 IMA_Unresolved,
766
767 /// The reference may be to an unresolved using declaration and the
768 /// context is not an instance method.
769 IMA_Unresolved_StaticContext,
770
771 /// The reference is to a member of an anonymous structure in a
772 /// non-class context.
773 IMA_AnonymousMember,
774
775 /// All possible referrents are instance members and the current
776 /// context is not an instance method.
777 IMA_Error_StaticContext,
778
779 /// All possible referrents are instance members of an unrelated
780 /// class.
781 IMA_Error_Unrelated
782};
783
784/// The given lookup names class member(s) and is not being used for
785/// an address-of-member expression. Classify the type of access
786/// according to whether it's possible that this reference names an
787/// instance member. This is best-effort; it is okay to
788/// conservatively answer "yes", in which case some errors will simply
789/// not be caught until template-instantiation.
790static IMAKind ClassifyImplicitMemberAccess(Sema &SemaRef,
791 const LookupResult &R) {
John McCall3b4294e2009-12-16 12:17:52 +0000792 assert(!R.empty() && (*R.begin())->isCXXClassMember());
John McCallaa81e162009-12-01 22:10:20 +0000793
John McCallea1471e2010-05-20 01:18:31 +0000794 DeclContext *DC = SemaRef.getFunctionLevelDeclContext();
John McCallaa81e162009-12-01 22:10:20 +0000795 bool isStaticContext =
John McCallea1471e2010-05-20 01:18:31 +0000796 (!isa<CXXMethodDecl>(DC) ||
797 cast<CXXMethodDecl>(DC)->isStatic());
John McCallaa81e162009-12-01 22:10:20 +0000798
799 if (R.isUnresolvableResult())
800 return isStaticContext ? IMA_Unresolved_StaticContext : IMA_Unresolved;
801
802 // Collect all the declaring classes of instance members we find.
803 bool hasNonInstance = false;
804 llvm::SmallPtrSet<CXXRecordDecl*, 4> Classes;
805 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
John McCall161755a2010-04-06 21:38:20 +0000806 NamedDecl *D = *I;
807 if (D->isCXXInstanceMember()) {
John McCallaa81e162009-12-01 22:10:20 +0000808 CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext());
809
810 // If this is a member of an anonymous record, move out to the
811 // innermost non-anonymous struct or union. If there isn't one,
812 // that's a special case.
813 while (R->isAnonymousStructOrUnion()) {
814 R = dyn_cast<CXXRecordDecl>(R->getParent());
815 if (!R) return IMA_AnonymousMember;
816 }
817 Classes.insert(R->getCanonicalDecl());
818 }
819 else
820 hasNonInstance = true;
821 }
822
823 // If we didn't find any instance members, it can't be an implicit
824 // member reference.
825 if (Classes.empty())
826 return IMA_Static;
827
828 // If the current context is not an instance method, it can't be
829 // an implicit member reference.
830 if (isStaticContext)
831 return (hasNonInstance ? IMA_Mixed_StaticContext : IMA_Error_StaticContext);
832
833 // If we can prove that the current context is unrelated to all the
834 // declaring classes, it can't be an implicit member reference (in
835 // which case it's an error if any of those members are selected).
836 if (IsProvablyNotDerivedFrom(SemaRef,
John McCallea1471e2010-05-20 01:18:31 +0000837 cast<CXXMethodDecl>(DC)->getParent(),
John McCallaa81e162009-12-01 22:10:20 +0000838 Classes))
839 return (hasNonInstance ? IMA_Mixed_Unrelated : IMA_Error_Unrelated);
840
841 return (hasNonInstance ? IMA_Mixed : IMA_Instance);
842}
843
844/// Diagnose a reference to a field with no object available.
845static void DiagnoseInstanceReference(Sema &SemaRef,
846 const CXXScopeSpec &SS,
847 const LookupResult &R) {
848 SourceLocation Loc = R.getNameLoc();
849 SourceRange Range(Loc);
850 if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
851
852 if (R.getAsSingle<FieldDecl>()) {
853 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(SemaRef.CurContext)) {
854 if (MD->isStatic()) {
855 // "invalid use of member 'x' in static member function"
856 SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method)
857 << Range << R.getLookupName();
858 return;
859 }
860 }
861
862 SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
863 << R.getLookupName() << Range;
864 return;
865 }
866
867 SemaRef.Diag(Loc, diag::err_member_call_without_object) << Range;
John McCall129e2df2009-11-30 22:42:35 +0000868}
869
John McCall578b69b2009-12-16 08:11:27 +0000870/// Diagnose an empty lookup.
871///
872/// \return false if new lookup candidates were found
Nick Lewycky03d98c52010-07-06 19:51:49 +0000873bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
874 CorrectTypoContext CTC) {
John McCall578b69b2009-12-16 08:11:27 +0000875 DeclarationName Name = R.getLookupName();
876
John McCall578b69b2009-12-16 08:11:27 +0000877 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregorbb092ba2009-12-31 05:20:13 +0000878 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCall578b69b2009-12-16 08:11:27 +0000879 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
880 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregorbb092ba2009-12-31 05:20:13 +0000881 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCall578b69b2009-12-16 08:11:27 +0000882 diagnostic = diag::err_undeclared_use;
Douglas Gregorbb092ba2009-12-31 05:20:13 +0000883 diagnostic_suggest = diag::err_undeclared_use_suggest;
884 }
John McCall578b69b2009-12-16 08:11:27 +0000885
Douglas Gregorbb092ba2009-12-31 05:20:13 +0000886 // If the original lookup was an unqualified lookup, fake an
887 // unqualified lookup. This is useful when (for example) the
888 // original lookup would not have found something because it was a
889 // dependent name.
Nick Lewycky03d98c52010-07-06 19:51:49 +0000890 for (DeclContext *DC = SS.isEmpty() ? CurContext : 0;
Douglas Gregorbb092ba2009-12-31 05:20:13 +0000891 DC; DC = DC->getParent()) {
John McCall578b69b2009-12-16 08:11:27 +0000892 if (isa<CXXRecordDecl>(DC)) {
893 LookupQualifiedName(R, DC);
894
895 if (!R.empty()) {
896 // Don't give errors about ambiguities in this lookup.
897 R.suppressDiagnostics();
898
899 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
900 bool isInstance = CurMethod &&
901 CurMethod->isInstance() &&
902 DC == CurMethod->getParent();
903
904 // Give a code modification hint to insert 'this->'.
905 // TODO: fixit for inserting 'Base<T>::' in the other cases.
906 // Actually quite difficult!
Nick Lewycky03d98c52010-07-06 19:51:49 +0000907 if (isInstance) {
John McCall578b69b2009-12-16 08:11:27 +0000908 Diag(R.getNameLoc(), diagnostic) << Name
Douglas Gregor849b2432010-03-31 17:46:05 +0000909 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
Nick Lewycky03d98c52010-07-06 19:51:49 +0000910
911 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
912 CallsUndergoingInstantiation.back()->getCallee());
913 CXXMethodDecl *DepMethod = cast<CXXMethodDecl>(
914 CurMethod->getInstantiatedFromMemberFunction());
915 QualType DepThisType = DepMethod->getThisType(Context);
916 CXXThisExpr *DepThis = new (Context) CXXThisExpr(R.getNameLoc(),
917 DepThisType, false);
918 TemplateArgumentListInfo TList;
919 if (ULE->hasExplicitTemplateArgs())
920 ULE->copyTemplateArgumentsInto(TList);
921 CXXDependentScopeMemberExpr *DepExpr =
922 CXXDependentScopeMemberExpr::Create(
923 Context, DepThis, DepThisType, true, SourceLocation(),
924 ULE->getQualifier(), ULE->getQualifierRange(), NULL, Name,
925 R.getNameLoc(), &TList);
926 CallsUndergoingInstantiation.back()->setCallee(DepExpr);
927 } else {
John McCall578b69b2009-12-16 08:11:27 +0000928 Diag(R.getNameLoc(), diagnostic) << Name;
Nick Lewycky03d98c52010-07-06 19:51:49 +0000929 }
John McCall578b69b2009-12-16 08:11:27 +0000930
931 // Do we really want to note all of these?
932 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
933 Diag((*I)->getLocation(), diag::note_dependent_var_use);
934
935 // Tell the callee to try to recover.
936 return false;
937 }
938 }
939 }
940
Douglas Gregorbb092ba2009-12-31 05:20:13 +0000941 // We didn't find anything, so try to correct for a typo.
Douglas Gregoraaf87162010-04-14 20:04:41 +0000942 DeclarationName Corrected;
Daniel Dunbardc32cdf2010-06-02 15:46:52 +0000943 if (S && (Corrected = CorrectTypo(R, S, &SS, 0, false, CTC))) {
Douglas Gregoraaf87162010-04-14 20:04:41 +0000944 if (!R.empty()) {
945 if (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin())) {
946 if (SS.isEmpty())
947 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName()
948 << FixItHint::CreateReplacement(R.getNameLoc(),
949 R.getLookupName().getAsString());
950 else
951 Diag(R.getNameLoc(), diag::err_no_member_suggest)
952 << Name << computeDeclContext(SS, false) << R.getLookupName()
953 << SS.getRange()
954 << FixItHint::CreateReplacement(R.getNameLoc(),
955 R.getLookupName().getAsString());
956 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
957 Diag(ND->getLocation(), diag::note_previous_decl)
958 << ND->getDeclName();
959
960 // Tell the callee to try to recover.
961 return false;
962 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +0000963
Douglas Gregoraaf87162010-04-14 20:04:41 +0000964 if (isa<TypeDecl>(*R.begin()) || isa<ObjCInterfaceDecl>(*R.begin())) {
965 // FIXME: If we ended up with a typo for a type name or
966 // Objective-C class name, we're in trouble because the parser
967 // is in the wrong place to recover. Suggest the typo
968 // correction, but don't make it a fix-it since we're not going
969 // to recover well anyway.
970 if (SS.isEmpty())
971 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName();
972 else
973 Diag(R.getNameLoc(), diag::err_no_member_suggest)
974 << Name << computeDeclContext(SS, false) << R.getLookupName()
975 << SS.getRange();
976
977 // Don't try to recover; it won't work.
978 return true;
979 }
980 } else {
Sean Hunt1e3f5ba2010-04-28 23:02:27 +0000981 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
Douglas Gregoraaf87162010-04-14 20:04:41 +0000982 // because we aren't able to recover.
Douglas Gregord203a162010-01-01 00:15:04 +0000983 if (SS.isEmpty())
Douglas Gregoraaf87162010-04-14 20:04:41 +0000984 Diag(R.getNameLoc(), diagnostic_suggest) << Name << Corrected;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000985 else
Douglas Gregord203a162010-01-01 00:15:04 +0000986 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregoraaf87162010-04-14 20:04:41 +0000987 << Name << computeDeclContext(SS, false) << Corrected
988 << SS.getRange();
Douglas Gregord203a162010-01-01 00:15:04 +0000989 return true;
990 }
Douglas Gregord203a162010-01-01 00:15:04 +0000991 R.clear();
Douglas Gregorbb092ba2009-12-31 05:20:13 +0000992 }
993
994 // Emit a special diagnostic for failed member lookups.
995 // FIXME: computing the declaration context might fail here (?)
996 if (!SS.isEmpty()) {
997 Diag(R.getNameLoc(), diag::err_no_member)
998 << Name << computeDeclContext(SS, false)
999 << SS.getRange();
1000 return true;
1001 }
1002
John McCall578b69b2009-12-16 08:11:27 +00001003 // Give up, we can't recover.
1004 Diag(R.getNameLoc(), diagnostic) << Name;
1005 return true;
1006}
1007
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001008static ObjCIvarDecl *SynthesizeProvisionalIvar(Sema &SemaRef,
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001009 IdentifierInfo *II,
1010 SourceLocation NameLoc) {
1011 ObjCMethodDecl *CurMeth = SemaRef.getCurMethodDecl();
1012 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1013 if (!IDecl)
1014 return 0;
1015 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
Fariborz Jahanian84ef4b22010-07-19 16:14:33 +00001016 if (!ClassImpDecl)
1017 return 0;
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001018 bool DynamicImplSeen = false;
1019 ObjCPropertyDecl *property = SemaRef.LookupPropertyDecl(IDecl, II);
1020 if (!property)
1021 return 0;
1022 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II))
1023 DynamicImplSeen =
1024 (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic);
1025 if (!DynamicImplSeen) {
Fariborz Jahanian84ef4b22010-07-19 16:14:33 +00001026 QualType PropType = SemaRef.Context.getCanonicalType(property->getType());
1027 ObjCIvarDecl *Ivar = ObjCIvarDecl::Create(SemaRef.Context, ClassImpDecl,
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001028 NameLoc,
1029 II, PropType, /*Dinfo=*/0,
1030 ObjCIvarDecl::Protected,
1031 (Expr *)0, true);
1032 ClassImpDecl->addDecl(Ivar);
1033 IDecl->makeDeclVisibleInContext(Ivar, false);
1034 property->setPropertyIvarDecl(Ivar);
1035 return Ivar;
1036 }
1037 return 0;
1038}
1039
John McCallf7a1a742009-11-24 19:00:30 +00001040Sema::OwningExprResult Sema::ActOnIdExpression(Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001041 CXXScopeSpec &SS,
John McCallf7a1a742009-11-24 19:00:30 +00001042 UnqualifiedId &Id,
1043 bool HasTrailingLParen,
1044 bool isAddressOfOperand) {
1045 assert(!(isAddressOfOperand && HasTrailingLParen) &&
1046 "cannot be direct & operand and have a trailing lparen");
1047
1048 if (SS.isInvalid())
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001049 return ExprError();
Douglas Gregor5953d8b2009-03-19 17:26:29 +00001050
John McCall129e2df2009-11-30 22:42:35 +00001051 TemplateArgumentListInfo TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +00001052
1053 // Decompose the UnqualifiedId into the following data.
1054 DeclarationName Name;
1055 SourceLocation NameLoc;
1056 const TemplateArgumentListInfo *TemplateArgs;
John McCall129e2df2009-11-30 22:42:35 +00001057 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer,
1058 Name, NameLoc, TemplateArgs);
Douglas Gregor5953d8b2009-03-19 17:26:29 +00001059
Douglas Gregor10c42622008-11-18 15:03:34 +00001060 IdentifierInfo *II = Name.getAsIdentifierInfo();
John McCallba135432009-11-21 08:51:07 +00001061
John McCallf7a1a742009-11-24 19:00:30 +00001062 // C++ [temp.dep.expr]p3:
1063 // An id-expression is type-dependent if it contains:
Douglas Gregor48026d22010-01-11 18:40:55 +00001064 // -- an identifier that was declared with a dependent type,
1065 // (note: handled after lookup)
1066 // -- a template-id that is dependent,
1067 // (note: handled in BuildTemplateIdExpr)
1068 // -- a conversion-function-id that specifies a dependent type,
John McCallf7a1a742009-11-24 19:00:30 +00001069 // -- a nested-name-specifier that contains a class-name that
1070 // names a dependent type.
1071 // Determine whether this is a member of an unknown specialization;
1072 // we need to handle these differently.
Douglas Gregor48026d22010-01-11 18:40:55 +00001073 if ((Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1074 Name.getCXXNameType()->isDependentType()) ||
1075 (SS.isSet() && IsDependentIdExpression(*this, SS))) {
John McCallf7a1a742009-11-24 19:00:30 +00001076 return ActOnDependentIdExpression(SS, Name, NameLoc,
John McCall2f841ba2009-12-02 03:53:29 +00001077 isAddressOfOperand,
John McCallf7a1a742009-11-24 19:00:30 +00001078 TemplateArgs);
1079 }
John McCallba135432009-11-21 08:51:07 +00001080
John McCallf7a1a742009-11-24 19:00:30 +00001081 // Perform the required lookup.
1082 LookupResult R(*this, Name, NameLoc, LookupOrdinaryName);
1083 if (TemplateArgs) {
Douglas Gregord2235f62010-05-20 20:58:56 +00001084 // Lookup the template name again to correctly establish the context in
1085 // which it was found. This is really unfortunate as we already did the
1086 // lookup to determine that it was a template name in the first place. If
1087 // this becomes a performance hit, we can work harder to preserve those
1088 // results until we get here but it's likely not worth it.
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001089 bool MemberOfUnknownSpecialization;
1090 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1091 MemberOfUnknownSpecialization);
John McCallf7a1a742009-11-24 19:00:30 +00001092 } else {
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001093 bool IvarLookupFollowUp = (!SS.isSet() && II && getCurMethodDecl());
1094 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump1eb44332009-09-09 15:08:12 +00001095
John McCallf7a1a742009-11-24 19:00:30 +00001096 // If this reference is in an Objective-C method, then we need to do
1097 // some special Objective-C lookup, too.
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001098 if (IvarLookupFollowUp) {
1099 OwningExprResult E(LookupInObjCMethod(R, S, II, true));
John McCallf7a1a742009-11-24 19:00:30 +00001100 if (E.isInvalid())
1101 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001102
John McCallf7a1a742009-11-24 19:00:30 +00001103 Expr *Ex = E.takeAs<Expr>();
1104 if (Ex) return Owned(Ex);
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001105 // Synthesize ivars lazily
1106 if (getLangOptions().ObjCNonFragileABI2) {
Fariborz Jahanian84ef4b22010-07-19 16:14:33 +00001107 if (SynthesizeProvisionalIvar(*this, II, NameLoc))
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001108 return ActOnIdExpression(S, SS, Id, HasTrailingLParen,
1109 isAddressOfOperand);
1110 }
Steve Naroffe3e9add2008-06-02 23:03:37 +00001111 }
Chris Lattner8a934232008-03-31 00:36:02 +00001112 }
Douglas Gregorc71e28c2009-02-16 19:28:42 +00001113
John McCallf7a1a742009-11-24 19:00:30 +00001114 if (R.isAmbiguous())
1115 return ExprError();
1116
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001117 // Determine whether this name might be a candidate for
1118 // argument-dependent lookup.
John McCallf7a1a742009-11-24 19:00:30 +00001119 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001120
John McCallf7a1a742009-11-24 19:00:30 +00001121 if (R.empty() && !ADL) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001122 // Otherwise, this could be an implicitly declared function reference (legal
John McCallf7a1a742009-11-24 19:00:30 +00001123 // in C90, extension in C99, forbidden in C++).
1124 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
1125 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1126 if (D) R.addDecl(D);
1127 }
1128
1129 // If this name wasn't predeclared and if this is not a function
1130 // call, diagnose the problem.
1131 if (R.empty()) {
Douglas Gregor91f7ac72010-05-18 16:14:23 +00001132 if (DiagnoseEmptyLookup(S, SS, R, CTC_Unknown))
John McCall578b69b2009-12-16 08:11:27 +00001133 return ExprError();
1134
1135 assert(!R.empty() &&
1136 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001137
1138 // If we found an Objective-C instance variable, let
1139 // LookupInObjCMethod build the appropriate expression to
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001140 // reference the ivar.
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001141 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1142 R.clear();
1143 OwningExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
1144 assert(E.isInvalid() || E.get());
1145 return move(E);
1146 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001147 }
1148 }
Mike Stump1eb44332009-09-09 15:08:12 +00001149
John McCallf7a1a742009-11-24 19:00:30 +00001150 // This is guaranteed from this point on.
1151 assert(!R.empty() || ADL);
1152
1153 if (VarDecl *Var = R.getAsSingle<VarDecl>()) {
Douglas Gregor751f9a42009-06-30 15:47:41 +00001154 // Warn about constructs like:
1155 // if (void *X = foo()) { ... } else { X }.
1156 // In the else block, the pointer is always false.
Douglas Gregor751f9a42009-06-30 15:47:41 +00001157 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
1158 Scope *CheckS = S;
Douglas Gregor9c4b8382009-11-05 17:49:26 +00001159 while (CheckS && CheckS->getControlParent()) {
Chris Lattner966c78b2010-04-12 06:12:50 +00001160 if ((CheckS->getFlags() & Scope::ElseScope) &&
Douglas Gregor751f9a42009-06-30 15:47:41 +00001161 CheckS->getControlParent()->isDeclScope(DeclPtrTy::make(Var))) {
John McCallf7a1a742009-11-24 19:00:30 +00001162 ExprError(Diag(NameLoc, diag::warn_value_always_zero)
Douglas Gregor9c4b8382009-11-05 17:49:26 +00001163 << Var->getDeclName()
Chris Lattner966c78b2010-04-12 06:12:50 +00001164 << (Var->getType()->isPointerType() ? 2 :
1165 Var->getType()->isBooleanType() ? 1 : 0));
Douglas Gregor751f9a42009-06-30 15:47:41 +00001166 break;
1167 }
Mike Stump1eb44332009-09-09 15:08:12 +00001168
Douglas Gregor9c4b8382009-11-05 17:49:26 +00001169 // Move to the parent of this scope.
1170 CheckS = CheckS->getParent();
Douglas Gregor751f9a42009-06-30 15:47:41 +00001171 }
1172 }
John McCallf7a1a742009-11-24 19:00:30 +00001173 } else if (FunctionDecl *Func = R.getAsSingle<FunctionDecl>()) {
Douglas Gregor751f9a42009-06-30 15:47:41 +00001174 if (!getLangOptions().CPlusPlus && !Func->hasPrototype()) {
1175 // C99 DR 316 says that, if a function type comes from a
1176 // function definition (without a prototype), that type is only
1177 // used for checking compatibility. Therefore, when referencing
1178 // the function, we pretend that we don't have the full function
1179 // type.
John McCallf7a1a742009-11-24 19:00:30 +00001180 if (DiagnoseUseOfDecl(Func, NameLoc))
Douglas Gregor751f9a42009-06-30 15:47:41 +00001181 return ExprError();
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001182
Douglas Gregor751f9a42009-06-30 15:47:41 +00001183 QualType T = Func->getType();
1184 QualType NoProtoType = T;
John McCall183700f2009-09-21 23:43:11 +00001185 if (const FunctionProtoType *Proto = T->getAs<FunctionProtoType>())
Eli Friedman9a0fcfe2010-05-17 02:50:18 +00001186 NoProtoType = Context.getFunctionNoProtoType(Proto->getResultType(),
1187 Proto->getExtInfo());
John McCallf7a1a742009-11-24 19:00:30 +00001188 return BuildDeclRefExpr(Func, NoProtoType, NameLoc, &SS);
Douglas Gregor751f9a42009-06-30 15:47:41 +00001189 }
1190 }
Mike Stump1eb44332009-09-09 15:08:12 +00001191
John McCallaa81e162009-12-01 22:10:20 +00001192 // Check whether this might be a C++ implicit instance member access.
1193 // C++ [expr.prim.general]p6:
1194 // Within the definition of a non-static member function, an
1195 // identifier that names a non-static member is transformed to a
1196 // class member access expression.
1197 // But note that &SomeClass::foo is grammatically distinct, even
1198 // though we don't parse it that way.
John McCall3b4294e2009-12-16 12:17:52 +00001199 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCallf7a1a742009-11-24 19:00:30 +00001200 bool isAbstractMemberPointer = (isAddressOfOperand && !SS.isEmpty());
John McCall3b4294e2009-12-16 12:17:52 +00001201 if (!isAbstractMemberPointer)
1202 return BuildPossibleImplicitMemberExpr(SS, R, TemplateArgs);
John McCall5b3f9132009-11-22 01:44:31 +00001203 }
1204
John McCallf7a1a742009-11-24 19:00:30 +00001205 if (TemplateArgs)
1206 return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
John McCall5b3f9132009-11-22 01:44:31 +00001207
John McCallf7a1a742009-11-24 19:00:30 +00001208 return BuildDeclarationNameExpr(SS, R, ADL);
1209}
1210
John McCall3b4294e2009-12-16 12:17:52 +00001211/// Builds an expression which might be an implicit member expression.
1212Sema::OwningExprResult
1213Sema::BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
1214 LookupResult &R,
1215 const TemplateArgumentListInfo *TemplateArgs) {
1216 switch (ClassifyImplicitMemberAccess(*this, R)) {
1217 case IMA_Instance:
1218 return BuildImplicitMemberExpr(SS, R, TemplateArgs, true);
1219
1220 case IMA_AnonymousMember:
1221 assert(R.isSingleResult());
1222 return BuildAnonymousStructUnionMemberReference(R.getNameLoc(),
1223 R.getAsSingle<FieldDecl>());
1224
1225 case IMA_Mixed:
1226 case IMA_Mixed_Unrelated:
1227 case IMA_Unresolved:
1228 return BuildImplicitMemberExpr(SS, R, TemplateArgs, false);
1229
1230 case IMA_Static:
1231 case IMA_Mixed_StaticContext:
1232 case IMA_Unresolved_StaticContext:
1233 if (TemplateArgs)
1234 return BuildTemplateIdExpr(SS, R, false, *TemplateArgs);
1235 return BuildDeclarationNameExpr(SS, R, false);
1236
1237 case IMA_Error_StaticContext:
1238 case IMA_Error_Unrelated:
1239 DiagnoseInstanceReference(*this, SS, R);
1240 return ExprError();
1241 }
1242
1243 llvm_unreachable("unexpected instance member access kind");
1244 return ExprError();
1245}
1246
John McCall129e2df2009-11-30 22:42:35 +00001247/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1248/// declaration name, generally during template instantiation.
1249/// There's a large number of things which don't need to be done along
1250/// this path.
John McCallf7a1a742009-11-24 19:00:30 +00001251Sema::OwningExprResult
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001252Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
John McCallf7a1a742009-11-24 19:00:30 +00001253 DeclarationName Name,
1254 SourceLocation NameLoc) {
1255 DeclContext *DC;
Douglas Gregore6ec5c42010-04-28 07:04:26 +00001256 if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
John McCallf7a1a742009-11-24 19:00:30 +00001257 return BuildDependentDeclRefExpr(SS, Name, NameLoc, 0);
1258
John McCall77bb1aa2010-05-01 00:40:08 +00001259 if (RequireCompleteDeclContext(SS, DC))
Douglas Gregore6ec5c42010-04-28 07:04:26 +00001260 return ExprError();
1261
John McCallf7a1a742009-11-24 19:00:30 +00001262 LookupResult R(*this, Name, NameLoc, LookupOrdinaryName);
1263 LookupQualifiedName(R, DC);
1264
1265 if (R.isAmbiguous())
1266 return ExprError();
1267
1268 if (R.empty()) {
1269 Diag(NameLoc, diag::err_no_member) << Name << DC << SS.getRange();
1270 return ExprError();
1271 }
1272
1273 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1274}
1275
1276/// LookupInObjCMethod - The parser has read a name in, and Sema has
1277/// detected that we're currently inside an ObjC method. Perform some
1278/// additional lookup.
1279///
1280/// Ideally, most of this would be done by lookup, but there's
1281/// actually quite a lot of extra work involved.
1282///
1283/// Returns a null sentinel to indicate trivial success.
1284Sema::OwningExprResult
1285Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Chris Lattnereb483eb2010-04-11 08:28:14 +00001286 IdentifierInfo *II, bool AllowBuiltinCreation) {
John McCallf7a1a742009-11-24 19:00:30 +00001287 SourceLocation Loc = Lookup.getNameLoc();
Chris Lattneraec43db2010-04-12 05:10:17 +00001288 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001289
John McCallf7a1a742009-11-24 19:00:30 +00001290 // There are two cases to handle here. 1) scoped lookup could have failed,
1291 // in which case we should look for an ivar. 2) scoped lookup could have
1292 // found a decl, but that decl is outside the current instance method (i.e.
1293 // a global variable). In these two cases, we do a lookup for an ivar with
1294 // this name, if the lookup sucedes, we replace it our current decl.
1295
1296 // If we're in a class method, we don't normally want to look for
1297 // ivars. But if we don't find anything else, and there's an
1298 // ivar, that's an error.
Chris Lattneraec43db2010-04-12 05:10:17 +00001299 bool IsClassMethod = CurMethod->isClassMethod();
John McCallf7a1a742009-11-24 19:00:30 +00001300
1301 bool LookForIvars;
1302 if (Lookup.empty())
1303 LookForIvars = true;
1304 else if (IsClassMethod)
1305 LookForIvars = false;
1306 else
1307 LookForIvars = (Lookup.isSingleResult() &&
1308 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
Fariborz Jahanian412e7982010-02-09 19:31:38 +00001309 ObjCInterfaceDecl *IFace = 0;
John McCallf7a1a742009-11-24 19:00:30 +00001310 if (LookForIvars) {
Chris Lattneraec43db2010-04-12 05:10:17 +00001311 IFace = CurMethod->getClassInterface();
John McCallf7a1a742009-11-24 19:00:30 +00001312 ObjCInterfaceDecl *ClassDeclared;
1313 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1314 // Diagnose using an ivar in a class method.
1315 if (IsClassMethod)
1316 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1317 << IV->getDeclName());
1318
1319 // If we're referencing an invalid decl, just return this as a silent
1320 // error node. The error diagnostic was already emitted on the decl.
1321 if (IV->isInvalidDecl())
1322 return ExprError();
1323
1324 // Check if referencing a field with __attribute__((deprecated)).
1325 if (DiagnoseUseOfDecl(IV, Loc))
1326 return ExprError();
1327
1328 // Diagnose the use of an ivar outside of the declaring class.
1329 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
1330 ClassDeclared != IFace)
1331 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1332
1333 // FIXME: This should use a new expr for a direct reference, don't
1334 // turn this into Self->ivar, just return a BareIVarExpr or something.
1335 IdentifierInfo &II = Context.Idents.get("self");
1336 UnqualifiedId SelfName;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001337 SelfName.setIdentifier(&II, SourceLocation());
John McCallf7a1a742009-11-24 19:00:30 +00001338 CXXScopeSpec SelfScopeSpec;
1339 OwningExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
1340 SelfName, false, false);
1341 MarkDeclarationReferenced(Loc, IV);
1342 return Owned(new (Context)
1343 ObjCIvarRefExpr(IV, IV->getType(), Loc,
1344 SelfExpr.takeAs<Expr>(), true, true));
1345 }
Chris Lattneraec43db2010-04-12 05:10:17 +00001346 } else if (CurMethod->isInstanceMethod()) {
John McCallf7a1a742009-11-24 19:00:30 +00001347 // We should warn if a local variable hides an ivar.
Chris Lattneraec43db2010-04-12 05:10:17 +00001348 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
John McCallf7a1a742009-11-24 19:00:30 +00001349 ObjCInterfaceDecl *ClassDeclared;
1350 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1351 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
1352 IFace == ClassDeclared)
1353 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
1354 }
1355 }
1356
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001357 if (Lookup.empty() && II && AllowBuiltinCreation) {
1358 // FIXME. Consolidate this with similar code in LookupName.
1359 if (unsigned BuiltinID = II->getBuiltinID()) {
1360 if (!(getLangOptions().CPlusPlus &&
1361 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
1362 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
1363 S, Lookup.isForRedeclaration(),
1364 Lookup.getNameLoc());
1365 if (D) Lookup.addDecl(D);
1366 }
1367 }
1368 }
John McCallf7a1a742009-11-24 19:00:30 +00001369 // Sentinel value saying that we didn't do anything special.
1370 return Owned((Expr*) 0);
Douglas Gregor751f9a42009-06-30 15:47:41 +00001371}
John McCallba135432009-11-21 08:51:07 +00001372
John McCall6bb80172010-03-30 21:47:33 +00001373/// \brief Cast a base object to a member's actual type.
1374///
1375/// Logically this happens in three phases:
1376///
1377/// * First we cast from the base type to the naming class.
1378/// The naming class is the class into which we were looking
1379/// when we found the member; it's the qualifier type if a
1380/// qualifier was provided, and otherwise it's the base type.
1381///
1382/// * Next we cast from the naming class to the declaring class.
1383/// If the member we found was brought into a class's scope by
1384/// a using declaration, this is that class; otherwise it's
1385/// the class declaring the member.
1386///
1387/// * Finally we cast from the declaring class to the "true"
1388/// declaring class of the member. This conversion does not
1389/// obey access control.
Fariborz Jahanianf3e53d32009-07-29 19:40:11 +00001390bool
Douglas Gregor5fccd362010-03-03 23:55:11 +00001391Sema::PerformObjectMemberConversion(Expr *&From,
1392 NestedNameSpecifier *Qualifier,
John McCall6bb80172010-03-30 21:47:33 +00001393 NamedDecl *FoundDecl,
Douglas Gregor5fccd362010-03-03 23:55:11 +00001394 NamedDecl *Member) {
1395 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
1396 if (!RD)
1397 return false;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001398
Douglas Gregor5fccd362010-03-03 23:55:11 +00001399 QualType DestRecordType;
1400 QualType DestType;
1401 QualType FromRecordType;
1402 QualType FromType = From->getType();
1403 bool PointerConversions = false;
1404 if (isa<FieldDecl>(Member)) {
1405 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001406
Douglas Gregor5fccd362010-03-03 23:55:11 +00001407 if (FromType->getAs<PointerType>()) {
1408 DestType = Context.getPointerType(DestRecordType);
1409 FromRecordType = FromType->getPointeeType();
1410 PointerConversions = true;
1411 } else {
1412 DestType = DestRecordType;
1413 FromRecordType = FromType;
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00001414 }
Douglas Gregor5fccd362010-03-03 23:55:11 +00001415 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
1416 if (Method->isStatic())
1417 return false;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001418
Douglas Gregor5fccd362010-03-03 23:55:11 +00001419 DestType = Method->getThisType(Context);
1420 DestRecordType = DestType->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001421
Douglas Gregor5fccd362010-03-03 23:55:11 +00001422 if (FromType->getAs<PointerType>()) {
1423 FromRecordType = FromType->getPointeeType();
1424 PointerConversions = true;
1425 } else {
1426 FromRecordType = FromType;
1427 DestType = DestRecordType;
1428 }
1429 } else {
1430 // No conversion necessary.
1431 return false;
1432 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001433
Douglas Gregor5fccd362010-03-03 23:55:11 +00001434 if (DestType->isDependentType() || FromType->isDependentType())
1435 return false;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001436
Douglas Gregor5fccd362010-03-03 23:55:11 +00001437 // If the unqualified types are the same, no conversion is necessary.
1438 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
1439 return false;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001440
John McCall6bb80172010-03-30 21:47:33 +00001441 SourceRange FromRange = From->getSourceRange();
1442 SourceLocation FromLoc = FromRange.getBegin();
1443
Sebastian Redl906082e2010-07-20 04:20:21 +00001444 ImplicitCastExpr::ResultCategory Category = CastCategory(From);
1445
Douglas Gregor5fccd362010-03-03 23:55:11 +00001446 // C++ [class.member.lookup]p8:
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001447 // [...] Ambiguities can often be resolved by qualifying a name with its
Douglas Gregor5fccd362010-03-03 23:55:11 +00001448 // class name.
1449 //
1450 // If the member was a qualified name and the qualified referred to a
1451 // specific base subobject type, we'll cast to that intermediate type
1452 // first and then to the object in which the member is declared. That allows
1453 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
1454 //
1455 // class Base { public: int x; };
1456 // class Derived1 : public Base { };
1457 // class Derived2 : public Base { };
1458 // class VeryDerived : public Derived1, public Derived2 { void f(); };
1459 //
1460 // void VeryDerived::f() {
1461 // x = 17; // error: ambiguous base subobjects
1462 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
1463 // }
Douglas Gregor5fccd362010-03-03 23:55:11 +00001464 if (Qualifier) {
John McCall6bb80172010-03-30 21:47:33 +00001465 QualType QType = QualType(Qualifier->getAsType(), 0);
1466 assert(!QType.isNull() && "lookup done with dependent qualifier?");
1467 assert(QType->isRecordType() && "lookup done with non-record type");
1468
1469 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
1470
1471 // In C++98, the qualifier type doesn't actually have to be a base
1472 // type of the object type, in which case we just ignore it.
1473 // Otherwise build the appropriate casts.
1474 if (IsDerivedFrom(FromRecordType, QRecordType)) {
Anders Carlssoncee22422010-04-24 19:22:20 +00001475 CXXBaseSpecifierArray BasePath;
John McCall6bb80172010-03-30 21:47:33 +00001476 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
Anders Carlssoncee22422010-04-24 19:22:20 +00001477 FromLoc, FromRange, &BasePath))
John McCall6bb80172010-03-30 21:47:33 +00001478 return true;
1479
Douglas Gregor5fccd362010-03-03 23:55:11 +00001480 if (PointerConversions)
John McCall6bb80172010-03-30 21:47:33 +00001481 QType = Context.getPointerType(QType);
John McCall23cba802010-03-30 23:58:03 +00001482 ImpCastExprToType(From, QType, CastExpr::CK_UncheckedDerivedToBase,
Sebastian Redl906082e2010-07-20 04:20:21 +00001483 Category, BasePath);
John McCall6bb80172010-03-30 21:47:33 +00001484
1485 FromType = QType;
1486 FromRecordType = QRecordType;
1487
1488 // If the qualifier type was the same as the destination type,
1489 // we're done.
1490 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
1491 return false;
Douglas Gregor5fccd362010-03-03 23:55:11 +00001492 }
1493 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001494
John McCall6bb80172010-03-30 21:47:33 +00001495 bool IgnoreAccess = false;
Douglas Gregor5fccd362010-03-03 23:55:11 +00001496
John McCall6bb80172010-03-30 21:47:33 +00001497 // If we actually found the member through a using declaration, cast
1498 // down to the using declaration's type.
1499 //
1500 // Pointer equality is fine here because only one declaration of a
1501 // class ever has member declarations.
1502 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
1503 assert(isa<UsingShadowDecl>(FoundDecl));
1504 QualType URecordType = Context.getTypeDeclType(
1505 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
1506
1507 // We only need to do this if the naming-class to declaring-class
1508 // conversion is non-trivial.
1509 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
1510 assert(IsDerivedFrom(FromRecordType, URecordType));
Anders Carlssoncee22422010-04-24 19:22:20 +00001511 CXXBaseSpecifierArray BasePath;
John McCall6bb80172010-03-30 21:47:33 +00001512 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
Anders Carlssoncee22422010-04-24 19:22:20 +00001513 FromLoc, FromRange, &BasePath))
John McCall6bb80172010-03-30 21:47:33 +00001514 return true;
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001515
John McCall6bb80172010-03-30 21:47:33 +00001516 QualType UType = URecordType;
1517 if (PointerConversions)
1518 UType = Context.getPointerType(UType);
John McCall23cba802010-03-30 23:58:03 +00001519 ImpCastExprToType(From, UType, CastExpr::CK_UncheckedDerivedToBase,
Sebastian Redl906082e2010-07-20 04:20:21 +00001520 Category, BasePath);
John McCall6bb80172010-03-30 21:47:33 +00001521 FromType = UType;
1522 FromRecordType = URecordType;
1523 }
1524
1525 // We don't do access control for the conversion from the
1526 // declaring class to the true declaring class.
1527 IgnoreAccess = true;
Douglas Gregor5fccd362010-03-03 23:55:11 +00001528 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001529
Anders Carlssoncee22422010-04-24 19:22:20 +00001530 CXXBaseSpecifierArray BasePath;
1531 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
1532 FromLoc, FromRange, &BasePath,
John McCall6bb80172010-03-30 21:47:33 +00001533 IgnoreAccess))
Douglas Gregor5fccd362010-03-03 23:55:11 +00001534 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001535
John McCall23cba802010-03-30 23:58:03 +00001536 ImpCastExprToType(From, DestType, CastExpr::CK_UncheckedDerivedToBase,
Sebastian Redl906082e2010-07-20 04:20:21 +00001537 Category, BasePath);
Fariborz Jahanianf3e53d32009-07-29 19:40:11 +00001538 return false;
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00001539}
Douglas Gregor751f9a42009-06-30 15:47:41 +00001540
Douglas Gregor83f6faf2009-08-31 23:41:50 +00001541/// \brief Build a MemberExpr AST node.
Mike Stump1eb44332009-09-09 15:08:12 +00001542static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow,
Eli Friedmanf595cc42009-12-04 06:40:45 +00001543 const CXXScopeSpec &SS, ValueDecl *Member,
John McCall161755a2010-04-06 21:38:20 +00001544 DeclAccessPair FoundDecl,
1545 SourceLocation Loc, QualType Ty,
John McCallf7a1a742009-11-24 19:00:30 +00001546 const TemplateArgumentListInfo *TemplateArgs = 0) {
1547 NestedNameSpecifier *Qualifier = 0;
1548 SourceRange QualifierRange;
John McCall129e2df2009-11-30 22:42:35 +00001549 if (SS.isSet()) {
1550 Qualifier = (NestedNameSpecifier *) SS.getScopeRep();
1551 QualifierRange = SS.getRange();
John McCallf7a1a742009-11-24 19:00:30 +00001552 }
Mike Stump1eb44332009-09-09 15:08:12 +00001553
John McCallf7a1a742009-11-24 19:00:30 +00001554 return MemberExpr::Create(C, Base, isArrow, Qualifier, QualifierRange,
John McCall6bb80172010-03-30 21:47:33 +00001555 Member, FoundDecl, Loc, TemplateArgs, Ty);
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +00001556}
1557
John McCallaa81e162009-12-01 22:10:20 +00001558/// Builds an implicit member access expression. The current context
1559/// is known to be an instance method, and the given unqualified lookup
1560/// set is known to contain only instance members, at least one of which
1561/// is from an appropriate type.
John McCall5b3f9132009-11-22 01:44:31 +00001562Sema::OwningExprResult
John McCallaa81e162009-12-01 22:10:20 +00001563Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
1564 LookupResult &R,
1565 const TemplateArgumentListInfo *TemplateArgs,
1566 bool IsKnownInstance) {
John McCallf7a1a742009-11-24 19:00:30 +00001567 assert(!R.empty() && !R.isAmbiguous());
1568
John McCallba135432009-11-21 08:51:07 +00001569 SourceLocation Loc = R.getNameLoc();
Sebastian Redlebc07d52009-02-03 20:19:35 +00001570
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001571 // We may have found a field within an anonymous union or struct
1572 // (C++ [class.union]).
Douglas Gregore961afb2009-10-22 07:08:30 +00001573 // FIXME: This needs to happen post-isImplicitMemberReference?
John McCallf7a1a742009-11-24 19:00:30 +00001574 // FIXME: template-ids inside anonymous structs?
John McCall129e2df2009-11-30 22:42:35 +00001575 if (FieldDecl *FD = R.getAsSingle<FieldDecl>())
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001576 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
John McCall5b3f9132009-11-22 01:44:31 +00001577 return BuildAnonymousStructUnionMemberReference(Loc, FD);
Sebastian Redlcd965b92009-01-18 18:53:16 +00001578
John McCallaa81e162009-12-01 22:10:20 +00001579 // If this is known to be an instance access, go ahead and build a
1580 // 'this' expression now.
John McCallea1471e2010-05-20 01:18:31 +00001581 DeclContext *DC = getFunctionLevelDeclContext();
1582 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(Context);
John McCallaa81e162009-12-01 22:10:20 +00001583 Expr *This = 0; // null signifies implicit access
1584 if (IsKnownInstance) {
Douglas Gregor828a1972010-01-07 23:12:05 +00001585 SourceLocation Loc = R.getNameLoc();
1586 if (SS.getRange().isValid())
1587 Loc = SS.getRange().getBegin();
1588 This = new (Context) CXXThisExpr(Loc, ThisType, /*isImplicit=*/true);
Douglas Gregor88a35142008-12-22 05:46:06 +00001589 }
1590
John McCallaa81e162009-12-01 22:10:20 +00001591 return BuildMemberReferenceExpr(ExprArg(*this, This), ThisType,
1592 /*OpLoc*/ SourceLocation(),
1593 /*IsArrow*/ true,
John McCallc2233c52010-01-15 08:34:02 +00001594 SS,
1595 /*FirstQualifierInScope*/ 0,
1596 R, TemplateArgs);
John McCallba135432009-11-21 08:51:07 +00001597}
1598
John McCallf7a1a742009-11-24 19:00:30 +00001599bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00001600 const LookupResult &R,
1601 bool HasTrailingLParen) {
John McCallba135432009-11-21 08:51:07 +00001602 // Only when used directly as the postfix-expression of a call.
1603 if (!HasTrailingLParen)
1604 return false;
1605
1606 // Never if a scope specifier was provided.
John McCallf7a1a742009-11-24 19:00:30 +00001607 if (SS.isSet())
John McCallba135432009-11-21 08:51:07 +00001608 return false;
1609
1610 // Only in C++ or ObjC++.
John McCall5b3f9132009-11-22 01:44:31 +00001611 if (!getLangOptions().CPlusPlus)
John McCallba135432009-11-21 08:51:07 +00001612 return false;
1613
1614 // Turn off ADL when we find certain kinds of declarations during
1615 // normal lookup:
1616 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
1617 NamedDecl *D = *I;
1618
1619 // C++0x [basic.lookup.argdep]p3:
1620 // -- a declaration of a class member
1621 // Since using decls preserve this property, we check this on the
1622 // original decl.
John McCall3b4294e2009-12-16 12:17:52 +00001623 if (D->isCXXClassMember())
John McCallba135432009-11-21 08:51:07 +00001624 return false;
1625
1626 // C++0x [basic.lookup.argdep]p3:
1627 // -- a block-scope function declaration that is not a
1628 // using-declaration
1629 // NOTE: we also trigger this for function templates (in fact, we
1630 // don't check the decl type at all, since all other decl types
1631 // turn off ADL anyway).
1632 if (isa<UsingShadowDecl>(D))
1633 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1634 else if (D->getDeclContext()->isFunctionOrMethod())
1635 return false;
1636
1637 // C++0x [basic.lookup.argdep]p3:
1638 // -- a declaration that is neither a function or a function
1639 // template
1640 // And also for builtin functions.
1641 if (isa<FunctionDecl>(D)) {
1642 FunctionDecl *FDecl = cast<FunctionDecl>(D);
1643
1644 // But also builtin functions.
1645 if (FDecl->getBuiltinID() && FDecl->isImplicit())
1646 return false;
1647 } else if (!isa<FunctionTemplateDecl>(D))
1648 return false;
1649 }
1650
1651 return true;
1652}
1653
1654
John McCallba135432009-11-21 08:51:07 +00001655/// Diagnoses obvious problems with the use of the given declaration
1656/// as an expression. This is only actually called for lookups that
1657/// were not overloaded, and it doesn't promise that the declaration
1658/// will in fact be used.
1659static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
1660 if (isa<TypedefDecl>(D)) {
1661 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
1662 return true;
1663 }
1664
1665 if (isa<ObjCInterfaceDecl>(D)) {
1666 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
1667 return true;
1668 }
1669
1670 if (isa<NamespaceDecl>(D)) {
1671 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
1672 return true;
1673 }
1674
1675 return false;
1676}
1677
1678Sema::OwningExprResult
John McCallf7a1a742009-11-24 19:00:30 +00001679Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00001680 LookupResult &R,
1681 bool NeedsADL) {
John McCallfead20c2009-12-08 22:45:53 +00001682 // If this is a single, fully-resolved result and we don't need ADL,
1683 // just build an ordinary singleton decl ref.
Douglas Gregor86b8e092010-01-29 17:15:43 +00001684 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
John McCall5b3f9132009-11-22 01:44:31 +00001685 return BuildDeclarationNameExpr(SS, R.getNameLoc(), R.getFoundDecl());
John McCallba135432009-11-21 08:51:07 +00001686
1687 // We only need to check the declaration if there's exactly one
1688 // result, because in the overloaded case the results can only be
1689 // functions and function templates.
John McCall5b3f9132009-11-22 01:44:31 +00001690 if (R.isSingleResult() &&
1691 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCallba135432009-11-21 08:51:07 +00001692 return ExprError();
1693
John McCallc373d482010-01-27 01:50:18 +00001694 // Otherwise, just build an unresolved lookup expression. Suppress
1695 // any lookup-related diagnostics; we'll hash these out later, when
1696 // we've picked a target.
1697 R.suppressDiagnostics();
1698
John McCallf7a1a742009-11-24 19:00:30 +00001699 bool Dependent
1700 = UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(), 0);
John McCallba135432009-11-21 08:51:07 +00001701 UnresolvedLookupExpr *ULE
John McCallc373d482010-01-27 01:50:18 +00001702 = UnresolvedLookupExpr::Create(Context, Dependent, R.getNamingClass(),
John McCallf7a1a742009-11-24 19:00:30 +00001703 (NestedNameSpecifier*) SS.getScopeRep(),
1704 SS.getRange(),
John McCall5b3f9132009-11-22 01:44:31 +00001705 R.getLookupName(), R.getNameLoc(),
Douglas Gregor5a84dec2010-05-23 18:57:34 +00001706 NeedsADL, R.isOverloadedResult(),
1707 R.begin(), R.end());
John McCallba135432009-11-21 08:51:07 +00001708
1709 return Owned(ULE);
1710}
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001711
John McCallba135432009-11-21 08:51:07 +00001712
1713/// \brief Complete semantic analysis for a reference to the given declaration.
1714Sema::OwningExprResult
John McCallf7a1a742009-11-24 19:00:30 +00001715Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCallba135432009-11-21 08:51:07 +00001716 SourceLocation Loc, NamedDecl *D) {
1717 assert(D && "Cannot refer to a NULL declaration");
John McCall7453ed42009-11-22 00:44:51 +00001718 assert(!isa<FunctionTemplateDecl>(D) &&
1719 "Cannot refer unambiguously to a function template");
John McCallba135432009-11-21 08:51:07 +00001720
1721 if (CheckDeclInExpr(*this, Loc, D))
1722 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001723
Douglas Gregor9af2f522009-12-01 16:58:18 +00001724 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
1725 // Specifically diagnose references to class templates that are missing
1726 // a template argument list.
1727 Diag(Loc, diag::err_template_decl_ref)
1728 << Template << SS.getRange();
1729 Diag(Template->getLocation(), diag::note_template_decl_here);
1730 return ExprError();
1731 }
1732
1733 // Make sure that we're referring to a value.
1734 ValueDecl *VD = dyn_cast<ValueDecl>(D);
1735 if (!VD) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001736 Diag(Loc, diag::err_ref_non_value)
Douglas Gregor9af2f522009-12-01 16:58:18 +00001737 << D << SS.getRange();
John McCall87cf6702009-12-18 18:35:10 +00001738 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregor9af2f522009-12-01 16:58:18 +00001739 return ExprError();
1740 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001741
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001742 // Check whether this declaration can be used. Note that we suppress
1743 // this check when we're going to perform argument-dependent lookup
1744 // on this function name, because this might not be the function
1745 // that overload resolution actually selects.
John McCallba135432009-11-21 08:51:07 +00001746 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001747 return ExprError();
1748
Steve Naroffdd972f22008-09-05 22:11:13 +00001749 // Only create DeclRefExpr's for valid Decl's.
1750 if (VD->isInvalidDecl())
Sebastian Redlcd965b92009-01-18 18:53:16 +00001751 return ExprError();
1752
Chris Lattner639e2d32008-10-20 05:16:36 +00001753 // If the identifier reference is inside a block, and it refers to a value
1754 // that is outside the block, create a BlockDeclRefExpr instead of a
1755 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
1756 // the block is formed.
Steve Naroffdd972f22008-09-05 22:11:13 +00001757 //
Chris Lattner639e2d32008-10-20 05:16:36 +00001758 // We do not do this for things like enum constants, global variables, etc,
1759 // as they do not get snapshotted.
1760 //
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001761 if (getCurBlock() &&
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00001762 ShouldSnapshotBlockValueReference(*this, getCurBlock(), VD)) {
Mike Stump0d6fd572010-01-05 02:56:35 +00001763 if (VD->getType().getTypePtr()->isVariablyModifiedType()) {
1764 Diag(Loc, diag::err_ref_vm_type);
1765 Diag(D->getLocation(), diag::note_declared_at);
1766 return ExprError();
1767 }
1768
Fariborz Jahanian8596bbe2010-03-16 23:39:51 +00001769 if (VD->getType()->isArrayType()) {
Mike Stump28497342010-01-05 03:10:36 +00001770 Diag(Loc, diag::err_ref_array_type);
1771 Diag(D->getLocation(), diag::note_declared_at);
1772 return ExprError();
1773 }
1774
Douglas Gregore0762c92009-06-19 23:52:42 +00001775 MarkDeclarationReferenced(Loc, VD);
Eli Friedman5fdeae12009-03-22 23:00:19 +00001776 QualType ExprTy = VD->getType().getNonReferenceType();
Steve Naroff090276f2008-10-10 01:28:17 +00001777 // The BlocksAttr indicates the variable is bound by-reference.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001778 if (VD->getAttr<BlocksAttr>())
Eli Friedman5fdeae12009-03-22 23:00:19 +00001779 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, true));
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00001780 // This is to record that a 'const' was actually synthesize and added.
1781 bool constAdded = !ExprTy.isConstQualified();
Steve Naroff090276f2008-10-10 01:28:17 +00001782 // Variable will be bound by-copy, make it const within the closure.
Mike Stump1eb44332009-09-09 15:08:12 +00001783
Eli Friedman5fdeae12009-03-22 23:00:19 +00001784 ExprTy.addConst();
Fariborz Jahanian52bc56a2010-07-12 17:26:57 +00001785 QualType T = VD->getType();
Fariborz Jahanian59da45a2010-06-04 21:35:44 +00001786 BlockDeclRefExpr *BDRE = new (Context) BlockDeclRefExpr(VD,
1787 ExprTy, Loc, false,
Fariborz Jahanian84ca0082010-07-12 18:12:03 +00001788 constAdded);
Fariborz Jahanian833f42e2010-07-09 22:21:32 +00001789 if (getLangOptions().CPlusPlus) {
1790 if (!T->isDependentType() && !T->isReferenceType()) {
1791 Expr *E = new (Context)
1792 DeclRefExpr(const_cast<ValueDecl*>(BDRE->getDecl()), T,
1793 SourceLocation());
Fariborz Jahanian59da45a2010-06-04 21:35:44 +00001794
Fariborz Jahanian833f42e2010-07-09 22:21:32 +00001795 OwningExprResult Res = PerformCopyInitialization(
1796 InitializedEntity::InitializeBlock(VD->getLocation(),
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00001797 T, false),
Fariborz Jahanian833f42e2010-07-09 22:21:32 +00001798 SourceLocation(),
1799 Owned(E));
1800 if (!Res.isInvalid()) {
1801 Res = MaybeCreateCXXExprWithTemporaries(move(Res));
1802 Expr *Init = Res.takeAs<Expr>();
1803 BDRE->setCopyConstructorExpr(Init);
1804 }
Fariborz Jahanian59da45a2010-06-04 21:35:44 +00001805 }
1806 }
1807 return Owned(BDRE);
Steve Naroff090276f2008-10-10 01:28:17 +00001808 }
1809 // If this reference is not in a block or if the referenced variable is
1810 // within the block, create a normal DeclRefExpr.
Douglas Gregor898574e2008-12-05 23:32:09 +00001811
John McCallf7a1a742009-11-24 19:00:30 +00001812 return BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc, &SS);
Reid Spencer5f016e22007-07-11 17:01:13 +00001813}
1814
Sebastian Redlcd965b92009-01-18 18:53:16 +00001815Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
1816 tok::TokenKind Kind) {
Chris Lattnerd9f69102008-08-10 01:53:14 +00001817 PredefinedExpr::IdentType IT;
Sebastian Redlcd965b92009-01-18 18:53:16 +00001818
Reid Spencer5f016e22007-07-11 17:01:13 +00001819 switch (Kind) {
Chris Lattner1423ea42008-01-12 18:39:25 +00001820 default: assert(0 && "Unknown simple primary expr!");
Chris Lattnerd9f69102008-08-10 01:53:14 +00001821 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
1822 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
1823 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00001824 }
Chris Lattner1423ea42008-01-12 18:39:25 +00001825
Chris Lattnerfa28b302008-01-12 08:14:25 +00001826 // Pre-defined identifiers are of type char[x], where x is the length of the
1827 // string.
Mike Stump1eb44332009-09-09 15:08:12 +00001828
Anders Carlsson3a082d82009-09-08 18:24:21 +00001829 Decl *currentDecl = getCurFunctionOrMethodDecl();
1830 if (!currentDecl) {
Chris Lattnerb0da9232008-12-12 05:05:20 +00001831 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson3a082d82009-09-08 18:24:21 +00001832 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerb0da9232008-12-12 05:05:20 +00001833 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001834
Anders Carlsson773f3972009-09-11 01:22:35 +00001835 QualType ResTy;
1836 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
1837 ResTy = Context.DependentTy;
1838 } else {
Anders Carlsson848fa642010-02-11 18:20:28 +00001839 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001840
Anders Carlsson773f3972009-09-11 01:22:35 +00001841 llvm::APInt LengthI(32, Length + 1);
John McCall0953e762009-09-24 19:53:00 +00001842 ResTy = Context.CharTy.withConst();
Anders Carlsson773f3972009-09-11 01:22:35 +00001843 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
1844 }
Steve Naroff6ece14c2009-01-21 00:14:39 +00001845 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Reid Spencer5f016e22007-07-11 17:01:13 +00001846}
1847
Sebastian Redlcd965b92009-01-18 18:53:16 +00001848Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001849 llvm::SmallString<16> CharBuffer;
Douglas Gregor453091c2010-03-16 22:30:13 +00001850 bool Invalid = false;
1851 llvm::StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
1852 if (Invalid)
1853 return ExprError();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001854
Benjamin Kramerddeea562010-02-27 13:44:12 +00001855 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
1856 PP);
Reid Spencer5f016e22007-07-11 17:01:13 +00001857 if (Literal.hadError())
Sebastian Redlcd965b92009-01-18 18:53:16 +00001858 return ExprError();
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00001859
Chris Lattnere8337df2009-12-30 21:19:39 +00001860 QualType Ty;
1861 if (!getLangOptions().CPlusPlus)
1862 Ty = Context.IntTy; // 'x' and L'x' -> int in C.
1863 else if (Literal.isWide())
1864 Ty = Context.WCharTy; // L'x' -> wchar_t in C++.
Eli Friedman136b0cd2010-02-03 18:21:45 +00001865 else if (Literal.isMultiChar())
1866 Ty = Context.IntTy; // 'wxyz' -> int in C++.
Chris Lattnere8337df2009-12-30 21:19:39 +00001867 else
1868 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00001869
Sebastian Redle91b3bc2009-01-20 22:23:13 +00001870 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
1871 Literal.isWide(),
Chris Lattnere8337df2009-12-30 21:19:39 +00001872 Ty, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00001873}
1874
Sebastian Redlcd965b92009-01-18 18:53:16 +00001875Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
1876 // Fast path for a single digit (which is quite common). A single digit
Reid Spencer5f016e22007-07-11 17:01:13 +00001877 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
1878 if (Tok.getLength() == 1) {
Chris Lattner7216dc92009-01-26 22:36:52 +00001879 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattner0c21e842009-01-16 07:10:29 +00001880 unsigned IntSize = Context.Target.getIntWidth();
Steve Naroff6ece14c2009-01-21 00:14:39 +00001881 return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
Steve Naroff0a473932009-01-20 19:53:53 +00001882 Context.IntTy, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00001883 }
Ted Kremenek28396602009-01-13 23:19:12 +00001884
Reid Spencer5f016e22007-07-11 17:01:13 +00001885 llvm::SmallString<512> IntegerBuffer;
Chris Lattner2a299042008-09-30 20:53:45 +00001886 // Add padding so that NumericLiteralParser can overread by one character.
1887 IntegerBuffer.resize(Tok.getLength()+1);
Reid Spencer5f016e22007-07-11 17:01:13 +00001888 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd965b92009-01-18 18:53:16 +00001889
Reid Spencer5f016e22007-07-11 17:01:13 +00001890 // Get the spelling of the token, which eliminates trigraphs, etc.
Douglas Gregor453091c2010-03-16 22:30:13 +00001891 bool Invalid = false;
1892 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
1893 if (Invalid)
1894 return ExprError();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001895
Mike Stump1eb44332009-09-09 15:08:12 +00001896 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Reid Spencer5f016e22007-07-11 17:01:13 +00001897 Tok.getLocation(), PP);
1898 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +00001899 return ExprError();
1900
Chris Lattner5d661452007-08-26 03:42:43 +00001901 Expr *Res;
Sebastian Redlcd965b92009-01-18 18:53:16 +00001902
Chris Lattner5d661452007-08-26 03:42:43 +00001903 if (Literal.isFloatingLiteral()) {
Chris Lattner525a0502007-09-22 18:29:59 +00001904 QualType Ty;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001905 if (Literal.isFloat)
Chris Lattner525a0502007-09-22 18:29:59 +00001906 Ty = Context.FloatTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001907 else if (!Literal.isLong)
Chris Lattner525a0502007-09-22 18:29:59 +00001908 Ty = Context.DoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001909 else
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001910 Ty = Context.LongDoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001911
1912 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
1913
John McCall94c939d2009-12-24 09:08:04 +00001914 using llvm::APFloat;
1915 APFloat Val(Format);
1916
1917 APFloat::opStatus result = Literal.GetFloatValue(Val);
John McCall9f2df882009-12-24 11:09:08 +00001918
1919 // Overflow is always an error, but underflow is only an error if
1920 // we underflowed to zero (APFloat reports denormals as underflow).
1921 if ((result & APFloat::opOverflow) ||
1922 ((result & APFloat::opUnderflow) && Val.isZero())) {
John McCall94c939d2009-12-24 09:08:04 +00001923 unsigned diagnostic;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001924 llvm::SmallString<20> buffer;
John McCall94c939d2009-12-24 09:08:04 +00001925 if (result & APFloat::opOverflow) {
John McCall2a0d7572010-02-26 23:35:57 +00001926 diagnostic = diag::warn_float_overflow;
John McCall94c939d2009-12-24 09:08:04 +00001927 APFloat::getLargest(Format).toString(buffer);
1928 } else {
John McCall2a0d7572010-02-26 23:35:57 +00001929 diagnostic = diag::warn_float_underflow;
John McCall94c939d2009-12-24 09:08:04 +00001930 APFloat::getSmallest(Format).toString(buffer);
1931 }
1932
1933 Diag(Tok.getLocation(), diagnostic)
1934 << Ty
1935 << llvm::StringRef(buffer.data(), buffer.size());
1936 }
1937
1938 bool isExact = (result == APFloat::opOK);
Chris Lattner001d64d2009-06-29 17:34:55 +00001939 Res = new (Context) FloatingLiteral(Val, isExact, Ty, Tok.getLocation());
Sebastian Redlcd965b92009-01-18 18:53:16 +00001940
Chris Lattner5d661452007-08-26 03:42:43 +00001941 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00001942 return ExprError();
Chris Lattner5d661452007-08-26 03:42:43 +00001943 } else {
Chris Lattnerf0467b32008-04-02 04:24:33 +00001944 QualType Ty;
Reid Spencer5f016e22007-07-11 17:01:13 +00001945
Neil Boothb9449512007-08-29 22:00:19 +00001946 // long long is a C99 feature.
1947 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth79859c32007-08-29 22:13:52 +00001948 Literal.isLongLong)
Neil Boothb9449512007-08-29 22:00:19 +00001949 Diag(Tok.getLocation(), diag::ext_longlong);
1950
Reid Spencer5f016e22007-07-11 17:01:13 +00001951 // Get the value in the widest-possible width.
Chris Lattner98be4942008-03-05 18:54:05 +00001952 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlcd965b92009-01-18 18:53:16 +00001953
Reid Spencer5f016e22007-07-11 17:01:13 +00001954 if (Literal.GetIntegerValue(ResultVal)) {
1955 // If this value didn't fit into uintmax_t, warn and force to ull.
1956 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattnerf0467b32008-04-02 04:24:33 +00001957 Ty = Context.UnsignedLongLongTy;
1958 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner98be4942008-03-05 18:54:05 +00001959 "long long is not intmax_t?");
Reid Spencer5f016e22007-07-11 17:01:13 +00001960 } else {
1961 // If this value fits into a ULL, try to figure out what else it fits into
1962 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd965b92009-01-18 18:53:16 +00001963
Reid Spencer5f016e22007-07-11 17:01:13 +00001964 // Octal, Hexadecimal, and integers with a U suffix are allowed to
1965 // be an unsigned int.
1966 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
1967
1968 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001969 unsigned Width = 0;
Chris Lattner97c51562007-08-23 21:58:08 +00001970 if (!Literal.isLong && !Literal.isLongLong) {
1971 // Are int/unsigned possibilities?
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001972 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001973
Reid Spencer5f016e22007-07-11 17:01:13 +00001974 // Does it fit in a unsigned int?
1975 if (ResultVal.isIntN(IntSize)) {
1976 // Does it fit in a signed int?
1977 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001978 Ty = Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001979 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001980 Ty = Context.UnsignedIntTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001981 Width = IntSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00001982 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001983 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001984
Reid Spencer5f016e22007-07-11 17:01:13 +00001985 // Are long/unsigned long possibilities?
Chris Lattnerf0467b32008-04-02 04:24:33 +00001986 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001987 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001988
Reid Spencer5f016e22007-07-11 17:01:13 +00001989 // Does it fit in a unsigned long?
1990 if (ResultVal.isIntN(LongSize)) {
1991 // Does it fit in a signed long?
1992 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001993 Ty = Context.LongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001994 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001995 Ty = Context.UnsignedLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001996 Width = LongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00001997 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001998 }
1999
Reid Spencer5f016e22007-07-11 17:01:13 +00002000 // Finally, check long long if needed.
Chris Lattnerf0467b32008-04-02 04:24:33 +00002001 if (Ty.isNull()) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002002 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002003
Reid Spencer5f016e22007-07-11 17:01:13 +00002004 // Does it fit in a unsigned long long?
2005 if (ResultVal.isIntN(LongLongSize)) {
2006 // Does it fit in a signed long long?
2007 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002008 Ty = Context.LongLongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002009 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002010 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002011 Width = LongLongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002012 }
2013 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002014
Reid Spencer5f016e22007-07-11 17:01:13 +00002015 // If we still couldn't decide a type, we probably have something that
2016 // does not fit in a signed long long, but has no U suffix.
Chris Lattnerf0467b32008-04-02 04:24:33 +00002017 if (Ty.isNull()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002018 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattnerf0467b32008-04-02 04:24:33 +00002019 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002020 Width = Context.Target.getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +00002021 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002022
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002023 if (ResultVal.getBitWidth() != Width)
2024 ResultVal.trunc(Width);
Reid Spencer5f016e22007-07-11 17:01:13 +00002025 }
Sebastian Redle91b3bc2009-01-20 22:23:13 +00002026 Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00002027 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002028
Chris Lattner5d661452007-08-26 03:42:43 +00002029 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
2030 if (Literal.isImaginary)
Mike Stump1eb44332009-09-09 15:08:12 +00002031 Res = new (Context) ImaginaryLiteral(Res,
Steve Naroff6ece14c2009-01-21 00:14:39 +00002032 Context.getComplexType(Res->getType()));
Sebastian Redlcd965b92009-01-18 18:53:16 +00002033
2034 return Owned(Res);
Reid Spencer5f016e22007-07-11 17:01:13 +00002035}
2036
Sebastian Redlcd965b92009-01-18 18:53:16 +00002037Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
2038 SourceLocation R, ExprArg Val) {
Anders Carlssone9146f22009-05-01 19:49:17 +00002039 Expr *E = Val.takeAs<Expr>();
Chris Lattnerf0467b32008-04-02 04:24:33 +00002040 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff6ece14c2009-01-21 00:14:39 +00002041 return Owned(new (Context) ParenExpr(L, R, E));
Reid Spencer5f016e22007-07-11 17:01:13 +00002042}
2043
2044/// The UsualUnaryConversions() function is *not* called by this routine.
2045/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl28507842009-02-26 14:39:58 +00002046bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Sebastian Redl05189992008-11-11 17:56:53 +00002047 SourceLocation OpLoc,
2048 const SourceRange &ExprRange,
2049 bool isSizeof) {
Sebastian Redl28507842009-02-26 14:39:58 +00002050 if (exprType->isDependentType())
2051 return false;
2052
Sebastian Redl5d484e82009-11-23 17:18:46 +00002053 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2054 // the result is the size of the referenced type."
2055 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2056 // result shall be the alignment of the referenced type."
2057 if (const ReferenceType *Ref = exprType->getAs<ReferenceType>())
2058 exprType = Ref->getPointeeType();
2059
Reid Spencer5f016e22007-07-11 17:01:13 +00002060 // C99 6.5.3.4p1:
John McCall5ab75172009-11-04 07:28:41 +00002061 if (exprType->isFunctionType()) {
Chris Lattner1efaa952009-04-24 00:30:45 +00002062 // alignof(function) is allowed as an extension.
Chris Lattner01072922009-01-24 19:46:37 +00002063 if (isSizeof)
2064 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
2065 return false;
2066 }
Mike Stump1eb44332009-09-09 15:08:12 +00002067
Chris Lattner1efaa952009-04-24 00:30:45 +00002068 // Allow sizeof(void)/alignof(void) as an extension.
Chris Lattner01072922009-01-24 19:46:37 +00002069 if (exprType->isVoidType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002070 Diag(OpLoc, diag::ext_sizeof_void_type)
2071 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattner01072922009-01-24 19:46:37 +00002072 return false;
2073 }
Mike Stump1eb44332009-09-09 15:08:12 +00002074
Chris Lattner1efaa952009-04-24 00:30:45 +00002075 if (RequireCompleteType(OpLoc, exprType,
Douglas Gregor5cc07df2009-12-15 16:44:32 +00002076 PDiag(diag::err_sizeof_alignof_incomplete_type)
2077 << int(!isSizeof) << ExprRange))
Chris Lattner1efaa952009-04-24 00:30:45 +00002078 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002079
Chris Lattner1efaa952009-04-24 00:30:45 +00002080 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
John McCallc12c5bb2010-05-15 11:32:37 +00002081 if (LangOpts.ObjCNonFragileABI && exprType->isObjCObjectType()) {
Chris Lattner1efaa952009-04-24 00:30:45 +00002082 Diag(OpLoc, diag::err_sizeof_nonfragile_interface)
Chris Lattner5cb10d32009-04-24 22:30:50 +00002083 << exprType << isSizeof << ExprRange;
2084 return true;
Chris Lattnerca790922009-04-21 19:55:16 +00002085 }
Mike Stump1eb44332009-09-09 15:08:12 +00002086
Douglas Gregor9ba6af82010-05-23 19:43:23 +00002087 if (Context.hasSameUnqualifiedType(exprType, Context.OverloadTy)) {
2088 Diag(OpLoc, diag::err_sizeof_alignof_overloaded_function_type)
2089 << !isSizeof << ExprRange;
2090 return true;
2091 }
2092
Chris Lattner1efaa952009-04-24 00:30:45 +00002093 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002094}
2095
Chris Lattner31e21e02009-01-24 20:17:12 +00002096bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
2097 const SourceRange &ExprRange) {
2098 E = E->IgnoreParens();
Sebastian Redl28507842009-02-26 14:39:58 +00002099
Mike Stump1eb44332009-09-09 15:08:12 +00002100 // alignof decl is always ok.
Chris Lattner31e21e02009-01-24 20:17:12 +00002101 if (isa<DeclRefExpr>(E))
2102 return false;
Sebastian Redl28507842009-02-26 14:39:58 +00002103
2104 // Cannot know anything else if the expression is dependent.
2105 if (E->isTypeDependent())
2106 return false;
2107
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002108 if (E->getBitField()) {
2109 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
2110 return true;
Chris Lattner31e21e02009-01-24 20:17:12 +00002111 }
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002112
2113 // Alignment of a field access is always okay, so long as it isn't a
2114 // bit-field.
2115 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump8e1fab22009-07-22 18:58:19 +00002116 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002117 return false;
2118
Chris Lattner31e21e02009-01-24 20:17:12 +00002119 return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
2120}
2121
Douglas Gregorba498172009-03-13 21:01:28 +00002122/// \brief Build a sizeof or alignof expression given a type operand.
Mike Stump1eb44332009-09-09 15:08:12 +00002123Action::OwningExprResult
John McCalla93c9342009-12-07 02:54:59 +00002124Sema::CreateSizeOfAlignOfExpr(TypeSourceInfo *TInfo,
John McCall5ab75172009-11-04 07:28:41 +00002125 SourceLocation OpLoc,
Douglas Gregorba498172009-03-13 21:01:28 +00002126 bool isSizeOf, SourceRange R) {
John McCalla93c9342009-12-07 02:54:59 +00002127 if (!TInfo)
Douglas Gregorba498172009-03-13 21:01:28 +00002128 return ExprError();
2129
John McCalla93c9342009-12-07 02:54:59 +00002130 QualType T = TInfo->getType();
John McCall5ab75172009-11-04 07:28:41 +00002131
Douglas Gregorba498172009-03-13 21:01:28 +00002132 if (!T->isDependentType() &&
2133 CheckSizeOfAlignOfOperand(T, OpLoc, R, isSizeOf))
2134 return ExprError();
2135
2136 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
John McCalla93c9342009-12-07 02:54:59 +00002137 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, TInfo,
Douglas Gregorba498172009-03-13 21:01:28 +00002138 Context.getSizeType(), OpLoc,
2139 R.getEnd()));
2140}
2141
2142/// \brief Build a sizeof or alignof expression given an expression
2143/// operand.
Mike Stump1eb44332009-09-09 15:08:12 +00002144Action::OwningExprResult
2145Sema::CreateSizeOfAlignOfExpr(Expr *E, SourceLocation OpLoc,
Douglas Gregorba498172009-03-13 21:01:28 +00002146 bool isSizeOf, SourceRange R) {
2147 // Verify that the operand is valid.
2148 bool isInvalid = false;
2149 if (E->isTypeDependent()) {
2150 // Delay type-checking for type-dependent expressions.
2151 } else if (!isSizeOf) {
2152 isInvalid = CheckAlignOfExpr(E, OpLoc, R);
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002153 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Douglas Gregorba498172009-03-13 21:01:28 +00002154 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
2155 isInvalid = true;
2156 } else {
2157 isInvalid = CheckSizeOfAlignOfOperand(E->getType(), OpLoc, R, true);
2158 }
2159
2160 if (isInvalid)
2161 return ExprError();
2162
2163 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
2164 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, E,
2165 Context.getSizeType(), OpLoc,
2166 R.getEnd()));
2167}
2168
Sebastian Redl05189992008-11-11 17:56:53 +00002169/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
2170/// the same for @c alignof and @c __alignof
2171/// Note that the ArgRange is invalid if isType is false.
Sebastian Redl0eb23302009-01-19 00:08:26 +00002172Action::OwningExprResult
Sebastian Redl05189992008-11-11 17:56:53 +00002173Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
2174 void *TyOrEx, const SourceRange &ArgRange) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002175 // If error parsing type, ignore.
Sebastian Redl0eb23302009-01-19 00:08:26 +00002176 if (TyOrEx == 0) return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00002177
Sebastian Redl05189992008-11-11 17:56:53 +00002178 if (isType) {
John McCalla93c9342009-12-07 02:54:59 +00002179 TypeSourceInfo *TInfo;
2180 (void) GetTypeFromParser(TyOrEx, &TInfo);
2181 return CreateSizeOfAlignOfExpr(TInfo, OpLoc, isSizeof, ArgRange);
Mike Stump1eb44332009-09-09 15:08:12 +00002182 }
Sebastian Redl05189992008-11-11 17:56:53 +00002183
Douglas Gregorba498172009-03-13 21:01:28 +00002184 Expr *ArgEx = (Expr *)TyOrEx;
2185 Action::OwningExprResult Result
2186 = CreateSizeOfAlignOfExpr(ArgEx, OpLoc, isSizeof, ArgEx->getSourceRange());
2187
2188 if (Result.isInvalid())
2189 DeleteExpr(ArgEx);
2190
2191 return move(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00002192}
2193
Chris Lattnerba27e2a2009-02-17 08:12:06 +00002194QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc, bool isReal) {
Sebastian Redl28507842009-02-26 14:39:58 +00002195 if (V->isTypeDependent())
2196 return Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00002197
Chris Lattnercc26ed72007-08-26 05:39:26 +00002198 // These operators return the element type of a complex type.
John McCall183700f2009-09-21 23:43:11 +00002199 if (const ComplexType *CT = V->getType()->getAs<ComplexType>())
Chris Lattnerdbb36972007-08-24 21:16:53 +00002200 return CT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00002201
Chris Lattnercc26ed72007-08-26 05:39:26 +00002202 // Otherwise they pass through real integer and floating point types here.
2203 if (V->getType()->isArithmeticType())
2204 return V->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002205
Chris Lattnercc26ed72007-08-26 05:39:26 +00002206 // Reject anything else.
Chris Lattnerba27e2a2009-02-17 08:12:06 +00002207 Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
2208 << (isReal ? "__real" : "__imag");
Chris Lattnercc26ed72007-08-26 05:39:26 +00002209 return QualType();
Chris Lattnerdbb36972007-08-24 21:16:53 +00002210}
2211
2212
Reid Spencer5f016e22007-07-11 17:01:13 +00002213
Sebastian Redl0eb23302009-01-19 00:08:26 +00002214Action::OwningExprResult
2215Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
2216 tok::TokenKind Kind, ExprArg Input) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002217 UnaryOperator::Opcode Opc;
2218 switch (Kind) {
2219 default: assert(0 && "Unknown unary op!");
2220 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
2221 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
2222 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002223
Eli Friedmane4216e92009-11-18 03:38:04 +00002224 return BuildUnaryOp(S, OpLoc, Opc, move(Input));
Reid Spencer5f016e22007-07-11 17:01:13 +00002225}
2226
Sebastian Redl0eb23302009-01-19 00:08:26 +00002227Action::OwningExprResult
2228Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
2229 ExprArg Idx, SourceLocation RLoc) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00002230 // Since this might be a postfix expression, get rid of ParenListExprs.
2231 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
2232
Sebastian Redl0eb23302009-01-19 00:08:26 +00002233 Expr *LHSExp = static_cast<Expr*>(Base.get()),
2234 *RHSExp = static_cast<Expr*>(Idx.get());
Mike Stump1eb44332009-09-09 15:08:12 +00002235
Douglas Gregor337c6b92008-11-19 17:17:41 +00002236 if (getLangOptions().CPlusPlus &&
Douglas Gregor3384c9c2009-05-19 00:01:19 +00002237 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
2238 Base.release();
2239 Idx.release();
2240 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
2241 Context.DependentTy, RLoc));
2242 }
2243
Mike Stump1eb44332009-09-09 15:08:12 +00002244 if (getLangOptions().CPlusPlus &&
Sebastian Redl0eb23302009-01-19 00:08:26 +00002245 (LHSExp->getType()->isRecordType() ||
Eli Friedman03f332a2008-12-15 22:34:21 +00002246 LHSExp->getType()->isEnumeralType() ||
2247 RHSExp->getType()->isRecordType() ||
2248 RHSExp->getType()->isEnumeralType())) {
Sebastian Redlf322ed62009-10-29 20:17:01 +00002249 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, move(Base),move(Idx));
Douglas Gregor337c6b92008-11-19 17:17:41 +00002250 }
2251
Sebastian Redlf322ed62009-10-29 20:17:01 +00002252 return CreateBuiltinArraySubscriptExpr(move(Base), LLoc, move(Idx), RLoc);
2253}
2254
2255
2256Action::OwningExprResult
2257Sema::CreateBuiltinArraySubscriptExpr(ExprArg Base, SourceLocation LLoc,
2258 ExprArg Idx, SourceLocation RLoc) {
2259 Expr *LHSExp = static_cast<Expr*>(Base.get());
2260 Expr *RHSExp = static_cast<Expr*>(Idx.get());
2261
Chris Lattner12d9ff62007-07-16 00:14:47 +00002262 // Perform default conversions.
Douglas Gregora873dfc2010-02-03 00:27:59 +00002263 if (!LHSExp->getType()->getAs<VectorType>())
2264 DefaultFunctionArrayLvalueConversion(LHSExp);
2265 DefaultFunctionArrayLvalueConversion(RHSExp);
Sebastian Redl0eb23302009-01-19 00:08:26 +00002266
Chris Lattner12d9ff62007-07-16 00:14:47 +00002267 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002268
Reid Spencer5f016e22007-07-11 17:01:13 +00002269 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002270 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stumpeed9cac2009-02-19 03:04:26 +00002271 // in the subscript position. As a result, we need to derive the array base
Reid Spencer5f016e22007-07-11 17:01:13 +00002272 // and index from the expression types.
Chris Lattner12d9ff62007-07-16 00:14:47 +00002273 Expr *BaseExpr, *IndexExpr;
2274 QualType ResultType;
Sebastian Redl28507842009-02-26 14:39:58 +00002275 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
2276 BaseExpr = LHSExp;
2277 IndexExpr = RHSExp;
2278 ResultType = Context.DependentTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00002279 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner12d9ff62007-07-16 00:14:47 +00002280 BaseExpr = LHSExp;
2281 IndexExpr = RHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00002282 ResultType = PTy->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002283 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattner7a2e0472007-07-16 00:23:25 +00002284 // Handle the uncommon case of "123[Ptr]".
Chris Lattner12d9ff62007-07-16 00:14:47 +00002285 BaseExpr = RHSExp;
2286 IndexExpr = LHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00002287 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00002288 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00002289 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00002290 BaseExpr = LHSExp;
2291 IndexExpr = RHSExp;
2292 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00002293 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00002294 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00002295 // Handle the uncommon case of "123[Ptr]".
2296 BaseExpr = RHSExp;
2297 IndexExpr = LHSExp;
2298 ResultType = PTy->getPointeeType();
John McCall183700f2009-09-21 23:43:11 +00002299 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattnerc8629632007-07-31 19:29:30 +00002300 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner12d9ff62007-07-16 00:14:47 +00002301 IndexExpr = RHSExp;
Nate Begeman334a8022009-01-18 00:45:31 +00002302
Chris Lattner12d9ff62007-07-16 00:14:47 +00002303 // FIXME: need to deal with const...
2304 ResultType = VTy->getElementType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00002305 } else if (LHSTy->isArrayType()) {
2306 // If we see an array that wasn't promoted by
Douglas Gregora873dfc2010-02-03 00:27:59 +00002307 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedman7c32f8e2009-04-25 23:46:54 +00002308 // wasn't promoted because of the C90 rule that doesn't
2309 // allow promoting non-lvalue arrays. Warn, then
2310 // force the promotion here.
2311 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
2312 LHSExp->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00002313 ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
2314 CastExpr::CK_ArrayToPointerDecay);
Eli Friedman7c32f8e2009-04-25 23:46:54 +00002315 LHSTy = LHSExp->getType();
2316
2317 BaseExpr = LHSExp;
2318 IndexExpr = RHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00002319 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00002320 } else if (RHSTy->isArrayType()) {
2321 // Same as previous, except for 123[f().a] case
2322 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
2323 RHSExp->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00002324 ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
2325 CastExpr::CK_ArrayToPointerDecay);
Eli Friedman7c32f8e2009-04-25 23:46:54 +00002326 RHSTy = RHSExp->getType();
2327
2328 BaseExpr = RHSExp;
2329 IndexExpr = LHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00002330 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002331 } else {
Chris Lattner338395d2009-04-25 22:50:55 +00002332 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
2333 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00002334 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002335 // C99 6.5.2.1p1
Nate Begeman2ef13e52009-08-10 23:49:36 +00002336 if (!(IndexExpr->getType()->isIntegerType() &&
2337 IndexExpr->getType()->isScalarType()) && !IndexExpr->isTypeDependent())
Chris Lattner338395d2009-04-25 22:50:55 +00002338 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
2339 << IndexExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00002340
Daniel Dunbar7e88a602009-09-17 06:31:17 +00002341 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinig0f9a5b52009-09-14 20:14:57 +00002342 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
2343 && !IndexExpr->isTypeDependent())
Sam Weinig76e2b712009-09-14 01:58:58 +00002344 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
2345
Douglas Gregore7450f52009-03-24 19:52:54 +00002346 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump1eb44332009-09-09 15:08:12 +00002347 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
2348 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregore7450f52009-03-24 19:52:54 +00002349 // incomplete types are not object types.
2350 if (ResultType->isFunctionType()) {
2351 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
2352 << ResultType << BaseExpr->getSourceRange();
2353 return ExprError();
2354 }
Mike Stump1eb44332009-09-09 15:08:12 +00002355
Douglas Gregore7450f52009-03-24 19:52:54 +00002356 if (!ResultType->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00002357 RequireCompleteType(LLoc, ResultType,
Anders Carlssonb7906612009-08-26 23:45:07 +00002358 PDiag(diag::err_subscript_incomplete_type)
2359 << BaseExpr->getSourceRange()))
Douglas Gregore7450f52009-03-24 19:52:54 +00002360 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00002361
Chris Lattner1efaa952009-04-24 00:30:45 +00002362 // Diagnose bad cases where we step over interface counts.
John McCallc12c5bb2010-05-15 11:32:37 +00002363 if (ResultType->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner1efaa952009-04-24 00:30:45 +00002364 Diag(LLoc, diag::err_subscript_nonfragile_interface)
2365 << ResultType << BaseExpr->getSourceRange();
2366 return ExprError();
2367 }
Mike Stump1eb44332009-09-09 15:08:12 +00002368
Sebastian Redl0eb23302009-01-19 00:08:26 +00002369 Base.release();
2370 Idx.release();
Mike Stumpeed9cac2009-02-19 03:04:26 +00002371 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
Steve Naroff6ece14c2009-01-21 00:14:39 +00002372 ResultType, RLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00002373}
2374
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002375QualType Sema::
Nate Begeman213541a2008-04-18 23:10:10 +00002376CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00002377 const IdentifierInfo *CompName,
Anders Carlsson8f28f992009-08-26 18:25:21 +00002378 SourceLocation CompLoc) {
Daniel Dunbar2ad32892009-10-18 02:09:38 +00002379 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
2380 // see FIXME there.
2381 //
2382 // FIXME: This logic can be greatly simplified by splitting it along
2383 // halving/not halving and reworking the component checking.
John McCall183700f2009-09-21 23:43:11 +00002384 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
Nate Begeman8a997642008-05-09 06:41:27 +00002385
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002386 // The vector accessor can't exceed the number of elements.
Daniel Dunbare013d682009-10-18 20:26:12 +00002387 const char *compStr = CompName->getNameStart();
Nate Begeman353417a2009-01-18 01:47:54 +00002388
Mike Stumpeed9cac2009-02-19 03:04:26 +00002389 // This flag determines whether or not the component is one of the four
Nate Begeman353417a2009-01-18 01:47:54 +00002390 // special names that indicate a subset of exactly half the elements are
2391 // to be selected.
2392 bool HalvingSwizzle = false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00002393
Nate Begeman353417a2009-01-18 01:47:54 +00002394 // This flag determines whether or not CompName has an 's' char prefix,
2395 // indicating that it is a string of hex values to be used as vector indices.
Nate Begeman131f4652009-06-25 21:06:09 +00002396 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
Nate Begeman8a997642008-05-09 06:41:27 +00002397
2398 // Check that we've found one of the special components, or that the component
2399 // names must come from the same set.
Mike Stumpeed9cac2009-02-19 03:04:26 +00002400 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begeman353417a2009-01-18 01:47:54 +00002401 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
2402 HalvingSwizzle = true;
Nate Begeman8a997642008-05-09 06:41:27 +00002403 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner88dca042007-08-02 22:33:49 +00002404 do
2405 compStr++;
2406 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
Nate Begeman353417a2009-01-18 01:47:54 +00002407 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
Chris Lattner88dca042007-08-02 22:33:49 +00002408 do
2409 compStr++;
Nate Begeman353417a2009-01-18 01:47:54 +00002410 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
Chris Lattner88dca042007-08-02 22:33:49 +00002411 }
Nate Begeman353417a2009-01-18 01:47:54 +00002412
Mike Stumpeed9cac2009-02-19 03:04:26 +00002413 if (!HalvingSwizzle && *compStr) {
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002414 // We didn't get to the end of the string. This means the component names
2415 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002416 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
2417 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002418 return QualType();
2419 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00002420
Nate Begeman353417a2009-01-18 01:47:54 +00002421 // Ensure no component accessor exceeds the width of the vector type it
2422 // operates on.
2423 if (!HalvingSwizzle) {
Daniel Dunbare013d682009-10-18 20:26:12 +00002424 compStr = CompName->getNameStart();
Nate Begeman353417a2009-01-18 01:47:54 +00002425
2426 if (HexSwizzle)
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002427 compStr++;
Nate Begeman353417a2009-01-18 01:47:54 +00002428
2429 while (*compStr) {
2430 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
2431 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
2432 << baseType << SourceRange(CompLoc);
2433 return QualType();
2434 }
2435 }
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002436 }
Nate Begeman8a997642008-05-09 06:41:27 +00002437
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002438 // The component accessor looks fine - now we need to compute the actual type.
Mike Stumpeed9cac2009-02-19 03:04:26 +00002439 // The vector type is implied by the component accessor. For example,
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002440 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman353417a2009-01-18 01:47:54 +00002441 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begeman8a997642008-05-09 06:41:27 +00002442 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begeman0479a0b2009-12-15 18:13:04 +00002443 unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2
Anders Carlsson8f28f992009-08-26 18:25:21 +00002444 : CompName->getLength();
Nate Begeman353417a2009-01-18 01:47:54 +00002445 if (HexSwizzle)
2446 CompSize--;
2447
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002448 if (CompSize == 1)
2449 return vecType->getElementType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00002450
Nate Begeman213541a2008-04-18 23:10:10 +00002451 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stumpeed9cac2009-02-19 03:04:26 +00002452 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begeman213541a2008-04-18 23:10:10 +00002453 // diagostics look bad. We want extended vector types to appear built-in.
2454 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
2455 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
2456 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroffbea0b342007-07-29 16:33:31 +00002457 }
2458 return VT; // should never get here (a typedef type should always be found).
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002459}
2460
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002461static Decl *FindGetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
Anders Carlsson8f28f992009-08-26 18:25:21 +00002462 IdentifierInfo *Member,
Douglas Gregor6ab35242009-04-09 21:40:53 +00002463 const Selector &Sel,
2464 ASTContext &Context) {
Mike Stump1eb44332009-09-09 15:08:12 +00002465
Anders Carlsson8f28f992009-08-26 18:25:21 +00002466 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002467 return PD;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002468 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002469 return OMD;
Mike Stump1eb44332009-09-09 15:08:12 +00002470
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002471 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
2472 E = PDecl->protocol_end(); I != E; ++I) {
Mike Stump1eb44332009-09-09 15:08:12 +00002473 if (Decl *D = FindGetterNameDeclFromProtocolList(*I, Member, Sel,
Douglas Gregor6ab35242009-04-09 21:40:53 +00002474 Context))
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002475 return D;
2476 }
2477 return 0;
2478}
2479
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002480static Decl *FindGetterNameDecl(const ObjCObjectPointerType *QIdTy,
Anders Carlsson8f28f992009-08-26 18:25:21 +00002481 IdentifierInfo *Member,
Douglas Gregor6ab35242009-04-09 21:40:53 +00002482 const Selector &Sel,
2483 ASTContext &Context) {
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002484 // Check protocols on qualified interfaces.
2485 Decl *GDecl = 0;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002486 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002487 E = QIdTy->qual_end(); I != E; ++I) {
Anders Carlsson8f28f992009-08-26 18:25:21 +00002488 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002489 GDecl = PD;
2490 break;
2491 }
2492 // Also must look for a getter name which uses property syntax.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002493 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002494 GDecl = OMD;
2495 break;
2496 }
2497 }
2498 if (!GDecl) {
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002499 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002500 E = QIdTy->qual_end(); I != E; ++I) {
2501 // Search in the protocol-qualifier list of current protocol.
Douglas Gregor6ab35242009-04-09 21:40:53 +00002502 GDecl = FindGetterNameDeclFromProtocolList(*I, Member, Sel, Context);
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002503 if (GDecl)
2504 return GDecl;
2505 }
2506 }
2507 return GDecl;
2508}
Chris Lattner76a642f2009-02-15 22:43:40 +00002509
John McCall129e2df2009-11-30 22:42:35 +00002510Sema::OwningExprResult
John McCallaa81e162009-12-01 22:10:20 +00002511Sema::ActOnDependentMemberExpr(ExprArg Base, QualType BaseType,
2512 bool IsArrow, SourceLocation OpLoc,
John McCall129e2df2009-11-30 22:42:35 +00002513 const CXXScopeSpec &SS,
2514 NamedDecl *FirstQualifierInScope,
2515 DeclarationName Name, SourceLocation NameLoc,
2516 const TemplateArgumentListInfo *TemplateArgs) {
2517 Expr *BaseExpr = Base.takeAs<Expr>();
2518
2519 // Even in dependent contexts, try to diagnose base expressions with
2520 // obviously wrong types, e.g.:
2521 //
2522 // T* t;
2523 // t.f;
2524 //
2525 // In Obj-C++, however, the above expression is valid, since it could be
2526 // accessing the 'f' property if T is an Obj-C interface. The extra check
2527 // allows this, while still reporting an error if T is a struct pointer.
2528 if (!IsArrow) {
John McCallaa81e162009-12-01 22:10:20 +00002529 const PointerType *PT = BaseType->getAs<PointerType>();
John McCall129e2df2009-11-30 22:42:35 +00002530 if (PT && (!getLangOptions().ObjC1 ||
2531 PT->getPointeeType()->isRecordType())) {
John McCallaa81e162009-12-01 22:10:20 +00002532 assert(BaseExpr && "cannot happen with implicit member accesses");
John McCall129e2df2009-11-30 22:42:35 +00002533 Diag(NameLoc, diag::err_typecheck_member_reference_struct_union)
John McCallaa81e162009-12-01 22:10:20 +00002534 << BaseType << BaseExpr->getSourceRange();
John McCall129e2df2009-11-30 22:42:35 +00002535 return ExprError();
2536 }
2537 }
2538
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00002539 assert(BaseType->isDependentType() || Name.isDependentName() ||
Douglas Gregor01e56ae2010-04-12 20:54:26 +00002540 isDependentScopeSpecifier(SS));
John McCall129e2df2009-11-30 22:42:35 +00002541
2542 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
2543 // must have pointer type, and the accessed type is the pointee.
John McCallaa81e162009-12-01 22:10:20 +00002544 return Owned(CXXDependentScopeMemberExpr::Create(Context, BaseExpr, BaseType,
John McCall129e2df2009-11-30 22:42:35 +00002545 IsArrow, OpLoc,
2546 static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
2547 SS.getRange(),
2548 FirstQualifierInScope,
2549 Name, NameLoc,
2550 TemplateArgs));
2551}
2552
2553/// We know that the given qualified member reference points only to
2554/// declarations which do not belong to the static type of the base
2555/// expression. Diagnose the problem.
2556static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
2557 Expr *BaseExpr,
2558 QualType BaseType,
John McCall2f841ba2009-12-02 03:53:29 +00002559 const CXXScopeSpec &SS,
John McCall129e2df2009-11-30 22:42:35 +00002560 const LookupResult &R) {
John McCall2f841ba2009-12-02 03:53:29 +00002561 // If this is an implicit member access, use a different set of
2562 // diagnostics.
2563 if (!BaseExpr)
2564 return DiagnoseInstanceReference(SemaRef, SS, R);
John McCall129e2df2009-11-30 22:42:35 +00002565
John McCall110acc12010-04-27 01:43:38 +00002566 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_of_unrelated)
2567 << SS.getRange() << R.getRepresentativeDecl() << BaseType;
John McCall129e2df2009-11-30 22:42:35 +00002568}
2569
2570// Check whether the declarations we found through a nested-name
2571// specifier in a member expression are actually members of the base
2572// type. The restriction here is:
2573//
2574// C++ [expr.ref]p2:
2575// ... In these cases, the id-expression shall name a
2576// member of the class or of one of its base classes.
2577//
2578// So it's perfectly legitimate for the nested-name specifier to name
2579// an unrelated class, and for us to find an overload set including
2580// decls from classes which are not superclasses, as long as the decl
2581// we actually pick through overload resolution is from a superclass.
2582bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
2583 QualType BaseType,
John McCall2f841ba2009-12-02 03:53:29 +00002584 const CXXScopeSpec &SS,
John McCall129e2df2009-11-30 22:42:35 +00002585 const LookupResult &R) {
John McCallaa81e162009-12-01 22:10:20 +00002586 const RecordType *BaseRT = BaseType->getAs<RecordType>();
2587 if (!BaseRT) {
2588 // We can't check this yet because the base type is still
2589 // dependent.
2590 assert(BaseType->isDependentType());
2591 return false;
2592 }
2593 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall129e2df2009-11-30 22:42:35 +00002594
2595 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
John McCallaa81e162009-12-01 22:10:20 +00002596 // If this is an implicit member reference and we find a
2597 // non-instance member, it's not an error.
John McCall161755a2010-04-06 21:38:20 +00002598 if (!BaseExpr && !(*I)->isCXXInstanceMember())
John McCallaa81e162009-12-01 22:10:20 +00002599 return false;
John McCall129e2df2009-11-30 22:42:35 +00002600
John McCallaa81e162009-12-01 22:10:20 +00002601 // Note that we use the DC of the decl, not the underlying decl.
2602 CXXRecordDecl *RecordD = cast<CXXRecordDecl>((*I)->getDeclContext());
2603 while (RecordD->isAnonymousStructOrUnion())
2604 RecordD = cast<CXXRecordDecl>(RecordD->getParent());
2605
2606 llvm::SmallPtrSet<CXXRecordDecl*,4> MemberRecord;
2607 MemberRecord.insert(RecordD->getCanonicalDecl());
2608
2609 if (!IsProvablyNotDerivedFrom(*this, BaseRecord, MemberRecord))
2610 return false;
2611 }
2612
John McCall2f841ba2009-12-02 03:53:29 +00002613 DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS, R);
John McCallaa81e162009-12-01 22:10:20 +00002614 return true;
2615}
2616
2617static bool
2618LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
2619 SourceRange BaseRange, const RecordType *RTy,
John McCallad00b772010-06-16 08:42:20 +00002620 SourceLocation OpLoc, CXXScopeSpec &SS,
2621 bool HasTemplateArgs) {
John McCallaa81e162009-12-01 22:10:20 +00002622 RecordDecl *RDecl = RTy->getDecl();
2623 if (SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002624 SemaRef.PDiag(diag::err_typecheck_incomplete_tag)
John McCallaa81e162009-12-01 22:10:20 +00002625 << BaseRange))
2626 return true;
2627
John McCallad00b772010-06-16 08:42:20 +00002628 if (HasTemplateArgs) {
2629 // LookupTemplateName doesn't expect these both to exist simultaneously.
2630 QualType ObjectType = SS.isSet() ? QualType() : QualType(RTy, 0);
2631
2632 bool MOUS;
2633 SemaRef.LookupTemplateName(R, 0, SS, ObjectType, false, MOUS);
2634 return false;
2635 }
2636
John McCallaa81e162009-12-01 22:10:20 +00002637 DeclContext *DC = RDecl;
2638 if (SS.isSet()) {
2639 // If the member name was a qualified-id, look into the
2640 // nested-name-specifier.
2641 DC = SemaRef.computeDeclContext(SS, false);
2642
John McCall77bb1aa2010-05-01 00:40:08 +00002643 if (SemaRef.RequireCompleteDeclContext(SS, DC)) {
John McCall2f841ba2009-12-02 03:53:29 +00002644 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
2645 << SS.getRange() << DC;
2646 return true;
2647 }
2648
John McCallaa81e162009-12-01 22:10:20 +00002649 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002650
John McCallaa81e162009-12-01 22:10:20 +00002651 if (!isa<TypeDecl>(DC)) {
2652 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
2653 << DC << SS.getRange();
2654 return true;
John McCall129e2df2009-11-30 22:42:35 +00002655 }
2656 }
2657
John McCallaa81e162009-12-01 22:10:20 +00002658 // The record definition is complete, now look up the member.
2659 SemaRef.LookupQualifiedName(R, DC);
John McCall129e2df2009-11-30 22:42:35 +00002660
Douglas Gregor2dcc0112009-12-31 07:42:17 +00002661 if (!R.empty())
2662 return false;
2663
2664 // We didn't find anything with the given name, so try to correct
2665 // for typos.
2666 DeclarationName Name = R.getLookupName();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00002667 if (SemaRef.CorrectTypo(R, 0, &SS, DC, false, Sema::CTC_MemberLookup) &&
Douglas Gregoraaf87162010-04-14 20:04:41 +00002668 !R.empty() &&
Douglas Gregor2dcc0112009-12-31 07:42:17 +00002669 (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin()))) {
2670 SemaRef.Diag(R.getNameLoc(), diag::err_no_member_suggest)
2671 << Name << DC << R.getLookupName() << SS.getRange()
Douglas Gregor849b2432010-03-31 17:46:05 +00002672 << FixItHint::CreateReplacement(R.getNameLoc(),
2673 R.getLookupName().getAsString());
Douglas Gregor67dd1d42010-01-07 00:17:44 +00002674 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
2675 SemaRef.Diag(ND->getLocation(), diag::note_previous_decl)
2676 << ND->getDeclName();
Douglas Gregor2dcc0112009-12-31 07:42:17 +00002677 return false;
2678 } else {
2679 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00002680 R.setLookupName(Name);
Douglas Gregor2dcc0112009-12-31 07:42:17 +00002681 }
2682
John McCall129e2df2009-11-30 22:42:35 +00002683 return false;
2684}
2685
2686Sema::OwningExprResult
John McCallaa81e162009-12-01 22:10:20 +00002687Sema::BuildMemberReferenceExpr(ExprArg BaseArg, QualType BaseType,
John McCall129e2df2009-11-30 22:42:35 +00002688 SourceLocation OpLoc, bool IsArrow,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00002689 CXXScopeSpec &SS,
John McCall129e2df2009-11-30 22:42:35 +00002690 NamedDecl *FirstQualifierInScope,
2691 DeclarationName Name, SourceLocation NameLoc,
2692 const TemplateArgumentListInfo *TemplateArgs) {
2693 Expr *Base = BaseArg.takeAs<Expr>();
2694
John McCall2f841ba2009-12-02 03:53:29 +00002695 if (BaseType->isDependentType() ||
2696 (SS.isSet() && isDependentScopeSpecifier(SS)))
John McCallaa81e162009-12-01 22:10:20 +00002697 return ActOnDependentMemberExpr(ExprArg(*this, Base), BaseType,
John McCall129e2df2009-11-30 22:42:35 +00002698 IsArrow, OpLoc,
2699 SS, FirstQualifierInScope,
2700 Name, NameLoc,
2701 TemplateArgs);
2702
2703 LookupResult R(*this, Name, NameLoc, LookupMemberName);
John McCall129e2df2009-11-30 22:42:35 +00002704
John McCallaa81e162009-12-01 22:10:20 +00002705 // Implicit member accesses.
2706 if (!Base) {
2707 QualType RecordTy = BaseType;
2708 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
2709 if (LookupMemberExprInRecord(*this, R, SourceRange(),
2710 RecordTy->getAs<RecordType>(),
John McCallad00b772010-06-16 08:42:20 +00002711 OpLoc, SS, TemplateArgs != 0))
John McCallaa81e162009-12-01 22:10:20 +00002712 return ExprError();
2713
2714 // Explicit member accesses.
2715 } else {
2716 OwningExprResult Result =
2717 LookupMemberExpr(R, Base, IsArrow, OpLoc,
John McCallad00b772010-06-16 08:42:20 +00002718 SS, /*ObjCImpDecl*/ DeclPtrTy(), TemplateArgs != 0);
John McCallaa81e162009-12-01 22:10:20 +00002719
2720 if (Result.isInvalid()) {
2721 Owned(Base);
2722 return ExprError();
2723 }
2724
2725 if (Result.get())
2726 return move(Result);
Sebastian Redlf3e63372010-05-07 09:25:11 +00002727
2728 // LookupMemberExpr can modify Base, and thus change BaseType
2729 BaseType = Base->getType();
John McCall129e2df2009-11-30 22:42:35 +00002730 }
2731
Sebastian Redl0aa866f2010-05-07 09:09:23 +00002732 return BuildMemberReferenceExpr(ExprArg(*this, Base), BaseType,
John McCallc2233c52010-01-15 08:34:02 +00002733 OpLoc, IsArrow, SS, FirstQualifierInScope,
2734 R, TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00002735}
2736
2737Sema::OwningExprResult
John McCallaa81e162009-12-01 22:10:20 +00002738Sema::BuildMemberReferenceExpr(ExprArg Base, QualType BaseExprType,
2739 SourceLocation OpLoc, bool IsArrow,
2740 const CXXScopeSpec &SS,
John McCallc2233c52010-01-15 08:34:02 +00002741 NamedDecl *FirstQualifierInScope,
John McCall129e2df2009-11-30 22:42:35 +00002742 LookupResult &R,
Douglas Gregor06a9f362010-05-01 20:49:11 +00002743 const TemplateArgumentListInfo *TemplateArgs,
2744 bool SuppressQualifierCheck) {
John McCall129e2df2009-11-30 22:42:35 +00002745 Expr *BaseExpr = Base.takeAs<Expr>();
John McCallaa81e162009-12-01 22:10:20 +00002746 QualType BaseType = BaseExprType;
John McCall129e2df2009-11-30 22:42:35 +00002747 if (IsArrow) {
2748 assert(BaseType->isPointerType());
2749 BaseType = BaseType->getAs<PointerType>()->getPointeeType();
2750 }
John McCall161755a2010-04-06 21:38:20 +00002751 R.setBaseObjectType(BaseType);
John McCall129e2df2009-11-30 22:42:35 +00002752
2753 NestedNameSpecifier *Qualifier =
2754 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
2755 DeclarationName MemberName = R.getLookupName();
2756 SourceLocation MemberLoc = R.getNameLoc();
2757
2758 if (R.isAmbiguous())
Douglas Gregorfe85ced2009-08-06 03:17:00 +00002759 return ExprError();
2760
John McCall129e2df2009-11-30 22:42:35 +00002761 if (R.empty()) {
2762 // Rederive where we looked up.
2763 DeclContext *DC = (SS.isSet()
2764 ? computeDeclContext(SS, false)
2765 : BaseType->getAs<RecordType>()->getDecl());
Nate Begeman2ef13e52009-08-10 23:49:36 +00002766
John McCall129e2df2009-11-30 22:42:35 +00002767 Diag(R.getNameLoc(), diag::err_no_member)
John McCallaa81e162009-12-01 22:10:20 +00002768 << MemberName << DC
2769 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
John McCall129e2df2009-11-30 22:42:35 +00002770 return ExprError();
2771 }
2772
John McCallc2233c52010-01-15 08:34:02 +00002773 // Diagnose lookups that find only declarations from a non-base
2774 // type. This is possible for either qualified lookups (which may
2775 // have been qualified with an unrelated type) or implicit member
2776 // expressions (which were found with unqualified lookup and thus
2777 // may have come from an enclosing scope). Note that it's okay for
2778 // lookup to find declarations from a non-base type as long as those
2779 // aren't the ones picked by overload resolution.
2780 if ((SS.isSet() || !BaseExpr ||
2781 (isa<CXXThisExpr>(BaseExpr) &&
2782 cast<CXXThisExpr>(BaseExpr)->isImplicit())) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00002783 !SuppressQualifierCheck &&
John McCallc2233c52010-01-15 08:34:02 +00002784 CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
John McCall129e2df2009-11-30 22:42:35 +00002785 return ExprError();
2786
2787 // Construct an unresolved result if we in fact got an unresolved
2788 // result.
2789 if (R.isOverloadedResult() || R.isUnresolvableResult()) {
John McCallaa81e162009-12-01 22:10:20 +00002790 bool Dependent =
John McCall410a3f32009-12-19 02:05:44 +00002791 BaseExprType->isDependentType() ||
John McCallaa81e162009-12-01 22:10:20 +00002792 R.isUnresolvableResult() ||
John McCall7bb12da2010-02-02 06:20:04 +00002793 OverloadExpr::ComputeDependence(R.begin(), R.end(), TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00002794
John McCallc373d482010-01-27 01:50:18 +00002795 // Suppress any lookup-related diagnostics; we'll do these when we
2796 // pick a member.
2797 R.suppressDiagnostics();
2798
John McCall129e2df2009-11-30 22:42:35 +00002799 UnresolvedMemberExpr *MemExpr
2800 = UnresolvedMemberExpr::Create(Context, Dependent,
2801 R.isUnresolvableResult(),
John McCallaa81e162009-12-01 22:10:20 +00002802 BaseExpr, BaseExprType,
2803 IsArrow, OpLoc,
John McCall129e2df2009-11-30 22:42:35 +00002804 Qualifier, SS.getRange(),
2805 MemberName, MemberLoc,
Douglas Gregor5a84dec2010-05-23 18:57:34 +00002806 TemplateArgs, R.begin(), R.end());
John McCall129e2df2009-11-30 22:42:35 +00002807
2808 return Owned(MemExpr);
2809 }
2810
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002811 assert(R.isSingleResult());
John McCall161755a2010-04-06 21:38:20 +00002812 DeclAccessPair FoundDecl = R.begin().getPair();
John McCall129e2df2009-11-30 22:42:35 +00002813 NamedDecl *MemberDecl = R.getFoundDecl();
2814
2815 // FIXME: diagnose the presence of template arguments now.
2816
2817 // If the decl being referenced had an error, return an error for this
2818 // sub-expr without emitting another error, in order to avoid cascading
2819 // error cases.
2820 if (MemberDecl->isInvalidDecl())
2821 return ExprError();
2822
John McCallaa81e162009-12-01 22:10:20 +00002823 // Handle the implicit-member-access case.
2824 if (!BaseExpr) {
2825 // If this is not an instance member, convert to a non-member access.
John McCall161755a2010-04-06 21:38:20 +00002826 if (!MemberDecl->isCXXInstanceMember())
John McCallaa81e162009-12-01 22:10:20 +00002827 return BuildDeclarationNameExpr(SS, R.getNameLoc(), MemberDecl);
2828
Douglas Gregor828a1972010-01-07 23:12:05 +00002829 SourceLocation Loc = R.getNameLoc();
2830 if (SS.getRange().isValid())
2831 Loc = SS.getRange().getBegin();
2832 BaseExpr = new (Context) CXXThisExpr(Loc, BaseExprType,/*isImplicit=*/true);
John McCallaa81e162009-12-01 22:10:20 +00002833 }
2834
John McCall129e2df2009-11-30 22:42:35 +00002835 bool ShouldCheckUse = true;
2836 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
2837 // Don't diagnose the use of a virtual member function unless it's
2838 // explicitly qualified.
2839 if (MD->isVirtual() && !SS.isSet())
2840 ShouldCheckUse = false;
2841 }
2842
2843 // Check the use of this member.
2844 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc)) {
2845 Owned(BaseExpr);
2846 return ExprError();
2847 }
2848
2849 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
2850 // We may have found a field within an anonymous union or struct
2851 // (C++ [class.union]).
Eli Friedman16c53782009-12-04 07:18:51 +00002852 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion() &&
2853 !BaseType->getAs<RecordType>()->getDecl()->isAnonymousStructOrUnion())
John McCall129e2df2009-11-30 22:42:35 +00002854 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
2855 BaseExpr, OpLoc);
2856
2857 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
2858 QualType MemberType = FD->getType();
2859 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>())
2860 MemberType = Ref->getPointeeType();
2861 else {
2862 Qualifiers BaseQuals = BaseType.getQualifiers();
2863 BaseQuals.removeObjCGCAttr();
2864 if (FD->isMutable()) BaseQuals.removeConst();
2865
2866 Qualifiers MemberQuals
2867 = Context.getCanonicalType(MemberType).getQualifiers();
2868
2869 Qualifiers Combined = BaseQuals + MemberQuals;
2870 if (Combined != MemberQuals)
2871 MemberType = Context.getQualifiedType(MemberType, Combined);
2872 }
2873
2874 MarkDeclarationReferenced(MemberLoc, FD);
John McCall6bb80172010-03-30 21:47:33 +00002875 if (PerformObjectMemberConversion(BaseExpr, Qualifier, FoundDecl, FD))
John McCall129e2df2009-11-30 22:42:35 +00002876 return ExprError();
2877 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
John McCall6bb80172010-03-30 21:47:33 +00002878 FD, FoundDecl, MemberLoc, MemberType));
John McCall129e2df2009-11-30 22:42:35 +00002879 }
2880
2881 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
2882 MarkDeclarationReferenced(MemberLoc, Var);
2883 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
John McCall6bb80172010-03-30 21:47:33 +00002884 Var, FoundDecl, MemberLoc,
John McCall129e2df2009-11-30 22:42:35 +00002885 Var->getType().getNonReferenceType()));
2886 }
2887
2888 if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl)) {
2889 MarkDeclarationReferenced(MemberLoc, MemberDecl);
2890 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
John McCall6bb80172010-03-30 21:47:33 +00002891 MemberFn, FoundDecl, MemberLoc,
John McCall129e2df2009-11-30 22:42:35 +00002892 MemberFn->getType()));
2893 }
2894
2895 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
2896 MarkDeclarationReferenced(MemberLoc, MemberDecl);
2897 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
John McCall6bb80172010-03-30 21:47:33 +00002898 Enum, FoundDecl, MemberLoc, Enum->getType()));
John McCall129e2df2009-11-30 22:42:35 +00002899 }
2900
2901 Owned(BaseExpr);
2902
Douglas Gregorb0fd4832010-04-25 20:55:08 +00002903 // We found something that we didn't expect. Complain.
John McCall129e2df2009-11-30 22:42:35 +00002904 if (isa<TypeDecl>(MemberDecl))
Douglas Gregorb0fd4832010-04-25 20:55:08 +00002905 Diag(MemberLoc,diag::err_typecheck_member_reference_type)
2906 << MemberName << BaseType << int(IsArrow);
2907 else
2908 Diag(MemberLoc, diag::err_typecheck_member_reference_unknown)
2909 << MemberName << BaseType << int(IsArrow);
John McCall129e2df2009-11-30 22:42:35 +00002910
Douglas Gregorb0fd4832010-04-25 20:55:08 +00002911 Diag(MemberDecl->getLocation(), diag::note_member_declared_here)
2912 << MemberName;
Douglas Gregor2b147f02010-04-25 21:15:30 +00002913 R.suppressDiagnostics();
Douglas Gregorb0fd4832010-04-25 20:55:08 +00002914 return ExprError();
John McCall129e2df2009-11-30 22:42:35 +00002915}
2916
2917/// Look up the given member of the given non-type-dependent
2918/// expression. This can return in one of two ways:
2919/// * If it returns a sentinel null-but-valid result, the caller will
2920/// assume that lookup was performed and the results written into
2921/// the provided structure. It will take over from there.
2922/// * Otherwise, the returned expression will be produced in place of
2923/// an ordinary member expression.
2924///
2925/// The ObjCImpDecl bit is a gross hack that will need to be properly
2926/// fixed for ObjC++.
2927Sema::OwningExprResult
2928Sema::LookupMemberExpr(LookupResult &R, Expr *&BaseExpr,
John McCall812c1542009-12-07 22:46:59 +00002929 bool &IsArrow, SourceLocation OpLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00002930 CXXScopeSpec &SS,
John McCallad00b772010-06-16 08:42:20 +00002931 DeclPtrTy ObjCImpDecl, bool HasTemplateArgs) {
Douglas Gregora71d8192009-09-04 17:36:40 +00002932 assert(BaseExpr && "no base expression");
Mike Stump1eb44332009-09-09 15:08:12 +00002933
Steve Naroff3cc4af82007-12-16 21:42:28 +00002934 // Perform default conversions.
2935 DefaultFunctionArrayConversion(BaseExpr);
Sebastian Redl0eb23302009-01-19 00:08:26 +00002936
Steve Naroffdfa6aae2007-07-26 03:11:44 +00002937 QualType BaseType = BaseExpr->getType();
John McCall129e2df2009-11-30 22:42:35 +00002938 assert(!BaseType->isDependentType());
2939
2940 DeclarationName MemberName = R.getLookupName();
2941 SourceLocation MemberLoc = R.getNameLoc();
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00002942
2943 // If the user is trying to apply -> or . to a function pointer
John McCall129e2df2009-11-30 22:42:35 +00002944 // type, it's probably because they forgot parentheses to call that
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00002945 // function. Suggest the addition of those parentheses, build the
2946 // call, and continue on.
2947 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
2948 if (const FunctionProtoType *Fun
2949 = Ptr->getPointeeType()->getAs<FunctionProtoType>()) {
2950 QualType ResultTy = Fun->getResultType();
2951 if (Fun->getNumArgs() == 0 &&
John McCall129e2df2009-11-30 22:42:35 +00002952 ((!IsArrow && ResultTy->isRecordType()) ||
2953 (IsArrow && ResultTy->isPointerType() &&
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00002954 ResultTy->getAs<PointerType>()->getPointeeType()
2955 ->isRecordType()))) {
2956 SourceLocation Loc = PP.getLocForEndOfToken(BaseExpr->getLocEnd());
2957 Diag(Loc, diag::err_member_reference_needs_call)
2958 << QualType(Fun, 0)
Douglas Gregor849b2432010-03-31 17:46:05 +00002959 << FixItHint::CreateInsertion(Loc, "()");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002960
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00002961 OwningExprResult NewBase
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002962 = ActOnCallExpr(0, ExprArg(*this, BaseExpr), Loc,
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00002963 MultiExprArg(*this, 0, 0), 0, Loc);
Douglas Gregorf918b832010-06-21 22:46:46 +00002964 BaseExpr = 0;
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00002965 if (NewBase.isInvalid())
John McCall129e2df2009-11-30 22:42:35 +00002966 return ExprError();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002967
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00002968 BaseExpr = NewBase.takeAs<Expr>();
2969 DefaultFunctionArrayConversion(BaseExpr);
2970 BaseType = BaseExpr->getType();
2971 }
2972 }
2973 }
2974
David Chisnall0f436562009-08-17 16:35:33 +00002975 // If this is an Objective-C pseudo-builtin and a definition is provided then
2976 // use that.
2977 if (BaseType->isObjCIdType()) {
Fariborz Jahanian6d910f02009-12-07 20:09:25 +00002978 if (IsArrow) {
2979 // Handle the following exceptional case PObj->isa.
2980 if (const ObjCObjectPointerType *OPT =
2981 BaseType->getAs<ObjCObjectPointerType>()) {
John McCallc12c5bb2010-05-15 11:32:37 +00002982 if (OPT->getObjectType()->isObjCId() &&
Fariborz Jahanian6d910f02009-12-07 20:09:25 +00002983 MemberName.getAsIdentifierInfo()->isStr("isa"))
Fariborz Jahanian83dc3252009-12-09 19:05:56 +00002984 return Owned(new (Context) ObjCIsaExpr(BaseExpr, true, MemberLoc,
2985 Context.getObjCClassType()));
Fariborz Jahanian6d910f02009-12-07 20:09:25 +00002986 }
2987 }
David Chisnall0f436562009-08-17 16:35:33 +00002988 // We have an 'id' type. Rather than fall through, we check if this
2989 // is a reference to 'isa'.
2990 if (BaseType != Context.ObjCIdRedefinitionType) {
2991 BaseType = Context.ObjCIdRedefinitionType;
Eli Friedman73c39ab2009-10-20 08:27:19 +00002992 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
David Chisnall0f436562009-08-17 16:35:33 +00002993 }
David Chisnall0f436562009-08-17 16:35:33 +00002994 }
John McCall129e2df2009-11-30 22:42:35 +00002995
Fariborz Jahanian369a3bd2009-11-25 23:07:42 +00002996 // If this is an Objective-C pseudo-builtin and a definition is provided then
2997 // use that.
2998 if (Context.isObjCSelType(BaseType)) {
2999 // We have an 'SEL' type. Rather than fall through, we check if this
3000 // is a reference to 'sel_id'.
3001 if (BaseType != Context.ObjCSelRedefinitionType) {
3002 BaseType = Context.ObjCSelRedefinitionType;
3003 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
3004 }
3005 }
John McCall129e2df2009-11-30 22:42:35 +00003006
Steve Naroffdfa6aae2007-07-26 03:11:44 +00003007 assert(!BaseType.isNull() && "no type for member expression");
Sebastian Redl0eb23302009-01-19 00:08:26 +00003008
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003009 // Handle properties on ObjC 'Class' types.
John McCall129e2df2009-11-30 22:42:35 +00003010 if (!IsArrow && BaseType->isObjCClassType()) {
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003011 // Also must look for a getter name which uses property syntax.
3012 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
3013 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
3014 if (ObjCMethodDecl *MD = getCurMethodDecl()) {
3015 ObjCInterfaceDecl *IFace = MD->getClassInterface();
3016 ObjCMethodDecl *Getter;
3017 // FIXME: need to also look locally in the implementation.
3018 if ((Getter = IFace->lookupClassMethod(Sel))) {
3019 // Check the use of this method.
3020 if (DiagnoseUseOfDecl(Getter, MemberLoc))
3021 return ExprError();
3022 }
3023 // If we found a getter then this may be a valid dot-reference, we
3024 // will look for the matching setter, in case it is needed.
3025 Selector SetterSel =
3026 SelectorTable::constructSetterName(PP.getIdentifierTable(),
3027 PP.getSelectorTable(), Member);
3028 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
3029 if (!Setter) {
3030 // If this reference is in an @implementation, also check for 'private'
3031 // methods.
Steve Naroffd789d3d2009-10-01 23:46:04 +00003032 Setter = IFace->lookupPrivateInstanceMethod(SetterSel);
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003033 }
3034 // Look through local category implementations associated with the class.
3035 if (!Setter)
3036 Setter = IFace->getCategoryClassMethod(SetterSel);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003037
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003038 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
3039 return ExprError();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003040
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003041 if (Getter || Setter) {
3042 QualType PType;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003043
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003044 if (Getter)
Douglas Gregor5291c3c2010-07-13 08:18:22 +00003045 PType = Getter->getSendResultType();
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003046 else
3047 // Get the expression type from Setter's incoming parameter.
3048 PType = (*(Setter->param_end() -1))->getType();
3049 // FIXME: we must check that the setter has property type.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003050 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter,
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003051 PType,
3052 Setter, MemberLoc, BaseExpr));
3053 }
3054 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
3055 << MemberName << BaseType);
3056 }
3057 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003058
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003059 if (BaseType->isObjCClassType() &&
3060 BaseType != Context.ObjCClassRedefinitionType) {
3061 BaseType = Context.ObjCClassRedefinitionType;
Eli Friedman73c39ab2009-10-20 08:27:19 +00003062 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003063 }
Mike Stump1eb44332009-09-09 15:08:12 +00003064
John McCall129e2df2009-11-30 22:42:35 +00003065 if (IsArrow) {
3066 if (const PointerType *PT = BaseType->getAs<PointerType>())
Steve Naroffdfa6aae2007-07-26 03:11:44 +00003067 BaseType = PT->getPointeeType();
Steve Naroff14108da2009-07-10 23:34:53 +00003068 else if (BaseType->isObjCObjectPointerType())
3069 ;
John McCall812c1542009-12-07 22:46:59 +00003070 else if (BaseType->isRecordType()) {
3071 // Recover from arrow accesses to records, e.g.:
3072 // struct MyRecord foo;
3073 // foo->bar
3074 // This is actually well-formed in C++ if MyRecord has an
3075 // overloaded operator->, but that should have been dealt with
3076 // by now.
3077 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
3078 << BaseType << int(IsArrow) << BaseExpr->getSourceRange()
Douglas Gregor849b2432010-03-31 17:46:05 +00003079 << FixItHint::CreateReplacement(OpLoc, ".");
John McCall812c1542009-12-07 22:46:59 +00003080 IsArrow = false;
3081 } else {
John McCall129e2df2009-11-30 22:42:35 +00003082 Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
3083 << BaseType << BaseExpr->getSourceRange();
3084 return ExprError();
Anders Carlsson4ef27702009-05-16 20:31:20 +00003085 }
John McCall812c1542009-12-07 22:46:59 +00003086 } else {
3087 // Recover from dot accesses to pointers, e.g.:
3088 // type *foo;
3089 // foo.bar
3090 // This is actually well-formed in two cases:
3091 // - 'type' is an Objective C type
3092 // - 'bar' is a pseudo-destructor name which happens to refer to
3093 // the appropriate pointer type
3094 if (MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
3095 const PointerType *PT = BaseType->getAs<PointerType>();
3096 if (PT && PT->getPointeeType()->isRecordType()) {
3097 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
3098 << BaseType << int(IsArrow) << BaseExpr->getSourceRange()
Douglas Gregor849b2432010-03-31 17:46:05 +00003099 << FixItHint::CreateReplacement(OpLoc, "->");
John McCall812c1542009-12-07 22:46:59 +00003100 BaseType = PT->getPointeeType();
3101 IsArrow = true;
3102 }
3103 }
John McCall129e2df2009-11-30 22:42:35 +00003104 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003105
John McCallc12c5bb2010-05-15 11:32:37 +00003106 // Handle field access to simple records.
Ted Kremenek6217b802009-07-29 21:53:49 +00003107 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
John McCallaa81e162009-12-01 22:10:20 +00003108 if (LookupMemberExprInRecord(*this, R, BaseExpr->getSourceRange(),
John McCallad00b772010-06-16 08:42:20 +00003109 RTy, OpLoc, SS, HasTemplateArgs))
Douglas Gregor4ec339f2009-01-19 19:26:10 +00003110 return ExprError();
John McCall129e2df2009-11-30 22:42:35 +00003111 return Owned((Expr*) 0);
Chris Lattnerfb173ec2008-07-21 04:28:12 +00003112 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00003113
Chris Lattnera38e6b12008-07-21 04:59:05 +00003114 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
3115 // (*Obj).ivar.
John McCall129e2df2009-11-30 22:42:35 +00003116 if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
John McCallc12c5bb2010-05-15 11:32:37 +00003117 (!IsArrow && BaseType->isObjCObjectType())) {
John McCall183700f2009-09-21 23:43:11 +00003118 const ObjCObjectPointerType *OPT = BaseType->getAs<ObjCObjectPointerType>();
John McCallc12c5bb2010-05-15 11:32:37 +00003119 ObjCInterfaceDecl *IDecl =
3120 OPT ? OPT->getInterfaceDecl()
3121 : BaseType->getAs<ObjCObjectType>()->getInterface();
3122 if (IDecl) {
Anders Carlsson8f28f992009-08-26 18:25:21 +00003123 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
3124
Steve Naroffc70e8d92009-07-16 00:25:06 +00003125 ObjCInterfaceDecl *ClassDeclared;
Anders Carlsson8f28f992009-08-26 18:25:21 +00003126 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
Mike Stump1eb44332009-09-09 15:08:12 +00003127
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003128 if (!IV) {
3129 // Attempt to correct for typos in ivar names.
3130 LookupResult Res(*this, R.getLookupName(), R.getNameLoc(),
3131 LookupMemberName);
Douglas Gregoraaf87162010-04-14 20:04:41 +00003132 if (CorrectTypo(Res, 0, 0, IDecl, false, CTC_MemberLookup) &&
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003133 (IV = Res.getAsSingle<ObjCIvarDecl>())) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003134 Diag(R.getNameLoc(),
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003135 diag::err_typecheck_member_reference_ivar_suggest)
3136 << IDecl->getDeclName() << MemberName << IV->getDeclName()
Douglas Gregor849b2432010-03-31 17:46:05 +00003137 << FixItHint::CreateReplacement(R.getNameLoc(),
3138 IV->getNameAsString());
Douglas Gregor67dd1d42010-01-07 00:17:44 +00003139 Diag(IV->getLocation(), diag::note_previous_decl)
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003140 << IV->getDeclName();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00003141 } else {
3142 Res.clear();
3143 Res.setLookupName(Member);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003144 }
3145 }
3146
Steve Naroffc70e8d92009-07-16 00:25:06 +00003147 if (IV) {
3148 // If the decl being referenced had an error, return an error for this
3149 // sub-expr without emitting another error, in order to avoid cascading
3150 // error cases.
3151 if (IV->isInvalidDecl())
3152 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003153
Steve Naroffc70e8d92009-07-16 00:25:06 +00003154 // Check whether we can reference this field.
3155 if (DiagnoseUseOfDecl(IV, MemberLoc))
3156 return ExprError();
3157 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
3158 IV->getAccessControl() != ObjCIvarDecl::Package) {
3159 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
3160 if (ObjCMethodDecl *MD = getCurMethodDecl())
3161 ClassOfMethodDecl = MD->getClassInterface();
3162 else if (ObjCImpDecl && getCurFunctionDecl()) {
3163 // Case of a c-function declared inside an objc implementation.
3164 // FIXME: For a c-style function nested inside an objc implementation
3165 // class, there is no implementation context available, so we pass
3166 // down the context as argument to this routine. Ideally, this context
3167 // need be passed down in the AST node and somehow calculated from the
3168 // AST for a function decl.
3169 Decl *ImplDecl = ObjCImpDecl.getAs<Decl>();
Mike Stump1eb44332009-09-09 15:08:12 +00003170 if (ObjCImplementationDecl *IMPD =
Steve Naroffc70e8d92009-07-16 00:25:06 +00003171 dyn_cast<ObjCImplementationDecl>(ImplDecl))
3172 ClassOfMethodDecl = IMPD->getClassInterface();
3173 else if (ObjCCategoryImplDecl* CatImplClass =
3174 dyn_cast<ObjCCategoryImplDecl>(ImplDecl))
3175 ClassOfMethodDecl = CatImplClass->getClassInterface();
3176 }
Mike Stump1eb44332009-09-09 15:08:12 +00003177
3178 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
3179 if (ClassDeclared != IDecl ||
Steve Naroffc70e8d92009-07-16 00:25:06 +00003180 ClassOfMethodDecl != ClassDeclared)
Mike Stump1eb44332009-09-09 15:08:12 +00003181 Diag(MemberLoc, diag::error_private_ivar_access)
Steve Naroffc70e8d92009-07-16 00:25:06 +00003182 << IV->getDeclName();
Mike Stumpac5fc7c2009-08-04 21:02:39 +00003183 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
3184 // @protected
Mike Stump1eb44332009-09-09 15:08:12 +00003185 Diag(MemberLoc, diag::error_protected_ivar_access)
Steve Naroffc70e8d92009-07-16 00:25:06 +00003186 << IV->getDeclName();
Steve Naroffb06d8752009-03-04 18:34:24 +00003187 }
Steve Naroffc70e8d92009-07-16 00:25:06 +00003188
3189 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
3190 MemberLoc, BaseExpr,
John McCall129e2df2009-11-30 22:42:35 +00003191 IsArrow));
Fariborz Jahanian935fd762009-03-03 01:21:12 +00003192 }
Steve Naroffc70e8d92009-07-16 00:25:06 +00003193 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
Anders Carlsson8f28f992009-08-26 18:25:21 +00003194 << IDecl->getDeclName() << MemberName
Steve Naroffc70e8d92009-07-16 00:25:06 +00003195 << BaseExpr->getSourceRange());
Fariborz Jahanianaaa63a72008-12-13 22:20:28 +00003196 }
Chris Lattnerfb173ec2008-07-21 04:28:12 +00003197 }
Steve Naroffde2e22d2009-07-15 18:40:39 +00003198 // Handle properties on 'id' and qualified "id".
John McCall129e2df2009-11-30 22:42:35 +00003199 if (!IsArrow && (BaseType->isObjCIdType() ||
3200 BaseType->isObjCQualifiedIdType())) {
John McCall183700f2009-09-21 23:43:11 +00003201 const ObjCObjectPointerType *QIdTy = BaseType->getAs<ObjCObjectPointerType>();
Anders Carlsson8f28f992009-08-26 18:25:21 +00003202 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Mike Stump1eb44332009-09-09 15:08:12 +00003203
Steve Naroff14108da2009-07-10 23:34:53 +00003204 // Check protocols on qualified interfaces.
Anders Carlsson8f28f992009-08-26 18:25:21 +00003205 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Steve Naroff14108da2009-07-10 23:34:53 +00003206 if (Decl *PMDecl = FindGetterNameDecl(QIdTy, Member, Sel, Context)) {
3207 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
3208 // Check the use of this declaration
3209 if (DiagnoseUseOfDecl(PD, MemberLoc))
3210 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003211
Steve Naroff14108da2009-07-10 23:34:53 +00003212 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
3213 MemberLoc, BaseExpr));
3214 }
3215 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
3216 // Check the use of this method.
3217 if (DiagnoseUseOfDecl(OMD, MemberLoc))
3218 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003219
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00003220 return Owned(ObjCMessageExpr::Create(Context,
Douglas Gregor5291c3c2010-07-13 08:18:22 +00003221 OMD->getSendResultType(),
Douglas Gregor04badcf2010-04-21 00:45:42 +00003222 OpLoc, BaseExpr, Sel,
3223 OMD, NULL, 0, MemberLoc));
Steve Naroff14108da2009-07-10 23:34:53 +00003224 }
3225 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00003226
Steve Naroff14108da2009-07-10 23:34:53 +00003227 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlsson8f28f992009-08-26 18:25:21 +00003228 << MemberName << BaseType);
Steve Naroff14108da2009-07-10 23:34:53 +00003229 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00003230
Chris Lattnera38e6b12008-07-21 04:59:05 +00003231 // Handle Objective-C property access, which is "Obj.property" where Obj is a
3232 // pointer to a (potentially qualified) interface type.
Chris Lattner7f816522010-04-11 07:45:24 +00003233 if (!IsArrow)
3234 if (const ObjCObjectPointerType *OPT =
3235 BaseType->getAsObjCInterfacePointerType())
Chris Lattnerb9d4fc12010-04-11 07:51:10 +00003236 return HandleExprPropertyRefExpr(OPT, BaseExpr, MemberName, MemberLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00003237
Steve Narofff242b1b2009-07-24 17:54:45 +00003238 // Handle the following exceptional case (*Obj).isa.
John McCall129e2df2009-11-30 22:42:35 +00003239 if (!IsArrow &&
John McCallc12c5bb2010-05-15 11:32:37 +00003240 BaseType->isObjCObjectType() &&
3241 BaseType->getAs<ObjCObjectType>()->isObjCId() &&
Anders Carlsson8f28f992009-08-26 18:25:21 +00003242 MemberName.getAsIdentifierInfo()->isStr("isa"))
Steve Narofff242b1b2009-07-24 17:54:45 +00003243 return Owned(new (Context) ObjCIsaExpr(BaseExpr, false, MemberLoc,
Fariborz Jahanian83dc3252009-12-09 19:05:56 +00003244 Context.getObjCClassType()));
Steve Narofff242b1b2009-07-24 17:54:45 +00003245
Chris Lattnerfb173ec2008-07-21 04:28:12 +00003246 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner73525de2009-02-16 21:11:58 +00003247 if (BaseType->isExtVectorType()) {
Anders Carlsson8f28f992009-08-26 18:25:21 +00003248 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Chris Lattnerfb173ec2008-07-21 04:28:12 +00003249 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
3250 if (ret.isNull())
Sebastian Redl0eb23302009-01-19 00:08:26 +00003251 return ExprError();
Anders Carlsson8f28f992009-08-26 18:25:21 +00003252 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, *Member,
Steve Naroff6ece14c2009-01-21 00:14:39 +00003253 MemberLoc));
Chris Lattnerfb173ec2008-07-21 04:28:12 +00003254 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003255
Douglas Gregor214f31a2009-03-27 06:00:30 +00003256 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
3257 << BaseType << BaseExpr->getSourceRange();
3258
Douglas Gregor214f31a2009-03-27 06:00:30 +00003259 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00003260}
3261
John McCall129e2df2009-11-30 22:42:35 +00003262/// The main callback when the parser finds something like
3263/// expression . [nested-name-specifier] identifier
3264/// expression -> [nested-name-specifier] identifier
3265/// where 'identifier' encompasses a fairly broad spectrum of
3266/// possibilities, including destructor and operator references.
3267///
3268/// \param OpKind either tok::arrow or tok::period
3269/// \param HasTrailingLParen whether the next token is '(', which
3270/// is used to diagnose mis-uses of special members that can
3271/// only be called
3272/// \param ObjCImpDecl the current ObjC @implementation decl;
3273/// this is an ugly hack around the fact that ObjC @implementations
3274/// aren't properly put in the context chain
3275Sema::OwningExprResult Sema::ActOnMemberAccessExpr(Scope *S, ExprArg BaseArg,
3276 SourceLocation OpLoc,
3277 tok::TokenKind OpKind,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003278 CXXScopeSpec &SS,
John McCall129e2df2009-11-30 22:42:35 +00003279 UnqualifiedId &Id,
3280 DeclPtrTy ObjCImpDecl,
3281 bool HasTrailingLParen) {
3282 if (SS.isSet() && SS.isInvalid())
3283 return ExprError();
3284
3285 TemplateArgumentListInfo TemplateArgsBuffer;
3286
3287 // Decompose the name into its component parts.
3288 DeclarationName Name;
3289 SourceLocation NameLoc;
3290 const TemplateArgumentListInfo *TemplateArgs;
3291 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer,
3292 Name, NameLoc, TemplateArgs);
3293
3294 bool IsArrow = (OpKind == tok::arrow);
3295
3296 NamedDecl *FirstQualifierInScope
3297 = (!SS.isSet() ? 0 : FindFirstQualifierInScope(S,
3298 static_cast<NestedNameSpecifier*>(SS.getScopeRep())));
3299
3300 // This is a postfix expression, so get rid of ParenListExprs.
3301 BaseArg = MaybeConvertParenListExprToParenExpr(S, move(BaseArg));
3302
3303 Expr *Base = BaseArg.takeAs<Expr>();
3304 OwningExprResult Result(*this);
Douglas Gregor01e56ae2010-04-12 20:54:26 +00003305 if (Base->getType()->isDependentType() || Name.isDependentName() ||
3306 isDependentScopeSpecifier(SS)) {
John McCallaa81e162009-12-01 22:10:20 +00003307 Result = ActOnDependentMemberExpr(ExprArg(*this, Base), Base->getType(),
John McCall129e2df2009-11-30 22:42:35 +00003308 IsArrow, OpLoc,
3309 SS, FirstQualifierInScope,
3310 Name, NameLoc,
3311 TemplateArgs);
3312 } else {
3313 LookupResult R(*this, Name, NameLoc, LookupMemberName);
John McCallad00b772010-06-16 08:42:20 +00003314 Result = LookupMemberExpr(R, Base, IsArrow, OpLoc,
3315 SS, ObjCImpDecl, TemplateArgs != 0);
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00003316
John McCallad00b772010-06-16 08:42:20 +00003317 if (Result.isInvalid()) {
3318 Owned(Base);
3319 return ExprError();
3320 }
John McCall129e2df2009-11-30 22:42:35 +00003321
John McCallad00b772010-06-16 08:42:20 +00003322 if (Result.get()) {
3323 // The only way a reference to a destructor can be used is to
3324 // immediately call it, which falls into this case. If the
3325 // next token is not a '(', produce a diagnostic and build the
3326 // call now.
3327 if (!HasTrailingLParen &&
3328 Id.getKind() == UnqualifiedId::IK_DestructorName)
3329 return DiagnoseDtorReference(NameLoc, move(Result));
John McCall129e2df2009-11-30 22:42:35 +00003330
John McCallad00b772010-06-16 08:42:20 +00003331 return move(Result);
John McCall129e2df2009-11-30 22:42:35 +00003332 }
3333
John McCallaa81e162009-12-01 22:10:20 +00003334 Result = BuildMemberReferenceExpr(ExprArg(*this, Base), Base->getType(),
John McCallc2233c52010-01-15 08:34:02 +00003335 OpLoc, IsArrow, SS, FirstQualifierInScope,
3336 R, TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00003337 }
3338
3339 return move(Result);
Anders Carlsson8f28f992009-08-26 18:25:21 +00003340}
3341
Anders Carlsson56c5e332009-08-25 03:49:14 +00003342Sema::OwningExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
3343 FunctionDecl *FD,
3344 ParmVarDecl *Param) {
3345 if (Param->hasUnparsedDefaultArg()) {
3346 Diag (CallLoc,
3347 diag::err_use_of_default_argument_to_function_declared_later) <<
3348 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00003349 Diag(UnparsedDefaultArgLocs[Param],
Anders Carlsson56c5e332009-08-25 03:49:14 +00003350 diag::note_default_argument_declared_here);
3351 } else {
3352 if (Param->hasUninstantiatedDefaultArg()) {
3353 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
3354
3355 // Instantiate the expression.
Douglas Gregor525f96c2010-02-05 07:33:43 +00003356 MultiLevelTemplateArgumentList ArgList
3357 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
Anders Carlsson25cae7f2009-09-05 05:14:19 +00003358
Douglas Gregor24bae922010-07-08 18:37:38 +00003359 std::pair<const TemplateArgument *, unsigned> Innermost
3360 = ArgList.getInnermost();
3361 InstantiatingTemplate Inst(*this, CallLoc, Param, Innermost.first,
3362 Innermost.second);
Anders Carlsson56c5e332009-08-25 03:49:14 +00003363
John McCallce3ff2b2009-08-25 22:02:44 +00003364 OwningExprResult Result = SubstExpr(UninstExpr, ArgList);
Mike Stump1eb44332009-09-09 15:08:12 +00003365 if (Result.isInvalid())
Anders Carlsson56c5e332009-08-25 03:49:14 +00003366 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003367
Douglas Gregor65222e82009-12-23 18:19:08 +00003368 // Check the expression as an initializer for the parameter.
3369 InitializedEntity Entity
3370 = InitializedEntity::InitializeParameter(Param);
3371 InitializationKind Kind
3372 = InitializationKind::CreateCopy(Param->getLocation(),
3373 /*FIXME:EqualLoc*/UninstExpr->getSourceRange().getBegin());
3374 Expr *ResultE = Result.takeAs<Expr>();
3375
3376 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003377 Result = InitSeq.Perform(*this, Entity, Kind,
Douglas Gregor65222e82009-12-23 18:19:08 +00003378 MultiExprArg(*this, (void**)&ResultE, 1));
3379 if (Result.isInvalid())
Anders Carlsson56c5e332009-08-25 03:49:14 +00003380 return ExprError();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003381
Douglas Gregor65222e82009-12-23 18:19:08 +00003382 // Build the default argument expression.
Douglas Gregor036aed12009-12-23 23:03:06 +00003383 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param,
Douglas Gregor65222e82009-12-23 18:19:08 +00003384 Result.takeAs<Expr>()));
Anders Carlsson56c5e332009-08-25 03:49:14 +00003385 }
Mike Stump1eb44332009-09-09 15:08:12 +00003386
Anders Carlsson56c5e332009-08-25 03:49:14 +00003387 // If the default expression creates temporaries, we need to
3388 // push them to the current stack of expression temporaries so they'll
3389 // be properly destroyed.
Douglas Gregor65222e82009-12-23 18:19:08 +00003390 // FIXME: We should really be rebuilding the default argument with new
3391 // bound temporaries; see the comment in PR5810.
Anders Carlsson337cba42009-12-15 19:16:31 +00003392 for (unsigned i = 0, e = Param->getNumDefaultArgTemporaries(); i != e; ++i)
3393 ExprTemporaries.push_back(Param->getDefaultArgTemporary(i));
Anders Carlsson56c5e332009-08-25 03:49:14 +00003394 }
3395
3396 // We already type-checked the argument, so we know it works.
Douglas Gregor036aed12009-12-23 23:03:06 +00003397 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson56c5e332009-08-25 03:49:14 +00003398}
3399
Douglas Gregor88a35142008-12-22 05:46:06 +00003400/// ConvertArgumentsForCall - Converts the arguments specified in
3401/// Args/NumArgs to the parameter types of the function FDecl with
3402/// function prototype Proto. Call is the call expression itself, and
3403/// Fn is the function expression. For a C++ member function, this
3404/// routine does not attempt to convert the object argument. Returns
3405/// true if the call is ill-formed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003406bool
3407Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor88a35142008-12-22 05:46:06 +00003408 FunctionDecl *FDecl,
Douglas Gregor72564e72009-02-26 23:50:07 +00003409 const FunctionProtoType *Proto,
Douglas Gregor88a35142008-12-22 05:46:06 +00003410 Expr **Args, unsigned NumArgs,
3411 SourceLocation RParenLoc) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00003412 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor88a35142008-12-22 05:46:06 +00003413 // assignment, to the types of the corresponding parameter, ...
3414 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor3fd56d72009-01-23 21:30:56 +00003415 bool Invalid = false;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003416
Douglas Gregor88a35142008-12-22 05:46:06 +00003417 // If too few arguments are available (and we don't have default
3418 // arguments for the remaining parameters), don't make the call.
3419 if (NumArgs < NumArgsInProto) {
3420 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
3421 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00003422 << Fn->getType()->isBlockPointerType()
Eric Christopherd77b9a22010-04-16 04:48:22 +00003423 << NumArgsInProto << NumArgs << Fn->getSourceRange();
Ted Kremenek8189cde2009-02-07 01:47:29 +00003424 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor88a35142008-12-22 05:46:06 +00003425 }
3426
3427 // If too many are passed and not variadic, error on the extras and drop
3428 // them.
3429 if (NumArgs > NumArgsInProto) {
3430 if (!Proto->isVariadic()) {
3431 Diag(Args[NumArgsInProto]->getLocStart(),
3432 diag::err_typecheck_call_too_many_args)
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00003433 << Fn->getType()->isBlockPointerType()
Eric Christopherccfa9632010-04-16 04:56:46 +00003434 << NumArgsInProto << NumArgs << Fn->getSourceRange()
Douglas Gregor88a35142008-12-22 05:46:06 +00003435 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3436 Args[NumArgs-1]->getLocEnd());
3437 // This deletes the extra arguments.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003438 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003439 return true;
Douglas Gregor88a35142008-12-22 05:46:06 +00003440 }
Douglas Gregor88a35142008-12-22 05:46:06 +00003441 }
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003442 llvm::SmallVector<Expr *, 8> AllArgs;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003443 VariadicCallType CallType =
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00003444 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
3445 if (Fn->getType()->isBlockPointerType())
3446 CallType = VariadicBlock; // Block
3447 else if (isa<MemberExpr>(Fn))
3448 CallType = VariadicMethod;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003449 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00003450 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003451 if (Invalid)
3452 return true;
3453 unsigned TotalNumArgs = AllArgs.size();
3454 for (unsigned i = 0; i < TotalNumArgs; ++i)
3455 Call->setArg(i, AllArgs[i]);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003456
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003457 return false;
3458}
Mike Stumpeed9cac2009-02-19 03:04:26 +00003459
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003460bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
3461 FunctionDecl *FDecl,
3462 const FunctionProtoType *Proto,
3463 unsigned FirstProtoArg,
3464 Expr **Args, unsigned NumArgs,
3465 llvm::SmallVector<Expr *, 8> &AllArgs,
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00003466 VariadicCallType CallType) {
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003467 unsigned NumArgsInProto = Proto->getNumArgs();
3468 unsigned NumArgsToCheck = NumArgs;
3469 bool Invalid = false;
3470 if (NumArgs != NumArgsInProto)
3471 // Use default arguments for missing arguments
3472 NumArgsToCheck = NumArgsInProto;
3473 unsigned ArgIx = 0;
Douglas Gregor88a35142008-12-22 05:46:06 +00003474 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003475 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor88a35142008-12-22 05:46:06 +00003476 QualType ProtoArgType = Proto->getArgType(i);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003477
Douglas Gregor88a35142008-12-22 05:46:06 +00003478 Expr *Arg;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003479 if (ArgIx < NumArgs) {
3480 Arg = Args[ArgIx++];
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003481
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003482 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3483 ProtoArgType,
Anders Carlssonb7906612009-08-26 23:45:07 +00003484 PDiag(diag::err_call_incomplete_argument)
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003485 << Arg->getSourceRange()))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003486 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003487
Douglas Gregora188ff22009-12-22 16:09:06 +00003488 // Pass the argument
3489 ParmVarDecl *Param = 0;
3490 if (FDecl && i < FDecl->getNumParams())
3491 Param = FDecl->getParamDecl(i);
Douglas Gregoraa037312009-12-22 07:24:36 +00003492
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003493
Douglas Gregora188ff22009-12-22 16:09:06 +00003494 InitializedEntity Entity =
3495 Param? InitializedEntity::InitializeParameter(Param)
3496 : InitializedEntity::InitializeParameter(ProtoArgType);
3497 OwningExprResult ArgE = PerformCopyInitialization(Entity,
3498 SourceLocation(),
3499 Owned(Arg));
3500 if (ArgE.isInvalid())
3501 return true;
3502
3503 Arg = ArgE.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00003504 } else {
Anders Carlssoned961f92009-08-25 02:29:20 +00003505 ParmVarDecl *Param = FDecl->getParamDecl(i);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003506
Mike Stump1eb44332009-09-09 15:08:12 +00003507 OwningExprResult ArgExpr =
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003508 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson56c5e332009-08-25 03:49:14 +00003509 if (ArgExpr.isInvalid())
3510 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003511
Anders Carlsson56c5e332009-08-25 03:49:14 +00003512 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00003513 }
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003514 AllArgs.push_back(Arg);
Douglas Gregor88a35142008-12-22 05:46:06 +00003515 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003516
Douglas Gregor88a35142008-12-22 05:46:06 +00003517 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00003518 if (CallType != VariadicDoesNotApply) {
Douglas Gregor88a35142008-12-22 05:46:06 +00003519 // Promote the arguments (C99 6.5.2.2p7).
Chris Lattner40378332010-05-16 04:01:30 +00003520 for (unsigned i = ArgIx; i != NumArgs; ++i) {
Douglas Gregor88a35142008-12-22 05:46:06 +00003521 Expr *Arg = Args[i];
Chris Lattner40378332010-05-16 04:01:30 +00003522 Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType, FDecl);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003523 AllArgs.push_back(Arg);
Douglas Gregor88a35142008-12-22 05:46:06 +00003524 }
3525 }
Douglas Gregor3fd56d72009-01-23 21:30:56 +00003526 return Invalid;
Douglas Gregor88a35142008-12-22 05:46:06 +00003527}
3528
Steve Narofff69936d2007-09-16 03:34:24 +00003529/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Reid Spencer5f016e22007-07-11 17:01:13 +00003530/// This provides the location of the left/right parens and a list of comma
3531/// locations.
Sebastian Redl0eb23302009-01-19 00:08:26 +00003532Action::OwningExprResult
3533Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
3534 MultiExprArg args,
Douglas Gregor88a35142008-12-22 05:46:06 +00003535 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Sebastian Redl0eb23302009-01-19 00:08:26 +00003536 unsigned NumArgs = args.size();
Nate Begeman2ef13e52009-08-10 23:49:36 +00003537
3538 // Since this might be a postfix expression, get rid of ParenListExprs.
3539 fn = MaybeConvertParenListExprToParenExpr(S, move(fn));
Mike Stump1eb44332009-09-09 15:08:12 +00003540
Anders Carlssonf1b1d592009-05-01 19:30:39 +00003541 Expr *Fn = fn.takeAs<Expr>();
Sebastian Redl0eb23302009-01-19 00:08:26 +00003542 Expr **Args = reinterpret_cast<Expr**>(args.release());
Chris Lattner74c469f2007-07-21 03:03:59 +00003543 assert(Fn && "no function call expression");
Mike Stump1eb44332009-09-09 15:08:12 +00003544
Douglas Gregor88a35142008-12-22 05:46:06 +00003545 if (getLangOptions().CPlusPlus) {
Douglas Gregora71d8192009-09-04 17:36:40 +00003546 // If this is a pseudo-destructor expression, build the call immediately.
3547 if (isa<CXXPseudoDestructorExpr>(Fn)) {
3548 if (NumArgs > 0) {
3549 // Pseudo-destructor calls should not have any arguments.
3550 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Douglas Gregor849b2432010-03-31 17:46:05 +00003551 << FixItHint::CreateRemoval(
Douglas Gregora71d8192009-09-04 17:36:40 +00003552 SourceRange(Args[0]->getLocStart(),
3553 Args[NumArgs-1]->getLocEnd()));
Mike Stump1eb44332009-09-09 15:08:12 +00003554
Douglas Gregora71d8192009-09-04 17:36:40 +00003555 for (unsigned I = 0; I != NumArgs; ++I)
3556 Args[I]->Destroy(Context);
Mike Stump1eb44332009-09-09 15:08:12 +00003557
Douglas Gregora71d8192009-09-04 17:36:40 +00003558 NumArgs = 0;
3559 }
Mike Stump1eb44332009-09-09 15:08:12 +00003560
Douglas Gregora71d8192009-09-04 17:36:40 +00003561 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
3562 RParenLoc));
3563 }
Mike Stump1eb44332009-09-09 15:08:12 +00003564
Douglas Gregor17330012009-02-04 15:01:18 +00003565 // Determine whether this is a dependent call inside a C++ template,
Mike Stumpeed9cac2009-02-19 03:04:26 +00003566 // in which case we won't do any semantic analysis now.
Mike Stump390b4cc2009-05-16 07:39:55 +00003567 // FIXME: Will need to cache the results of name lookup (including ADL) in
3568 // Fn.
Douglas Gregor17330012009-02-04 15:01:18 +00003569 bool Dependent = false;
3570 if (Fn->isTypeDependent())
3571 Dependent = true;
3572 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
3573 Dependent = true;
3574
3575 if (Dependent)
Ted Kremenek668bf912009-02-09 20:51:47 +00003576 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
Douglas Gregor17330012009-02-04 15:01:18 +00003577 Context.DependentTy, RParenLoc));
3578
3579 // Determine whether this is a call to an object (C++ [over.call.object]).
3580 if (Fn->getType()->isRecordType())
3581 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
3582 CommaLocs, RParenLoc));
3583
John McCall129e2df2009-11-30 22:42:35 +00003584 Expr *NakedFn = Fn->IgnoreParens();
3585
3586 // Determine whether this is a call to an unresolved member function.
3587 if (UnresolvedMemberExpr *MemE = dyn_cast<UnresolvedMemberExpr>(NakedFn)) {
3588 // If lookup was unresolved but not dependent (i.e. didn't find
3589 // an unresolved using declaration), it has to be an overloaded
3590 // function set, which means it must contain either multiple
3591 // declarations (all methods or method templates) or a single
3592 // method template.
3593 assert((MemE->getNumDecls() > 1) ||
Douglas Gregor2b147f02010-04-25 21:15:30 +00003594 isa<FunctionTemplateDecl>(
3595 (*MemE->decls_begin())->getUnderlyingDecl()));
Douglas Gregor958aeb02009-12-01 03:34:29 +00003596 (void)MemE;
John McCall129e2df2009-11-30 22:42:35 +00003597
John McCallaa81e162009-12-01 22:10:20 +00003598 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
3599 CommaLocs, RParenLoc);
John McCall129e2df2009-11-30 22:42:35 +00003600 }
3601
Douglas Gregorfa047642009-02-04 00:32:51 +00003602 // Determine whether this is a call to a member function.
John McCall129e2df2009-11-30 22:42:35 +00003603 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(NakedFn)) {
Douglas Gregore53060f2009-06-25 22:08:12 +00003604 NamedDecl *MemDecl = MemExpr->getMemberDecl();
John McCall129e2df2009-11-30 22:42:35 +00003605 if (isa<CXXMethodDecl>(MemDecl))
John McCallaa81e162009-12-01 22:10:20 +00003606 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
3607 CommaLocs, RParenLoc);
Douglas Gregore53060f2009-06-25 22:08:12 +00003608 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003609
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003610 // Determine whether this is a call to a pointer-to-member function.
John McCall129e2df2009-11-30 22:42:35 +00003611 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(NakedFn)) {
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003612 if (BO->getOpcode() == BinaryOperator::PtrMemD ||
3613 BO->getOpcode() == BinaryOperator::PtrMemI) {
Douglas Gregor5f970ee2010-05-04 18:18:31 +00003614 if (const FunctionProtoType *FPT
3615 = BO->getType()->getAs<FunctionProtoType>()) {
Douglas Gregor5291c3c2010-07-13 08:18:22 +00003616 QualType ResultTy = FPT->getCallResultType(Context);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003617
3618 ExprOwningPtr<CXXMemberCallExpr>
3619 TheCall(this, new (Context) CXXMemberCallExpr(Context, BO, Args,
Fariborz Jahanian5de24502009-10-28 16:49:46 +00003620 NumArgs, ResultTy,
3621 RParenLoc));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003622
3623 if (CheckCallReturnType(FPT->getResultType(),
3624 BO->getRHS()->getSourceRange().getBegin(),
Fariborz Jahanian5de24502009-10-28 16:49:46 +00003625 TheCall.get(), 0))
3626 return ExprError();
Anders Carlsson8d6d90d2009-10-15 00:41:48 +00003627
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003628 if (ConvertArgumentsForCall(&*TheCall, BO, 0, FPT, Args, NumArgs,
Fariborz Jahanian5de24502009-10-28 16:49:46 +00003629 RParenLoc))
3630 return ExprError();
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003631
Fariborz Jahanian5de24502009-10-28 16:49:46 +00003632 return Owned(MaybeBindToTemporary(TheCall.release()).release());
3633 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003634 return ExprError(Diag(Fn->getLocStart(),
Fariborz Jahanian5de24502009-10-28 16:49:46 +00003635 diag::err_typecheck_call_not_function)
3636 << Fn->getType() << Fn->getSourceRange());
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003637 }
3638 }
Douglas Gregor88a35142008-12-22 05:46:06 +00003639 }
3640
Douglas Gregorfa047642009-02-04 00:32:51 +00003641 // If we're directly calling a function, get the appropriate declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003642 // Also, in C++, keep track of whether we should perform argument-dependent
Douglas Gregor6db8ed42009-06-30 23:57:56 +00003643 // lookup and whether there were any explicitly-specified template arguments.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003644
Eli Friedmanefa42f72009-12-26 03:35:45 +00003645 Expr *NakedFn = Fn->IgnoreParens();
John McCall3b4294e2009-12-16 12:17:52 +00003646 if (isa<UnresolvedLookupExpr>(NakedFn)) {
3647 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(NakedFn);
Douglas Gregor1aae80b2010-04-14 20:27:54 +00003648 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs,
John McCall3b4294e2009-12-16 12:17:52 +00003649 CommaLocs, RParenLoc);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003650 }
Chris Lattner04421082008-04-08 04:40:51 +00003651
John McCall3b4294e2009-12-16 12:17:52 +00003652 NamedDecl *NDecl = 0;
3653 if (isa<DeclRefExpr>(NakedFn))
3654 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
3655
John McCallaa81e162009-12-01 22:10:20 +00003656 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc);
3657}
3658
John McCall3b4294e2009-12-16 12:17:52 +00003659/// BuildResolvedCallExpr - Build a call to a resolved expression,
3660/// i.e. an expression not of \p OverloadTy. The expression should
John McCallaa81e162009-12-01 22:10:20 +00003661/// unary-convert to an expression of function-pointer or
3662/// block-pointer type.
3663///
3664/// \param NDecl the declaration being called, if available
3665Sema::OwningExprResult
3666Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
3667 SourceLocation LParenLoc,
3668 Expr **Args, unsigned NumArgs,
3669 SourceLocation RParenLoc) {
3670 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
3671
Chris Lattner04421082008-04-08 04:40:51 +00003672 // Promote the function operand.
3673 UsualUnaryConversions(Fn);
3674
Chris Lattner925e60d2007-12-28 05:29:59 +00003675 // Make the call expr early, before semantic checks. This guarantees cleanup
3676 // of arguments and function on error.
Ted Kremenek668bf912009-02-09 20:51:47 +00003677 ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
3678 Args, NumArgs,
3679 Context.BoolTy,
3680 RParenLoc));
Sebastian Redl0eb23302009-01-19 00:08:26 +00003681
Steve Naroffdd972f22008-09-05 22:11:13 +00003682 const FunctionType *FuncT;
3683 if (!Fn->getType()->isBlockPointerType()) {
3684 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
3685 // have type pointer to function".
Ted Kremenek6217b802009-07-29 21:53:49 +00003686 const PointerType *PT = Fn->getType()->getAs<PointerType>();
Steve Naroffdd972f22008-09-05 22:11:13 +00003687 if (PT == 0)
Sebastian Redl0eb23302009-01-19 00:08:26 +00003688 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3689 << Fn->getType() << Fn->getSourceRange());
John McCall183700f2009-09-21 23:43:11 +00003690 FuncT = PT->getPointeeType()->getAs<FunctionType>();
Steve Naroffdd972f22008-09-05 22:11:13 +00003691 } else { // This is a block call.
Ted Kremenek6217b802009-07-29 21:53:49 +00003692 FuncT = Fn->getType()->getAs<BlockPointerType>()->getPointeeType()->
John McCall183700f2009-09-21 23:43:11 +00003693 getAs<FunctionType>();
Steve Naroffdd972f22008-09-05 22:11:13 +00003694 }
Chris Lattner925e60d2007-12-28 05:29:59 +00003695 if (FuncT == 0)
Sebastian Redl0eb23302009-01-19 00:08:26 +00003696 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3697 << Fn->getType() << Fn->getSourceRange());
3698
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003699 // Check for a valid return type
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003700 if (CheckCallReturnType(FuncT->getResultType(),
Anders Carlsson8c8d9192009-10-09 23:51:55 +00003701 Fn->getSourceRange().getBegin(), TheCall.get(),
3702 FDecl))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003703 return ExprError();
3704
Chris Lattner925e60d2007-12-28 05:29:59 +00003705 // We know the result type of the call, set it.
Douglas Gregor5291c3c2010-07-13 08:18:22 +00003706 TheCall->setType(FuncT->getCallResultType(Context));
Sebastian Redl0eb23302009-01-19 00:08:26 +00003707
Douglas Gregor72564e72009-02-26 23:50:07 +00003708 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00003709 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00003710 RParenLoc))
Sebastian Redl0eb23302009-01-19 00:08:26 +00003711 return ExprError();
Chris Lattner925e60d2007-12-28 05:29:59 +00003712 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00003713 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redl0eb23302009-01-19 00:08:26 +00003714
Douglas Gregor74734d52009-04-02 15:37:10 +00003715 if (FDecl) {
3716 // Check if we have too few/too many template arguments, based
3717 // on our knowledge of the function definition.
3718 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00003719 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00003720 const FunctionProtoType *Proto =
John McCall183700f2009-09-21 23:43:11 +00003721 Def->getType()->getAs<FunctionProtoType>();
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00003722 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size())) {
3723 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
3724 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
3725 }
3726 }
Douglas Gregor74734d52009-04-02 15:37:10 +00003727 }
3728
Steve Naroffb291ab62007-08-28 23:30:39 +00003729 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner925e60d2007-12-28 05:29:59 +00003730 for (unsigned i = 0; i != NumArgs; i++) {
3731 Expr *Arg = Args[i];
3732 DefaultArgumentPromotion(Arg);
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003733 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3734 Arg->getType(),
Anders Carlssonb7906612009-08-26 23:45:07 +00003735 PDiag(diag::err_call_incomplete_argument)
3736 << Arg->getSourceRange()))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003737 return ExprError();
Chris Lattner925e60d2007-12-28 05:29:59 +00003738 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +00003739 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003740 }
Chris Lattner925e60d2007-12-28 05:29:59 +00003741
Douglas Gregor88a35142008-12-22 05:46:06 +00003742 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3743 if (!Method->isStatic())
Sebastian Redl0eb23302009-01-19 00:08:26 +00003744 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
3745 << Fn->getSourceRange());
Douglas Gregor88a35142008-12-22 05:46:06 +00003746
Fariborz Jahaniandaf04152009-05-15 20:33:25 +00003747 // Check for sentinels
3748 if (NDecl)
3749 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00003750
Chris Lattner59907c42007-08-10 20:18:51 +00003751 // Do special checking on direct calls to functions.
Anders Carlssond406bf02009-08-16 01:56:34 +00003752 if (FDecl) {
3753 if (CheckFunctionCall(FDecl, TheCall.get()))
3754 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003755
Douglas Gregor7814e6d2009-09-12 00:22:50 +00003756 if (unsigned BuiltinID = FDecl->getBuiltinID())
Anders Carlssond406bf02009-08-16 01:56:34 +00003757 return CheckBuiltinFunctionCall(BuiltinID, TheCall.take());
3758 } else if (NDecl) {
3759 if (CheckBlockCall(NDecl, TheCall.get()))
3760 return ExprError();
3761 }
Chris Lattner59907c42007-08-10 20:18:51 +00003762
Anders Carlssonec74c592009-08-16 03:06:32 +00003763 return MaybeBindToTemporary(TheCall.take());
Reid Spencer5f016e22007-07-11 17:01:13 +00003764}
3765
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003766Action::OwningExprResult
3767Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
3768 SourceLocation RParenLoc, ExprArg InitExpr) {
Steve Narofff69936d2007-09-16 03:34:24 +00003769 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroffaff1edd2007-07-19 21:32:11 +00003770 // FIXME: put back this assert when initializers are worked out.
Steve Narofff69936d2007-09-16 03:34:24 +00003771 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCall42f56b52010-01-18 19:35:47 +00003772
3773 TypeSourceInfo *TInfo;
3774 QualType literalType = GetTypeFromParser(Ty, &TInfo);
3775 if (!TInfo)
3776 TInfo = Context.getTrivialTypeSourceInfo(literalType);
3777
3778 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, move(InitExpr));
3779}
3780
3781Action::OwningExprResult
3782Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
3783 SourceLocation RParenLoc, ExprArg InitExpr) {
3784 QualType literalType = TInfo->getType();
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003785 Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
Anders Carlssond35c8322007-12-05 07:24:19 +00003786
Eli Friedman6223c222008-05-20 05:22:08 +00003787 if (literalType->isArrayType()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003788 if (literalType->isVariableArrayType())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003789 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
3790 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor690dc7f2009-05-21 23:48:18 +00003791 } else if (!literalType->isDependentType() &&
3792 RequireCompleteType(LParenLoc, literalType,
Anders Carlssonb7906612009-08-26 23:45:07 +00003793 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump1eb44332009-09-09 15:08:12 +00003794 << SourceRange(LParenLoc,
Anders Carlssonb7906612009-08-26 23:45:07 +00003795 literalExpr->getSourceRange().getEnd())))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003796 return ExprError();
Eli Friedman6223c222008-05-20 05:22:08 +00003797
Douglas Gregor99a2e602009-12-16 01:38:02 +00003798 InitializedEntity Entity
Douglas Gregord6542d82009-12-22 15:35:07 +00003799 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor99a2e602009-12-16 01:38:02 +00003800 InitializationKind Kind
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003801 = InitializationKind::CreateCast(SourceRange(LParenLoc, RParenLoc),
Douglas Gregor99a2e602009-12-16 01:38:02 +00003802 /*IsCStyleCast=*/true);
Eli Friedman08544622009-12-22 02:35:53 +00003803 InitializationSequence InitSeq(*this, Entity, Kind, &literalExpr, 1);
3804 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
3805 MultiExprArg(*this, (void**)&literalExpr, 1),
3806 &literalType);
3807 if (Result.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003808 return ExprError();
Eli Friedman08544622009-12-22 02:35:53 +00003809 InitExpr.release();
3810 literalExpr = static_cast<Expr*>(Result.get());
Steve Naroffe9b12192008-01-14 18:19:28 +00003811
Chris Lattner371f2582008-12-04 23:50:19 +00003812 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffe9b12192008-01-14 18:19:28 +00003813 if (isFileScope) { // 6.5.2.5p3
Steve Naroffd0091aa2008-01-10 22:15:12 +00003814 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003815 return ExprError();
Steve Naroffd0091aa2008-01-10 22:15:12 +00003816 }
Eli Friedman08544622009-12-22 02:35:53 +00003817
3818 Result.release();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003819
John McCall1d7d8d62010-01-19 22:33:45 +00003820 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
Steve Naroff6ece14c2009-01-21 00:14:39 +00003821 literalExpr, isFileScope));
Steve Naroff4aa88f82007-07-19 01:06:55 +00003822}
3823
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003824Action::OwningExprResult
3825Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003826 SourceLocation RBraceLoc) {
3827 unsigned NumInit = initlist.size();
3828 Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00003829
Steve Naroff08d92e42007-09-15 18:49:24 +00003830 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stumpeed9cac2009-02-19 03:04:26 +00003831 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003832
Ted Kremenek709210f2010-04-13 23:39:13 +00003833 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList,
3834 NumInit, RBraceLoc);
Chris Lattnerf0467b32008-04-02 04:24:33 +00003835 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003836 return Owned(E);
Steve Naroff4aa88f82007-07-19 01:06:55 +00003837}
3838
Anders Carlsson82debc72009-10-18 18:12:03 +00003839static CastExpr::CastKind getScalarCastKind(ASTContext &Context,
3840 QualType SrcTy, QualType DestTy) {
Douglas Gregora4923eb2009-11-16 21:35:15 +00003841 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
Anders Carlsson82debc72009-10-18 18:12:03 +00003842 return CastExpr::CK_NoOp;
3843
3844 if (SrcTy->hasPointerRepresentation()) {
3845 if (DestTy->hasPointerRepresentation())
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003846 return DestTy->isObjCObjectPointerType() ?
3847 CastExpr::CK_AnyPointerToObjCPointerCast :
Fariborz Jahaniana7fa7cd2009-12-15 21:34:52 +00003848 CastExpr::CK_BitCast;
Anders Carlsson82debc72009-10-18 18:12:03 +00003849 if (DestTy->isIntegerType())
3850 return CastExpr::CK_PointerToIntegral;
3851 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003852
Anders Carlsson82debc72009-10-18 18:12:03 +00003853 if (SrcTy->isIntegerType()) {
3854 if (DestTy->isIntegerType())
3855 return CastExpr::CK_IntegralCast;
3856 if (DestTy->hasPointerRepresentation())
3857 return CastExpr::CK_IntegralToPointer;
3858 if (DestTy->isRealFloatingType())
3859 return CastExpr::CK_IntegralToFloating;
3860 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003861
Anders Carlsson82debc72009-10-18 18:12:03 +00003862 if (SrcTy->isRealFloatingType()) {
3863 if (DestTy->isRealFloatingType())
3864 return CastExpr::CK_FloatingCast;
3865 if (DestTy->isIntegerType())
3866 return CastExpr::CK_FloatingToIntegral;
3867 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003868
Anders Carlsson82debc72009-10-18 18:12:03 +00003869 // FIXME: Assert here.
3870 // assert(false && "Unhandled cast combination!");
3871 return CastExpr::CK_Unknown;
3872}
3873
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003874/// CheckCastTypes - Check type constraints for casting between types.
Sebastian Redlef0cb8e2009-07-29 13:50:23 +00003875bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr,
Mike Stump1eb44332009-09-09 15:08:12 +00003876 CastExpr::CastKind& Kind,
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00003877 CXXBaseSpecifierArray &BasePath,
Fariborz Jahaniane9f42082009-08-26 18:55:36 +00003878 bool FunctionalStyle) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00003879 if (getLangOptions().CPlusPlus)
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00003880 return CXXCheckCStyleCast(TyR, castType, castExpr, Kind, BasePath,
3881 FunctionalStyle);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00003882
Douglas Gregora873dfc2010-02-03 00:27:59 +00003883 DefaultFunctionArrayLvalueConversion(castExpr);
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003884
3885 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
3886 // type needs to be scalar.
3887 if (castType->isVoidType()) {
3888 // Cast to void allows any expr type.
Anders Carlssonebeaf202009-10-16 02:35:04 +00003889 Kind = CastExpr::CK_ToVoid;
3890 return false;
3891 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003892
Eli Friedman8d438082010-07-17 20:43:49 +00003893 if (RequireCompleteType(TyR.getBegin(), castType,
3894 diag::err_typecheck_cast_to_incomplete))
3895 return true;
3896
Anders Carlssonebeaf202009-10-16 02:35:04 +00003897 if (!castType->isScalarType() && !castType->isVectorType()) {
Douglas Gregora4923eb2009-11-16 21:35:15 +00003898 if (Context.hasSameUnqualifiedType(castType, castExpr->getType()) &&
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003899 (castType->isStructureType() || castType->isUnionType())) {
3900 // GCC struct/union extension: allow cast to self.
Eli Friedmanb1d796d2009-03-23 00:24:07 +00003901 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003902 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
3903 << castType << castExpr->getSourceRange();
Anders Carlsson4d8673b2009-08-07 23:22:37 +00003904 Kind = CastExpr::CK_NoOp;
Anders Carlssonc3516322009-10-16 02:48:28 +00003905 return false;
3906 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003907
Anders Carlssonc3516322009-10-16 02:48:28 +00003908 if (castType->isUnionType()) {
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003909 // GCC cast to union extension
Ted Kremenek6217b802009-07-29 21:53:49 +00003910 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003911 RecordDecl::field_iterator Field, FieldEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003912 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003913 Field != FieldEnd; ++Field) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003914 if (Context.hasSameUnqualifiedType(Field->getType(),
Douglas Gregora4923eb2009-11-16 21:35:15 +00003915 castExpr->getType())) {
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003916 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
3917 << castExpr->getSourceRange();
3918 break;
3919 }
3920 }
3921 if (Field == FieldEnd)
3922 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
3923 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlsson4d8673b2009-08-07 23:22:37 +00003924 Kind = CastExpr::CK_ToUnion;
Anders Carlssonc3516322009-10-16 02:48:28 +00003925 return false;
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003926 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003927
Anders Carlssonc3516322009-10-16 02:48:28 +00003928 // Reject any other conversions to non-scalar types.
3929 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
3930 << castType << castExpr->getSourceRange();
3931 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003932
3933 if (!castExpr->getType()->isScalarType() &&
Anders Carlssonc3516322009-10-16 02:48:28 +00003934 !castExpr->getType()->isVectorType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003935 return Diag(castExpr->getLocStart(),
3936 diag::err_typecheck_expect_scalar_operand)
Chris Lattnerd1625842008-11-24 06:25:27 +00003937 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlssonc3516322009-10-16 02:48:28 +00003938 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003939
3940 if (castType->isExtVectorType())
Anders Carlsson16a89042009-10-16 05:23:41 +00003941 return CheckExtVectorCast(TyR, castType, castExpr, Kind);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003942
Anders Carlssonc3516322009-10-16 02:48:28 +00003943 if (castType->isVectorType())
3944 return CheckVectorCast(TyR, castType, castExpr->getType(), Kind);
3945 if (castExpr->getType()->isVectorType())
3946 return CheckVectorCast(TyR, castExpr->getType(), castType, Kind);
3947
Anders Carlsson16a89042009-10-16 05:23:41 +00003948 if (isa<ObjCSelectorExpr>(castExpr))
3949 return Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003950
Anders Carlssonc3516322009-10-16 02:48:28 +00003951 if (!castType->isArithmeticType()) {
Eli Friedman41826bb2009-05-01 02:23:58 +00003952 QualType castExprType = castExpr->getType();
Douglas Gregor9d3347a2010-06-16 00:35:25 +00003953 if (!castExprType->isIntegralType(Context) &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003954 castExprType->isArithmeticType())
Eli Friedman41826bb2009-05-01 02:23:58 +00003955 return Diag(castExpr->getLocStart(),
3956 diag::err_cast_pointer_from_non_pointer_int)
3957 << castExprType << castExpr->getSourceRange();
3958 } else if (!castExpr->getType()->isArithmeticType()) {
Douglas Gregor9d3347a2010-06-16 00:35:25 +00003959 if (!castType->isIntegralType(Context) && castType->isArithmeticType())
Eli Friedman41826bb2009-05-01 02:23:58 +00003960 return Diag(castExpr->getLocStart(),
3961 diag::err_cast_pointer_to_non_pointer_int)
3962 << castType << castExpr->getSourceRange();
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003963 }
Anders Carlsson82debc72009-10-18 18:12:03 +00003964
3965 Kind = getScalarCastKind(Context, castExpr->getType(), castType);
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003966 return false;
3967}
3968
Anders Carlssonc3516322009-10-16 02:48:28 +00003969bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
3970 CastExpr::CastKind &Kind) {
Anders Carlssona64db8f2007-11-27 05:51:55 +00003971 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00003972
Anders Carlssona64db8f2007-11-27 05:51:55 +00003973 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner98be4942008-03-05 18:54:05 +00003974 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssona64db8f2007-11-27 05:51:55 +00003975 return Diag(R.getBegin(),
Mike Stumpeed9cac2009-02-19 03:04:26 +00003976 Ty->isVectorType() ?
Anders Carlssona64db8f2007-11-27 05:51:55 +00003977 diag::err_invalid_conversion_between_vectors :
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003978 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00003979 << VectorTy << Ty << R;
Anders Carlssona64db8f2007-11-27 05:51:55 +00003980 } else
3981 return Diag(R.getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003982 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattnerd1625842008-11-24 06:25:27 +00003983 << VectorTy << Ty << R;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003984
Anders Carlssonc3516322009-10-16 02:48:28 +00003985 Kind = CastExpr::CK_BitCast;
Anders Carlssona64db8f2007-11-27 05:51:55 +00003986 return false;
3987}
3988
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003989bool Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *&CastExpr,
Anders Carlsson16a89042009-10-16 05:23:41 +00003990 CastExpr::CastKind &Kind) {
Nate Begeman58d29a42009-06-26 00:50:28 +00003991 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003992
Anders Carlsson16a89042009-10-16 05:23:41 +00003993 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003994
Nate Begeman9b10da62009-06-27 22:05:55 +00003995 // If SrcTy is a VectorType, the total size must match to explicitly cast to
3996 // an ExtVectorType.
Nate Begeman58d29a42009-06-26 00:50:28 +00003997 if (SrcTy->isVectorType()) {
3998 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
3999 return Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
4000 << DestTy << SrcTy << R;
Anders Carlsson16a89042009-10-16 05:23:41 +00004001 Kind = CastExpr::CK_BitCast;
Nate Begeman58d29a42009-06-26 00:50:28 +00004002 return false;
4003 }
4004
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004005 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begeman58d29a42009-06-26 00:50:28 +00004006 // conversion will take place first from scalar to elt type, and then
4007 // splat from elt type to vector.
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004008 if (SrcTy->isPointerType())
4009 return Diag(R.getBegin(),
4010 diag::err_invalid_conversion_between_vector_and_scalar)
4011 << DestTy << SrcTy << R;
Eli Friedman73c39ab2009-10-20 08:27:19 +00004012
4013 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
4014 ImpCastExprToType(CastExpr, DestElemTy,
4015 getScalarCastKind(Context, SrcTy, DestElemTy));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004016
Anders Carlsson16a89042009-10-16 05:23:41 +00004017 Kind = CastExpr::CK_VectorSplat;
Nate Begeman58d29a42009-06-26 00:50:28 +00004018 return false;
4019}
4020
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004021Action::OwningExprResult
Nate Begeman2ef13e52009-08-10 23:49:36 +00004022Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, TypeTy *Ty,
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004023 SourceLocation RParenLoc, ExprArg Op) {
4024 assert((Ty != 0) && (Op.get() != 0) &&
4025 "ActOnCastExpr(): missing type or expr");
Steve Naroff16beff82007-07-16 23:25:18 +00004026
John McCall9d125032010-01-15 18:39:57 +00004027 TypeSourceInfo *castTInfo;
4028 QualType castType = GetTypeFromParser(Ty, &castTInfo);
4029 if (!castTInfo)
John McCall42f56b52010-01-18 19:35:47 +00004030 castTInfo = Context.getTrivialTypeSourceInfo(castType);
Mike Stump1eb44332009-09-09 15:08:12 +00004031
Nate Begeman2ef13e52009-08-10 23:49:36 +00004032 // If the Expr being casted is a ParenListExpr, handle it specially.
John McCallb042fdf2010-01-15 18:56:44 +00004033 Expr *castExpr = (Expr *)Op.get();
Nate Begeman2ef13e52009-08-10 23:49:36 +00004034 if (isa<ParenListExpr>(castExpr))
John McCall42f56b52010-01-18 19:35:47 +00004035 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, move(Op),
4036 castTInfo);
John McCallb042fdf2010-01-15 18:56:44 +00004037
4038 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, move(Op));
4039}
4040
4041Action::OwningExprResult
4042Sema::BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty,
4043 SourceLocation RParenLoc, ExprArg Op) {
4044 Expr *castExpr = static_cast<Expr*>(Op.get());
4045
John McCallb042fdf2010-01-15 18:56:44 +00004046 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Anders Carlsson41b2dcd2010-04-24 18:38:56 +00004047 CXXBaseSpecifierArray BasePath;
John McCallb042fdf2010-01-15 18:56:44 +00004048 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), Ty->getType(), castExpr,
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00004049 Kind, BasePath))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004050 return ExprError();
Anders Carlsson0aebc812009-09-09 21:33:21 +00004051
Douglas Gregord6e44a32010-04-16 22:09:46 +00004052 Op.release();
Douglas Gregor63982352010-07-13 18:40:04 +00004053 return Owned(new (Context) CStyleCastExpr(
4054 Ty->getType().getNonLValueExprType(Context),
Anders Carlsson41b2dcd2010-04-24 18:38:56 +00004055 Kind, castExpr, BasePath, Ty,
Anders Carlssoncdb61972009-08-07 22:21:05 +00004056 LParenLoc, RParenLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00004057}
4058
Nate Begeman2ef13e52009-08-10 23:49:36 +00004059/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
4060/// of comma binary operators.
4061Action::OwningExprResult
4062Sema::MaybeConvertParenListExprToParenExpr(Scope *S, ExprArg EA) {
4063 Expr *expr = EA.takeAs<Expr>();
4064 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
4065 if (!E)
4066 return Owned(expr);
Mike Stump1eb44332009-09-09 15:08:12 +00004067
Nate Begeman2ef13e52009-08-10 23:49:36 +00004068 OwningExprResult Result(*this, E->getExpr(0));
Mike Stump1eb44332009-09-09 15:08:12 +00004069
Nate Begeman2ef13e52009-08-10 23:49:36 +00004070 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
4071 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, move(Result),
4072 Owned(E->getExpr(i)));
Mike Stump1eb44332009-09-09 15:08:12 +00004073
Nate Begeman2ef13e52009-08-10 23:49:36 +00004074 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), move(Result));
4075}
4076
4077Action::OwningExprResult
4078Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
4079 SourceLocation RParenLoc, ExprArg Op,
John McCall42f56b52010-01-18 19:35:47 +00004080 TypeSourceInfo *TInfo) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00004081 ParenListExpr *PE = (ParenListExpr *)Op.get();
John McCall42f56b52010-01-18 19:35:47 +00004082 QualType Ty = TInfo->getType();
John Thompson8bb59a82010-06-30 22:55:51 +00004083 bool isAltiVecLiteral = false;
Mike Stump1eb44332009-09-09 15:08:12 +00004084
John Thompson8bb59a82010-06-30 22:55:51 +00004085 // Check for an altivec literal,
4086 // i.e. all the elements are integer constants.
Nate Begeman2ef13e52009-08-10 23:49:36 +00004087 if (getLangOptions().AltiVec && Ty->isVectorType()) {
4088 if (PE->getNumExprs() == 0) {
4089 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
4090 return ExprError();
4091 }
John Thompson8bb59a82010-06-30 22:55:51 +00004092 if (PE->getNumExprs() == 1) {
4093 if (!PE->getExpr(0)->getType()->isVectorType())
4094 isAltiVecLiteral = true;
4095 }
4096 else
4097 isAltiVecLiteral = true;
4098 }
Nate Begeman2ef13e52009-08-10 23:49:36 +00004099
John Thompson8bb59a82010-06-30 22:55:51 +00004100 // If this is an altivec initializer, '(' type ')' '(' init, ..., init ')'
4101 // then handle it as such.
4102 if (isAltiVecLiteral) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00004103 llvm::SmallVector<Expr *, 8> initExprs;
4104 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
4105 initExprs.push_back(PE->getExpr(i));
4106
4107 // FIXME: This means that pretty-printing the final AST will produce curly
4108 // braces instead of the original commas.
4109 Op.release();
Ted Kremenek709210f2010-04-13 23:39:13 +00004110 InitListExpr *E = new (Context) InitListExpr(Context, LParenLoc,
4111 &initExprs[0],
Nate Begeman2ef13e52009-08-10 23:49:36 +00004112 initExprs.size(), RParenLoc);
4113 E->setType(Ty);
John McCall42f56b52010-01-18 19:35:47 +00004114 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, Owned(E));
Nate Begeman2ef13e52009-08-10 23:49:36 +00004115 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00004116 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
Nate Begeman2ef13e52009-08-10 23:49:36 +00004117 // sequence of BinOp comma operators.
4118 Op = MaybeConvertParenListExprToParenExpr(S, move(Op));
John McCall42f56b52010-01-18 19:35:47 +00004119 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, move(Op));
Nate Begeman2ef13e52009-08-10 23:49:36 +00004120 }
4121}
4122
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00004123Action::OwningExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
Nate Begeman2ef13e52009-08-10 23:49:36 +00004124 SourceLocation R,
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00004125 MultiExprArg Val,
4126 TypeTy *TypeOfCast) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00004127 unsigned nexprs = Val.size();
4128 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00004129 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
4130 Expr *expr;
4131 if (nexprs == 1 && TypeOfCast && !TypeIsVectorType(TypeOfCast))
4132 expr = new (Context) ParenExpr(L, R, exprs[0]);
4133 else
4134 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
Nate Begeman2ef13e52009-08-10 23:49:36 +00004135 return Owned(expr);
4136}
4137
Sebastian Redl28507842009-02-26 14:39:58 +00004138/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
4139/// In that case, lhs = cond.
Chris Lattnera119a3b2009-02-18 04:38:20 +00004140/// C99 6.5.15
4141QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
4142 SourceLocation QuestionLoc) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004143 // C++ is sufficiently different to merit its own checker.
4144 if (getLangOptions().CPlusPlus)
4145 return CXXCheckConditionalOperands(Cond, LHS, RHS, QuestionLoc);
4146
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004147 UsualUnaryConversions(Cond);
4148 UsualUnaryConversions(LHS);
4149 UsualUnaryConversions(RHS);
4150 QualType CondTy = Cond->getType();
4151 QualType LHSTy = LHS->getType();
4152 QualType RHSTy = RHS->getType();
Steve Naroffc80b4ee2007-07-16 21:54:35 +00004153
Reid Spencer5f016e22007-07-11 17:01:13 +00004154 // first, check the condition.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004155 if (!CondTy->isScalarType()) { // C99 6.5.15p2
4156 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4157 << CondTy;
4158 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00004159 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004160
Chris Lattner70d67a92008-01-06 22:42:25 +00004161 // Now check the two expressions.
Nate Begeman2ef13e52009-08-10 23:49:36 +00004162 if (LHSTy->isVectorType() || RHSTy->isVectorType())
4163 return CheckVectorOperands(QuestionLoc, LHS, RHS);
Douglas Gregor898574e2008-12-05 23:32:09 +00004164
Chris Lattner70d67a92008-01-06 22:42:25 +00004165 // If both operands have arithmetic type, do the usual arithmetic conversions
4166 // to find a common type: C99 6.5.15p3,5.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004167 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
4168 UsualArithmeticConversions(LHS, RHS);
4169 return LHS->getType();
Steve Naroffa4332e22007-07-17 00:58:39 +00004170 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004171
Chris Lattner70d67a92008-01-06 22:42:25 +00004172 // If both operands are the same structure or union type, the result is that
4173 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00004174 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
4175 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattnera21ddb32007-11-26 01:40:58 +00004176 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stumpeed9cac2009-02-19 03:04:26 +00004177 // "If both the operands have structure or union type, the result has
Chris Lattner70d67a92008-01-06 22:42:25 +00004178 // that type." This implies that CV qualifiers are dropped.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004179 return LHSTy.getUnqualifiedType();
Eli Friedmanb1d796d2009-03-23 00:24:07 +00004180 // FIXME: Type of conditional expression must be complete in C mode.
Reid Spencer5f016e22007-07-11 17:01:13 +00004181 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004182
Chris Lattner70d67a92008-01-06 22:42:25 +00004183 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffe701c0a2008-05-12 21:44:38 +00004184 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004185 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
4186 if (!LHSTy->isVoidType())
4187 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
4188 << RHS->getSourceRange();
4189 if (!RHSTy->isVoidType())
4190 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
4191 << LHS->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00004192 ImpCastExprToType(LHS, Context.VoidTy, CastExpr::CK_ToVoid);
4193 ImpCastExprToType(RHS, Context.VoidTy, CastExpr::CK_ToVoid);
Eli Friedman0e724012008-06-04 19:47:51 +00004194 return Context.VoidTy;
Steve Naroffe701c0a2008-05-12 21:44:38 +00004195 }
Steve Naroffb6d54e52008-01-08 01:11:38 +00004196 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
4197 // the type of the other operand."
Steve Naroff58f9f2c2009-07-14 18:25:06 +00004198 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
Douglas Gregorce940492009-09-25 04:25:58 +00004199 RHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004200 // promote the null to a pointer.
4201 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_Unknown);
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004202 return LHSTy;
Steve Naroffb6d54e52008-01-08 01:11:38 +00004203 }
Steve Naroff58f9f2c2009-07-14 18:25:06 +00004204 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
Douglas Gregorce940492009-09-25 04:25:58 +00004205 LHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004206 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_Unknown);
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004207 return RHSTy;
Steve Naroffb6d54e52008-01-08 01:11:38 +00004208 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004209
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004210 // All objective-c pointer type analysis is done here.
4211 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
4212 QuestionLoc);
4213 if (!compositeType.isNull())
4214 return compositeType;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004215
4216
Steve Naroff7154a772009-07-01 14:36:47 +00004217 // Handle block pointer types.
4218 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
4219 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
4220 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
4221 QualType destType = Context.getPointerType(Context.VoidTy);
Eli Friedman73c39ab2009-10-20 08:27:19 +00004222 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
4223 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00004224 return destType;
4225 }
4226 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004227 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Steve Naroff7154a772009-07-01 14:36:47 +00004228 return QualType();
Mike Stumpdd3e1662009-05-07 03:14:14 +00004229 }
Steve Naroff7154a772009-07-01 14:36:47 +00004230 // We have 2 block pointer types.
4231 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4232 // Two identical block pointer types are always compatible.
Mike Stumpdd3e1662009-05-07 03:14:14 +00004233 return LHSTy;
4234 }
Steve Naroff7154a772009-07-01 14:36:47 +00004235 // The block pointer types aren't identical, continue checking.
Ted Kremenek6217b802009-07-29 21:53:49 +00004236 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
4237 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004238
Steve Naroff7154a772009-07-01 14:36:47 +00004239 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
4240 rhptee.getUnqualifiedType())) {
Mike Stumpdd3e1662009-05-07 03:14:14 +00004241 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004242 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stumpdd3e1662009-05-07 03:14:14 +00004243 // In this situation, we assume void* type. No especially good
4244 // reason, but this is what gcc does, and we do have to pick
4245 // to get a consistent AST.
4246 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Eli Friedman73c39ab2009-10-20 08:27:19 +00004247 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
4248 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
Mike Stumpdd3e1662009-05-07 03:14:14 +00004249 return incompatTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00004250 }
Steve Naroff7154a772009-07-01 14:36:47 +00004251 // The block pointer types are compatible.
Eli Friedman73c39ab2009-10-20 08:27:19 +00004252 ImpCastExprToType(LHS, LHSTy, CastExpr::CK_BitCast);
4253 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
Steve Naroff91588042009-04-08 17:05:15 +00004254 return LHSTy;
4255 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004256
Steve Naroff7154a772009-07-01 14:36:47 +00004257 // Check constraints for C object pointers types (C99 6.5.15p3,6).
4258 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
4259 // get the "pointed to" types
Ted Kremenek6217b802009-07-29 21:53:49 +00004260 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4261 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff7154a772009-07-01 14:36:47 +00004262
4263 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
4264 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
4265 // Figure out necessary qualifiers (C99 6.5.15p6)
John McCall0953e762009-09-24 19:53:00 +00004266 QualType destPointee
4267 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
Steve Naroff7154a772009-07-01 14:36:47 +00004268 QualType destType = Context.getPointerType(destPointee);
Eli Friedman73c39ab2009-10-20 08:27:19 +00004269 // Add qualifiers if necessary.
4270 ImpCastExprToType(LHS, destType, CastExpr::CK_NoOp);
4271 // Promote to void*.
4272 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00004273 return destType;
4274 }
4275 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
John McCall0953e762009-09-24 19:53:00 +00004276 QualType destPointee
4277 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
Steve Naroff7154a772009-07-01 14:36:47 +00004278 QualType destType = Context.getPointerType(destPointee);
Eli Friedman73c39ab2009-10-20 08:27:19 +00004279 // Add qualifiers if necessary.
Eli Friedman16fea9b2009-11-17 01:22:05 +00004280 ImpCastExprToType(RHS, destType, CastExpr::CK_NoOp);
Eli Friedman73c39ab2009-10-20 08:27:19 +00004281 // Promote to void*.
Eli Friedman16fea9b2009-11-17 01:22:05 +00004282 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00004283 return destType;
4284 }
4285
4286 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4287 // Two identical pointer types are always compatible.
4288 return LHSTy;
4289 }
4290 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
4291 rhptee.getUnqualifiedType())) {
4292 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
4293 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
4294 // In this situation, we assume void* type. No especially good
4295 // reason, but this is what gcc does, and we do have to pick
4296 // to get a consistent AST.
4297 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Eli Friedman73c39ab2009-10-20 08:27:19 +00004298 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
4299 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00004300 return incompatTy;
4301 }
4302 // The pointer types are compatible.
4303 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
4304 // differently qualified versions of compatible types, the result type is
4305 // a pointer to an appropriately qualified version of the *composite*
4306 // type.
4307 // FIXME: Need to calculate the composite type.
4308 // FIXME: Need to add qualifiers
Eli Friedman73c39ab2009-10-20 08:27:19 +00004309 ImpCastExprToType(LHS, LHSTy, CastExpr::CK_BitCast);
4310 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00004311 return LHSTy;
4312 }
Mike Stump1eb44332009-09-09 15:08:12 +00004313
Steve Naroff7154a772009-07-01 14:36:47 +00004314 // GCC compatibility: soften pointer/integer mismatch.
4315 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
4316 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4317 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00004318 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_IntegralToPointer);
Steve Naroff7154a772009-07-01 14:36:47 +00004319 return RHSTy;
4320 }
4321 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
4322 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4323 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00004324 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_IntegralToPointer);
Steve Naroff7154a772009-07-01 14:36:47 +00004325 return LHSTy;
4326 }
Daniel Dunbar5e155f02008-09-11 23:12:46 +00004327
Chris Lattner70d67a92008-01-06 22:42:25 +00004328 // Otherwise, the operands are not compatible.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004329 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
4330 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00004331 return QualType();
4332}
4333
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004334/// FindCompositeObjCPointerType - Helper method to find composite type of
4335/// two objective-c pointer types of the two input expressions.
4336QualType Sema::FindCompositeObjCPointerType(Expr *&LHS, Expr *&RHS,
4337 SourceLocation QuestionLoc) {
4338 QualType LHSTy = LHS->getType();
4339 QualType RHSTy = RHS->getType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004340
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004341 // Handle things like Class and struct objc_class*. Here we case the result
4342 // to the pseudo-builtin, because that will be implicitly cast back to the
4343 // redefinition type if an attempt is made to access its fields.
4344 if (LHSTy->isObjCClassType() &&
4345 (RHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
4346 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
4347 return LHSTy;
4348 }
4349 if (RHSTy->isObjCClassType() &&
4350 (LHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
4351 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
4352 return RHSTy;
4353 }
4354 // And the same for struct objc_object* / id
4355 if (LHSTy->isObjCIdType() &&
4356 (RHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
4357 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
4358 return LHSTy;
4359 }
4360 if (RHSTy->isObjCIdType() &&
4361 (LHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
4362 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
4363 return RHSTy;
4364 }
4365 // And the same for struct objc_selector* / SEL
4366 if (Context.isObjCSelType(LHSTy) &&
4367 (RHSTy.getDesugaredType() == Context.ObjCSelRedefinitionType)) {
4368 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
4369 return LHSTy;
4370 }
4371 if (Context.isObjCSelType(RHSTy) &&
4372 (LHSTy.getDesugaredType() == Context.ObjCSelRedefinitionType)) {
4373 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
4374 return RHSTy;
4375 }
4376 // Check constraints for Objective-C object pointers types.
4377 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004378
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004379 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4380 // Two identical object pointer types are always compatible.
4381 return LHSTy;
4382 }
4383 const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>();
4384 const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>();
4385 QualType compositeType = LHSTy;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004386
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004387 // If both operands are interfaces and either operand can be
4388 // assigned to the other, use that type as the composite
4389 // type. This allows
4390 // xxx ? (A*) a : (B*) b
4391 // where B is a subclass of A.
4392 //
4393 // Additionally, as for assignment, if either type is 'id'
4394 // allow silent coercion. Finally, if the types are
4395 // incompatible then make sure to use 'id' as the composite
4396 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004397
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004398 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
4399 // It could return the composite type.
4400 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
4401 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
4402 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
4403 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
4404 } else if ((LHSTy->isObjCQualifiedIdType() ||
4405 RHSTy->isObjCQualifiedIdType()) &&
4406 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
4407 // Need to handle "id<xx>" explicitly.
4408 // GCC allows qualified id and any Objective-C type to devolve to
4409 // id. Currently localizing to here until clear this should be
4410 // part of ObjCQualifiedIdTypesAreCompatible.
4411 compositeType = Context.getObjCIdType();
4412 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
4413 compositeType = Context.getObjCIdType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004414 } else if (!(compositeType =
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004415 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
4416 ;
4417 else {
4418 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
4419 << LHSTy << RHSTy
4420 << LHS->getSourceRange() << RHS->getSourceRange();
4421 QualType incompatTy = Context.getObjCIdType();
4422 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
4423 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
4424 return incompatTy;
4425 }
4426 // The object pointer types are compatible.
4427 ImpCastExprToType(LHS, compositeType, CastExpr::CK_BitCast);
4428 ImpCastExprToType(RHS, compositeType, CastExpr::CK_BitCast);
4429 return compositeType;
4430 }
4431 // Check Objective-C object pointer types and 'void *'
4432 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
4433 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4434 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4435 QualType destPointee
4436 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4437 QualType destType = Context.getPointerType(destPointee);
4438 // Add qualifiers if necessary.
4439 ImpCastExprToType(LHS, destType, CastExpr::CK_NoOp);
4440 // Promote to void*.
4441 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
4442 return destType;
4443 }
4444 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
4445 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4446 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4447 QualType destPointee
4448 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4449 QualType destType = Context.getPointerType(destPointee);
4450 // Add qualifiers if necessary.
4451 ImpCastExprToType(RHS, destType, CastExpr::CK_NoOp);
4452 // Promote to void*.
4453 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
4454 return destType;
4455 }
4456 return QualType();
4457}
4458
Steve Narofff69936d2007-09-16 03:34:24 +00004459/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Reid Spencer5f016e22007-07-11 17:01:13 +00004460/// in the case of a the GNU conditional expr extension.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004461Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
4462 SourceLocation ColonLoc,
4463 ExprArg Cond, ExprArg LHS,
4464 ExprArg RHS) {
4465 Expr *CondExpr = (Expr *) Cond.get();
4466 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
Chris Lattnera21ddb32007-11-26 01:40:58 +00004467
4468 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
4469 // was the condition.
4470 bool isLHSNull = LHSExpr == 0;
4471 if (isLHSNull)
4472 LHSExpr = CondExpr;
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004473
4474 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
Chris Lattner26824902007-07-16 21:39:03 +00004475 RHSExpr, QuestionLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00004476 if (result.isNull())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004477 return ExprError();
4478
4479 Cond.release();
4480 LHS.release();
4481 RHS.release();
Douglas Gregor47e1f7c2009-08-26 14:37:04 +00004482 return Owned(new (Context) ConditionalOperator(CondExpr, QuestionLoc,
Steve Naroff6ece14c2009-01-21 00:14:39 +00004483 isLHSNull ? 0 : LHSExpr,
Douglas Gregor47e1f7c2009-08-26 14:37:04 +00004484 ColonLoc, RHSExpr, result));
Reid Spencer5f016e22007-07-11 17:01:13 +00004485}
4486
Reid Spencer5f016e22007-07-11 17:01:13 +00004487// CheckPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stumpeed9cac2009-02-19 03:04:26 +00004488// being closely modeled after the C99 spec:-). The odd characteristic of this
Reid Spencer5f016e22007-07-11 17:01:13 +00004489// routine is it effectively iqnores the qualifiers on the top level pointee.
4490// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
4491// FIXME: add a couple examples in this comment.
Mike Stumpeed9cac2009-02-19 03:04:26 +00004492Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00004493Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
4494 QualType lhptee, rhptee;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004495
David Chisnall0f436562009-08-17 16:35:33 +00004496 if ((lhsType->isObjCClassType() &&
4497 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
4498 (rhsType->isObjCClassType() &&
4499 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
4500 return Compatible;
4501 }
4502
Reid Spencer5f016e22007-07-11 17:01:13 +00004503 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenek6217b802009-07-29 21:53:49 +00004504 lhptee = lhsType->getAs<PointerType>()->getPointeeType();
4505 rhptee = rhsType->getAs<PointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004506
Reid Spencer5f016e22007-07-11 17:01:13 +00004507 // make sure we operate on the canonical type
Chris Lattnerb77792e2008-07-26 22:17:49 +00004508 lhptee = Context.getCanonicalType(lhptee);
4509 rhptee = Context.getCanonicalType(rhptee);
Reid Spencer5f016e22007-07-11 17:01:13 +00004510
Chris Lattner5cf216b2008-01-04 18:04:52 +00004511 AssignConvertType ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004512
4513 // C99 6.5.16.1p1: This following citation is common to constraints
4514 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
4515 // qualifiers of the type *pointed to* by the right;
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00004516 // FIXME: Handle ExtQualType
Douglas Gregor98cd5992008-10-21 23:43:52 +00004517 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner5cf216b2008-01-04 18:04:52 +00004518 ConvTy = CompatiblePointerDiscardsQualifiers;
Reid Spencer5f016e22007-07-11 17:01:13 +00004519
Mike Stumpeed9cac2009-02-19 03:04:26 +00004520 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
4521 // incomplete type and the other is a pointer to a qualified or unqualified
Reid Spencer5f016e22007-07-11 17:01:13 +00004522 // version of void...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00004523 if (lhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00004524 if (rhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00004525 return ConvTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004526
Chris Lattnerbfe639e2008-01-03 22:56:36 +00004527 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00004528 assert(rhptee->isFunctionType());
4529 return FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00004530 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004531
Chris Lattnerbfe639e2008-01-03 22:56:36 +00004532 if (rhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00004533 if (lhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00004534 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00004535
4536 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00004537 assert(lhptee->isFunctionType());
4538 return FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00004539 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004540 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Reid Spencer5f016e22007-07-11 17:01:13 +00004541 // unqualified versions of compatible types, ...
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004542 lhptee = lhptee.getUnqualifiedType();
4543 rhptee = rhptee.getUnqualifiedType();
4544 if (!Context.typesAreCompatible(lhptee, rhptee)) {
4545 // Check if the pointee types are compatible ignoring the sign.
4546 // We explicitly check for char so that we catch "char" vs
4547 // "unsigned char" on systems where "char" is unsigned.
Chris Lattner6a2b9262009-10-17 20:33:28 +00004548 if (lhptee->isCharType())
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004549 lhptee = Context.UnsignedCharTy;
Chris Lattner6a2b9262009-10-17 20:33:28 +00004550 else if (lhptee->isSignedIntegerType())
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004551 lhptee = Context.getCorrespondingUnsignedType(lhptee);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004552
Chris Lattner6a2b9262009-10-17 20:33:28 +00004553 if (rhptee->isCharType())
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004554 rhptee = Context.UnsignedCharTy;
Chris Lattner6a2b9262009-10-17 20:33:28 +00004555 else if (rhptee->isSignedIntegerType())
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004556 rhptee = Context.getCorrespondingUnsignedType(rhptee);
Chris Lattner6a2b9262009-10-17 20:33:28 +00004557
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004558 if (lhptee == rhptee) {
4559 // Types are compatible ignoring the sign. Qualifier incompatibility
4560 // takes priority over sign incompatibility because the sign
4561 // warning can be disabled.
4562 if (ConvTy != Compatible)
4563 return ConvTy;
4564 return IncompatiblePointerSign;
4565 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004566
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00004567 // If we are a multi-level pointer, it's possible that our issue is simply
4568 // one of qualification - e.g. char ** -> const char ** is not allowed. If
4569 // the eventual target type is the same and the pointers have the same
4570 // level of indirection, this must be the issue.
4571 if (lhptee->isPointerType() && rhptee->isPointerType()) {
4572 do {
4573 lhptee = lhptee->getAs<PointerType>()->getPointeeType();
4574 rhptee = rhptee->getAs<PointerType>()->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004575
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00004576 lhptee = Context.getCanonicalType(lhptee);
4577 rhptee = Context.getCanonicalType(rhptee);
4578 } while (lhptee->isPointerType() && rhptee->isPointerType());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004579
Douglas Gregora4923eb2009-11-16 21:35:15 +00004580 if (Context.hasSameUnqualifiedType(lhptee, rhptee))
Sean Huntc9132b62009-11-08 07:46:34 +00004581 return IncompatibleNestedPointerQualifiers;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00004582 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004583
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004584 // General pointer incompatibility takes priority over qualifiers.
Mike Stump1eb44332009-09-09 15:08:12 +00004585 return IncompatiblePointer;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004586 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00004587 return ConvTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00004588}
4589
Steve Naroff1c7d0672008-09-04 15:10:53 +00004590/// CheckBlockPointerTypesForAssignment - This routine determines whether two
4591/// block pointer types are compatible or whether a block and normal pointer
4592/// are compatible. It is more restrict than comparing two function pointer
4593// types.
Mike Stumpeed9cac2009-02-19 03:04:26 +00004594Sema::AssignConvertType
4595Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
Steve Naroff1c7d0672008-09-04 15:10:53 +00004596 QualType rhsType) {
4597 QualType lhptee, rhptee;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004598
Steve Naroff1c7d0672008-09-04 15:10:53 +00004599 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenek6217b802009-07-29 21:53:49 +00004600 lhptee = lhsType->getAs<BlockPointerType>()->getPointeeType();
4601 rhptee = rhsType->getAs<BlockPointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004602
Steve Naroff1c7d0672008-09-04 15:10:53 +00004603 // make sure we operate on the canonical type
4604 lhptee = Context.getCanonicalType(lhptee);
4605 rhptee = Context.getCanonicalType(rhptee);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004606
Steve Naroff1c7d0672008-09-04 15:10:53 +00004607 AssignConvertType ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004608
Steve Naroff1c7d0672008-09-04 15:10:53 +00004609 // For blocks we enforce that qualifiers are identical.
Douglas Gregora4923eb2009-11-16 21:35:15 +00004610 if (lhptee.getLocalCVRQualifiers() != rhptee.getLocalCVRQualifiers())
Steve Naroff1c7d0672008-09-04 15:10:53 +00004611 ConvTy = CompatiblePointerDiscardsQualifiers;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004612
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004613 if (!getLangOptions().CPlusPlus) {
4614 if (!Context.typesAreBlockPointerCompatible(lhsType, rhsType))
4615 return IncompatibleBlockPointer;
4616 }
4617 else if (!Context.typesAreCompatible(lhptee, rhptee))
Mike Stumpeed9cac2009-02-19 03:04:26 +00004618 return IncompatibleBlockPointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00004619 return ConvTy;
4620}
4621
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00004622/// CheckObjCPointerTypesForAssignment - Compares two objective-c pointer types
4623/// for assignment compatibility.
4624Sema::AssignConvertType
4625Sema::CheckObjCPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00004626 if (lhsType->isObjCBuiltinType()) {
4627 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian528adb12010-03-24 21:00:27 +00004628 if (lhsType->isObjCClassType() && !rhsType->isObjCBuiltinType() &&
4629 !rhsType->isObjCQualifiedClassType())
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00004630 return IncompatiblePointer;
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00004631 return Compatible;
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00004632 }
4633 if (rhsType->isObjCBuiltinType()) {
4634 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian528adb12010-03-24 21:00:27 +00004635 if (rhsType->isObjCClassType() && !lhsType->isObjCBuiltinType() &&
4636 !lhsType->isObjCQualifiedClassType())
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00004637 return IncompatiblePointer;
4638 return Compatible;
4639 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004640 QualType lhptee =
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00004641 lhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004642 QualType rhptee =
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00004643 rhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
4644 // make sure we operate on the canonical type
4645 lhptee = Context.getCanonicalType(lhptee);
4646 rhptee = Context.getCanonicalType(rhptee);
4647 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
4648 return CompatiblePointerDiscardsQualifiers;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004649
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00004650 if (Context.typesAreCompatible(lhsType, rhsType))
4651 return Compatible;
4652 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
4653 return IncompatibleObjCQualifiedId;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004654 return IncompatiblePointer;
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00004655}
4656
Mike Stumpeed9cac2009-02-19 03:04:26 +00004657/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
4658/// has code to accommodate several GCC extensions when type checking
Reid Spencer5f016e22007-07-11 17:01:13 +00004659/// pointers. Here are some objectionable examples that GCC considers warnings:
4660///
4661/// int a, *pint;
4662/// short *pshort;
4663/// struct foo *pfoo;
4664///
4665/// pint = pshort; // warning: assignment from incompatible pointer type
4666/// a = pint; // warning: assignment makes integer from pointer without a cast
4667/// pint = a; // warning: assignment makes pointer from integer without a cast
4668/// pint = pfoo; // warning: assignment from incompatible pointer type
4669///
4670/// As a result, the code for dealing with pointers is more complex than the
Mike Stumpeed9cac2009-02-19 03:04:26 +00004671/// C99 spec dictates.
Reid Spencer5f016e22007-07-11 17:01:13 +00004672///
Chris Lattner5cf216b2008-01-04 18:04:52 +00004673Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00004674Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattnerfc144e22008-01-04 23:18:45 +00004675 // Get canonical types. We're not formatting these types, just comparing
4676 // them.
Chris Lattnerb77792e2008-07-26 22:17:49 +00004677 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
4678 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedmanf8f873d2008-05-30 18:07:22 +00004679
4680 if (lhsType == rhsType)
Chris Lattnerd2656dd2008-01-07 17:51:46 +00004681 return Compatible; // Common case: fast path an exact match.
Steve Naroff700204c2007-07-24 21:46:40 +00004682
David Chisnall0f436562009-08-17 16:35:33 +00004683 if ((lhsType->isObjCClassType() &&
4684 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
4685 (rhsType->isObjCClassType() &&
4686 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
4687 return Compatible;
4688 }
4689
Douglas Gregor9d293df2008-10-28 00:22:11 +00004690 // If the left-hand side is a reference type, then we are in a
4691 // (rare!) case where we've allowed the use of references in C,
4692 // e.g., as a parameter type in a built-in function. In this case,
4693 // just make sure that the type referenced is compatible with the
4694 // right-hand side type. The caller is responsible for adjusting
4695 // lhsType so that the resulting expression does not have reference
4696 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00004697 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
Douglas Gregor9d293df2008-10-28 00:22:11 +00004698 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlsson793680e2007-10-12 23:56:29 +00004699 return Compatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00004700 return Incompatible;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00004701 }
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004702 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
4703 // to the same ExtVector type.
4704 if (lhsType->isExtVectorType()) {
4705 if (rhsType->isExtVectorType())
4706 return lhsType == rhsType ? Compatible : Incompatible;
Douglas Gregor00619622010-06-22 23:41:02 +00004707 if (rhsType->isArithmeticType())
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004708 return Compatible;
4709 }
Mike Stump1eb44332009-09-09 15:08:12 +00004710
Nate Begemanbe2341d2008-07-14 18:02:46 +00004711 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00004712 // If we are allowing lax vector conversions, and LHS and RHS are both
Mike Stumpeed9cac2009-02-19 03:04:26 +00004713 // vectors, the total size only needs to be the same. This is a bitcast;
Nate Begemanbe2341d2008-07-14 18:02:46 +00004714 // no bits are changed but the result type is different.
Chris Lattnere8b3e962008-01-04 23:32:24 +00004715 if (getLangOptions().LaxVectorConversions &&
4716 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00004717 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00004718 return IncompatibleVectors;
Chris Lattnere8b3e962008-01-04 23:32:24 +00004719 }
4720 return Incompatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004721 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00004722
Douglas Gregor88623ad2010-05-23 21:53:47 +00004723 if (lhsType->isArithmeticType() && rhsType->isArithmeticType() &&
4724 !(getLangOptions().CPlusPlus && lhsType->isEnumeralType()))
Reid Spencer5f016e22007-07-11 17:01:13 +00004725 return Compatible;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00004726
Chris Lattner78eca282008-04-07 06:49:41 +00004727 if (isa<PointerType>(lhsType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00004728 if (rhsType->isIntegerType())
Chris Lattnerb7b61152008-01-04 18:22:42 +00004729 return IntToPointer;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00004730
Chris Lattner78eca282008-04-07 06:49:41 +00004731 if (isa<PointerType>(rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00004732 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004733
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004734 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff14108da2009-07-10 23:34:53 +00004735 if (isa<ObjCObjectPointerType>(rhsType)) {
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004736 if (lhsType->isVoidPointerType()) // an exception to the rule.
4737 return Compatible;
4738 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00004739 }
Ted Kremenek6217b802009-07-29 21:53:49 +00004740 if (rhsType->getAs<BlockPointerType>()) {
4741 if (lhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00004742 return Compatible;
Steve Naroffb4406862008-09-29 18:10:17 +00004743
4744 // Treat block pointers as objects.
Steve Naroff14108da2009-07-10 23:34:53 +00004745 if (getLangOptions().ObjC1 && lhsType->isObjCIdType())
Steve Naroffb4406862008-09-29 18:10:17 +00004746 return Compatible;
4747 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00004748 return Incompatible;
4749 }
4750
4751 if (isa<BlockPointerType>(lhsType)) {
4752 if (rhsType->isIntegerType())
Eli Friedmand8f4f432009-02-25 04:20:42 +00004753 return IntToBlockPointer;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004754
Steve Naroffb4406862008-09-29 18:10:17 +00004755 // Treat block pointers as objects.
Steve Naroff14108da2009-07-10 23:34:53 +00004756 if (getLangOptions().ObjC1 && rhsType->isObjCIdType())
Steve Naroffb4406862008-09-29 18:10:17 +00004757 return Compatible;
4758
Steve Naroff1c7d0672008-09-04 15:10:53 +00004759 if (rhsType->isBlockPointerType())
4760 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004761
Ted Kremenek6217b802009-07-29 21:53:49 +00004762 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff1c7d0672008-09-04 15:10:53 +00004763 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00004764 return Compatible;
Steve Naroff1c7d0672008-09-04 15:10:53 +00004765 }
Chris Lattnerfc144e22008-01-04 23:18:45 +00004766 return Incompatible;
4767 }
4768
Steve Naroff14108da2009-07-10 23:34:53 +00004769 if (isa<ObjCObjectPointerType>(lhsType)) {
4770 if (rhsType->isIntegerType())
4771 return IntToPointer;
Mike Stump1eb44332009-09-09 15:08:12 +00004772
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004773 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff14108da2009-07-10 23:34:53 +00004774 if (isa<PointerType>(rhsType)) {
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004775 if (rhsType->isVoidPointerType()) // an exception to the rule.
4776 return Compatible;
4777 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00004778 }
4779 if (rhsType->isObjCObjectPointerType()) {
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00004780 return CheckObjCPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff14108da2009-07-10 23:34:53 +00004781 }
Ted Kremenek6217b802009-07-29 21:53:49 +00004782 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00004783 if (RHSPT->getPointeeType()->isVoidType())
4784 return Compatible;
4785 }
4786 // Treat block pointers as objects.
4787 if (rhsType->isBlockPointerType())
4788 return Compatible;
4789 return Incompatible;
4790 }
Chris Lattner78eca282008-04-07 06:49:41 +00004791 if (isa<PointerType>(rhsType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00004792 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedmanf8f873d2008-05-30 18:07:22 +00004793 if (lhsType == Context.BoolTy)
4794 return Compatible;
4795
4796 if (lhsType->isIntegerType())
Chris Lattnerb7b61152008-01-04 18:22:42 +00004797 return PointerToInt;
Reid Spencer5f016e22007-07-11 17:01:13 +00004798
Mike Stumpeed9cac2009-02-19 03:04:26 +00004799 if (isa<PointerType>(lhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00004800 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004801
4802 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenek6217b802009-07-29 21:53:49 +00004803 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00004804 return Compatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00004805 return Incompatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00004806 }
Steve Naroff14108da2009-07-10 23:34:53 +00004807 if (isa<ObjCObjectPointerType>(rhsType)) {
4808 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
4809 if (lhsType == Context.BoolTy)
4810 return Compatible;
4811
4812 if (lhsType->isIntegerType())
4813 return PointerToInt;
4814
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004815 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff14108da2009-07-10 23:34:53 +00004816 if (isa<PointerType>(lhsType)) {
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004817 if (lhsType->isVoidPointerType()) // an exception to the rule.
4818 return Compatible;
4819 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00004820 }
4821 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenek6217b802009-07-29 21:53:49 +00004822 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Steve Naroff14108da2009-07-10 23:34:53 +00004823 return Compatible;
4824 return Incompatible;
4825 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00004826
Chris Lattnerfc144e22008-01-04 23:18:45 +00004827 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner78eca282008-04-07 06:49:41 +00004828 if (Context.typesAreCompatible(lhsType, rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00004829 return Compatible;
Reid Spencer5f016e22007-07-11 17:01:13 +00004830 }
4831 return Incompatible;
4832}
4833
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004834/// \brief Constructs a transparent union from an expression that is
4835/// used to initialize the transparent union.
Mike Stump1eb44332009-09-09 15:08:12 +00004836static void ConstructTransparentUnion(ASTContext &C, Expr *&E,
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004837 QualType UnionType, FieldDecl *Field) {
4838 // Build an initializer list that designates the appropriate member
4839 // of the transparent union.
Ted Kremenek709210f2010-04-13 23:39:13 +00004840 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
Ted Kremenekba7bc552010-02-19 01:50:18 +00004841 &E, 1,
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004842 SourceLocation());
4843 Initializer->setType(UnionType);
4844 Initializer->setInitializedFieldInUnion(Field);
4845
4846 // Build a compound literal constructing a value of the transparent
4847 // union type from this initializer list.
John McCall42f56b52010-01-18 19:35:47 +00004848 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John McCall1d7d8d62010-01-19 22:33:45 +00004849 E = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
John McCall42f56b52010-01-18 19:35:47 +00004850 Initializer, false);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004851}
4852
4853Sema::AssignConvertType
4854Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) {
4855 QualType FromType = rExpr->getType();
4856
Mike Stump1eb44332009-09-09 15:08:12 +00004857 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004858 // transparent_union GCC extension.
4859 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00004860 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004861 return Incompatible;
4862
4863 // The field to initialize within the transparent union.
4864 RecordDecl *UD = UT->getDecl();
4865 FieldDecl *InitField = 0;
4866 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004867 for (RecordDecl::field_iterator it = UD->field_begin(),
4868 itend = UD->field_end();
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004869 it != itend; ++it) {
4870 if (it->getType()->isPointerType()) {
4871 // If the transparent union contains a pointer type, we allow:
4872 // 1) void pointer
4873 // 2) null pointer constant
4874 if (FromType->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +00004875 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004876 ImpCastExprToType(rExpr, it->getType(), CastExpr::CK_BitCast);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004877 InitField = *it;
4878 break;
4879 }
Mike Stump1eb44332009-09-09 15:08:12 +00004880
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004881 if (rExpr->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00004882 Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004883 ImpCastExprToType(rExpr, it->getType(), CastExpr::CK_IntegralToPointer);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004884 InitField = *it;
4885 break;
4886 }
4887 }
4888
4889 if (CheckAssignmentConstraints(it->getType(), rExpr->getType())
4890 == Compatible) {
4891 InitField = *it;
4892 break;
4893 }
4894 }
4895
4896 if (!InitField)
4897 return Incompatible;
4898
4899 ConstructTransparentUnion(Context, rExpr, ArgType, InitField);
4900 return Compatible;
4901}
4902
Chris Lattner5cf216b2008-01-04 18:04:52 +00004903Sema::AssignConvertType
Steve Naroff90045e82007-07-13 23:32:42 +00004904Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00004905 if (getLangOptions().CPlusPlus) {
4906 if (!lhsType->isRecordType()) {
4907 // C++ 5.17p3: If the left operand is not of class type, the
4908 // expression is implicitly converted (C++ 4) to the
4909 // cv-unqualified type of the left operand.
Douglas Gregor45920e82008-12-19 17:40:08 +00004910 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
Douglas Gregor68647482009-12-16 03:45:30 +00004911 AA_Assigning))
Douglas Gregor98cd5992008-10-21 23:43:52 +00004912 return Incompatible;
Chris Lattner2c4463f2009-04-12 09:02:39 +00004913 return Compatible;
Douglas Gregor98cd5992008-10-21 23:43:52 +00004914 }
4915
4916 // FIXME: Currently, we fall through and treat C++ classes like C
4917 // structures.
4918 }
4919
Steve Naroff529a4ad2007-11-27 17:58:44 +00004920 // C99 6.5.16.1p1: the left operand is a pointer and the right is
4921 // a null pointer constant.
Mike Stump1eb44332009-09-09 15:08:12 +00004922 if ((lhsType->isPointerType() ||
4923 lhsType->isObjCObjectPointerType() ||
Mike Stumpeed9cac2009-02-19 03:04:26 +00004924 lhsType->isBlockPointerType())
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004925 && rExpr->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00004926 Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004927 ImpCastExprToType(rExpr, lhsType, CastExpr::CK_Unknown);
Steve Naroff529a4ad2007-11-27 17:58:44 +00004928 return Compatible;
4929 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004930
Chris Lattner943140e2007-10-16 02:55:40 +00004931 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroff90045e82007-07-13 23:32:42 +00004932 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregor02a24ee2009-11-03 16:56:39 +00004933 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Steve Naroff90045e82007-07-13 23:32:42 +00004934 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner943140e2007-10-16 02:55:40 +00004935 //
Mike Stumpeed9cac2009-02-19 03:04:26 +00004936 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner943140e2007-10-16 02:55:40 +00004937 if (!lhsType->isReferenceType())
Douglas Gregora873dfc2010-02-03 00:27:59 +00004938 DefaultFunctionArrayLvalueConversion(rExpr);
Steve Narofff1120de2007-08-24 22:33:52 +00004939
Chris Lattner5cf216b2008-01-04 18:04:52 +00004940 Sema::AssignConvertType result =
4941 CheckAssignmentConstraints(lhsType, rExpr->getType());
Mike Stumpeed9cac2009-02-19 03:04:26 +00004942
Steve Narofff1120de2007-08-24 22:33:52 +00004943 // C99 6.5.16.1p2: The value of the right operand is converted to the
4944 // type of the assignment expression.
Douglas Gregor9d293df2008-10-28 00:22:11 +00004945 // CheckAssignmentConstraints allows the left-hand side to be a reference,
4946 // so that we can use references in built-in functions even in C.
4947 // The getNonReferenceType() call makes sure that the resulting expression
4948 // does not have reference type.
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004949 if (result != Incompatible && rExpr->getType() != lhsType)
Douglas Gregor63982352010-07-13 18:40:04 +00004950 ImpCastExprToType(rExpr, lhsType.getNonLValueExprType(Context),
Eli Friedman73c39ab2009-10-20 08:27:19 +00004951 CastExpr::CK_Unknown);
Steve Narofff1120de2007-08-24 22:33:52 +00004952 return result;
Steve Naroff90045e82007-07-13 23:32:42 +00004953}
4954
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004955QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004956 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattner22caddc2008-11-23 09:13:29 +00004957 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004958 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerca5eede2007-12-12 05:47:28 +00004959 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00004960}
4961
Chris Lattner7ef655a2010-01-12 21:23:57 +00004962QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00004963 // For conversion purposes, we ignore any qualifiers.
Nate Begeman1330b0e2008-04-04 01:30:25 +00004964 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +00004965 QualType lhsType =
4966 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
4967 QualType rhsType =
4968 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004969
Nate Begemanbe2341d2008-07-14 18:02:46 +00004970 // If the vector types are identical, return.
Nate Begeman1330b0e2008-04-04 01:30:25 +00004971 if (lhsType == rhsType)
Reid Spencer5f016e22007-07-11 17:01:13 +00004972 return lhsType;
Nate Begeman4119d1a2007-12-30 02:59:45 +00004973
Nate Begemanbe2341d2008-07-14 18:02:46 +00004974 // Handle the case of a vector & extvector type of the same size and element
4975 // type. It would be nice if we only had one vector type someday.
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00004976 if (getLangOptions().LaxVectorConversions) {
4977 // FIXME: Should we warn here?
John McCall183700f2009-09-21 23:43:11 +00004978 if (const VectorType *LV = lhsType->getAs<VectorType>()) {
4979 if (const VectorType *RV = rhsType->getAs<VectorType>())
Nate Begemanbe2341d2008-07-14 18:02:46 +00004980 if (LV->getElementType() == RV->getElementType() &&
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00004981 LV->getNumElements() == RV->getNumElements()) {
Douglas Gregor26bcf672010-05-19 03:21:00 +00004982 if (lhsType->isExtVectorType()) {
4983 ImpCastExprToType(rex, lhsType, CastExpr::CK_BitCast);
4984 return lhsType;
4985 }
4986
4987 ImpCastExprToType(lex, rhsType, CastExpr::CK_BitCast);
4988 return rhsType;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00004989 }
4990 }
4991 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004992
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004993 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
4994 // swap back (so that we don't reverse the inputs to a subtract, for instance.
4995 bool swapped = false;
4996 if (rhsType->isExtVectorType()) {
4997 swapped = true;
4998 std::swap(rex, lex);
4999 std::swap(rhsType, lhsType);
5000 }
Mike Stump1eb44332009-09-09 15:08:12 +00005001
Nate Begemandde25982009-06-28 19:12:57 +00005002 // Handle the case of an ext vector and scalar.
John McCall183700f2009-09-21 23:43:11 +00005003 if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) {
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005004 QualType EltTy = LV->getElementType();
Douglas Gregor9d3347a2010-06-16 00:35:25 +00005005 if (EltTy->isIntegralType(Context) && rhsType->isIntegralType(Context)) {
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005006 if (Context.getIntegerTypeOrder(EltTy, rhsType) >= 0) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00005007 ImpCastExprToType(rex, lhsType, CastExpr::CK_IntegralCast);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005008 if (swapped) std::swap(rex, lex);
5009 return lhsType;
5010 }
5011 }
5012 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
5013 rhsType->isRealFloatingType()) {
5014 if (Context.getFloatingTypeOrder(EltTy, rhsType) >= 0) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00005015 ImpCastExprToType(rex, lhsType, CastExpr::CK_FloatingCast);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005016 if (swapped) std::swap(rex, lex);
5017 return lhsType;
5018 }
Nate Begeman4119d1a2007-12-30 02:59:45 +00005019 }
5020 }
Mike Stump1eb44332009-09-09 15:08:12 +00005021
Nate Begemandde25982009-06-28 19:12:57 +00005022 // Vectors of different size or scalar and non-ext-vector are errors.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00005023 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattnerd1625842008-11-24 06:25:27 +00005024 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00005025 << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00005026 return QualType();
Sebastian Redl22460502009-02-07 00:15:38 +00005027}
5028
Chris Lattner7ef655a2010-01-12 21:23:57 +00005029QualType Sema::CheckMultiplyDivideOperands(
5030 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign, bool isDiv) {
Daniel Dunbar69d1d002009-01-05 22:42:10 +00005031 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005032 return CheckVectorOperands(Loc, lex, rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005033
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00005034 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005035
Chris Lattner7ef655a2010-01-12 21:23:57 +00005036 if (!lex->getType()->isArithmeticType() ||
5037 !rex->getType()->isArithmeticType())
5038 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005039
Chris Lattner7ef655a2010-01-12 21:23:57 +00005040 // Check for division by zero.
5041 if (isDiv &&
5042 rex->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005043 DiagRuntimeBehavior(Loc, PDiag(diag::warn_division_by_zero)
Chris Lattnercb329c52010-01-12 21:30:55 +00005044 << rex->getSourceRange());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005045
Chris Lattner7ef655a2010-01-12 21:23:57 +00005046 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00005047}
5048
Chris Lattner7ef655a2010-01-12 21:23:57 +00005049QualType Sema::CheckRemainderOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00005050 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Daniel Dunbar523aa602009-01-05 22:55:36 +00005051 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
5052 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
5053 return CheckVectorOperands(Loc, lex, rex);
5054 return InvalidOperands(Loc, lex, rex);
5055 }
Steve Naroff90045e82007-07-13 23:32:42 +00005056
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00005057 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005058
Chris Lattner7ef655a2010-01-12 21:23:57 +00005059 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
5060 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005061
Chris Lattner7ef655a2010-01-12 21:23:57 +00005062 // Check for remainder by zero.
5063 if (rex->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
Chris Lattnercb329c52010-01-12 21:30:55 +00005064 DiagRuntimeBehavior(Loc, PDiag(diag::warn_remainder_by_zero)
5065 << rex->getSourceRange());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005066
Chris Lattner7ef655a2010-01-12 21:23:57 +00005067 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00005068}
5069
Chris Lattner7ef655a2010-01-12 21:23:57 +00005070QualType Sema::CheckAdditionOperands( // C99 6.5.6
Mike Stump1eb44332009-09-09 15:08:12 +00005071 Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00005072 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
5073 QualType compType = CheckVectorOperands(Loc, lex, rex);
5074 if (CompLHSTy) *CompLHSTy = compType;
5075 return compType;
5076 }
Steve Naroff49b45262007-07-13 16:58:59 +00005077
Eli Friedmanab3a8522009-03-28 01:22:36 +00005078 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Eli Friedmand72d16e2008-05-18 18:08:51 +00005079
Reid Spencer5f016e22007-07-11 17:01:13 +00005080 // handle the common case first (both operands are arithmetic).
Eli Friedmanab3a8522009-03-28 01:22:36 +00005081 if (lex->getType()->isArithmeticType() &&
5082 rex->getType()->isArithmeticType()) {
5083 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00005084 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00005085 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005086
Eli Friedmand72d16e2008-05-18 18:08:51 +00005087 // Put any potential pointer into PExp
5088 Expr* PExp = lex, *IExp = rex;
Steve Naroff58f9f2c2009-07-14 18:25:06 +00005089 if (IExp->getType()->isAnyPointerType())
Eli Friedmand72d16e2008-05-18 18:08:51 +00005090 std::swap(PExp, IExp);
5091
Steve Naroff58f9f2c2009-07-14 18:25:06 +00005092 if (PExp->getType()->isAnyPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00005093
Eli Friedmand72d16e2008-05-18 18:08:51 +00005094 if (IExp->getType()->isIntegerType()) {
Steve Naroff760e3c42009-07-13 21:20:41 +00005095 QualType PointeeTy = PExp->getType()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00005096
Chris Lattnerb5f15622009-04-24 23:50:08 +00005097 // Check for arithmetic on pointers to incomplete types.
5098 if (PointeeTy->isVoidType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +00005099 if (getLangOptions().CPlusPlus) {
5100 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005101 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor4ec339f2009-01-19 19:26:10 +00005102 return QualType();
Eli Friedmand72d16e2008-05-18 18:08:51 +00005103 }
Douglas Gregore7450f52009-03-24 19:52:54 +00005104
5105 // GNU extension: arithmetic on pointer to void
5106 Diag(Loc, diag::ext_gnu_void_ptr)
5107 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerb5f15622009-04-24 23:50:08 +00005108 } else if (PointeeTy->isFunctionType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +00005109 if (getLangOptions().CPlusPlus) {
5110 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
5111 << lex->getType() << lex->getSourceRange();
5112 return QualType();
5113 }
5114
5115 // GNU extension: arithmetic on pointer to function
5116 Diag(Loc, diag::ext_gnu_ptr_func_arith)
5117 << lex->getType() << lex->getSourceRange();
Steve Naroff9deaeca2009-07-13 21:32:29 +00005118 } else {
Steve Naroff760e3c42009-07-13 21:20:41 +00005119 // Check if we require a complete type.
Mike Stump1eb44332009-09-09 15:08:12 +00005120 if (((PExp->getType()->isPointerType() &&
Steve Naroff9deaeca2009-07-13 21:32:29 +00005121 !PExp->getType()->isDependentType()) ||
Steve Naroff760e3c42009-07-13 21:20:41 +00005122 PExp->getType()->isObjCObjectPointerType()) &&
5123 RequireCompleteType(Loc, PointeeTy,
Mike Stump1eb44332009-09-09 15:08:12 +00005124 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
5125 << PExp->getSourceRange()
Anders Carlssond497ba72009-08-26 22:59:12 +00005126 << PExp->getType()))
Steve Naroff760e3c42009-07-13 21:20:41 +00005127 return QualType();
5128 }
Chris Lattnerb5f15622009-04-24 23:50:08 +00005129 // Diagnose bad cases where we step over interface counts.
John McCallc12c5bb2010-05-15 11:32:37 +00005130 if (PointeeTy->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattnerb5f15622009-04-24 23:50:08 +00005131 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
5132 << PointeeTy << PExp->getSourceRange();
5133 return QualType();
5134 }
Mike Stump1eb44332009-09-09 15:08:12 +00005135
Eli Friedmanab3a8522009-03-28 01:22:36 +00005136 if (CompLHSTy) {
Eli Friedman04e83572009-08-20 04:21:42 +00005137 QualType LHSTy = Context.isPromotableBitField(lex);
5138 if (LHSTy.isNull()) {
5139 LHSTy = lex->getType();
5140 if (LHSTy->isPromotableIntegerType())
5141 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregor2d833e32009-05-02 00:36:19 +00005142 }
Eli Friedmanab3a8522009-03-28 01:22:36 +00005143 *CompLHSTy = LHSTy;
5144 }
Eli Friedmand72d16e2008-05-18 18:08:51 +00005145 return PExp->getType();
5146 }
5147 }
5148
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005149 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00005150}
5151
Chris Lattnereca7be62008-04-07 05:30:13 +00005152// C99 6.5.6
5153QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Eli Friedmanab3a8522009-03-28 01:22:36 +00005154 SourceLocation Loc, QualType* CompLHSTy) {
5155 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
5156 QualType compType = CheckVectorOperands(Loc, lex, rex);
5157 if (CompLHSTy) *CompLHSTy = compType;
5158 return compType;
5159 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005160
Eli Friedmanab3a8522009-03-28 01:22:36 +00005161 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005162
Chris Lattner6e4ab612007-12-09 21:53:25 +00005163 // Enforce type constraints: C99 6.5.6p3.
Mike Stumpeed9cac2009-02-19 03:04:26 +00005164
Chris Lattner6e4ab612007-12-09 21:53:25 +00005165 // Handle the common case first (both operands are arithmetic).
Mike Stumpaf199f32009-05-07 18:43:07 +00005166 if (lex->getType()->isArithmeticType()
5167 && rex->getType()->isArithmeticType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00005168 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00005169 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00005170 }
Mike Stump1eb44332009-09-09 15:08:12 +00005171
Chris Lattner6e4ab612007-12-09 21:53:25 +00005172 // Either ptr - int or ptr - ptr.
Steve Naroff58f9f2c2009-07-14 18:25:06 +00005173 if (lex->getType()->isAnyPointerType()) {
Steve Naroff430ee5a2009-07-13 17:19:15 +00005174 QualType lpointee = lex->getType()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005175
Douglas Gregore7450f52009-03-24 19:52:54 +00005176 // The LHS must be an completely-defined object type.
Douglas Gregorc983b862009-01-23 00:36:41 +00005177
Douglas Gregore7450f52009-03-24 19:52:54 +00005178 bool ComplainAboutVoid = false;
5179 Expr *ComplainAboutFunc = 0;
5180 if (lpointee->isVoidType()) {
5181 if (getLangOptions().CPlusPlus) {
5182 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
5183 << lex->getSourceRange() << rex->getSourceRange();
5184 return QualType();
5185 }
5186
5187 // GNU C extension: arithmetic on pointer to void
5188 ComplainAboutVoid = true;
5189 } else if (lpointee->isFunctionType()) {
5190 if (getLangOptions().CPlusPlus) {
5191 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattnerd1625842008-11-24 06:25:27 +00005192 << lex->getType() << lex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00005193 return QualType();
5194 }
Douglas Gregore7450f52009-03-24 19:52:54 +00005195
5196 // GNU C extension: arithmetic on pointer to function
5197 ComplainAboutFunc = lex;
5198 } else if (!lpointee->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00005199 RequireCompleteType(Loc, lpointee,
Anders Carlssond497ba72009-08-26 22:59:12 +00005200 PDiag(diag::err_typecheck_sub_ptr_object)
Mike Stump1eb44332009-09-09 15:08:12 +00005201 << lex->getSourceRange()
Anders Carlssond497ba72009-08-26 22:59:12 +00005202 << lex->getType()))
Douglas Gregore7450f52009-03-24 19:52:54 +00005203 return QualType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00005204
Chris Lattnerb5f15622009-04-24 23:50:08 +00005205 // Diagnose bad cases where we step over interface counts.
John McCallc12c5bb2010-05-15 11:32:37 +00005206 if (lpointee->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattnerb5f15622009-04-24 23:50:08 +00005207 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
5208 << lpointee << lex->getSourceRange();
5209 return QualType();
5210 }
Mike Stump1eb44332009-09-09 15:08:12 +00005211
Chris Lattner6e4ab612007-12-09 21:53:25 +00005212 // The result type of a pointer-int computation is the pointer type.
Douglas Gregore7450f52009-03-24 19:52:54 +00005213 if (rex->getType()->isIntegerType()) {
5214 if (ComplainAboutVoid)
5215 Diag(Loc, diag::ext_gnu_void_ptr)
5216 << lex->getSourceRange() << rex->getSourceRange();
5217 if (ComplainAboutFunc)
5218 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump1eb44332009-09-09 15:08:12 +00005219 << ComplainAboutFunc->getType()
Douglas Gregore7450f52009-03-24 19:52:54 +00005220 << ComplainAboutFunc->getSourceRange();
5221
Eli Friedmanab3a8522009-03-28 01:22:36 +00005222 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00005223 return lex->getType();
Douglas Gregore7450f52009-03-24 19:52:54 +00005224 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005225
Chris Lattner6e4ab612007-12-09 21:53:25 +00005226 // Handle pointer-pointer subtractions.
Ted Kremenek6217b802009-07-29 21:53:49 +00005227 if (const PointerType *RHSPTy = rex->getType()->getAs<PointerType>()) {
Eli Friedman8e54ad02008-02-08 01:19:44 +00005228 QualType rpointee = RHSPTy->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005229
Douglas Gregore7450f52009-03-24 19:52:54 +00005230 // RHS must be a completely-type object type.
5231 // Handle the GNU void* extension.
5232 if (rpointee->isVoidType()) {
5233 if (getLangOptions().CPlusPlus) {
5234 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
5235 << lex->getSourceRange() << rex->getSourceRange();
5236 return QualType();
5237 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005238
Douglas Gregore7450f52009-03-24 19:52:54 +00005239 ComplainAboutVoid = true;
5240 } else if (rpointee->isFunctionType()) {
5241 if (getLangOptions().CPlusPlus) {
5242 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattnerd1625842008-11-24 06:25:27 +00005243 << rex->getType() << rex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00005244 return QualType();
5245 }
Douglas Gregore7450f52009-03-24 19:52:54 +00005246
5247 // GNU extension: arithmetic on pointer to function
5248 if (!ComplainAboutFunc)
5249 ComplainAboutFunc = rex;
5250 } else if (!rpointee->isDependentType() &&
5251 RequireCompleteType(Loc, rpointee,
Anders Carlssond497ba72009-08-26 22:59:12 +00005252 PDiag(diag::err_typecheck_sub_ptr_object)
5253 << rex->getSourceRange()
5254 << rex->getType()))
Douglas Gregore7450f52009-03-24 19:52:54 +00005255 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005256
Eli Friedman88d936b2009-05-16 13:54:38 +00005257 if (getLangOptions().CPlusPlus) {
5258 // Pointee types must be the same: C++ [expr.add]
5259 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
5260 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
5261 << lex->getType() << rex->getType()
5262 << lex->getSourceRange() << rex->getSourceRange();
5263 return QualType();
5264 }
5265 } else {
5266 // Pointee types must be compatible C99 6.5.6p3
5267 if (!Context.typesAreCompatible(
5268 Context.getCanonicalType(lpointee).getUnqualifiedType(),
5269 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
5270 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
5271 << lex->getType() << rex->getType()
5272 << lex->getSourceRange() << rex->getSourceRange();
5273 return QualType();
5274 }
Chris Lattner6e4ab612007-12-09 21:53:25 +00005275 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005276
Douglas Gregore7450f52009-03-24 19:52:54 +00005277 if (ComplainAboutVoid)
5278 Diag(Loc, diag::ext_gnu_void_ptr)
5279 << lex->getSourceRange() << rex->getSourceRange();
5280 if (ComplainAboutFunc)
5281 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump1eb44332009-09-09 15:08:12 +00005282 << ComplainAboutFunc->getType()
Douglas Gregore7450f52009-03-24 19:52:54 +00005283 << ComplainAboutFunc->getSourceRange();
Eli Friedmanab3a8522009-03-28 01:22:36 +00005284
5285 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00005286 return Context.getPointerDiffType();
5287 }
5288 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005289
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005290 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00005291}
5292
Chris Lattnereca7be62008-04-07 05:30:13 +00005293// C99 6.5.7
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005294QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnereca7be62008-04-07 05:30:13 +00005295 bool isCompAssign) {
Chris Lattnerca5eede2007-12-12 05:47:28 +00005296 // C99 6.5.7p2: Each of the operands shall have integer type.
5297 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005298 return InvalidOperands(Loc, lex, rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005299
Nate Begeman2207d792009-10-25 02:26:48 +00005300 // Vector shifts promote their scalar inputs to vector type.
5301 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
5302 return CheckVectorOperands(Loc, lex, rex);
5303
Chris Lattnerca5eede2007-12-12 05:47:28 +00005304 // Shifts don't perform usual arithmetic conversions, they just do integer
5305 // promotions on each operand. C99 6.5.7p3
Eli Friedman04e83572009-08-20 04:21:42 +00005306 QualType LHSTy = Context.isPromotableBitField(lex);
5307 if (LHSTy.isNull()) {
5308 LHSTy = lex->getType();
5309 if (LHSTy->isPromotableIntegerType())
5310 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregor2d833e32009-05-02 00:36:19 +00005311 }
Chris Lattner1dcf2c82007-12-13 07:28:16 +00005312 if (!isCompAssign)
Eli Friedman73c39ab2009-10-20 08:27:19 +00005313 ImpCastExprToType(lex, LHSTy, CastExpr::CK_IntegralCast);
Eli Friedmanab3a8522009-03-28 01:22:36 +00005314
Chris Lattnerca5eede2007-12-12 05:47:28 +00005315 UsualUnaryConversions(rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005316
Ryan Flynnd0439682009-08-07 16:20:20 +00005317 // Sanity-check shift operands
5318 llvm::APSInt Right;
5319 // Check right/shifter operand
Daniel Dunbar3f180c62009-09-17 06:31:27 +00005320 if (!rex->isValueDependent() &&
5321 rex->isIntegerConstantExpr(Right, Context)) {
Ryan Flynn8045c732009-08-08 19:18:23 +00005322 if (Right.isNegative())
Ryan Flynnd0439682009-08-07 16:20:20 +00005323 Diag(Loc, diag::warn_shift_negative) << rex->getSourceRange();
5324 else {
5325 llvm::APInt LeftBits(Right.getBitWidth(),
5326 Context.getTypeSize(lex->getType()));
5327 if (Right.uge(LeftBits))
5328 Diag(Loc, diag::warn_shift_gt_typewidth) << rex->getSourceRange();
5329 }
5330 }
5331
Chris Lattnerca5eede2007-12-12 05:47:28 +00005332 // "The type of the result is that of the promoted left operand."
Eli Friedmanab3a8522009-03-28 01:22:36 +00005333 return LHSTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00005334}
5335
Chandler Carruth99919472010-07-10 12:30:03 +00005336static bool IsWithinTemplateSpecialization(Decl *D) {
5337 if (DeclContext *DC = D->getDeclContext()) {
5338 if (isa<ClassTemplateSpecializationDecl>(DC))
5339 return true;
5340 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
5341 return FD->isFunctionTemplateSpecialization();
5342 }
5343 return false;
5344}
5345
Douglas Gregor0c6db942009-05-04 06:07:12 +00005346// C99 6.5.8, C++ [expr.rel]
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005347QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Douglas Gregora86b8322009-04-06 18:45:53 +00005348 unsigned OpaqueOpc, bool isRelational) {
5349 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)OpaqueOpc;
5350
Chris Lattner02dd4b12009-12-05 05:40:13 +00005351 // Handle vector comparisons separately.
Nate Begemanbe2341d2008-07-14 18:02:46 +00005352 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005353 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005354
Steve Naroffc80b4ee2007-07-16 21:54:35 +00005355 QualType lType = lex->getType();
5356 QualType rType = rex->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005357
Douglas Gregor8eee1192010-06-22 22:12:46 +00005358 if (!lType->hasFloatingRepresentation() &&
5359 !(lType->isBlockPointerType() && isRelational)) {
Chris Lattner55660a72009-03-08 19:39:53 +00005360 // For non-floating point types, check for self-comparisons of the form
5361 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
5362 // often indicate logic errors in the program.
Chandler Carruth64d092c2010-07-12 06:23:38 +00005363 //
5364 // NOTE: Don't warn about comparison expressions resulting from macro
5365 // expansion. Also don't warn about comparisons which are only self
5366 // comparisons within a template specialization. The warnings should catch
5367 // obvious cases in the definition of the template anyways. The idea is to
5368 // warn when the typed comparison operator will always evaluate to the same
5369 // result.
Chris Lattner55660a72009-03-08 19:39:53 +00005370 Expr *LHSStripped = lex->IgnoreParens();
5371 Expr *RHSStripped = rex->IgnoreParens();
Chandler Carruth99919472010-07-10 12:30:03 +00005372 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
Douglas Gregord64fdd02010-06-08 19:50:34 +00005373 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
Chandler Carruth64d092c2010-07-12 06:23:38 +00005374 if (DRL->getDecl() == DRR->getDecl() && !Loc.isMacroID() &&
Chandler Carruth99919472010-07-10 12:30:03 +00005375 !IsWithinTemplateSpecialization(DRL->getDecl())) {
Douglas Gregord64fdd02010-06-08 19:50:34 +00005376 DiagRuntimeBehavior(Loc, PDiag(diag::warn_comparison_always)
5377 << 0 // self-
5378 << (Opc == BinaryOperator::EQ
5379 || Opc == BinaryOperator::LE
5380 || Opc == BinaryOperator::GE));
5381 } else if (lType->isArrayType() && rType->isArrayType() &&
5382 !DRL->getDecl()->getType()->isReferenceType() &&
5383 !DRR->getDecl()->getType()->isReferenceType()) {
5384 // what is it always going to eval to?
5385 char always_evals_to;
5386 switch(Opc) {
5387 case BinaryOperator::EQ: // e.g. array1 == array2
5388 always_evals_to = 0; // false
5389 break;
5390 case BinaryOperator::NE: // e.g. array1 != array2
5391 always_evals_to = 1; // true
5392 break;
5393 default:
5394 // best we can say is 'a constant'
5395 always_evals_to = 2; // e.g. array1 <= array2
5396 break;
5397 }
5398 DiagRuntimeBehavior(Loc, PDiag(diag::warn_comparison_always)
5399 << 1 // array
5400 << always_evals_to);
5401 }
5402 }
Chandler Carruth99919472010-07-10 12:30:03 +00005403 }
Mike Stump1eb44332009-09-09 15:08:12 +00005404
Chris Lattner55660a72009-03-08 19:39:53 +00005405 if (isa<CastExpr>(LHSStripped))
5406 LHSStripped = LHSStripped->IgnoreParenCasts();
5407 if (isa<CastExpr>(RHSStripped))
5408 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00005409
Chris Lattner55660a72009-03-08 19:39:53 +00005410 // Warn about comparisons against a string constant (unless the other
5411 // operand is null), the user probably wants strcmp.
Douglas Gregora86b8322009-04-06 18:45:53 +00005412 Expr *literalString = 0;
5413 Expr *literalStringStripped = 0;
Chris Lattner55660a72009-03-08 19:39:53 +00005414 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005415 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00005416 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregora86b8322009-04-06 18:45:53 +00005417 literalString = lex;
5418 literalStringStripped = LHSStripped;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00005419 } else if ((isa<StringLiteral>(RHSStripped) ||
5420 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005421 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00005422 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregora86b8322009-04-06 18:45:53 +00005423 literalString = rex;
5424 literalStringStripped = RHSStripped;
5425 }
5426
5427 if (literalString) {
5428 std::string resultComparison;
5429 switch (Opc) {
5430 case BinaryOperator::LT: resultComparison = ") < 0"; break;
5431 case BinaryOperator::GT: resultComparison = ") > 0"; break;
5432 case BinaryOperator::LE: resultComparison = ") <= 0"; break;
5433 case BinaryOperator::GE: resultComparison = ") >= 0"; break;
5434 case BinaryOperator::EQ: resultComparison = ") == 0"; break;
5435 case BinaryOperator::NE: resultComparison = ") != 0"; break;
5436 default: assert(false && "Invalid comparison operator");
5437 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005438
Douglas Gregord1e4d9b2010-01-12 23:18:54 +00005439 DiagRuntimeBehavior(Loc,
5440 PDiag(diag::warn_stringcompare)
5441 << isa<ObjCEncodeExpr>(literalStringStripped)
Ted Kremenek03a4bee2010-04-09 20:26:53 +00005442 << literalString->getSourceRange());
Douglas Gregora86b8322009-04-06 18:45:53 +00005443 }
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00005444 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005445
Douglas Gregord64fdd02010-06-08 19:50:34 +00005446 // C99 6.5.8p3 / C99 6.5.9p4
5447 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
5448 UsualArithmeticConversions(lex, rex);
5449 else {
5450 UsualUnaryConversions(lex);
5451 UsualUnaryConversions(rex);
5452 }
5453
5454 lType = lex->getType();
5455 rType = rex->getType();
5456
Douglas Gregor447b69e2008-11-19 03:25:36 +00005457 // The result of comparisons is 'bool' in C++, 'int' in C.
Chris Lattner02dd4b12009-12-05 05:40:13 +00005458 QualType ResultTy = getLangOptions().CPlusPlus ? Context.BoolTy:Context.IntTy;
Douglas Gregor447b69e2008-11-19 03:25:36 +00005459
Chris Lattnera5937dd2007-08-26 01:18:55 +00005460 if (isRelational) {
5461 if (lType->isRealType() && rType->isRealType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00005462 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00005463 } else {
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00005464 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor8eee1192010-06-22 22:12:46 +00005465 if (lType->hasFloatingRepresentation())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005466 CheckFloatComparison(Loc,lex,rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005467
Chris Lattnera5937dd2007-08-26 01:18:55 +00005468 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00005469 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00005470 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005471
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005472 bool LHSIsNull = lex->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00005473 Expr::NPC_ValueDependentIsNull);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005474 bool RHSIsNull = rex->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00005475 Expr::NPC_ValueDependentIsNull);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005476
Douglas Gregor6e5122c2010-06-15 21:38:40 +00005477 // All of the following pointer-related warnings are GCC extensions, except
5478 // when handling null pointer constants.
Steve Naroff77878cc2007-08-27 04:08:11 +00005479 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00005480 QualType LCanPointeeTy =
Ted Kremenek6217b802009-07-29 21:53:49 +00005481 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattnerbc896f52008-04-03 05:07:25 +00005482 QualType RCanPointeeTy =
Ted Kremenek6217b802009-07-29 21:53:49 +00005483 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stumpeed9cac2009-02-19 03:04:26 +00005484
Douglas Gregor0c6db942009-05-04 06:07:12 +00005485 if (getLangOptions().CPlusPlus) {
Eli Friedman3075e762009-08-23 00:27:47 +00005486 if (LCanPointeeTy == RCanPointeeTy)
5487 return ResultTy;
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00005488 if (!isRelational &&
5489 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
5490 // Valid unless comparison between non-null pointer and function pointer
5491 // This is a gcc extension compatibility comparison.
Douglas Gregor6e5122c2010-06-15 21:38:40 +00005492 // In a SFINAE context, we treat this as a hard error to maintain
5493 // conformance with the C++ standard.
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00005494 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
5495 && !LHSIsNull && !RHSIsNull) {
Douglas Gregor6e5122c2010-06-15 21:38:40 +00005496 Diag(Loc,
5497 isSFINAEContext()?
5498 diag::err_typecheck_comparison_of_fptr_to_void
5499 : diag::ext_typecheck_comparison_of_fptr_to_void)
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00005500 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor6e5122c2010-06-15 21:38:40 +00005501
5502 if (isSFINAEContext())
5503 return QualType();
5504
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00005505 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
5506 return ResultTy;
5507 }
5508 }
Douglas Gregor0c6db942009-05-04 06:07:12 +00005509 // C++ [expr.rel]p2:
5510 // [...] Pointer conversions (4.10) and qualification
5511 // conversions (4.4) are performed on pointer operands (or on
5512 // a pointer operand and a null pointer constant) to bring
5513 // them to their composite pointer type. [...]
5514 //
Douglas Gregor20b3e992009-08-24 17:42:35 +00005515 // C++ [expr.eq]p1 uses the same notion for (in)equality
Douglas Gregor0c6db942009-05-04 06:07:12 +00005516 // comparisons of pointers.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00005517 bool NonStandardCompositeType = false;
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00005518 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00005519 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregor0c6db942009-05-04 06:07:12 +00005520 if (T.isNull()) {
5521 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
5522 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5523 return QualType();
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00005524 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005525 Diag(Loc,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00005526 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005527 << lType << rType << T
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00005528 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor0c6db942009-05-04 06:07:12 +00005529 }
5530
Eli Friedman73c39ab2009-10-20 08:27:19 +00005531 ImpCastExprToType(lex, T, CastExpr::CK_BitCast);
5532 ImpCastExprToType(rex, T, CastExpr::CK_BitCast);
Douglas Gregor0c6db942009-05-04 06:07:12 +00005533 return ResultTy;
5534 }
Eli Friedman3075e762009-08-23 00:27:47 +00005535 // C99 6.5.9p2 and C99 6.5.8p2
5536 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
5537 RCanPointeeTy.getUnqualifiedType())) {
5538 // Valid unless a relational comparison of function pointers
5539 if (isRelational && LCanPointeeTy->isFunctionType()) {
5540 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
5541 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5542 }
5543 } else if (!isRelational &&
5544 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
5545 // Valid unless comparison between non-null pointer and function pointer
5546 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
5547 && !LHSIsNull && !RHSIsNull) {
5548 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
5549 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5550 }
5551 } else {
5552 // Invalid
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00005553 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattnerd1625842008-11-24 06:25:27 +00005554 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00005555 }
Eli Friedman3075e762009-08-23 00:27:47 +00005556 if (LCanPointeeTy != RCanPointeeTy)
Eli Friedman73c39ab2009-10-20 08:27:19 +00005557 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005558 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00005559 }
Mike Stump1eb44332009-09-09 15:08:12 +00005560
Sebastian Redl6e8ed162009-05-10 18:38:11 +00005561 if (getLangOptions().CPlusPlus) {
Mike Stump1eb44332009-09-09 15:08:12 +00005562 // Comparison of pointers with null pointer constants and equality
Douglas Gregor20b3e992009-08-24 17:42:35 +00005563 // comparisons of member pointers to null pointer constants.
Mike Stump1eb44332009-09-09 15:08:12 +00005564 if (RHSIsNull &&
Douglas Gregor20b3e992009-08-24 17:42:35 +00005565 (lType->isPointerType() ||
5566 (!isRelational && lType->isMemberPointerType()))) {
Anders Carlsson26ba8502009-08-24 18:03:14 +00005567 ImpCastExprToType(rex, lType, CastExpr::CK_NullToMemberPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00005568 return ResultTy;
5569 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00005570 if (LHSIsNull &&
5571 (rType->isPointerType() ||
5572 (!isRelational && rType->isMemberPointerType()))) {
Anders Carlsson26ba8502009-08-24 18:03:14 +00005573 ImpCastExprToType(lex, rType, CastExpr::CK_NullToMemberPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00005574 return ResultTy;
5575 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00005576
5577 // Comparison of member pointers.
Mike Stump1eb44332009-09-09 15:08:12 +00005578 if (!isRelational &&
Douglas Gregor20b3e992009-08-24 17:42:35 +00005579 lType->isMemberPointerType() && rType->isMemberPointerType()) {
5580 // C++ [expr.eq]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00005581 // In addition, pointers to members can be compared, or a pointer to
5582 // member and a null pointer constant. Pointer to member conversions
5583 // (4.11) and qualification conversions (4.4) are performed to bring
5584 // them to a common type. If one operand is a null pointer constant,
5585 // the common type is the type of the other operand. Otherwise, the
5586 // common type is a pointer to member type similar (4.4) to the type
5587 // of one of the operands, with a cv-qualification signature (4.4)
5588 // that is the union of the cv-qualification signatures of the operand
Douglas Gregor20b3e992009-08-24 17:42:35 +00005589 // types.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00005590 bool NonStandardCompositeType = false;
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00005591 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00005592 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregor20b3e992009-08-24 17:42:35 +00005593 if (T.isNull()) {
5594 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00005595 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor20b3e992009-08-24 17:42:35 +00005596 return QualType();
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00005597 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005598 Diag(Loc,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00005599 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005600 << lType << rType << T
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00005601 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor20b3e992009-08-24 17:42:35 +00005602 }
Mike Stump1eb44332009-09-09 15:08:12 +00005603
Eli Friedman73c39ab2009-10-20 08:27:19 +00005604 ImpCastExprToType(lex, T, CastExpr::CK_BitCast);
5605 ImpCastExprToType(rex, T, CastExpr::CK_BitCast);
Douglas Gregor20b3e992009-08-24 17:42:35 +00005606 return ResultTy;
5607 }
Mike Stump1eb44332009-09-09 15:08:12 +00005608
Douglas Gregor20b3e992009-08-24 17:42:35 +00005609 // Comparison of nullptr_t with itself.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00005610 if (lType->isNullPtrType() && rType->isNullPtrType())
5611 return ResultTy;
5612 }
Mike Stump1eb44332009-09-09 15:08:12 +00005613
Steve Naroff1c7d0672008-09-04 15:10:53 +00005614 // Handle block pointer types.
Mike Stumpdd3e1662009-05-07 03:14:14 +00005615 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00005616 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
5617 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005618
Steve Naroff1c7d0672008-09-04 15:10:53 +00005619 if (!LHSIsNull && !RHSIsNull &&
Eli Friedman26784c12009-06-08 05:08:54 +00005620 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00005621 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattnerd1625842008-11-24 06:25:27 +00005622 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff1c7d0672008-09-04 15:10:53 +00005623 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00005624 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005625 return ResultTy;
Steve Naroff1c7d0672008-09-04 15:10:53 +00005626 }
Steve Naroff59f53942008-09-28 01:11:11 +00005627 // Allow block pointers to be compared with null pointer constants.
Mike Stumpdd3e1662009-05-07 03:14:14 +00005628 if (!isRelational
5629 && ((lType->isBlockPointerType() && rType->isPointerType())
5630 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Naroff59f53942008-09-28 01:11:11 +00005631 if (!LHSIsNull && !RHSIsNull) {
Ted Kremenek6217b802009-07-29 21:53:49 +00005632 if (!((rType->isPointerType() && rType->getAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00005633 ->getPointeeType()->isVoidType())
Ted Kremenek6217b802009-07-29 21:53:49 +00005634 || (lType->isPointerType() && lType->getAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00005635 ->getPointeeType()->isVoidType())))
5636 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
5637 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff59f53942008-09-28 01:11:11 +00005638 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00005639 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005640 return ResultTy;
Steve Naroff59f53942008-09-28 01:11:11 +00005641 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00005642
Steve Naroff14108da2009-07-10 23:34:53 +00005643 if ((lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType())) {
Steve Naroffa5ad8632008-10-27 10:33:19 +00005644 if (lType->isPointerType() || rType->isPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00005645 const PointerType *LPT = lType->getAs<PointerType>();
5646 const PointerType *RPT = rType->getAs<PointerType>();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005647 bool LPtrToVoid = LPT ?
Steve Naroffa8069f12008-11-17 19:49:16 +00005648 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005649 bool RPtrToVoid = RPT ?
Steve Naroffa8069f12008-11-17 19:49:16 +00005650 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005651
Steve Naroffa8069f12008-11-17 19:49:16 +00005652 if (!LPtrToVoid && !RPtrToVoid &&
5653 !Context.typesAreCompatible(lType, rType)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00005654 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattnerd1625842008-11-24 06:25:27 +00005655 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroffa5ad8632008-10-27 10:33:19 +00005656 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00005657 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005658 return ResultTy;
Steve Naroff87f3b932008-10-20 18:19:10 +00005659 }
Steve Naroff14108da2009-07-10 23:34:53 +00005660 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00005661 if (!Context.areComparableObjCPointerTypes(lType, rType))
Steve Naroff14108da2009-07-10 23:34:53 +00005662 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
5663 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00005664 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005665 return ResultTy;
Steve Naroff20373222008-06-03 14:04:54 +00005666 }
Fariborz Jahanian7359f042007-12-20 01:06:58 +00005667 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00005668 if ((lType->isAnyPointerType() && rType->isIntegerType()) ||
5669 (lType->isIntegerType() && rType->isAnyPointerType())) {
Chris Lattner06c0f5b2009-08-23 00:03:44 +00005670 unsigned DiagID = 0;
Douglas Gregor6e5122c2010-06-15 21:38:40 +00005671 bool isError = false;
5672 if ((LHSIsNull && lType->isIntegerType()) ||
5673 (RHSIsNull && rType->isIntegerType())) {
5674 if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattner06c0f5b2009-08-23 00:03:44 +00005675 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
Douglas Gregor6e5122c2010-06-15 21:38:40 +00005676 } else if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattner06c0f5b2009-08-23 00:03:44 +00005677 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
Douglas Gregor6e5122c2010-06-15 21:38:40 +00005678 else if (getLangOptions().CPlusPlus) {
5679 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
5680 isError = true;
5681 } else
Chris Lattner06c0f5b2009-08-23 00:03:44 +00005682 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump1eb44332009-09-09 15:08:12 +00005683
Chris Lattner06c0f5b2009-08-23 00:03:44 +00005684 if (DiagID) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00005685 Diag(Loc, DiagID)
Chris Lattner149f1382009-06-30 06:24:05 +00005686 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor6e5122c2010-06-15 21:38:40 +00005687 if (isError)
5688 return QualType();
Chris Lattner6365e3e2009-08-22 18:58:31 +00005689 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00005690
5691 if (lType->isIntegerType())
5692 ImpCastExprToType(lex, rType, CastExpr::CK_IntegralToPointer);
Chris Lattner06c0f5b2009-08-23 00:03:44 +00005693 else
Douglas Gregor6e5122c2010-06-15 21:38:40 +00005694 ImpCastExprToType(rex, lType, CastExpr::CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005695 return ResultTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00005696 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00005697
Steve Naroff39218df2008-09-04 16:56:14 +00005698 // Handle block pointers.
Mike Stumpaf199f32009-05-07 18:43:07 +00005699 if (!isRelational && RHSIsNull
5700 && lType->isBlockPointerType() && rType->isIntegerType()) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00005701 ImpCastExprToType(rex, lType, CastExpr::CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005702 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00005703 }
Mike Stumpaf199f32009-05-07 18:43:07 +00005704 if (!isRelational && LHSIsNull
5705 && lType->isIntegerType() && rType->isBlockPointerType()) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00005706 ImpCastExprToType(lex, rType, CastExpr::CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005707 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00005708 }
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005709 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00005710}
5711
Nate Begemanbe2341d2008-07-14 18:02:46 +00005712/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stumpeed9cac2009-02-19 03:04:26 +00005713/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begemanbe2341d2008-07-14 18:02:46 +00005714/// like a scalar comparison, a vector comparison produces a vector of integer
5715/// types.
5716QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005717 SourceLocation Loc,
Nate Begemanbe2341d2008-07-14 18:02:46 +00005718 bool isRelational) {
5719 // Check to make sure we're operating on vectors of the same type and width,
5720 // Allowing one side to be a scalar of element type.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005721 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanbe2341d2008-07-14 18:02:46 +00005722 if (vType.isNull())
5723 return vType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005724
Nate Begemanbe2341d2008-07-14 18:02:46 +00005725 QualType lType = lex->getType();
5726 QualType rType = rex->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005727
Nate Begemanbe2341d2008-07-14 18:02:46 +00005728 // For non-floating point types, check for self-comparisons of the form
5729 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
5730 // often indicate logic errors in the program.
Douglas Gregor8eee1192010-06-22 22:12:46 +00005731 if (!lType->hasFloatingRepresentation()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00005732 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
5733 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
5734 if (DRL->getDecl() == DRR->getDecl())
Douglas Gregord64fdd02010-06-08 19:50:34 +00005735 DiagRuntimeBehavior(Loc,
5736 PDiag(diag::warn_comparison_always)
5737 << 0 // self-
5738 << 2 // "a constant"
5739 );
Nate Begemanbe2341d2008-07-14 18:02:46 +00005740 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005741
Nate Begemanbe2341d2008-07-14 18:02:46 +00005742 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor8eee1192010-06-22 22:12:46 +00005743 if (!isRelational && lType->hasFloatingRepresentation()) {
5744 assert (rType->hasFloatingRepresentation());
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005745 CheckFloatComparison(Loc,lex,rex);
Nate Begemanbe2341d2008-07-14 18:02:46 +00005746 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005747
Nate Begemanbe2341d2008-07-14 18:02:46 +00005748 // Return the type for the comparison, which is the same as vector type for
5749 // integer vectors, or an integer type of identical size and number of
5750 // elements for floating point vectors.
5751 if (lType->isIntegerType())
5752 return lType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005753
John McCall183700f2009-09-21 23:43:11 +00005754 const VectorType *VTy = lType->getAs<VectorType>();
Nate Begemanbe2341d2008-07-14 18:02:46 +00005755 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman59b5da62009-01-18 03:20:47 +00005756 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanbe2341d2008-07-14 18:02:46 +00005757 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattnerd013aa12009-03-31 07:46:52 +00005758 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman59b5da62009-01-18 03:20:47 +00005759 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
5760
Mike Stumpeed9cac2009-02-19 03:04:26 +00005761 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman59b5da62009-01-18 03:20:47 +00005762 "Unhandled vector element size in vector compare");
Nate Begemanbe2341d2008-07-14 18:02:46 +00005763 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
5764}
5765
Reid Spencer5f016e22007-07-11 17:01:13 +00005766inline QualType Sema::CheckBitwiseOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00005767 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Steve Naroff3e5e5562007-07-16 22:23:01 +00005768 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005769 return CheckVectorOperands(Loc, lex, rex);
Steve Naroff90045e82007-07-13 23:32:42 +00005770
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00005771 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005772
Steve Naroffa4332e22007-07-17 00:58:39 +00005773 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00005774 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005775 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00005776}
5777
5778inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Chris Lattner90a8f272010-07-13 19:41:32 +00005779 Expr *&lex, Expr *&rex, SourceLocation Loc, unsigned Opc) {
5780
5781 // Diagnose cases where the user write a logical and/or but probably meant a
5782 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
5783 // is a constant.
5784 if (lex->getType()->isIntegerType() && !lex->getType()->isBooleanType() &&
5785 rex->getType()->isIntegerType() && rex->isEvaluatable(Context) &&
Chris Lattner23ef3e42010-07-15 00:26:43 +00005786 // Don't warn if the RHS is a (constant folded) boolean expression like
5787 // "sizeof(int) == 4".
5788 !rex->isKnownToHaveBooleanValue() &&
5789 // Don't warn in macros.
Chris Lattner90a8f272010-07-13 19:41:32 +00005790 !Loc.isMacroID())
5791 Diag(Loc, diag::warn_logical_instead_of_bitwise)
5792 << rex->getSourceRange()
5793 << (Opc == BinaryOperator::LAnd ? "&&" : "||")
5794 << (Opc == BinaryOperator::LAnd ? "&" : "|");
5795
5796
5797
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005798 if (!Context.getLangOptions().CPlusPlus) {
5799 UsualUnaryConversions(lex);
5800 UsualUnaryConversions(rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005801
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005802 if (!lex->getType()->isScalarType() || !rex->getType()->isScalarType())
5803 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005804
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005805 return Context.IntTy;
Anders Carlsson04905012009-10-16 01:44:21 +00005806 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005807
John McCall75f7c0f2010-06-04 00:29:51 +00005808 // The following is safe because we only use this method for
5809 // non-overloadable operands.
5810
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005811 // C++ [expr.log.and]p1
5812 // C++ [expr.log.or]p1
John McCall75f7c0f2010-06-04 00:29:51 +00005813 // The operands are both contextually converted to type bool.
5814 if (PerformContextuallyConvertToBool(lex) ||
5815 PerformContextuallyConvertToBool(rex))
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005816 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005817
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005818 // C++ [expr.log.and]p2
5819 // C++ [expr.log.or]p2
5820 // The result is a bool.
5821 return Context.BoolTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00005822}
5823
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00005824/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
5825/// is a read-only property; return true if so. A readonly property expression
5826/// depends on various declarations and thus must be treated specially.
5827///
Mike Stump1eb44332009-09-09 15:08:12 +00005828static bool IsReadonlyProperty(Expr *E, Sema &S) {
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00005829 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
5830 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
5831 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
5832 QualType BaseType = PropExpr->getBase()->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00005833 if (const ObjCObjectPointerType *OPT =
Steve Naroff14108da2009-07-10 23:34:53 +00005834 BaseType->getAsObjCInterfacePointerType())
5835 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
5836 if (S.isPropertyReadonly(PDecl, IFace))
5837 return true;
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00005838 }
5839 }
5840 return false;
5841}
5842
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005843/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
5844/// emit an error and return true. If so, return false.
5845static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbar44e35f72009-04-15 00:08:05 +00005846 SourceLocation OrigLoc = Loc;
Mike Stump1eb44332009-09-09 15:08:12 +00005847 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbar44e35f72009-04-15 00:08:05 +00005848 &Loc);
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00005849 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
5850 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005851 if (IsLV == Expr::MLV_Valid)
5852 return false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005853
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005854 unsigned Diag = 0;
5855 bool NeedType = false;
5856 switch (IsLV) { // C99 6.5.16p2
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005857 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005858 case Expr::MLV_ArrayType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005859 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
5860 NeedType = true;
5861 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005862 case Expr::MLV_NotObjectType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005863 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
5864 NeedType = true;
5865 break;
Chris Lattnerca354fa2008-11-17 19:51:54 +00005866 case Expr::MLV_LValueCast:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005867 Diag = diag::err_typecheck_lvalue_casts_not_supported;
5868 break;
Douglas Gregore873fb72010-02-16 21:39:57 +00005869 case Expr::MLV_Valid:
5870 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner5cf216b2008-01-04 18:04:52 +00005871 case Expr::MLV_InvalidExpression:
Douglas Gregore873fb72010-02-16 21:39:57 +00005872 case Expr::MLV_MemberFunction:
5873 case Expr::MLV_ClassTemporary:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005874 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
5875 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00005876 case Expr::MLV_IncompleteType:
5877 case Expr::MLV_IncompleteVoidType:
Douglas Gregor86447ec2009-03-09 16:13:40 +00005878 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00005879 S.PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
Anders Carlssonb7906612009-08-26 23:45:07 +00005880 << E->getSourceRange());
Chris Lattner5cf216b2008-01-04 18:04:52 +00005881 case Expr::MLV_DuplicateVectorComponents:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005882 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
5883 break;
Steve Naroff4f6a7d72008-09-26 14:41:28 +00005884 case Expr::MLV_NotBlockQualified:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005885 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
5886 break;
Fariborz Jahanian5daf5702008-11-22 18:39:36 +00005887 case Expr::MLV_ReadonlyProperty:
5888 Diag = diag::error_readonly_property_assignment;
5889 break;
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00005890 case Expr::MLV_NoSetterProperty:
5891 Diag = diag::error_nosetter_property_assignment;
5892 break;
Fariborz Jahanian2514a302009-12-15 23:59:41 +00005893 case Expr::MLV_SubObjCPropertySetting:
5894 Diag = diag::error_no_subobject_property_setting;
5895 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00005896 }
Steve Naroffd1861fd2007-07-31 12:34:36 +00005897
Daniel Dunbar44e35f72009-04-15 00:08:05 +00005898 SourceRange Assign;
5899 if (Loc != OrigLoc)
5900 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005901 if (NeedType)
Daniel Dunbar44e35f72009-04-15 00:08:05 +00005902 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005903 else
Mike Stump1eb44332009-09-09 15:08:12 +00005904 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005905 return true;
5906}
5907
5908
5909
5910// C99 6.5.16.1
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005911QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
5912 SourceLocation Loc,
5913 QualType CompoundType) {
5914 // Verify that LHS is a modifiable lvalue, and emit error if not.
5915 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005916 return QualType();
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005917
5918 QualType LHSType = LHS->getType();
5919 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Chris Lattner5cf216b2008-01-04 18:04:52 +00005920 AssignConvertType ConvTy;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005921 if (CompoundType.isNull()) {
Fariborz Jahaniane2a901a2010-06-07 22:02:01 +00005922 QualType LHSTy(LHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00005923 // Simple assignment "x = y".
Fariborz Jahaniane2a901a2010-06-07 22:02:01 +00005924 if (const ObjCImplicitSetterGetterRefExpr *OISGE =
5925 dyn_cast<ObjCImplicitSetterGetterRefExpr>(LHS)) {
5926 // If using property-dot syntax notation for assignment, and there is a
5927 // setter, RHS expression is being passed to the setter argument. So,
5928 // type conversion (and comparison) is RHS to setter's argument type.
5929 if (const ObjCMethodDecl *SetterMD = OISGE->getSetterMethod()) {
5930 ObjCMethodDecl::param_iterator P = SetterMD->param_begin();
5931 LHSTy = (*P)->getType();
5932 }
5933 }
5934
5935 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00005936 // Special case of NSObject attributes on c-style pointer types.
5937 if (ConvTy == IncompatiblePointer &&
5938 ((Context.isObjCNSObjectType(LHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00005939 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00005940 (Context.isObjCNSObjectType(RHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00005941 LHSType->isObjCObjectPointerType())))
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00005942 ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005943
Chris Lattner2c156472008-08-21 18:04:13 +00005944 // If the RHS is a unary plus or minus, check to see if they = and + are
5945 // right next to each other. If so, the user may have typo'd "x =+ 4"
5946 // instead of "x += 4".
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005947 Expr *RHSCheck = RHS;
Chris Lattner2c156472008-08-21 18:04:13 +00005948 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
5949 RHSCheck = ICE->getSubExpr();
5950 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
5951 if ((UO->getOpcode() == UnaryOperator::Plus ||
5952 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005953 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner2c156472008-08-21 18:04:13 +00005954 // Only if the two operators are exactly adjacent.
Chris Lattner399bd1b2009-03-08 06:51:10 +00005955 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
5956 // And there is a space or other character before the subexpr of the
5957 // unary +/-. We don't want to warn on "x=-1".
Chris Lattner3e872092009-03-09 07:11:10 +00005958 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
5959 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00005960 Diag(Loc, diag::warn_not_compound_assign)
5961 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
5962 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner399bd1b2009-03-08 06:51:10 +00005963 }
Chris Lattner2c156472008-08-21 18:04:13 +00005964 }
5965 } else {
5966 // Compound assignment "x += y"
Eli Friedman623712b2009-05-16 05:56:02 +00005967 ConvTy = CheckAssignmentConstraints(LHSType, RHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00005968 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00005969
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005970 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
Douglas Gregor68647482009-12-16 03:45:30 +00005971 RHS, AA_Assigning))
Chris Lattner5cf216b2008-01-04 18:04:52 +00005972 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005973
Chris Lattner8b5dec32010-07-07 06:14:23 +00005974
5975 // Check to see if the destination operand is a dereferenced null pointer. If
5976 // so, and if not volatile-qualified, this is undefined behavior that the
5977 // optimizer will delete, so warn about it. People sometimes try to use this
5978 // to get a deterministic trap and are surprised by clang's behavior. This
5979 // only handles the pattern "*null = whatever", which is a very syntactic
5980 // check.
5981 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS->IgnoreParenCasts()))
5982 if (UO->getOpcode() == UnaryOperator::Deref &&
5983 UO->getSubExpr()->IgnoreParenCasts()->
5984 isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) &&
5985 !UO->getType().isVolatileQualified()) {
5986 Diag(UO->getOperatorLoc(), diag::warn_indirection_through_null)
5987 << UO->getSubExpr()->getSourceRange();
5988 Diag(UO->getOperatorLoc(), diag::note_indirection_through_null);
5989 }
5990
Reid Spencer5f016e22007-07-11 17:01:13 +00005991 // C99 6.5.16p3: The type of an assignment expression is the type of the
5992 // left operand unless the left operand has qualified type, in which case
Mike Stumpeed9cac2009-02-19 03:04:26 +00005993 // it is the unqualified version of the type of the left operand.
Reid Spencer5f016e22007-07-11 17:01:13 +00005994 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
5995 // is converted to the type of the assignment expression (above).
Chris Lattner73d0d4f2007-08-30 17:45:32 +00005996 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregor2d833e32009-05-02 00:36:19 +00005997 // operand.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005998 return LHSType.getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +00005999}
6000
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006001// C99 6.5.17
6002QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
Argyrios Kyrtzidis25973452010-06-30 10:53:14 +00006003 DiagnoseUnusedExprResult(LHS);
6004
Chris Lattner53fcaa92008-07-25 20:54:07 +00006005 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Douglas Gregora873dfc2010-02-03 00:27:59 +00006006 // C++ does not perform this conversion (C++ [expr.comma]p1).
6007 if (!getLangOptions().CPlusPlus)
6008 DefaultFunctionArrayLvalueConversion(RHS);
Eli Friedmanb1d796d2009-03-23 00:24:07 +00006009
6010 // FIXME: Check that RHS type is complete in C mode (it's legal for it to be
6011 // incomplete in C++).
6012
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006013 return RHS->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00006014}
6015
Steve Naroff49b45262007-07-13 16:58:59 +00006016/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
6017/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00006018QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00006019 bool isInc, bool isPrefix) {
Sebastian Redl28507842009-02-26 14:39:58 +00006020 if (Op->isTypeDependent())
6021 return Context.DependentTy;
6022
Chris Lattner3528d352008-11-21 07:05:48 +00006023 QualType ResType = Op->getType();
6024 assert(!ResType.isNull() && "no type for increment/decrement expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00006025
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00006026 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
6027 // Decrement of bool is not allowed.
6028 if (!isInc) {
6029 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
6030 return QualType();
6031 }
6032 // Increment of bool sets it to true, but is deprecated.
6033 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
6034 } else if (ResType->isRealType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00006035 // OK!
Steve Naroff58f9f2c2009-07-14 18:25:06 +00006036 } else if (ResType->isAnyPointerType()) {
6037 QualType PointeeTy = ResType->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00006038
Chris Lattner3528d352008-11-21 07:05:48 +00006039 // C99 6.5.2.4p2, 6.5.6p2
Steve Naroff14108da2009-07-10 23:34:53 +00006040 if (PointeeTy->isVoidType()) {
Douglas Gregorc983b862009-01-23 00:36:41 +00006041 if (getLangOptions().CPlusPlus) {
6042 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
6043 << Op->getSourceRange();
6044 return QualType();
6045 }
6046
6047 // Pointer to void is a GNU extension in C.
Chris Lattner3528d352008-11-21 07:05:48 +00006048 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Steve Naroff14108da2009-07-10 23:34:53 +00006049 } else if (PointeeTy->isFunctionType()) {
Douglas Gregorc983b862009-01-23 00:36:41 +00006050 if (getLangOptions().CPlusPlus) {
6051 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
6052 << Op->getType() << Op->getSourceRange();
6053 return QualType();
6054 }
6055
6056 Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattnerd1625842008-11-24 06:25:27 +00006057 << ResType << Op->getSourceRange();
Steve Naroff14108da2009-07-10 23:34:53 +00006058 } else if (RequireCompleteType(OpLoc, PointeeTy,
Anders Carlssond497ba72009-08-26 22:59:12 +00006059 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
Mike Stump1eb44332009-09-09 15:08:12 +00006060 << Op->getSourceRange()
Anders Carlssond497ba72009-08-26 22:59:12 +00006061 << ResType))
Douglas Gregor4ec339f2009-01-19 19:26:10 +00006062 return QualType();
Fariborz Jahanian9f8a04f2009-07-16 17:59:14 +00006063 // Diagnose bad cases where we step over interface counts.
John McCallc12c5bb2010-05-15 11:32:37 +00006064 else if (PointeeTy->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Fariborz Jahanian9f8a04f2009-07-16 17:59:14 +00006065 Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
6066 << PointeeTy << Op->getSourceRange();
6067 return QualType();
6068 }
Eli Friedman5b088a12010-01-03 00:20:48 +00006069 } else if (ResType->isAnyComplexType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00006070 // C99 does not support ++/-- on complex types, we allow as an extension.
6071 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00006072 << ResType << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00006073 } else {
6074 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Douglas Gregor5cc07df2009-12-15 16:44:32 +00006075 << ResType << int(isInc) << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00006076 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00006077 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006078 // At this point, we know we have a real, complex or pointer type.
Steve Naroffdd10e022007-08-23 21:37:33 +00006079 // Now make sure the operand is a modifiable lvalue.
Chris Lattner3528d352008-11-21 07:05:48 +00006080 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Reid Spencer5f016e22007-07-11 17:01:13 +00006081 return QualType();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00006082 // In C++, a prefix increment is the same type as the operand. Otherwise
6083 // (in C or with postfix), the increment is the unqualified type of the
6084 // operand.
6085 return isPrefix && getLangOptions().CPlusPlus
6086 ? ResType : ResType.getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +00006087}
6088
Anders Carlsson369dee42008-02-01 07:15:58 +00006089/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Reid Spencer5f016e22007-07-11 17:01:13 +00006090/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00006091/// where the declaration is needed for type checking. We only need to
6092/// handle cases when the expression references a function designator
6093/// or is an lvalue. Here are some examples:
6094/// - &(x) => x
6095/// - &*****f => f for f a function designator.
6096/// - &s.xx => s
6097/// - &s.zz[1].yy -> s, if zz is an array
6098/// - *(x + 1) -> x, if x is an array
6099/// - &"123"[2] -> 0
6100/// - & __real__ x -> x
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006101static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00006102 switch (E->getStmtClass()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00006103 case Stmt::DeclRefExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00006104 return cast<DeclRefExpr>(E)->getDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00006105 case Stmt::MemberExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00006106 // If this is an arrow operator, the address is an offset from
6107 // the base's value, so the object the base refers to is
6108 // irrelevant.
Chris Lattnerf0467b32008-04-02 04:24:33 +00006109 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnerf82228f2007-11-16 17:46:48 +00006110 return 0;
Eli Friedman23d58ce2009-04-20 08:23:18 +00006111 // Otherwise, the expression refers to a part of the base
Chris Lattnerf0467b32008-04-02 04:24:33 +00006112 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson369dee42008-02-01 07:15:58 +00006113 case Stmt::ArraySubscriptExprClass: {
Mike Stump390b4cc2009-05-16 07:39:55 +00006114 // FIXME: This code shouldn't be necessary! We should catch the implicit
6115 // promotion of register arrays earlier.
Eli Friedman23d58ce2009-04-20 08:23:18 +00006116 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
6117 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
6118 if (ICE->getSubExpr()->getType()->isArrayType())
6119 return getPrimaryDecl(ICE->getSubExpr());
6120 }
6121 return 0;
Anders Carlsson369dee42008-02-01 07:15:58 +00006122 }
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00006123 case Stmt::UnaryOperatorClass: {
6124 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006125
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00006126 switch(UO->getOpcode()) {
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00006127 case UnaryOperator::Real:
6128 case UnaryOperator::Imag:
6129 case UnaryOperator::Extension:
6130 return getPrimaryDecl(UO->getSubExpr());
6131 default:
6132 return 0;
6133 }
6134 }
Reid Spencer5f016e22007-07-11 17:01:13 +00006135 case Stmt::ParenExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00006136 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnerf82228f2007-11-16 17:46:48 +00006137 case Stmt::ImplicitCastExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00006138 // If the result of an implicit cast is an l-value, we care about
6139 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattnerf0467b32008-04-02 04:24:33 +00006140 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Reid Spencer5f016e22007-07-11 17:01:13 +00006141 default:
6142 return 0;
6143 }
6144}
6145
6146/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stumpeed9cac2009-02-19 03:04:26 +00006147/// designator or an lvalue designating an object. If it is an lvalue, the
Reid Spencer5f016e22007-07-11 17:01:13 +00006148/// object cannot be declared with storage class register or be a bit field.
Mike Stumpeed9cac2009-02-19 03:04:26 +00006149/// Note: The usual conversions are *not* applied to the operand of the &
Reid Spencer5f016e22007-07-11 17:01:13 +00006150/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stumpeed9cac2009-02-19 03:04:26 +00006151/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregor904eed32008-11-10 20:40:00 +00006152/// we allow the '&' but retain the overloaded-function type.
Reid Spencer5f016e22007-07-11 17:01:13 +00006153QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Eli Friedman23d58ce2009-04-20 08:23:18 +00006154 // Make sure to ignore parentheses in subsequent checks
6155 op = op->IgnoreParens();
6156
Douglas Gregor9103bb22008-12-17 22:52:20 +00006157 if (op->isTypeDependent())
6158 return Context.DependentTy;
6159
Steve Naroff08f19672008-01-13 17:10:08 +00006160 if (getLangOptions().C99) {
6161 // Implement C99-only parts of addressof rules.
6162 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
6163 if (uOp->getOpcode() == UnaryOperator::Deref)
6164 // Per C99 6.5.3.2, the address of a deref always returns a valid result
6165 // (assuming the deref expression is valid).
6166 return uOp->getSubExpr()->getType();
6167 }
6168 // Technically, there should be a check for array subscript
6169 // expressions here, but the result of one is always an lvalue anyway.
6170 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006171 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner28be73f2008-07-26 21:30:36 +00006172 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes6b6609f2008-12-16 22:59:47 +00006173
Sebastian Redle27d87f2010-01-11 15:56:56 +00006174 MemberExpr *ME = dyn_cast<MemberExpr>(op);
6175 if (lval == Expr::LV_MemberFunction && ME &&
6176 isa<CXXMethodDecl>(ME->getMemberDecl())) {
6177 ValueDecl *dcl = cast<MemberExpr>(op)->getMemberDecl();
6178 // &f where f is a member of the current object, or &o.f, or &p->f
6179 // All these are not allowed, and we need to catch them before the dcl
6180 // branch of the if, below.
6181 Diag(OpLoc, diag::err_unqualified_pointer_member_function)
6182 << dcl;
6183 // FIXME: Improve this diagnostic and provide a fixit.
6184
6185 // Now recover by acting as if the function had been accessed qualified.
6186 return Context.getMemberPointerType(op->getType(),
6187 Context.getTypeDeclType(cast<RecordDecl>(dcl->getDeclContext()))
6188 .getTypePtr());
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00006189 }
6190
6191 if (lval == Expr::LV_ClassTemporary) {
Douglas Gregore873fb72010-02-16 21:39:57 +00006192 Diag(OpLoc, isSFINAEContext()? diag::err_typecheck_addrof_class_temporary
6193 : diag::ext_typecheck_addrof_class_temporary)
6194 << op->getType() << op->getSourceRange();
6195 if (isSFINAEContext())
6196 return QualType();
Chris Lattnerc721ae82010-07-05 19:36:34 +00006197 } else if (isa<ObjCSelectorExpr>(op))
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00006198 return Context.getPointerType(op->getType());
Chris Lattnerc721ae82010-07-05 19:36:34 +00006199 else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedman441cf102009-05-16 23:27:50 +00006200 // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00006201 // The operand must be either an l-value or a function designator
Eli Friedman441cf102009-05-16 23:27:50 +00006202 if (!op->getType()->isFunctionType()) {
Chris Lattnerf82228f2007-11-16 17:46:48 +00006203 // FIXME: emit more specific diag...
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00006204 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
6205 << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00006206 return QualType();
6207 }
Douglas Gregor33bbbc52009-05-02 02:18:30 +00006208 } else if (op->getBitField()) { // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00006209 // The operand cannot be a bit-field
6210 Diag(OpLoc, diag::err_typecheck_address_of)
6211 << "bit-field" << op->getSourceRange();
Douglas Gregor86f19402008-12-20 23:49:58 +00006212 return QualType();
Anders Carlsson09380262010-01-31 17:18:49 +00006213 } else if (op->refersToVectorElement()) {
Eli Friedman23d58ce2009-04-20 08:23:18 +00006214 // The operand cannot be an element of a vector
Chris Lattnerd3a94e22008-11-20 06:06:08 +00006215 Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemanb104b1f2009-02-15 22:45:20 +00006216 << "vector element" << op->getSourceRange();
Steve Naroffbcb2b612008-02-29 23:30:25 +00006217 return QualType();
Fariborz Jahanian0337f212009-07-07 18:50:52 +00006218 } else if (isa<ObjCPropertyRefExpr>(op)) {
6219 // cannot take address of a property expression.
6220 Diag(OpLoc, diag::err_typecheck_address_of)
6221 << "property expression" << op->getSourceRange();
6222 return QualType();
Anders Carlsson1d524c32009-09-14 23:15:26 +00006223 } else if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(op)) {
6224 // FIXME: Can LHS ever be null here?
Anders Carlsson474e1022009-09-15 16:03:44 +00006225 if (!CheckAddressOfOperand(CO->getTrueExpr(), OpLoc).isNull())
6226 return CheckAddressOfOperand(CO->getFalseExpr(), OpLoc);
John McCallba135432009-11-21 08:51:07 +00006227 } else if (isa<UnresolvedLookupExpr>(op)) {
6228 return Context.OverloadTy;
Steve Naroffbcb2b612008-02-29 23:30:25 +00006229 } else if (dcl) { // C99 6.5.3.2p1
Mike Stumpeed9cac2009-02-19 03:04:26 +00006230 // We have an lvalue with a decl. Make sure the decl is not declared
Reid Spencer5f016e22007-07-11 17:01:13 +00006231 // with the register storage-class specifier.
6232 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
6233 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00006234 Diag(OpLoc, diag::err_typecheck_address_of)
6235 << "register variable" << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00006236 return QualType();
6237 }
John McCallba135432009-11-21 08:51:07 +00006238 } else if (isa<FunctionTemplateDecl>(dcl)) {
Douglas Gregor904eed32008-11-10 20:40:00 +00006239 return Context.OverloadTy;
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00006240 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(dcl)) {
Douglas Gregor29882052008-12-10 21:26:49 +00006241 // Okay: we can take the address of a field.
Sebastian Redlebc07d52009-02-03 20:19:35 +00006242 // Could be a pointer to member, though, if there is an explicit
6243 // scope qualifier for the class.
Douglas Gregora2813ce2009-10-23 18:54:35 +00006244 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redlebc07d52009-02-03 20:19:35 +00006245 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00006246 if (Ctx && Ctx->isRecord()) {
6247 if (FD->getType()->isReferenceType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00006248 Diag(OpLoc,
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00006249 diag::err_cannot_form_pointer_to_member_of_reference_type)
6250 << FD->getDeclName() << FD->getType();
6251 return QualType();
6252 }
Mike Stump1eb44332009-09-09 15:08:12 +00006253
Sebastian Redlebc07d52009-02-03 20:19:35 +00006254 return Context.getMemberPointerType(op->getType(),
6255 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00006256 }
Sebastian Redlebc07d52009-02-03 20:19:35 +00006257 }
Anders Carlsson196f7d02009-05-16 21:43:42 +00006258 } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(dcl)) {
Nuno Lopes6fea8d22008-12-16 22:58:26 +00006259 // Okay: we can take the address of a function.
Sebastian Redl33b399a2009-02-04 21:23:32 +00006260 // As above.
Douglas Gregora2813ce2009-10-23 18:54:35 +00006261 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier() &&
6262 MD->isInstance())
Anders Carlsson196f7d02009-05-16 21:43:42 +00006263 return Context.getMemberPointerType(op->getType(),
6264 Context.getTypeDeclType(MD->getParent()).getTypePtr());
6265 } else if (!isa<FunctionDecl>(dcl))
Reid Spencer5f016e22007-07-11 17:01:13 +00006266 assert(0 && "Unknown/unexpected decl type");
Reid Spencer5f016e22007-07-11 17:01:13 +00006267 }
Sebastian Redl33b399a2009-02-04 21:23:32 +00006268
Eli Friedman441cf102009-05-16 23:27:50 +00006269 if (lval == Expr::LV_IncompleteVoidType) {
6270 // Taking the address of a void variable is technically illegal, but we
6271 // allow it in cases which are otherwise valid.
6272 // Example: "extern void x; void* y = &x;".
6273 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
6274 }
6275
Reid Spencer5f016e22007-07-11 17:01:13 +00006276 // If the operand has type "type", the result has type "pointer to type".
6277 return Context.getPointerType(op->getType());
6278}
6279
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00006280/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
Chris Lattner22caddc2008-11-23 09:13:29 +00006281QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
Sebastian Redl28507842009-02-26 14:39:58 +00006282 if (Op->isTypeDependent())
6283 return Context.DependentTy;
6284
Chris Lattner22caddc2008-11-23 09:13:29 +00006285 UsualUnaryConversions(Op);
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00006286 QualType OpTy = Op->getType();
6287 QualType Result;
6288
6289 // Note that per both C89 and C99, indirection is always legal, even if OpTy
6290 // is an incomplete type or void. It would be possible to warn about
6291 // dereferencing a void pointer, but it's completely well-defined, and such a
6292 // warning is unlikely to catch any mistakes.
6293 if (const PointerType *PT = OpTy->getAs<PointerType>())
6294 Result = PT->getPointeeType();
6295 else if (const ObjCObjectPointerType *OPT =
6296 OpTy->getAs<ObjCObjectPointerType>())
6297 Result = OPT->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006298
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00006299 if (Result.isNull()) {
6300 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
6301 << OpTy << Op->getSourceRange();
6302 return QualType();
6303 }
6304
6305 return Result;
Reid Spencer5f016e22007-07-11 17:01:13 +00006306}
6307
6308static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
6309 tok::TokenKind Kind) {
6310 BinaryOperator::Opcode Opc;
6311 switch (Kind) {
6312 default: assert(0 && "Unknown binop!");
Sebastian Redl22460502009-02-07 00:15:38 +00006313 case tok::periodstar: Opc = BinaryOperator::PtrMemD; break;
6314 case tok::arrowstar: Opc = BinaryOperator::PtrMemI; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00006315 case tok::star: Opc = BinaryOperator::Mul; break;
6316 case tok::slash: Opc = BinaryOperator::Div; break;
6317 case tok::percent: Opc = BinaryOperator::Rem; break;
6318 case tok::plus: Opc = BinaryOperator::Add; break;
6319 case tok::minus: Opc = BinaryOperator::Sub; break;
6320 case tok::lessless: Opc = BinaryOperator::Shl; break;
6321 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
6322 case tok::lessequal: Opc = BinaryOperator::LE; break;
6323 case tok::less: Opc = BinaryOperator::LT; break;
6324 case tok::greaterequal: Opc = BinaryOperator::GE; break;
6325 case tok::greater: Opc = BinaryOperator::GT; break;
6326 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
6327 case tok::equalequal: Opc = BinaryOperator::EQ; break;
6328 case tok::amp: Opc = BinaryOperator::And; break;
6329 case tok::caret: Opc = BinaryOperator::Xor; break;
6330 case tok::pipe: Opc = BinaryOperator::Or; break;
6331 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
6332 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
6333 case tok::equal: Opc = BinaryOperator::Assign; break;
6334 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
6335 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
6336 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
6337 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
6338 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
6339 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
6340 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
6341 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
6342 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
6343 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
6344 case tok::comma: Opc = BinaryOperator::Comma; break;
6345 }
6346 return Opc;
6347}
6348
6349static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
6350 tok::TokenKind Kind) {
6351 UnaryOperator::Opcode Opc;
6352 switch (Kind) {
6353 default: assert(0 && "Unknown unary op!");
6354 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
6355 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
6356 case tok::amp: Opc = UnaryOperator::AddrOf; break;
6357 case tok::star: Opc = UnaryOperator::Deref; break;
6358 case tok::plus: Opc = UnaryOperator::Plus; break;
6359 case tok::minus: Opc = UnaryOperator::Minus; break;
6360 case tok::tilde: Opc = UnaryOperator::Not; break;
6361 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00006362 case tok::kw___real: Opc = UnaryOperator::Real; break;
6363 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
6364 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
6365 }
6366 return Opc;
6367}
6368
Douglas Gregoreaebc752008-11-06 23:29:22 +00006369/// CreateBuiltinBinOp - Creates a new built-in binary operation with
6370/// operator @p Opc at location @c TokLoc. This routine only supports
6371/// built-in operations; ActOnBinOp handles overloaded operators.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00006372Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
6373 unsigned Op,
6374 Expr *lhs, Expr *rhs) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00006375 QualType ResultTy; // Result type of the binary operator.
Douglas Gregoreaebc752008-11-06 23:29:22 +00006376 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
Eli Friedmanab3a8522009-03-28 01:22:36 +00006377 // The following two variables are used for compound assignment operators
6378 QualType CompLHSTy; // Type of LHS after promotions for computation
6379 QualType CompResultTy; // Type of computation result
Douglas Gregoreaebc752008-11-06 23:29:22 +00006380
6381 switch (Opc) {
Douglas Gregoreaebc752008-11-06 23:29:22 +00006382 case BinaryOperator::Assign:
6383 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
6384 break;
Sebastian Redl22460502009-02-07 00:15:38 +00006385 case BinaryOperator::PtrMemD:
6386 case BinaryOperator::PtrMemI:
6387 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
6388 Opc == BinaryOperator::PtrMemI);
6389 break;
6390 case BinaryOperator::Mul:
Douglas Gregoreaebc752008-11-06 23:29:22 +00006391 case BinaryOperator::Div:
Chris Lattner7ef655a2010-01-12 21:23:57 +00006392 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, false,
6393 Opc == BinaryOperator::Div);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006394 break;
6395 case BinaryOperator::Rem:
6396 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
6397 break;
6398 case BinaryOperator::Add:
6399 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
6400 break;
6401 case BinaryOperator::Sub:
6402 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
6403 break;
Sebastian Redl22460502009-02-07 00:15:38 +00006404 case BinaryOperator::Shl:
Douglas Gregoreaebc752008-11-06 23:29:22 +00006405 case BinaryOperator::Shr:
6406 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
6407 break;
6408 case BinaryOperator::LE:
6409 case BinaryOperator::LT:
6410 case BinaryOperator::GE:
6411 case BinaryOperator::GT:
Douglas Gregora86b8322009-04-06 18:45:53 +00006412 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006413 break;
6414 case BinaryOperator::EQ:
6415 case BinaryOperator::NE:
Douglas Gregora86b8322009-04-06 18:45:53 +00006416 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006417 break;
6418 case BinaryOperator::And:
6419 case BinaryOperator::Xor:
6420 case BinaryOperator::Or:
6421 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
6422 break;
6423 case BinaryOperator::LAnd:
6424 case BinaryOperator::LOr:
Chris Lattner90a8f272010-07-13 19:41:32 +00006425 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc, Opc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006426 break;
6427 case BinaryOperator::MulAssign:
6428 case BinaryOperator::DivAssign:
Chris Lattner7ef655a2010-01-12 21:23:57 +00006429 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true,
6430 Opc == BinaryOperator::DivAssign);
Eli Friedmanab3a8522009-03-28 01:22:36 +00006431 CompLHSTy = CompResultTy;
6432 if (!CompResultTy.isNull())
6433 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006434 break;
6435 case BinaryOperator::RemAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00006436 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
6437 CompLHSTy = CompResultTy;
6438 if (!CompResultTy.isNull())
6439 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006440 break;
6441 case BinaryOperator::AddAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00006442 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
6443 if (!CompResultTy.isNull())
6444 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006445 break;
6446 case BinaryOperator::SubAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00006447 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
6448 if (!CompResultTy.isNull())
6449 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006450 break;
6451 case BinaryOperator::ShlAssign:
6452 case BinaryOperator::ShrAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00006453 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
6454 CompLHSTy = CompResultTy;
6455 if (!CompResultTy.isNull())
6456 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006457 break;
6458 case BinaryOperator::AndAssign:
6459 case BinaryOperator::XorAssign:
6460 case BinaryOperator::OrAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00006461 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
6462 CompLHSTy = CompResultTy;
6463 if (!CompResultTy.isNull())
6464 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006465 break;
6466 case BinaryOperator::Comma:
6467 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
6468 break;
6469 }
6470 if (ResultTy.isNull())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00006471 return ExprError();
Eli Friedmanab3a8522009-03-28 01:22:36 +00006472 if (CompResultTy.isNull())
Steve Naroff6ece14c2009-01-21 00:14:39 +00006473 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
6474 else
6475 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
Eli Friedmanab3a8522009-03-28 01:22:36 +00006476 CompLHSTy, CompResultTy,
6477 OpLoc));
Douglas Gregoreaebc752008-11-06 23:29:22 +00006478}
6479
Sebastian Redlaee3c932009-10-27 12:10:02 +00006480/// SuggestParentheses - Emit a diagnostic together with a fixit hint that wraps
6481/// ParenRange in parentheses.
Sebastian Redl6b169ac2009-10-26 17:01:32 +00006482static void SuggestParentheses(Sema &Self, SourceLocation Loc,
6483 const PartialDiagnostic &PD,
Douglas Gregor55b38842010-04-14 16:09:52 +00006484 const PartialDiagnostic &FirstNote,
6485 SourceRange FirstParenRange,
6486 const PartialDiagnostic &SecondNote,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00006487 SourceRange SecondParenRange) {
Douglas Gregor55b38842010-04-14 16:09:52 +00006488 Self.Diag(Loc, PD);
6489
6490 if (!FirstNote.getDiagID())
6491 return;
6492
6493 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(FirstParenRange.getEnd());
6494 if (!FirstParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
6495 // We can't display the parentheses, so just return.
Sebastian Redl6b169ac2009-10-26 17:01:32 +00006496 return;
6497 }
6498
Douglas Gregor55b38842010-04-14 16:09:52 +00006499 Self.Diag(Loc, FirstNote)
6500 << FixItHint::CreateInsertion(FirstParenRange.getBegin(), "(")
Douglas Gregor849b2432010-03-31 17:46:05 +00006501 << FixItHint::CreateInsertion(EndLoc, ")");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006502
Douglas Gregor55b38842010-04-14 16:09:52 +00006503 if (!SecondNote.getDiagID())
Douglas Gregor827feec2010-01-08 00:20:23 +00006504 return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006505
Douglas Gregor827feec2010-01-08 00:20:23 +00006506 EndLoc = Self.PP.getLocForEndOfToken(SecondParenRange.getEnd());
6507 if (!SecondParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
6508 // We can't display the parentheses, so just dig the
6509 // warning/error and return.
Douglas Gregor55b38842010-04-14 16:09:52 +00006510 Self.Diag(Loc, SecondNote);
Douglas Gregor827feec2010-01-08 00:20:23 +00006511 return;
6512 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006513
Douglas Gregor55b38842010-04-14 16:09:52 +00006514 Self.Diag(Loc, SecondNote)
Douglas Gregor849b2432010-03-31 17:46:05 +00006515 << FixItHint::CreateInsertion(SecondParenRange.getBegin(), "(")
6516 << FixItHint::CreateInsertion(EndLoc, ")");
Sebastian Redl6b169ac2009-10-26 17:01:32 +00006517}
6518
Sebastian Redlaee3c932009-10-27 12:10:02 +00006519/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
6520/// operators are mixed in a way that suggests that the programmer forgot that
6521/// comparison operators have higher precedence. The most typical example of
6522/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006523static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperator::Opcode Opc,
6524 SourceLocation OpLoc,Expr *lhs,Expr *rhs){
Sebastian Redlaee3c932009-10-27 12:10:02 +00006525 typedef BinaryOperator BinOp;
6526 BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1),
6527 rhsopc = static_cast<BinOp::Opcode>(-1);
6528 if (BinOp *BO = dyn_cast<BinOp>(lhs))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006529 lhsopc = BO->getOpcode();
Sebastian Redlaee3c932009-10-27 12:10:02 +00006530 if (BinOp *BO = dyn_cast<BinOp>(rhs))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006531 rhsopc = BO->getOpcode();
6532
6533 // Subs are not binary operators.
6534 if (lhsopc == -1 && rhsopc == -1)
6535 return;
6536
6537 // Bitwise operations are sometimes used as eager logical ops.
6538 // Don't diagnose this.
Sebastian Redlaee3c932009-10-27 12:10:02 +00006539 if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) &&
6540 (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc)))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006541 return;
6542
Sebastian Redlaee3c932009-10-27 12:10:02 +00006543 if (BinOp::isComparisonOp(lhsopc))
Sebastian Redl6b169ac2009-10-26 17:01:32 +00006544 SuggestParentheses(Self, OpLoc,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00006545 Self.PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redlaee3c932009-10-27 12:10:02 +00006546 << SourceRange(lhs->getLocStart(), OpLoc)
6547 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(lhsopc),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00006548 Self.PDiag(diag::note_precedence_bitwise_first)
Douglas Gregor827feec2010-01-08 00:20:23 +00006549 << BinOp::getOpcodeStr(Opc),
Douglas Gregor55b38842010-04-14 16:09:52 +00006550 SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(), rhs->getLocEnd()),
6551 Self.PDiag(diag::note_precedence_bitwise_silence)
6552 << BinOp::getOpcodeStr(lhsopc),
6553 lhs->getSourceRange());
Sebastian Redlaee3c932009-10-27 12:10:02 +00006554 else if (BinOp::isComparisonOp(rhsopc))
Sebastian Redl6b169ac2009-10-26 17:01:32 +00006555 SuggestParentheses(Self, OpLoc,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00006556 Self.PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redlaee3c932009-10-27 12:10:02 +00006557 << SourceRange(OpLoc, rhs->getLocEnd())
6558 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(rhsopc),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00006559 Self.PDiag(diag::note_precedence_bitwise_first)
Douglas Gregor827feec2010-01-08 00:20:23 +00006560 << BinOp::getOpcodeStr(Opc),
Douglas Gregor55b38842010-04-14 16:09:52 +00006561 SourceRange(lhs->getLocEnd(), cast<BinOp>(rhs)->getLHS()->getLocStart()),
6562 Self.PDiag(diag::note_precedence_bitwise_silence)
6563 << BinOp::getOpcodeStr(rhsopc),
6564 rhs->getSourceRange());
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006565}
6566
6567/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
6568/// precedence. This currently diagnoses only "arg1 'bitwise' arg2 'eq' arg3".
6569/// But it could also warn about arg1 && arg2 || arg3, as GCC 4.3+ does.
6570static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperator::Opcode Opc,
6571 SourceLocation OpLoc, Expr *lhs, Expr *rhs){
Sebastian Redlaee3c932009-10-27 12:10:02 +00006572 if (BinaryOperator::isBitwiseOp(Opc))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006573 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs);
6574}
6575
Reid Spencer5f016e22007-07-11 17:01:13 +00006576// Binary Operators. 'Tok' is the token for the operator.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00006577Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
6578 tok::TokenKind Kind,
6579 ExprArg LHS, ExprArg RHS) {
Reid Spencer5f016e22007-07-11 17:01:13 +00006580 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
Anders Carlssone9146f22009-05-01 19:49:17 +00006581 Expr *lhs = LHS.takeAs<Expr>(), *rhs = RHS.takeAs<Expr>();
Reid Spencer5f016e22007-07-11 17:01:13 +00006582
Steve Narofff69936d2007-09-16 03:34:24 +00006583 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
6584 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00006585
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006586 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
6587 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs);
6588
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006589 return BuildBinOp(S, TokLoc, Opc, lhs, rhs);
6590}
6591
6592Action::OwningExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
6593 BinaryOperator::Opcode Opc,
6594 Expr *lhs, Expr *rhs) {
Douglas Gregor063daf62009-03-13 18:40:31 +00006595 if (getLangOptions().CPlusPlus &&
Mike Stump1eb44332009-09-09 15:08:12 +00006596 (lhs->getType()->isOverloadableType() ||
Douglas Gregor063daf62009-03-13 18:40:31 +00006597 rhs->getType()->isOverloadableType())) {
6598 // Find all of the overloaded operators visible from this
6599 // point. We perform both an operator-name lookup from the local
6600 // scope and an argument-dependent lookup based on the types of
6601 // the arguments.
John McCall6e266892010-01-26 03:27:55 +00006602 UnresolvedSet<16> Functions;
Douglas Gregor063daf62009-03-13 18:40:31 +00006603 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
John McCall6e266892010-01-26 03:27:55 +00006604 if (S && OverOp != OO_None)
6605 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
6606 Functions);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006607
Douglas Gregor063daf62009-03-13 18:40:31 +00006608 // Build the (potentially-overloaded, potentially-dependent)
6609 // binary operation.
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006610 return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs);
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00006611 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006612
Douglas Gregoreaebc752008-11-06 23:29:22 +00006613 // Build a built-in binary operation.
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006614 return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs);
Reid Spencer5f016e22007-07-11 17:01:13 +00006615}
6616
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006617Action::OwningExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00006618 unsigned OpcIn,
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006619 ExprArg InputArg) {
6620 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor74253732008-11-19 15:42:04 +00006621
Mike Stump390b4cc2009-05-16 07:39:55 +00006622 // FIXME: Input is modified below, but InputArg is not updated appropriately.
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006623 Expr *Input = (Expr *)InputArg.get();
Reid Spencer5f016e22007-07-11 17:01:13 +00006624 QualType resultType;
6625 switch (Opc) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006626 case UnaryOperator::OffsetOf:
6627 assert(false && "Invalid unary operator");
6628 break;
Douglas Gregor8ecdb652010-04-28 22:16:22 +00006629
Reid Spencer5f016e22007-07-11 17:01:13 +00006630 case UnaryOperator::PreInc:
6631 case UnaryOperator::PreDec:
Eli Friedmande99a452009-07-22 22:25:00 +00006632 case UnaryOperator::PostInc:
6633 case UnaryOperator::PostDec:
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00006634 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
Eli Friedmande99a452009-07-22 22:25:00 +00006635 Opc == UnaryOperator::PreInc ||
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00006636 Opc == UnaryOperator::PostInc,
6637 Opc == UnaryOperator::PreInc ||
6638 Opc == UnaryOperator::PreDec);
Reid Spencer5f016e22007-07-11 17:01:13 +00006639 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006640 case UnaryOperator::AddrOf:
Reid Spencer5f016e22007-07-11 17:01:13 +00006641 resultType = CheckAddressOfOperand(Input, OpLoc);
6642 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006643 case UnaryOperator::Deref:
Douglas Gregora873dfc2010-02-03 00:27:59 +00006644 DefaultFunctionArrayLvalueConversion(Input);
Reid Spencer5f016e22007-07-11 17:01:13 +00006645 resultType = CheckIndirectionOperand(Input, OpLoc);
6646 break;
6647 case UnaryOperator::Plus:
6648 case UnaryOperator::Minus:
Steve Naroffc80b4ee2007-07-16 21:54:35 +00006649 UsualUnaryConversions(Input);
6650 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00006651 if (resultType->isDependentType())
6652 break;
Douglas Gregor00619622010-06-22 23:41:02 +00006653 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
6654 resultType->isVectorType())
Douglas Gregor74253732008-11-19 15:42:04 +00006655 break;
6656 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
6657 resultType->isEnumeralType())
6658 break;
6659 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
6660 Opc == UnaryOperator::Plus &&
6661 resultType->isPointerType())
6662 break;
6663
Sebastian Redl0eb23302009-01-19 00:08:26 +00006664 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
6665 << resultType << Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00006666 case UnaryOperator::Not: // bitwise complement
Steve Naroffc80b4ee2007-07-16 21:54:35 +00006667 UsualUnaryConversions(Input);
6668 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00006669 if (resultType->isDependentType())
6670 break;
Chris Lattner02a65142008-07-25 23:52:49 +00006671 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
6672 if (resultType->isComplexType() || resultType->isComplexIntegerType())
6673 // C99 does not support '~' for complex conjugation.
Chris Lattnerd3a94e22008-11-20 06:06:08 +00006674 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00006675 << resultType << Input->getSourceRange();
Chris Lattner02a65142008-07-25 23:52:49 +00006676 else if (!resultType->isIntegerType())
Sebastian Redl0eb23302009-01-19 00:08:26 +00006677 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
6678 << resultType << Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00006679 break;
6680 case UnaryOperator::LNot: // logical negation
6681 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Douglas Gregora873dfc2010-02-03 00:27:59 +00006682 DefaultFunctionArrayLvalueConversion(Input);
Steve Naroffc80b4ee2007-07-16 21:54:35 +00006683 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00006684 if (resultType->isDependentType())
6685 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00006686 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redl0eb23302009-01-19 00:08:26 +00006687 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
6688 << resultType << Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00006689 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl0eb23302009-01-19 00:08:26 +00006690 // In C++, it's bool. C++ 5.3.1p8
6691 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00006692 break;
Chris Lattnerdbb36972007-08-24 21:16:53 +00006693 case UnaryOperator::Real:
Chris Lattnerdbb36972007-08-24 21:16:53 +00006694 case UnaryOperator::Imag:
Chris Lattnerba27e2a2009-02-17 08:12:06 +00006695 resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real);
Chris Lattnerdbb36972007-08-24 21:16:53 +00006696 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00006697 case UnaryOperator::Extension:
Reid Spencer5f016e22007-07-11 17:01:13 +00006698 resultType = Input->getType();
6699 break;
6700 }
6701 if (resultType.isNull())
Sebastian Redl0eb23302009-01-19 00:08:26 +00006702 return ExprError();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006703
6704 InputArg.release();
Steve Naroff6ece14c2009-01-21 00:14:39 +00006705 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00006706}
6707
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006708Action::OwningExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
6709 UnaryOperator::Opcode Opc,
6710 ExprArg input) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006711 Expr *Input = (Expr*)input.get();
Anders Carlssona8a1e3d2009-11-14 21:26:41 +00006712 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
6713 Opc != UnaryOperator::Extension) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006714 // Find all of the overloaded operators visible from this
6715 // point. We perform both an operator-name lookup from the local
6716 // scope and an argument-dependent lookup based on the types of
6717 // the arguments.
John McCall6e266892010-01-26 03:27:55 +00006718 UnresolvedSet<16> Functions;
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006719 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall6e266892010-01-26 03:27:55 +00006720 if (S && OverOp != OO_None)
6721 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
6722 Functions);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006723
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006724 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, move(input));
6725 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006726
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006727 return CreateBuiltinUnaryOp(OpLoc, Opc, move(input));
6728}
6729
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006730// Unary Operators. 'Tok' is the token for the operator.
6731Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
6732 tok::TokenKind Op, ExprArg input) {
6733 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), move(input));
6734}
6735
Steve Naroff1b273c42007-09-16 14:56:35 +00006736/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Sebastian Redlf53597f2009-03-15 17:47:39 +00006737Sema::OwningExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
6738 SourceLocation LabLoc,
6739 IdentifierInfo *LabelII) {
Reid Spencer5f016e22007-07-11 17:01:13 +00006740 // Look up the record for this label identifier.
Chris Lattnerea29a3a2009-04-18 20:01:55 +00006741 LabelStmt *&LabelDecl = getLabelMap()[LabelII];
Mike Stumpeed9cac2009-02-19 03:04:26 +00006742
Daniel Dunbar0ffb1252008-08-04 16:51:22 +00006743 // If we haven't seen this label yet, create a forward reference. It
6744 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Steve Naroffcaaacec2009-03-13 15:38:40 +00006745 if (LabelDecl == 0)
Steve Naroff6ece14c2009-01-21 00:14:39 +00006746 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006747
Reid Spencer5f016e22007-07-11 17:01:13 +00006748 // Create the AST node. The address of a label always has type 'void*'.
Sebastian Redlf53597f2009-03-15 17:47:39 +00006749 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
6750 Context.getPointerType(Context.VoidTy)));
Reid Spencer5f016e22007-07-11 17:01:13 +00006751}
6752
Sebastian Redlf53597f2009-03-15 17:47:39 +00006753Sema::OwningExprResult
6754Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtArg substmt,
6755 SourceLocation RPLoc) { // "({..})"
6756 Stmt *SubStmt = static_cast<Stmt*>(substmt.get());
Chris Lattnerab18c4c2007-07-24 16:58:17 +00006757 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
6758 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
6759
Douglas Gregordd8f5692010-03-10 04:54:39 +00006760 bool isFileScope
6761 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
Chris Lattner4a049f02009-04-25 19:11:05 +00006762 if (isFileScope)
Sebastian Redlf53597f2009-03-15 17:47:39 +00006763 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedmandca2b732009-01-24 23:09:00 +00006764
Chris Lattnerab18c4c2007-07-24 16:58:17 +00006765 // FIXME: there are a variety of strange constraints to enforce here, for
6766 // example, it is not possible to goto into a stmt expression apparently.
6767 // More semantic analysis is needed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00006768
Chris Lattnerab18c4c2007-07-24 16:58:17 +00006769 // If there are sub stmts in the compound stmt, take the type of the last one
6770 // as the type of the stmtexpr.
6771 QualType Ty = Context.VoidTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006772
Chris Lattner611b2ec2008-07-26 19:51:01 +00006773 if (!Compound->body_empty()) {
6774 Stmt *LastStmt = Compound->body_back();
6775 // If LastStmt is a label, skip down through into the body.
6776 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
6777 LastStmt = Label->getSubStmt();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006778
Chris Lattner611b2ec2008-07-26 19:51:01 +00006779 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattnerab18c4c2007-07-24 16:58:17 +00006780 Ty = LastExpr->getType();
Chris Lattner611b2ec2008-07-26 19:51:01 +00006781 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006782
Eli Friedmanb1d796d2009-03-23 00:24:07 +00006783 // FIXME: Check that expression type is complete/non-abstract; statement
6784 // expressions are not lvalues.
6785
Sebastian Redlf53597f2009-03-15 17:47:39 +00006786 substmt.release();
6787 return Owned(new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc));
Chris Lattnerab18c4c2007-07-24 16:58:17 +00006788}
Steve Naroffd34e9152007-08-01 22:05:33 +00006789
Douglas Gregor8ecdb652010-04-28 22:16:22 +00006790Sema::OwningExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
6791 TypeSourceInfo *TInfo,
Sebastian Redlf53597f2009-03-15 17:47:39 +00006792 OffsetOfComponent *CompPtr,
6793 unsigned NumComponents,
Douglas Gregor8ecdb652010-04-28 22:16:22 +00006794 SourceLocation RParenLoc) {
6795 QualType ArgTy = TInfo->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00006796 bool Dependent = ArgTy->isDependentType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00006797 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00006798
Chris Lattner73d0d4f2007-08-30 17:45:32 +00006799 // We must have at least one component that refers to the type, and the first
6800 // one is known to be a field designator. Verify that the ArgTy represents
6801 // a struct/union/class.
Sebastian Redl28507842009-02-26 14:39:58 +00006802 if (!Dependent && !ArgTy->isRecordType())
Douglas Gregor8ecdb652010-04-28 22:16:22 +00006803 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
6804 << ArgTy << TypeRange);
6805
6806 // Type must be complete per C99 7.17p3 because a declaring a variable
6807 // with an incomplete type would be ill-formed.
6808 if (!Dependent
6809 && RequireCompleteType(BuiltinLoc, ArgTy,
6810 PDiag(diag::err_offsetof_incomplete_type)
6811 << TypeRange))
6812 return ExprError();
6813
Chris Lattner9e2b75c2007-08-31 21:49:13 +00006814 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
6815 // GCC extension, diagnose them.
Eli Friedman35183ac2009-02-27 06:44:11 +00006816 // FIXME: This diagnostic isn't actually visible because the location is in
6817 // a system header!
Chris Lattner9e2b75c2007-08-31 21:49:13 +00006818 if (NumComponents != 1)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00006819 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
6820 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00006821
6822 bool DidWarnAboutNonPOD = false;
6823 QualType CurrentType = ArgTy;
6824 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
6825 llvm::SmallVector<OffsetOfNode, 4> Comps;
6826 llvm::SmallVector<Expr*, 4> Exprs;
6827 for (unsigned i = 0; i != NumComponents; ++i) {
6828 const OffsetOfComponent &OC = CompPtr[i];
6829 if (OC.isBrackets) {
6830 // Offset of an array sub-field. TODO: Should we allow vector elements?
6831 if (!CurrentType->isDependentType()) {
6832 const ArrayType *AT = Context.getAsArrayType(CurrentType);
6833 if(!AT)
6834 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
6835 << CurrentType);
6836 CurrentType = AT->getElementType();
6837 } else
6838 CurrentType = Context.DependentTy;
6839
6840 // The expression must be an integral expression.
6841 // FIXME: An integral constant expression?
6842 Expr *Idx = static_cast<Expr*>(OC.U.E);
6843 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
6844 !Idx->getType()->isIntegerType())
6845 return ExprError(Diag(Idx->getLocStart(),
6846 diag::err_typecheck_subscript_not_integer)
6847 << Idx->getSourceRange());
6848
6849 // Record this array index.
6850 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
6851 Exprs.push_back(Idx);
6852 continue;
6853 }
6854
6855 // Offset of a field.
6856 if (CurrentType->isDependentType()) {
6857 // We have the offset of a field, but we can't look into the dependent
6858 // type. Just record the identifier of the field.
6859 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
6860 CurrentType = Context.DependentTy;
6861 continue;
6862 }
6863
6864 // We need to have a complete type to look into.
6865 if (RequireCompleteType(OC.LocStart, CurrentType,
6866 diag::err_offsetof_incomplete_type))
6867 return ExprError();
6868
6869 // Look for the designated field.
6870 const RecordType *RC = CurrentType->getAs<RecordType>();
6871 if (!RC)
6872 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
6873 << CurrentType);
6874 RecordDecl *RD = RC->getDecl();
6875
6876 // C++ [lib.support.types]p5:
6877 // The macro offsetof accepts a restricted set of type arguments in this
6878 // International Standard. type shall be a POD structure or a POD union
6879 // (clause 9).
6880 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
6881 if (!CRD->isPOD() && !DidWarnAboutNonPOD &&
6882 DiagRuntimeBehavior(BuiltinLoc,
6883 PDiag(diag::warn_offsetof_non_pod_type)
6884 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
6885 << CurrentType))
6886 DidWarnAboutNonPOD = true;
6887 }
6888
6889 // Look for the field.
6890 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
6891 LookupQualifiedName(R, RD);
6892 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
6893 if (!MemberDecl)
6894 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
6895 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
6896 OC.LocEnd));
6897
Douglas Gregor9d5d60f2010-04-28 22:36:06 +00006898 // C99 7.17p3:
6899 // (If the specified member is a bit-field, the behavior is undefined.)
6900 //
6901 // We diagnose this as an error.
6902 if (MemberDecl->getBitWidth()) {
6903 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
6904 << MemberDecl->getDeclName()
6905 << SourceRange(BuiltinLoc, RParenLoc);
6906 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
6907 return ExprError();
6908 }
6909
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00006910 // If the member was found in a base class, introduce OffsetOfNodes for
6911 // the base class indirections.
6912 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
6913 /*DetectVirtual=*/false);
6914 if (IsDerivedFrom(CurrentType,
6915 Context.getTypeDeclType(MemberDecl->getParent()),
6916 Paths)) {
6917 CXXBasePath &Path = Paths.front();
6918 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
6919 B != BEnd; ++B)
6920 Comps.push_back(OffsetOfNode(B->Base));
6921 }
6922
Douglas Gregor8ecdb652010-04-28 22:16:22 +00006923 if (cast<RecordDecl>(MemberDecl->getDeclContext())->
Douglas Gregor9d5d60f2010-04-28 22:36:06 +00006924 isAnonymousStructOrUnion()) {
Douglas Gregor8ecdb652010-04-28 22:16:22 +00006925 llvm::SmallVector<FieldDecl*, 4> Path;
6926 BuildAnonymousStructUnionMemberPath(MemberDecl, Path);
6927 unsigned n = Path.size();
6928 for (int j = n - 1; j > -1; --j)
6929 Comps.push_back(OffsetOfNode(OC.LocStart, Path[j], OC.LocEnd));
6930 } else {
6931 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
6932 }
6933 CurrentType = MemberDecl->getType().getNonReferenceType();
6934 }
6935
6936 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
6937 TInfo, Comps.data(), Comps.size(),
6938 Exprs.data(), Exprs.size(), RParenLoc));
6939}
Mike Stumpeed9cac2009-02-19 03:04:26 +00006940
Douglas Gregor8ecdb652010-04-28 22:16:22 +00006941Sema::OwningExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
6942 SourceLocation BuiltinLoc,
6943 SourceLocation TypeLoc,
6944 TypeTy *argty,
6945 OffsetOfComponent *CompPtr,
6946 unsigned NumComponents,
6947 SourceLocation RPLoc) {
6948
6949 TypeSourceInfo *ArgTInfo;
6950 QualType ArgTy = GetTypeFromParser(argty, &ArgTInfo);
6951 if (ArgTy.isNull())
6952 return ExprError();
6953
6954 if (getLangOptions().CPlusPlus) {
6955 if (!ArgTInfo)
6956 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
6957
6958 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
6959 RPLoc);
6960 }
6961
6962 // FIXME: The code below is marked for death, once we have proper CodeGen
6963 // support for non-constant OffsetOf expressions.
6964
6965 bool Dependent = ArgTy->isDependentType();
6966
6967 // We must have at least one component that refers to the type, and the first
6968 // one is known to be a field designator. Verify that the ArgTy represents
6969 // a struct/union/class.
6970 if (!Dependent && !ArgTy->isRecordType())
6971 return ExprError(Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy);
6972
6973 // FIXME: Type must be complete per C99 7.17p3 because a declaring a variable
6974 // with an incomplete type would be illegal.
6975
6976 // Otherwise, create a null pointer as the base, and iteratively process
6977 // the offsetof designators.
6978 QualType ArgTyPtr = Context.getPointerType(ArgTy);
6979 Expr* Res = new (Context) ImplicitValueInitExpr(ArgTyPtr);
6980 Res = new (Context) UnaryOperator(Res, UnaryOperator::Deref,
6981 ArgTy, SourceLocation());
6982
6983 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
6984 // GCC extension, diagnose them.
6985 // FIXME: This diagnostic isn't actually visible because the location is in
6986 // a system header!
6987 if (NumComponents != 1)
6988 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
6989 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
6990
Sebastian Redl28507842009-02-26 14:39:58 +00006991 if (!Dependent) {
Eli Friedmanc0d600c2009-05-03 21:22:18 +00006992 bool DidWarnAboutNonPOD = false;
Douglas Gregor8ecdb652010-04-28 22:16:22 +00006993
John McCalld00f2002009-11-04 03:03:43 +00006994 if (RequireCompleteType(TypeLoc, Res->getType(),
6995 diag::err_offsetof_incomplete_type))
6996 return ExprError();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00006997
Sebastian Redl28507842009-02-26 14:39:58 +00006998 // FIXME: Dependent case loses a lot of information here. And probably
6999 // leaks like a sieve.
7000 for (unsigned i = 0; i != NumComponents; ++i) {
7001 const OffsetOfComponent &OC = CompPtr[i];
7002 if (OC.isBrackets) {
7003 // Offset of an array sub-field. TODO: Should we allow vector elements?
7004 const ArrayType *AT = Context.getAsArrayType(Res->getType());
7005 if (!AT) {
7006 Res->Destroy(Context);
Sebastian Redlf53597f2009-03-15 17:47:39 +00007007 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
Douglas Gregor8ecdb652010-04-28 22:16:22 +00007008 << Res->getType());
Sebastian Redl28507842009-02-26 14:39:58 +00007009 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00007010
Sebastian Redl28507842009-02-26 14:39:58 +00007011 // FIXME: C++: Verify that operator[] isn't overloaded.
Douglas Gregor8ecdb652010-04-28 22:16:22 +00007012
Eli Friedman35183ac2009-02-27 06:44:11 +00007013 // Promote the array so it looks more like a normal array subscript
7014 // expression.
Douglas Gregora873dfc2010-02-03 00:27:59 +00007015 DefaultFunctionArrayLvalueConversion(Res);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00007016
Sebastian Redl28507842009-02-26 14:39:58 +00007017 // C99 6.5.2.1p1
7018 Expr *Idx = static_cast<Expr*>(OC.U.E);
Sebastian Redlf53597f2009-03-15 17:47:39 +00007019 // FIXME: Leaks Res
Sebastian Redl28507842009-02-26 14:39:58 +00007020 if (!Idx->isTypeDependent() && !Idx->getType()->isIntegerType())
Sebastian Redlf53597f2009-03-15 17:47:39 +00007021 return ExprError(Diag(Idx->getLocStart(),
Chris Lattner338395d2009-04-25 22:50:55 +00007022 diag::err_typecheck_subscript_not_integer)
Douglas Gregor8ecdb652010-04-28 22:16:22 +00007023 << Idx->getSourceRange());
7024
Sebastian Redl28507842009-02-26 14:39:58 +00007025 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
7026 OC.LocEnd);
7027 continue;
Chris Lattner73d0d4f2007-08-30 17:45:32 +00007028 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00007029
Ted Kremenek6217b802009-07-29 21:53:49 +00007030 const RecordType *RC = Res->getType()->getAs<RecordType>();
Sebastian Redl28507842009-02-26 14:39:58 +00007031 if (!RC) {
7032 Res->Destroy(Context);
Sebastian Redlf53597f2009-03-15 17:47:39 +00007033 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
Douglas Gregor8ecdb652010-04-28 22:16:22 +00007034 << Res->getType());
Sebastian Redl28507842009-02-26 14:39:58 +00007035 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00007036
Sebastian Redl28507842009-02-26 14:39:58 +00007037 // Get the decl corresponding to this.
7038 RecordDecl *RD = RC->getDecl();
Anders Carlsson6d7f1492009-05-01 23:20:30 +00007039 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00007040 if (!CRD->isPOD() && !DidWarnAboutNonPOD &&
7041 DiagRuntimeBehavior(BuiltinLoc,
7042 PDiag(diag::warn_offsetof_non_pod_type)
Douglas Gregor8ecdb652010-04-28 22:16:22 +00007043 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
7044 << Res->getType()))
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00007045 DidWarnAboutNonPOD = true;
Anders Carlsson6d7f1492009-05-01 23:20:30 +00007046 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00007047
John McCalla24dc2e2009-11-17 02:14:36 +00007048 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
7049 LookupQualifiedName(R, RD);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00007050
John McCall1bcee0a2009-12-02 08:25:40 +00007051 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Sebastian Redlf53597f2009-03-15 17:47:39 +00007052 // FIXME: Leaks Res
Sebastian Redl28507842009-02-26 14:39:58 +00007053 if (!MemberDecl)
Douglas Gregor3f093272009-10-13 21:16:44 +00007054 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
Douglas Gregor8ecdb652010-04-28 22:16:22 +00007055 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, OC.LocEnd));
7056
Douglas Gregor9d5d60f2010-04-28 22:36:06 +00007057 // C99 7.17p3:
7058 // (If the specified member is a bit-field, the behavior is undefined.)
7059 //
7060 // We diagnose this as an error.
7061 if (MemberDecl->getBitWidth()) {
7062 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
7063 << MemberDecl->getDeclName()
7064 << SourceRange(BuiltinLoc, RPLoc);
7065 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
7066 return ExprError();
7067 }
7068
Sebastian Redl28507842009-02-26 14:39:58 +00007069 // FIXME: C++: Verify that MemberDecl isn't a static field.
7070 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedmane9356962009-04-26 20:50:44 +00007071 if (cast<RecordDecl>(MemberDecl->getDeclContext())->isAnonymousStructOrUnion()) {
Anders Carlssonf1b1d592009-05-01 19:30:39 +00007072 Res = BuildAnonymousStructUnionMemberReference(
Douglas Gregor8ecdb652010-04-28 22:16:22 +00007073 OC.LocEnd, MemberDecl, Res, OC.LocEnd).takeAs<Expr>();
Eli Friedmane9356962009-04-26 20:50:44 +00007074 } else {
John McCall6bb80172010-03-30 21:47:33 +00007075 PerformObjectMemberConversion(Res, /*Qualifier=*/0,
7076 *R.begin(), MemberDecl);
Eli Friedmane9356962009-04-26 20:50:44 +00007077 // MemberDecl->getType() doesn't get the right qualifiers, but it
7078 // doesn't matter here.
7079 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
Douglas Gregor8ecdb652010-04-28 22:16:22 +00007080 MemberDecl->getType().getNonReferenceType());
Eli Friedmane9356962009-04-26 20:50:44 +00007081 }
Sebastian Redl28507842009-02-26 14:39:58 +00007082 }
Chris Lattner73d0d4f2007-08-30 17:45:32 +00007083 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00007084
Sebastian Redlf53597f2009-03-15 17:47:39 +00007085 return Owned(new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
7086 Context.getSizeType(), BuiltinLoc));
Chris Lattner73d0d4f2007-08-30 17:45:32 +00007087}
7088
7089
Sebastian Redlf53597f2009-03-15 17:47:39 +00007090Sema::OwningExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
7091 TypeTy *arg1,TypeTy *arg2,
7092 SourceLocation RPLoc) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00007093 // FIXME: Preserve type source info.
7094 QualType argT1 = GetTypeFromParser(arg1);
7095 QualType argT2 = GetTypeFromParser(arg2);
Mike Stumpeed9cac2009-02-19 03:04:26 +00007096
Steve Naroffd34e9152007-08-01 22:05:33 +00007097 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
Mike Stumpeed9cac2009-02-19 03:04:26 +00007098
Douglas Gregorc12a9c52009-05-19 22:28:02 +00007099 if (getLangOptions().CPlusPlus) {
7100 Diag(BuiltinLoc, diag::err_types_compatible_p_in_cplusplus)
7101 << SourceRange(BuiltinLoc, RPLoc);
7102 return ExprError();
7103 }
7104
Sebastian Redlf53597f2009-03-15 17:47:39 +00007105 return Owned(new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc,
7106 argT1, argT2, RPLoc));
Steve Naroffd34e9152007-08-01 22:05:33 +00007107}
7108
Sebastian Redlf53597f2009-03-15 17:47:39 +00007109Sema::OwningExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
7110 ExprArg cond,
7111 ExprArg expr1, ExprArg expr2,
7112 SourceLocation RPLoc) {
7113 Expr *CondExpr = static_cast<Expr*>(cond.get());
7114 Expr *LHSExpr = static_cast<Expr*>(expr1.get());
7115 Expr *RHSExpr = static_cast<Expr*>(expr2.get());
Mike Stumpeed9cac2009-02-19 03:04:26 +00007116
Steve Naroffd04fdd52007-08-03 21:21:27 +00007117 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
7118
Sebastian Redl28507842009-02-26 14:39:58 +00007119 QualType resType;
Douglas Gregorce940492009-09-25 04:25:58 +00007120 bool ValueDependent = false;
Douglas Gregorc9ecc572009-05-19 22:43:30 +00007121 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl28507842009-02-26 14:39:58 +00007122 resType = Context.DependentTy;
Douglas Gregorce940492009-09-25 04:25:58 +00007123 ValueDependent = true;
Sebastian Redl28507842009-02-26 14:39:58 +00007124 } else {
7125 // The conditional expression is required to be a constant expression.
7126 llvm::APSInt condEval(32);
7127 SourceLocation ExpLoc;
7128 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redlf53597f2009-03-15 17:47:39 +00007129 return ExprError(Diag(ExpLoc,
7130 diag::err_typecheck_choose_expr_requires_constant)
7131 << CondExpr->getSourceRange());
Steve Naroffd04fdd52007-08-03 21:21:27 +00007132
Sebastian Redl28507842009-02-26 14:39:58 +00007133 // If the condition is > zero, then the AST type is the same as the LSHExpr.
7134 resType = condEval.getZExtValue() ? LHSExpr->getType() : RHSExpr->getType();
Douglas Gregorce940492009-09-25 04:25:58 +00007135 ValueDependent = condEval.getZExtValue() ? LHSExpr->isValueDependent()
7136 : RHSExpr->isValueDependent();
Sebastian Redl28507842009-02-26 14:39:58 +00007137 }
7138
Sebastian Redlf53597f2009-03-15 17:47:39 +00007139 cond.release(); expr1.release(); expr2.release();
7140 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
Douglas Gregorce940492009-09-25 04:25:58 +00007141 resType, RPLoc,
7142 resType->isDependentType(),
7143 ValueDependent));
Steve Naroffd04fdd52007-08-03 21:21:27 +00007144}
7145
Steve Naroff4eb206b2008-09-03 18:15:37 +00007146//===----------------------------------------------------------------------===//
7147// Clang Extensions.
7148//===----------------------------------------------------------------------===//
7149
7150/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff090276f2008-10-10 01:28:17 +00007151void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00007152 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
7153 PushBlockScope(BlockScope, Block);
7154 CurContext->addDecl(Block);
Fariborz Jahaniana729da22010-07-09 18:44:02 +00007155 if (BlockScope)
7156 PushDeclContext(BlockScope, Block);
7157 else
7158 CurContext = Block;
Steve Naroff090276f2008-10-10 01:28:17 +00007159}
7160
Mike Stump98eb8a72009-02-04 22:31:32 +00007161void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpaf199f32009-05-07 18:43:07 +00007162 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00007163 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007164
John McCallbf1a0282010-06-04 23:28:52 +00007165 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
John McCall82dc0092010-06-04 11:21:44 +00007166 CurBlock->TheDecl->setSignatureAsWritten(Sig);
John McCallbf1a0282010-06-04 23:28:52 +00007167 QualType T = Sig->getType();
Mike Stump98eb8a72009-02-04 22:31:32 +00007168
John McCallc71a4912010-06-04 19:02:56 +00007169 bool isVariadic;
John McCall82dc0092010-06-04 11:21:44 +00007170 QualType RetTy;
7171 if (const FunctionType *Fn = T->getAs<FunctionType>()) {
John McCallc71a4912010-06-04 19:02:56 +00007172 CurBlock->FunctionType = T;
John McCall82dc0092010-06-04 11:21:44 +00007173 RetTy = Fn->getResultType();
John McCallc71a4912010-06-04 19:02:56 +00007174 isVariadic =
John McCall82dc0092010-06-04 11:21:44 +00007175 !isa<FunctionProtoType>(Fn) || cast<FunctionProtoType>(Fn)->isVariadic();
7176 } else {
7177 RetTy = T;
John McCallc71a4912010-06-04 19:02:56 +00007178 isVariadic = false;
John McCall82dc0092010-06-04 11:21:44 +00007179 }
Mike Stump1eb44332009-09-09 15:08:12 +00007180
John McCallc71a4912010-06-04 19:02:56 +00007181 CurBlock->TheDecl->setIsVariadic(isVariadic);
Douglas Gregora873dfc2010-02-03 00:27:59 +00007182
John McCall82dc0092010-06-04 11:21:44 +00007183 // Don't allow returning an array by value.
7184 if (RetTy->isArrayType()) {
7185 Diag(ParamInfo.getSourceRange().getBegin(), diag::err_block_returns_array);
Mike Stump98eb8a72009-02-04 22:31:32 +00007186 return;
7187 }
7188
John McCall82dc0092010-06-04 11:21:44 +00007189 // Don't allow returning a objc interface by value.
7190 if (RetTy->isObjCObjectType()) {
7191 Diag(ParamInfo.getSourceRange().getBegin(),
7192 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
7193 return;
7194 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007195
John McCall82dc0092010-06-04 11:21:44 +00007196 // Context.DependentTy is used as a placeholder for a missing block
John McCallc71a4912010-06-04 19:02:56 +00007197 // return type. TODO: what should we do with declarators like:
7198 // ^ * { ... }
7199 // If the answer is "apply template argument deduction"....
John McCall82dc0092010-06-04 11:21:44 +00007200 if (RetTy != Context.DependentTy)
7201 CurBlock->ReturnType = RetTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007202
John McCall82dc0092010-06-04 11:21:44 +00007203 // Push block parameters from the declarator if we had them.
John McCallc71a4912010-06-04 19:02:56 +00007204 llvm::SmallVector<ParmVarDecl*, 8> Params;
John McCall82dc0092010-06-04 11:21:44 +00007205 if (isa<FunctionProtoType>(T)) {
7206 FunctionProtoTypeLoc TL = cast<FunctionProtoTypeLoc>(Sig->getTypeLoc());
7207 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
7208 ParmVarDecl *Param = TL.getArg(I);
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00007209 if (Param->getIdentifier() == 0 &&
7210 !Param->isImplicit() &&
7211 !Param->isInvalidDecl() &&
7212 !getLangOptions().CPlusPlus)
7213 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
John McCallc71a4912010-06-04 19:02:56 +00007214 Params.push_back(Param);
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00007215 }
John McCall82dc0092010-06-04 11:21:44 +00007216
7217 // Fake up parameter variables if we have a typedef, like
7218 // ^ fntype { ... }
7219 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
7220 for (FunctionProtoType::arg_type_iterator
7221 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
7222 ParmVarDecl *Param =
7223 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
7224 ParamInfo.getSourceRange().getBegin(),
7225 *I);
John McCallc71a4912010-06-04 19:02:56 +00007226 Params.push_back(Param);
John McCall82dc0092010-06-04 11:21:44 +00007227 }
Steve Naroff4eb206b2008-09-03 18:15:37 +00007228 }
John McCall82dc0092010-06-04 11:21:44 +00007229
John McCallc71a4912010-06-04 19:02:56 +00007230 // Set the parameters on the block decl.
7231 if (!Params.empty())
7232 CurBlock->TheDecl->setParams(Params.data(), Params.size());
John McCall82dc0092010-06-04 11:21:44 +00007233
7234 // Finally we can process decl attributes.
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00007235 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCall053f4bd2010-03-22 09:20:08 +00007236
John McCallc71a4912010-06-04 19:02:56 +00007237 if (!isVariadic && CurBlock->TheDecl->getAttr<SentinelAttr>()) {
John McCall82dc0092010-06-04 11:21:44 +00007238 Diag(ParamInfo.getAttributes()->getLoc(),
7239 diag::warn_attribute_sentinel_not_variadic) << 1;
7240 // FIXME: remove the attribute.
7241 }
7242
7243 // Put the parameter variables in scope. We can bail out immediately
7244 // if we don't have any.
John McCallc71a4912010-06-04 19:02:56 +00007245 if (Params.empty())
John McCall82dc0092010-06-04 11:21:44 +00007246 return;
7247
John McCall053f4bd2010-03-22 09:20:08 +00007248 bool ShouldCheckShadow =
7249 Diags.getDiagnosticLevel(diag::warn_decl_shadow) != Diagnostic::Ignored;
7250
Steve Naroff090276f2008-10-10 01:28:17 +00007251 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCall7a9813c2010-01-22 00:28:27 +00007252 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
7253 (*AI)->setOwningFunction(CurBlock->TheDecl);
7254
Steve Naroff090276f2008-10-10 01:28:17 +00007255 // If this has an identifier, add it to the scope stack.
John McCall053f4bd2010-03-22 09:20:08 +00007256 if ((*AI)->getIdentifier()) {
7257 if (ShouldCheckShadow)
7258 CheckShadow(CurBlock->TheScope, *AI);
7259
Steve Naroff090276f2008-10-10 01:28:17 +00007260 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCall053f4bd2010-03-22 09:20:08 +00007261 }
John McCall7a9813c2010-01-22 00:28:27 +00007262 }
Steve Naroff4eb206b2008-09-03 18:15:37 +00007263}
7264
7265/// ActOnBlockError - If there is an error parsing a block, this callback
7266/// is invoked to pop the information about the block from the action impl.
7267void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00007268 // Pop off CurBlock, handle nested blocks.
Chris Lattner5c59e2b2009-04-21 22:38:46 +00007269 PopDeclContext();
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00007270 PopFunctionOrBlockScope();
Steve Naroff4eb206b2008-09-03 18:15:37 +00007271 // FIXME: Delete the ParmVarDecl objects as well???
Steve Naroff4eb206b2008-09-03 18:15:37 +00007272}
7273
7274/// ActOnBlockStmtExpr - This is called when the body of a block statement
7275/// literal was successfully completed. ^(int x){...}
Sebastian Redlf53597f2009-03-15 17:47:39 +00007276Sema::OwningExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
7277 StmtArg body, Scope *CurScope) {
Chris Lattner9af55002009-03-27 04:18:06 +00007278 // If blocks are disabled, emit an error.
7279 if (!LangOpts.Blocks)
7280 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump1eb44332009-09-09 15:08:12 +00007281
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00007282 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Fariborz Jahaniana729da22010-07-09 18:44:02 +00007283
Steve Naroff090276f2008-10-10 01:28:17 +00007284 PopDeclContext();
7285
Steve Naroff4eb206b2008-09-03 18:15:37 +00007286 QualType RetTy = Context.VoidTy;
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00007287 if (!BSI->ReturnType.isNull())
7288 RetTy = BSI->ReturnType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007289
Mike Stump56925862009-07-28 22:04:01 +00007290 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroff4eb206b2008-09-03 18:15:37 +00007291 QualType BlockTy;
John McCallc71a4912010-06-04 19:02:56 +00007292
7293 // If the user wrote a function type in some form, try to use that.
7294 if (!BSI->FunctionType.isNull()) {
7295 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
7296
7297 FunctionType::ExtInfo Ext = FTy->getExtInfo();
7298 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
7299
7300 // Turn protoless block types into nullary block types.
7301 if (isa<FunctionNoProtoType>(FTy)) {
7302 BlockTy = Context.getFunctionType(RetTy, 0, 0, false, 0,
7303 false, false, 0, 0, Ext);
7304
7305 // Otherwise, if we don't need to change anything about the function type,
7306 // preserve its sugar structure.
7307 } else if (FTy->getResultType() == RetTy &&
7308 (!NoReturn || FTy->getNoReturnAttr())) {
7309 BlockTy = BSI->FunctionType;
7310
7311 // Otherwise, make the minimal modifications to the function type.
7312 } else {
7313 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
7314 BlockTy = Context.getFunctionType(RetTy,
7315 FPT->arg_type_begin(),
7316 FPT->getNumArgs(),
7317 FPT->isVariadic(),
7318 /*quals*/ 0,
7319 FPT->hasExceptionSpec(),
7320 FPT->hasAnyExceptionSpec(),
7321 FPT->getNumExceptions(),
7322 FPT->exception_begin(),
7323 Ext);
7324 }
7325
7326 // If we don't have a function type, just build one from nothing.
7327 } else {
7328 BlockTy = Context.getFunctionType(RetTy, 0, 0, false, 0,
7329 false, false, 0, 0,
7330 FunctionType::ExtInfo(NoReturn, 0, CC_Default));
7331 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007332
Eli Friedmanb1d796d2009-03-23 00:24:07 +00007333 // FIXME: Check that return/parameter types are complete/non-abstract
John McCallc71a4912010-06-04 19:02:56 +00007334 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
7335 BSI->TheDecl->param_end());
Steve Naroff4eb206b2008-09-03 18:15:37 +00007336 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00007337
Chris Lattner17a78302009-04-19 05:28:12 +00007338 // If needed, diagnose invalid gotos and switches in the block.
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00007339 if (FunctionNeedsScopeChecking() && !hasAnyErrorsInThisFunction())
Chris Lattner17a78302009-04-19 05:28:12 +00007340 DiagnoseInvalidJumps(static_cast<CompoundStmt*>(body.get()));
Mike Stump1eb44332009-09-09 15:08:12 +00007341
Anders Carlssone9146f22009-05-01 19:49:17 +00007342 BSI->TheDecl->setBody(body.takeAs<CompoundStmt>());
Mike Stumpa3899eb2010-01-19 23:08:01 +00007343
7344 bool Good = true;
7345 // Check goto/label use.
7346 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
7347 I = BSI->LabelMap.begin(), E = BSI->LabelMap.end(); I != E; ++I) {
7348 LabelStmt *L = I->second;
7349
7350 // Verify that we have no forward references left. If so, there was a goto
7351 // or address of a label taken, but no definition of it.
7352 if (L->getSubStmt() != 0)
7353 continue;
7354
7355 // Emit error.
7356 Diag(L->getIdentLoc(), diag::err_undeclared_label_use) << L->getName();
7357 Good = false;
7358 }
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00007359 if (!Good) {
7360 PopFunctionOrBlockScope();
Mike Stumpa3899eb2010-01-19 23:08:01 +00007361 return ExprError();
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00007362 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007363
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00007364 // Issue any analysis-based warnings.
Ted Kremenekd064fdc2010-03-23 00:13:23 +00007365 const sema::AnalysisBasedWarnings::Policy &WP =
7366 AnalysisWarnings.getDefaultPolicy();
7367 AnalysisWarnings.IssueWarnings(WP, BSI->TheDecl, BlockTy);
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00007368
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00007369 Expr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy,
7370 BSI->hasBlockDeclRefExprs);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007371 PopFunctionOrBlockScope();
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00007372 return Owned(Result);
Steve Naroff4eb206b2008-09-03 18:15:37 +00007373}
7374
Sebastian Redlf53597f2009-03-15 17:47:39 +00007375Sema::OwningExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
7376 ExprArg expr, TypeTy *type,
7377 SourceLocation RPLoc) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00007378 QualType T = GetTypeFromParser(type);
Chris Lattner0d20b8a2009-04-05 15:49:53 +00007379 Expr *E = static_cast<Expr*>(expr.get());
7380 Expr *OrigExpr = E;
Mike Stump1eb44332009-09-09 15:08:12 +00007381
Anders Carlsson7c50aca2007-10-15 20:28:48 +00007382 InitBuiltinVaListType();
Eli Friedmanc34bcde2008-08-09 23:32:40 +00007383
7384 // Get the va_list type
7385 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedman5c091ba2009-05-16 12:46:54 +00007386 if (VaListType->isArrayType()) {
7387 // Deal with implicit array decay; for example, on x86-64,
7388 // va_list is an array, but it's supposed to decay to
7389 // a pointer for va_arg.
Eli Friedmanc34bcde2008-08-09 23:32:40 +00007390 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman5c091ba2009-05-16 12:46:54 +00007391 // Make sure the input expression also decays appropriately.
7392 UsualUnaryConversions(E);
7393 } else {
7394 // Otherwise, the va_list argument must be an l-value because
7395 // it is modified by va_arg.
Mike Stump1eb44332009-09-09 15:08:12 +00007396 if (!E->isTypeDependent() &&
Douglas Gregordd027302009-05-19 23:10:31 +00007397 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedman5c091ba2009-05-16 12:46:54 +00007398 return ExprError();
7399 }
Eli Friedmanc34bcde2008-08-09 23:32:40 +00007400
Douglas Gregordd027302009-05-19 23:10:31 +00007401 if (!E->isTypeDependent() &&
7402 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redlf53597f2009-03-15 17:47:39 +00007403 return ExprError(Diag(E->getLocStart(),
7404 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner0d20b8a2009-04-05 15:49:53 +00007405 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner9dc8f192009-04-05 00:59:53 +00007406 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007407
Eli Friedmanb1d796d2009-03-23 00:24:07 +00007408 // FIXME: Check that type is complete/non-abstract
Anders Carlsson7c50aca2007-10-15 20:28:48 +00007409 // FIXME: Warn if a non-POD type is passed in.
Mike Stumpeed9cac2009-02-19 03:04:26 +00007410
Sebastian Redlf53597f2009-03-15 17:47:39 +00007411 expr.release();
Douglas Gregor63982352010-07-13 18:40:04 +00007412 return Owned(new (Context) VAArgExpr(BuiltinLoc, E,
7413 T.getNonLValueExprType(Context),
Sebastian Redlf53597f2009-03-15 17:47:39 +00007414 RPLoc));
Anders Carlsson7c50aca2007-10-15 20:28:48 +00007415}
7416
Sebastian Redlf53597f2009-03-15 17:47:39 +00007417Sema::OwningExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor2d8b2732008-11-29 04:51:27 +00007418 // The type of __null will be int or long, depending on the size of
7419 // pointers on the target.
7420 QualType Ty;
7421 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
7422 Ty = Context.IntTy;
7423 else
7424 Ty = Context.LongTy;
7425
Sebastian Redlf53597f2009-03-15 17:47:39 +00007426 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor2d8b2732008-11-29 04:51:27 +00007427}
7428
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00007429static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
Douglas Gregor849b2432010-03-31 17:46:05 +00007430 Expr *SrcExpr, FixItHint &Hint) {
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00007431 if (!SemaRef.getLangOptions().ObjC1)
7432 return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007433
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00007434 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
7435 if (!PT)
7436 return;
7437
7438 // Check if the destination is of type 'id'.
7439 if (!PT->isObjCIdType()) {
7440 // Check if the destination is the 'NSString' interface.
7441 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
7442 if (!ID || !ID->getIdentifier()->isStr("NSString"))
7443 return;
7444 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007445
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00007446 // Strip off any parens and casts.
7447 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
7448 if (!SL || SL->isWide())
7449 return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007450
Douglas Gregor849b2432010-03-31 17:46:05 +00007451 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00007452}
7453
Chris Lattner5cf216b2008-01-04 18:04:52 +00007454bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
7455 SourceLocation Loc,
7456 QualType DstType, QualType SrcType,
Douglas Gregora41a8c52010-04-22 00:20:18 +00007457 Expr *SrcExpr, AssignmentAction Action,
7458 bool *Complained) {
7459 if (Complained)
7460 *Complained = false;
7461
Chris Lattner5cf216b2008-01-04 18:04:52 +00007462 // Decode the result (notice that AST's are still created for extensions).
7463 bool isInvalid = false;
7464 unsigned DiagKind;
Douglas Gregor849b2432010-03-31 17:46:05 +00007465 FixItHint Hint;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007466
Chris Lattner5cf216b2008-01-04 18:04:52 +00007467 switch (ConvTy) {
7468 default: assert(0 && "Unknown conversion type");
7469 case Compatible: return false;
Chris Lattnerb7b61152008-01-04 18:22:42 +00007470 case PointerToInt:
Chris Lattner5cf216b2008-01-04 18:04:52 +00007471 DiagKind = diag::ext_typecheck_convert_pointer_int;
7472 break;
Chris Lattnerb7b61152008-01-04 18:22:42 +00007473 case IntToPointer:
7474 DiagKind = diag::ext_typecheck_convert_int_pointer;
7475 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00007476 case IncompatiblePointer:
Douglas Gregor849b2432010-03-31 17:46:05 +00007477 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
Chris Lattner5cf216b2008-01-04 18:04:52 +00007478 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
7479 break;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00007480 case IncompatiblePointerSign:
7481 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
7482 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00007483 case FunctionVoidPointer:
7484 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
7485 break;
7486 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor77a52232008-09-12 00:47:35 +00007487 // If the qualifiers lost were because we were applying the
7488 // (deprecated) C++ conversion from a string literal to a char*
7489 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
7490 // Ideally, this check would be performed in
7491 // CheckPointerTypesForAssignment. However, that would require a
7492 // bit of refactoring (so that the second argument is an
7493 // expression, rather than a type), which should be done as part
7494 // of a larger effort to fix CheckPointerTypesForAssignment for
7495 // C++ semantics.
7496 if (getLangOptions().CPlusPlus &&
7497 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
7498 return false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00007499 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
7500 break;
Sean Huntc9132b62009-11-08 07:46:34 +00007501 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanian3451e922009-11-09 22:16:37 +00007502 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00007503 break;
Steve Naroff1c7d0672008-09-04 15:10:53 +00007504 case IntToBlockPointer:
7505 DiagKind = diag::err_int_to_block_pointer;
7506 break;
7507 case IncompatibleBlockPointer:
Mike Stump25efa102009-04-21 22:51:42 +00007508 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00007509 break;
Steve Naroff39579072008-10-14 22:18:38 +00007510 case IncompatibleObjCQualifiedId:
Mike Stumpeed9cac2009-02-19 03:04:26 +00007511 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff39579072008-10-14 22:18:38 +00007512 // it can give a more specific diagnostic.
7513 DiagKind = diag::warn_incompatible_qualified_id;
7514 break;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00007515 case IncompatibleVectors:
7516 DiagKind = diag::warn_incompatible_vectors;
7517 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00007518 case Incompatible:
7519 DiagKind = diag::err_typecheck_convert_incompatible;
7520 isInvalid = true;
7521 break;
7522 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007523
Douglas Gregord4eea832010-04-09 00:35:39 +00007524 QualType FirstType, SecondType;
7525 switch (Action) {
7526 case AA_Assigning:
7527 case AA_Initializing:
7528 // The destination type comes first.
7529 FirstType = DstType;
7530 SecondType = SrcType;
7531 break;
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00007532
Douglas Gregord4eea832010-04-09 00:35:39 +00007533 case AA_Returning:
7534 case AA_Passing:
7535 case AA_Converting:
7536 case AA_Sending:
7537 case AA_Casting:
7538 // The source type comes first.
7539 FirstType = SrcType;
7540 SecondType = DstType;
7541 break;
7542 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00007543
Douglas Gregord4eea832010-04-09 00:35:39 +00007544 Diag(Loc, DiagKind) << FirstType << SecondType << Action
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00007545 << SrcExpr->getSourceRange() << Hint;
Douglas Gregora41a8c52010-04-22 00:20:18 +00007546 if (Complained)
7547 *Complained = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00007548 return isInvalid;
7549}
Anders Carlssone21555e2008-11-30 19:50:32 +00007550
Chris Lattner3bf68932009-04-25 21:59:05 +00007551bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedman3b5ccca2009-04-25 22:26:58 +00007552 llvm::APSInt ICEResult;
7553 if (E->isIntegerConstantExpr(ICEResult, Context)) {
7554 if (Result)
7555 *Result = ICEResult;
7556 return false;
7557 }
7558
Anders Carlssone21555e2008-11-30 19:50:32 +00007559 Expr::EvalResult EvalResult;
7560
Mike Stumpeed9cac2009-02-19 03:04:26 +00007561 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone21555e2008-11-30 19:50:32 +00007562 EvalResult.HasSideEffects) {
7563 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
7564
7565 if (EvalResult.Diag) {
7566 // We only show the note if it's not the usual "invalid subexpression"
7567 // or if it's actually in a subexpression.
7568 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
7569 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
7570 Diag(EvalResult.DiagLoc, EvalResult.Diag);
7571 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007572
Anders Carlssone21555e2008-11-30 19:50:32 +00007573 return true;
7574 }
7575
Eli Friedman3b5ccca2009-04-25 22:26:58 +00007576 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
7577 E->getSourceRange();
Anders Carlssone21555e2008-11-30 19:50:32 +00007578
Eli Friedman3b5ccca2009-04-25 22:26:58 +00007579 if (EvalResult.Diag &&
7580 Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
7581 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stumpeed9cac2009-02-19 03:04:26 +00007582
Anders Carlssone21555e2008-11-30 19:50:32 +00007583 if (Result)
7584 *Result = EvalResult.Val.getInt();
7585 return false;
7586}
Douglas Gregore0762c92009-06-19 23:52:42 +00007587
Douglas Gregor2afce722009-11-26 00:44:06 +00007588void
Mike Stump1eb44332009-09-09 15:08:12 +00007589Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregor2afce722009-11-26 00:44:06 +00007590 ExprEvalContexts.push_back(
7591 ExpressionEvaluationContextRecord(NewContext, ExprTemporaries.size()));
Douglas Gregorac7610d2009-06-22 20:57:11 +00007592}
7593
Mike Stump1eb44332009-09-09 15:08:12 +00007594void
Douglas Gregor2afce722009-11-26 00:44:06 +00007595Sema::PopExpressionEvaluationContext() {
7596 // Pop the current expression evaluation context off the stack.
7597 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
7598 ExprEvalContexts.pop_back();
Douglas Gregorac7610d2009-06-22 20:57:11 +00007599
Douglas Gregor06d33692009-12-12 07:57:52 +00007600 if (Rec.Context == PotentiallyPotentiallyEvaluated) {
7601 if (Rec.PotentiallyReferenced) {
7602 // Mark any remaining declarations in the current position of the stack
7603 // as "referenced". If they were not meant to be referenced, semantic
7604 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007605 for (PotentiallyReferencedDecls::iterator
Douglas Gregor06d33692009-12-12 07:57:52 +00007606 I = Rec.PotentiallyReferenced->begin(),
7607 IEnd = Rec.PotentiallyReferenced->end();
7608 I != IEnd; ++I)
7609 MarkDeclarationReferenced(I->first, I->second);
7610 }
7611
7612 if (Rec.PotentiallyDiagnosed) {
7613 // Emit any pending diagnostics.
7614 for (PotentiallyEmittedDiagnostics::iterator
7615 I = Rec.PotentiallyDiagnosed->begin(),
7616 IEnd = Rec.PotentiallyDiagnosed->end();
7617 I != IEnd; ++I)
7618 Diag(I->first, I->second);
7619 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007620 }
Douglas Gregor2afce722009-11-26 00:44:06 +00007621
7622 // When are coming out of an unevaluated context, clear out any
7623 // temporaries that we may have created as part of the evaluation of
7624 // the expression in that context: they aren't relevant because they
7625 // will never be constructed.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007626 if (Rec.Context == Unevaluated &&
Douglas Gregor2afce722009-11-26 00:44:06 +00007627 ExprTemporaries.size() > Rec.NumTemporaries)
7628 ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
7629 ExprTemporaries.end());
7630
7631 // Destroy the popped expression evaluation record.
7632 Rec.Destroy();
Douglas Gregorac7610d2009-06-22 20:57:11 +00007633}
Douglas Gregore0762c92009-06-19 23:52:42 +00007634
7635/// \brief Note that the given declaration was referenced in the source code.
7636///
7637/// This routine should be invoke whenever a given declaration is referenced
7638/// in the source code, and where that reference occurred. If this declaration
7639/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
7640/// C99 6.9p3), then the declaration will be marked as used.
7641///
7642/// \param Loc the location where the declaration was referenced.
7643///
7644/// \param D the declaration that has been referenced by the source code.
7645void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
7646 assert(D && "No declaration?");
Mike Stump1eb44332009-09-09 15:08:12 +00007647
Douglas Gregorc070cc62010-06-17 23:14:26 +00007648 if (D->isUsed(false))
Douglas Gregord7f37bf2009-06-22 23:06:13 +00007649 return;
Mike Stump1eb44332009-09-09 15:08:12 +00007650
Douglas Gregorb5352cf2009-10-08 21:35:42 +00007651 // Mark a parameter or variable declaration "used", regardless of whether we're in a
7652 // template or not. The reason for this is that unevaluated expressions
7653 // (e.g. (void)sizeof()) constitute a use for warning purposes (-Wunused-variables and
7654 // -Wunused-parameters)
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007655 if (isa<ParmVarDecl>(D) ||
Douglas Gregorfc2ca562010-04-07 20:29:57 +00007656 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod())) {
Douglas Gregore0762c92009-06-19 23:52:42 +00007657 D->setUsed(true);
Douglas Gregorfc2ca562010-04-07 20:29:57 +00007658 return;
7659 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00007660
Douglas Gregorfc2ca562010-04-07 20:29:57 +00007661 if (!isa<VarDecl>(D) && !isa<FunctionDecl>(D))
7662 return;
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00007663
Douglas Gregore0762c92009-06-19 23:52:42 +00007664 // Do not mark anything as "used" within a dependent context; wait for
7665 // an instantiation.
7666 if (CurContext->isDependentContext())
7667 return;
Mike Stump1eb44332009-09-09 15:08:12 +00007668
Douglas Gregor2afce722009-11-26 00:44:06 +00007669 switch (ExprEvalContexts.back().Context) {
Douglas Gregorac7610d2009-06-22 20:57:11 +00007670 case Unevaluated:
7671 // We are in an expression that is not potentially evaluated; do nothing.
7672 return;
Mike Stump1eb44332009-09-09 15:08:12 +00007673
Douglas Gregorac7610d2009-06-22 20:57:11 +00007674 case PotentiallyEvaluated:
7675 // We are in a potentially-evaluated expression, so this declaration is
7676 // "used"; handle this below.
7677 break;
Mike Stump1eb44332009-09-09 15:08:12 +00007678
Douglas Gregorac7610d2009-06-22 20:57:11 +00007679 case PotentiallyPotentiallyEvaluated:
7680 // We are in an expression that may be potentially evaluated; queue this
7681 // declaration reference until we know whether the expression is
7682 // potentially evaluated.
Douglas Gregor2afce722009-11-26 00:44:06 +00007683 ExprEvalContexts.back().addReferencedDecl(Loc, D);
Douglas Gregorac7610d2009-06-22 20:57:11 +00007684 return;
7685 }
Mike Stump1eb44332009-09-09 15:08:12 +00007686
Douglas Gregore0762c92009-06-19 23:52:42 +00007687 // Note that this declaration has been used.
Fariborz Jahanianb7f4cc02009-06-22 17:30:33 +00007688 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00007689 unsigned TypeQuals;
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00007690 if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) {
Douglas Gregorc070cc62010-06-17 23:14:26 +00007691 if (!Constructor->isUsed(false))
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00007692 DefineImplicitDefaultConstructor(Loc, Constructor);
Mike Stump1eb44332009-09-09 15:08:12 +00007693 } else if (Constructor->isImplicit() &&
Douglas Gregor9e9199d2009-12-22 00:34:07 +00007694 Constructor->isCopyConstructor(TypeQuals)) {
Douglas Gregorc070cc62010-06-17 23:14:26 +00007695 if (!Constructor->isUsed(false))
Fariborz Jahanian485f0872009-06-22 23:34:40 +00007696 DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals);
7697 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007698
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007699 MarkVTableUsed(Loc, Constructor->getParent());
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007700 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Douglas Gregorc070cc62010-06-17 23:14:26 +00007701 if (Destructor->isImplicit() && !Destructor->isUsed(false))
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007702 DefineImplicitDestructor(Loc, Destructor);
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007703 if (Destructor->isVirtual())
7704 MarkVTableUsed(Loc, Destructor->getParent());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007705 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
7706 if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
7707 MethodDecl->getOverloadedOperator() == OO_Equal) {
Douglas Gregorc070cc62010-06-17 23:14:26 +00007708 if (!MethodDecl->isUsed(false))
Douglas Gregor39957dc2010-05-01 15:04:51 +00007709 DefineImplicitCopyAssignment(Loc, MethodDecl);
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007710 } else if (MethodDecl->isVirtual())
7711 MarkVTableUsed(Loc, MethodDecl->getParent());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007712 }
Fariborz Jahanianf5ed9e02009-06-24 22:09:44 +00007713 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Mike Stump1eb44332009-09-09 15:08:12 +00007714 // Implicit instantiation of function templates and member functions of
Douglas Gregor1637be72009-06-26 00:10:03 +00007715 // class templates.
Douglas Gregor6cfacfe2010-05-17 17:34:56 +00007716 if (Function->isImplicitlyInstantiable()) {
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00007717 bool AlreadyInstantiated = false;
7718 if (FunctionTemplateSpecializationInfo *SpecInfo
7719 = Function->getTemplateSpecializationInfo()) {
7720 if (SpecInfo->getPointOfInstantiation().isInvalid())
7721 SpecInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007722 else if (SpecInfo->getTemplateSpecializationKind()
Douglas Gregor3b846b62009-10-27 20:53:28 +00007723 == TSK_ImplicitInstantiation)
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00007724 AlreadyInstantiated = true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007725 } else if (MemberSpecializationInfo *MSInfo
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00007726 = Function->getMemberSpecializationInfo()) {
7727 if (MSInfo->getPointOfInstantiation().isInvalid())
7728 MSInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007729 else if (MSInfo->getTemplateSpecializationKind()
Douglas Gregor3b846b62009-10-27 20:53:28 +00007730 == TSK_ImplicitInstantiation)
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00007731 AlreadyInstantiated = true;
7732 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007733
Douglas Gregor60406be2010-01-16 22:29:39 +00007734 if (!AlreadyInstantiated) {
7735 if (isa<CXXRecordDecl>(Function->getDeclContext()) &&
7736 cast<CXXRecordDecl>(Function->getDeclContext())->isLocalClass())
7737 PendingLocalImplicitInstantiations.push_back(std::make_pair(Function,
7738 Loc));
7739 else
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007740 PendingImplicitInstantiations.push_back(std::make_pair(Function,
Douglas Gregor60406be2010-01-16 22:29:39 +00007741 Loc));
7742 }
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00007743 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007744
Douglas Gregore0762c92009-06-19 23:52:42 +00007745 // FIXME: keep track of references to static functions
Douglas Gregore0762c92009-06-19 23:52:42 +00007746 Function->setUsed(true);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007747
Douglas Gregore0762c92009-06-19 23:52:42 +00007748 return;
Douglas Gregord7f37bf2009-06-22 23:06:13 +00007749 }
Mike Stump1eb44332009-09-09 15:08:12 +00007750
Douglas Gregore0762c92009-06-19 23:52:42 +00007751 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00007752 // Implicit instantiation of static data members of class templates.
Mike Stump1eb44332009-09-09 15:08:12 +00007753 if (Var->isStaticDataMember() &&
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00007754 Var->getInstantiatedFromStaticDataMember()) {
7755 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
7756 assert(MSInfo && "Missing member specialization information?");
7757 if (MSInfo->getPointOfInstantiation().isInvalid() &&
7758 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
7759 MSInfo->setPointOfInstantiation(Loc);
7760 PendingImplicitInstantiations.push_back(std::make_pair(Var, Loc));
7761 }
7762 }
Mike Stump1eb44332009-09-09 15:08:12 +00007763
Douglas Gregore0762c92009-06-19 23:52:42 +00007764 // FIXME: keep track of references to static data?
Douglas Gregor7caa6822009-07-24 20:34:43 +00007765
Douglas Gregore0762c92009-06-19 23:52:42 +00007766 D->setUsed(true);
Douglas Gregor7caa6822009-07-24 20:34:43 +00007767 return;
Sam Weinigcce6ebc2009-09-11 03:29:30 +00007768 }
Douglas Gregore0762c92009-06-19 23:52:42 +00007769}
Anders Carlsson8c8d9192009-10-09 23:51:55 +00007770
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00007771namespace {
Chandler Carruthdfc35e32010-06-09 08:17:30 +00007772 // Mark all of the declarations referenced
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00007773 // FIXME: Not fully implemented yet! We need to have a better understanding
Chandler Carruthdfc35e32010-06-09 08:17:30 +00007774 // of when we're entering
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00007775 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
7776 Sema &S;
7777 SourceLocation Loc;
Chandler Carruthdfc35e32010-06-09 08:17:30 +00007778
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00007779 public:
7780 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
Chandler Carruthdfc35e32010-06-09 08:17:30 +00007781
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00007782 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
Chandler Carruthdfc35e32010-06-09 08:17:30 +00007783
7784 bool TraverseTemplateArgument(const TemplateArgument &Arg);
7785 bool TraverseRecordType(RecordType *T);
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00007786 };
7787}
7788
Chandler Carruthdfc35e32010-06-09 08:17:30 +00007789bool MarkReferencedDecls::TraverseTemplateArgument(
7790 const TemplateArgument &Arg) {
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00007791 if (Arg.getKind() == TemplateArgument::Declaration) {
7792 S.MarkDeclarationReferenced(Loc, Arg.getAsDecl());
7793 }
Chandler Carruthdfc35e32010-06-09 08:17:30 +00007794
7795 return Inherited::TraverseTemplateArgument(Arg);
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00007796}
7797
Chandler Carruthdfc35e32010-06-09 08:17:30 +00007798bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00007799 if (ClassTemplateSpecializationDecl *Spec
7800 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
7801 const TemplateArgumentList &Args = Spec->getTemplateArgs();
Chandler Carruthdfc35e32010-06-09 08:17:30 +00007802 return TraverseTemplateArguments(Args.getFlatArgumentList(),
7803 Args.flat_size());
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00007804 }
7805
Chandler Carruthe3e210c2010-06-10 10:31:57 +00007806 return true;
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00007807}
7808
7809void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
7810 MarkReferencedDecls Marker(*this, Loc);
Chandler Carruthdfc35e32010-06-09 08:17:30 +00007811 Marker.TraverseType(Context.getCanonicalType(T));
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00007812}
7813
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00007814/// \brief Emit a diagnostic that describes an effect on the run-time behavior
7815/// of the program being compiled.
7816///
7817/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007818/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00007819/// possibility that the code will actually be executable. Code in sizeof()
7820/// expressions, code used only during overload resolution, etc., are not
7821/// potentially evaluated. This routine will suppress such diagnostics or,
7822/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007823/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00007824/// later.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007825///
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00007826/// This routine should be used for all diagnostics that describe the run-time
7827/// behavior of a program, such as passing a non-POD value through an ellipsis.
7828/// Failure to do so will likely result in spurious diagnostics or failures
7829/// during overload resolution or within sizeof/alignof/typeof/typeid.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007830bool Sema::DiagRuntimeBehavior(SourceLocation Loc,
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00007831 const PartialDiagnostic &PD) {
7832 switch (ExprEvalContexts.back().Context ) {
7833 case Unevaluated:
7834 // The argument will never be evaluated, so don't complain.
7835 break;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007836
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00007837 case PotentiallyEvaluated:
7838 Diag(Loc, PD);
7839 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007840
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00007841 case PotentiallyPotentiallyEvaluated:
7842 ExprEvalContexts.back().addDiagnostic(Loc, PD);
7843 break;
7844 }
7845
7846 return false;
7847}
7848
Anders Carlsson8c8d9192009-10-09 23:51:55 +00007849bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
7850 CallExpr *CE, FunctionDecl *FD) {
7851 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
7852 return false;
7853
7854 PartialDiagnostic Note =
7855 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
7856 << FD->getDeclName() : PDiag();
7857 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007858
Anders Carlsson8c8d9192009-10-09 23:51:55 +00007859 if (RequireCompleteType(Loc, ReturnType,
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007860 FD ?
Anders Carlsson8c8d9192009-10-09 23:51:55 +00007861 PDiag(diag::err_call_function_incomplete_return)
7862 << CE->getSourceRange() << FD->getDeclName() :
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007863 PDiag(diag::err_call_incomplete_return)
Anders Carlsson8c8d9192009-10-09 23:51:55 +00007864 << CE->getSourceRange(),
7865 std::make_pair(NoteLoc, Note)))
7866 return true;
7867
7868 return false;
7869}
7870
John McCall5a881bb2009-10-12 21:59:07 +00007871// Diagnose the common s/=/==/ typo. Note that adding parentheses
7872// will prevent this condition from triggering, which is what we want.
7873void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
7874 SourceLocation Loc;
7875
John McCalla52ef082009-11-11 02:41:58 +00007876 unsigned diagnostic = diag::warn_condition_is_assignment;
7877
John McCall5a881bb2009-10-12 21:59:07 +00007878 if (isa<BinaryOperator>(E)) {
7879 BinaryOperator *Op = cast<BinaryOperator>(E);
7880 if (Op->getOpcode() != BinaryOperator::Assign)
7881 return;
7882
John McCallc8d8ac52009-11-12 00:06:05 +00007883 // Greylist some idioms by putting them into a warning subcategory.
7884 if (ObjCMessageExpr *ME
7885 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
7886 Selector Sel = ME->getSelector();
7887
John McCallc8d8ac52009-11-12 00:06:05 +00007888 // self = [<foo> init...]
7889 if (isSelfExpr(Op->getLHS())
7890 && Sel.getIdentifierInfoForSlot(0)->getName().startswith("init"))
7891 diagnostic = diag::warn_condition_is_idiomatic_assignment;
7892
7893 // <foo> = [<bar> nextObject]
7894 else if (Sel.isUnarySelector() &&
7895 Sel.getIdentifierInfoForSlot(0)->getName() == "nextObject")
7896 diagnostic = diag::warn_condition_is_idiomatic_assignment;
7897 }
John McCalla52ef082009-11-11 02:41:58 +00007898
John McCall5a881bb2009-10-12 21:59:07 +00007899 Loc = Op->getOperatorLoc();
7900 } else if (isa<CXXOperatorCallExpr>(E)) {
7901 CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(E);
7902 if (Op->getOperator() != OO_Equal)
7903 return;
7904
7905 Loc = Op->getOperatorLoc();
7906 } else {
7907 // Not an assignment.
7908 return;
7909 }
7910
John McCall5a881bb2009-10-12 21:59:07 +00007911 SourceLocation Open = E->getSourceRange().getBegin();
John McCall2d152152009-10-12 22:25:59 +00007912 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007913
Douglas Gregor55b38842010-04-14 16:09:52 +00007914 Diag(Loc, diagnostic) << E->getSourceRange();
Douglas Gregor827feec2010-01-08 00:20:23 +00007915 Diag(Loc, diag::note_condition_assign_to_comparison)
Douglas Gregor849b2432010-03-31 17:46:05 +00007916 << FixItHint::CreateReplacement(Loc, "==");
Douglas Gregor55b38842010-04-14 16:09:52 +00007917 Diag(Loc, diag::note_condition_assign_silence)
7918 << FixItHint::CreateInsertion(Open, "(")
7919 << FixItHint::CreateInsertion(Close, ")");
John McCall5a881bb2009-10-12 21:59:07 +00007920}
7921
7922bool Sema::CheckBooleanCondition(Expr *&E, SourceLocation Loc) {
7923 DiagnoseAssignmentAsCondition(E);
7924
7925 if (!E->isTypeDependent()) {
Douglas Gregora873dfc2010-02-03 00:27:59 +00007926 DefaultFunctionArrayLvalueConversion(E);
John McCall5a881bb2009-10-12 21:59:07 +00007927
7928 QualType T = E->getType();
7929
7930 if (getLangOptions().CPlusPlus) {
7931 if (CheckCXXBooleanCondition(E)) // C++ 6.4p4
7932 return true;
7933 } else if (!T->isScalarType()) { // C99 6.8.4.1p1
7934 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
7935 << T << E->getSourceRange();
7936 return true;
7937 }
7938 }
7939
7940 return false;
7941}
Douglas Gregor586596f2010-05-06 17:25:47 +00007942
7943Sema::OwningExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
7944 ExprArg SubExpr) {
Douglas Gregoreecf38f2010-05-06 21:39:56 +00007945 Expr *Sub = SubExpr.takeAs<Expr>();
7946 if (!Sub)
Douglas Gregor586596f2010-05-06 17:25:47 +00007947 return ExprError();
7948
Douglas Gregor586596f2010-05-06 17:25:47 +00007949 if (CheckBooleanCondition(Sub, Loc)) {
7950 Sub->Destroy(Context);
7951 return ExprError();
7952 }
7953
7954 return Owned(Sub);
7955}