blob: 987de9b5b45dce03daeb71e817f623274e13ee65 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
John McCall7d384dd2009-11-18 07:57:50 +000015#include "Lookup.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000016#include "clang/AST/ASTContext.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000017#include "clang/AST/DeclObjC.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000018#include "clang/AST/DeclTemplate.h"
Chris Lattner04421082008-04-08 04:40:51 +000019#include "clang/AST/ExprCXX.h"
Steve Narofff494b572008-05-29 21:12:08 +000020#include "clang/AST/ExprObjC.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000021#include "clang/Basic/PartialDiagnostic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000022#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000023#include "clang/Basic/TargetInfo.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000024#include "clang/Lex/LiteralSupport.h"
25#include "clang/Lex/Preprocessor.h"
Steve Naroff4eb206b2008-09-03 18:15:37 +000026#include "clang/Parse/DeclSpec.h"
Chris Lattner418f6c72008-10-26 23:43:26 +000027#include "clang/Parse/Designator.h"
Steve Naroff4eb206b2008-09-03 18:15:37 +000028#include "clang/Parse/Scope.h"
Douglas Gregor314b97f2009-11-10 19:49:08 +000029#include "clang/Parse/Template.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000030using namespace clang;
31
David Chisnall0f436562009-08-17 16:35:33 +000032
Douglas Gregor48f3bb92009-02-18 21:56:37 +000033/// \brief Determine whether the use of this declaration is valid, and
34/// emit any corresponding diagnostics.
35///
36/// This routine diagnoses various problems with referencing
37/// declarations that can occur when using a declaration. For example,
38/// it might warn if a deprecated or unavailable declaration is being
39/// used, or produce an error (and return true) if a C++0x deleted
40/// function is being used.
41///
Chris Lattner52338262009-10-25 22:31:57 +000042/// If IgnoreDeprecated is set to true, this should not want about deprecated
43/// decls.
44///
Douglas Gregor48f3bb92009-02-18 21:56:37 +000045/// \returns true if there was an error (this declaration cannot be
46/// referenced), false otherwise.
Chris Lattner52338262009-10-25 22:31:57 +000047///
John McCall54abf7d2009-11-04 02:18:39 +000048bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc) {
Chris Lattner76a642f2009-02-15 22:43:40 +000049 // See if the decl is deprecated.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +000050 if (D->getAttr<DeprecatedAttr>()) {
John McCall54abf7d2009-11-04 02:18:39 +000051 EmitDeprecationWarning(D, Loc);
Chris Lattner76a642f2009-02-15 22:43:40 +000052 }
53
Chris Lattnerffb93682009-10-25 17:21:40 +000054 // See if the decl is unavailable
55 if (D->getAttr<UnavailableAttr>()) {
56 Diag(Loc, diag::warn_unavailable) << D->getDeclName();
57 Diag(D->getLocation(), diag::note_unavailable_here) << 0;
58 }
59
Douglas Gregor48f3bb92009-02-18 21:56:37 +000060 // See if this is a deleted function.
Douglas Gregor25d944a2009-02-24 04:26:15 +000061 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +000062 if (FD->isDeleted()) {
63 Diag(Loc, diag::err_deleted_function_use);
64 Diag(D->getLocation(), diag::note_unavailable_here) << true;
65 return true;
66 }
Douglas Gregor25d944a2009-02-24 04:26:15 +000067 }
Douglas Gregor48f3bb92009-02-18 21:56:37 +000068
Douglas Gregor48f3bb92009-02-18 21:56:37 +000069 return false;
Chris Lattner76a642f2009-02-15 22:43:40 +000070}
71
Fariborz Jahanian5b530052009-05-13 18:09:35 +000072/// DiagnoseSentinelCalls - This routine checks on method dispatch calls
Mike Stump1eb44332009-09-09 15:08:12 +000073/// (and other functions in future), which have been declared with sentinel
Fariborz Jahanian5b530052009-05-13 18:09:35 +000074/// attribute. It warns if call does not have the sentinel argument.
75///
76void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +000077 Expr **Args, unsigned NumArgs) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +000078 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Mike Stump1eb44332009-09-09 15:08:12 +000079 if (!attr)
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +000080 return;
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +000081 int sentinelPos = attr->getSentinel();
82 int nullPos = attr->getNullPos();
Mike Stump1eb44332009-09-09 15:08:12 +000083
Mike Stump390b4cc2009-05-16 07:39:55 +000084 // FIXME. ObjCMethodDecl and FunctionDecl need be derived from the same common
85 // base class. Then we won't be needing two versions of the same code.
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +000086 unsigned int i = 0;
Fariborz Jahanian236673e2009-05-14 18:00:00 +000087 bool warnNotEnoughArgs = false;
88 int isMethod = 0;
89 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
90 // skip over named parameters.
91 ObjCMethodDecl::param_iterator P, E = MD->param_end();
92 for (P = MD->param_begin(); (P != E && i < NumArgs); ++P) {
93 if (nullPos)
94 --nullPos;
95 else
96 ++i;
97 }
98 warnNotEnoughArgs = (P != E || i >= NumArgs);
99 isMethod = 1;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000100 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000101 // skip over named parameters.
102 ObjCMethodDecl::param_iterator P, E = FD->param_end();
103 for (P = FD->param_begin(); (P != E && i < NumArgs); ++P) {
104 if (nullPos)
105 --nullPos;
106 else
107 ++i;
108 }
109 warnNotEnoughArgs = (P != E || i >= NumArgs);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000110 } else if (VarDecl *V = dyn_cast<VarDecl>(D)) {
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000111 // block or function pointer call.
112 QualType Ty = V->getType();
113 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000114 const FunctionType *FT = Ty->isFunctionPointerType()
John McCall183700f2009-09-21 23:43:11 +0000115 ? Ty->getAs<PointerType>()->getPointeeType()->getAs<FunctionType>()
116 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000117 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT)) {
118 unsigned NumArgsInProto = Proto->getNumArgs();
119 unsigned k;
120 for (k = 0; (k != NumArgsInProto && i < NumArgs); k++) {
121 if (nullPos)
122 --nullPos;
123 else
124 ++i;
125 }
126 warnNotEnoughArgs = (k != NumArgsInProto || i >= NumArgs);
127 }
128 if (Ty->isBlockPointerType())
129 isMethod = 2;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000130 } else
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000131 return;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000132 } else
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000133 return;
134
135 if (warnNotEnoughArgs) {
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000136 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000137 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000138 return;
139 }
140 int sentinel = i;
141 while (sentinelPos > 0 && i < NumArgs-1) {
142 --sentinelPos;
143 ++i;
144 }
145 if (sentinelPos > 0) {
146 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000147 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000148 return;
149 }
150 while (i < NumArgs-1) {
151 ++i;
152 ++sentinel;
153 }
154 Expr *sentinelExpr = Args[sentinel];
Anders Carlssone4d2bdd2009-11-24 17:24:21 +0000155 if (sentinelExpr && (!isa<GNUNullExpr>(sentinelExpr) &&
156 (!sentinelExpr->getType()->isPointerType() ||
157 !sentinelExpr->isNullPointerConstant(Context,
158 Expr::NPC_ValueDependentIsNull)))) {
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000159 Diag(Loc, diag::warn_missing_sentinel) << isMethod;
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000160 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000161 }
162 return;
Fariborz Jahanian5b530052009-05-13 18:09:35 +0000163}
164
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000165SourceRange Sema::getExprRange(ExprTy *E) const {
166 Expr *Ex = (Expr *)E;
167 return Ex? Ex->getSourceRange() : SourceRange();
168}
169
Chris Lattnere7a2e912008-07-25 21:10:04 +0000170//===----------------------------------------------------------------------===//
171// Standard Promotions and Conversions
172//===----------------------------------------------------------------------===//
173
Chris Lattnere7a2e912008-07-25 21:10:04 +0000174/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
175void Sema::DefaultFunctionArrayConversion(Expr *&E) {
176 QualType Ty = E->getType();
177 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
178
Chris Lattnere7a2e912008-07-25 21:10:04 +0000179 if (Ty->isFunctionType())
Mike Stump1eb44332009-09-09 15:08:12 +0000180 ImpCastExprToType(E, Context.getPointerType(Ty),
Anders Carlssonb633c4e2009-09-01 20:37:18 +0000181 CastExpr::CK_FunctionToPointerDecay);
Chris Lattner67d33d82008-07-25 21:33:13 +0000182 else if (Ty->isArrayType()) {
183 // In C90 mode, arrays only promote to pointers if the array expression is
184 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
185 // type 'array of type' is converted to an expression that has type 'pointer
186 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
187 // that has type 'array of type' ...". The relevant change is "an lvalue"
188 // (C90) to "an expression" (C99).
Argyrios Kyrtzidisc39a3d72008-09-11 04:25:59 +0000189 //
190 // C++ 4.2p1:
191 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
192 // T" can be converted to an rvalue of type "pointer to T".
193 //
194 if (getLangOptions().C99 || getLangOptions().CPlusPlus ||
195 E->isLvalue(Context) == Expr::LV_Valid)
Anders Carlsson112a0a82009-08-07 23:48:20 +0000196 ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
197 CastExpr::CK_ArrayToPointerDecay);
Chris Lattner67d33d82008-07-25 21:33:13 +0000198 }
Chris Lattnere7a2e912008-07-25 21:10:04 +0000199}
200
201/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump1eb44332009-09-09 15:08:12 +0000202/// operators (C99 6.3). The conversions of array and function types are
Chris Lattnere7a2e912008-07-25 21:10:04 +0000203/// sometimes surpressed. For example, the array->pointer conversion doesn't
204/// apply if the array is an argument to the sizeof or address (&) operators.
205/// In these instances, this routine should *not* be called.
206Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
207 QualType Ty = Expr->getType();
208 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
Mike Stump1eb44332009-09-09 15:08:12 +0000209
Douglas Gregorfc24e442009-05-01 20:41:21 +0000210 // C99 6.3.1.1p2:
211 //
212 // The following may be used in an expression wherever an int or
213 // unsigned int may be used:
214 // - an object or expression with an integer type whose integer
215 // conversion rank is less than or equal to the rank of int
216 // and unsigned int.
217 // - A bit-field of type _Bool, int, signed int, or unsigned int.
218 //
219 // If an int can represent all values of the original type, the
220 // value is converted to an int; otherwise, it is converted to an
221 // unsigned int. These are called the integer promotions. All
222 // other types are unchanged by the integer promotions.
Eli Friedman04e83572009-08-20 04:21:42 +0000223 QualType PTy = Context.isPromotableBitField(Expr);
224 if (!PTy.isNull()) {
Eli Friedman73c39ab2009-10-20 08:27:19 +0000225 ImpCastExprToType(Expr, PTy, CastExpr::CK_IntegralCast);
Eli Friedman04e83572009-08-20 04:21:42 +0000226 return Expr;
227 }
Douglas Gregorfc24e442009-05-01 20:41:21 +0000228 if (Ty->isPromotableIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +0000229 QualType PT = Context.getPromotedIntegerType(Ty);
Eli Friedman73c39ab2009-10-20 08:27:19 +0000230 ImpCastExprToType(Expr, PT, CastExpr::CK_IntegralCast);
Douglas Gregorfc24e442009-05-01 20:41:21 +0000231 return Expr;
Eli Friedman04e83572009-08-20 04:21:42 +0000232 }
233
Douglas Gregorfc24e442009-05-01 20:41:21 +0000234 DefaultFunctionArrayConversion(Expr);
Chris Lattnere7a2e912008-07-25 21:10:04 +0000235 return Expr;
236}
237
Chris Lattner05faf172008-07-25 22:25:12 +0000238/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Mike Stump1eb44332009-09-09 15:08:12 +0000239/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner05faf172008-07-25 22:25:12 +0000240/// double. All other argument types are converted by UsualUnaryConversions().
241void Sema::DefaultArgumentPromotion(Expr *&Expr) {
242 QualType Ty = Expr->getType();
243 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump1eb44332009-09-09 15:08:12 +0000244
Chris Lattner05faf172008-07-25 22:25:12 +0000245 // If this is a 'float' (CVR qualified or typedef) promote to double.
John McCall183700f2009-09-21 23:43:11 +0000246 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
Chris Lattner05faf172008-07-25 22:25:12 +0000247 if (BT->getKind() == BuiltinType::Float)
Eli Friedman73c39ab2009-10-20 08:27:19 +0000248 return ImpCastExprToType(Expr, Context.DoubleTy,
249 CastExpr::CK_FloatingCast);
Mike Stump1eb44332009-09-09 15:08:12 +0000250
Chris Lattner05faf172008-07-25 22:25:12 +0000251 UsualUnaryConversions(Expr);
252}
253
Chris Lattner312531a2009-04-12 08:11:20 +0000254/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
255/// will warn if the resulting type is not a POD type, and rejects ObjC
256/// interfaces passed by value. This returns true if the argument type is
257/// completely illegal.
258bool Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT) {
Anders Carlssondce5e2c2009-01-16 16:48:51 +0000259 DefaultArgumentPromotion(Expr);
Mike Stump1eb44332009-09-09 15:08:12 +0000260
Chris Lattner312531a2009-04-12 08:11:20 +0000261 if (Expr->getType()->isObjCInterfaceType()) {
262 Diag(Expr->getLocStart(),
263 diag::err_cannot_pass_objc_interface_to_vararg)
264 << Expr->getType() << CT;
265 return true;
Anders Carlssondce5e2c2009-01-16 16:48:51 +0000266 }
Mike Stump1eb44332009-09-09 15:08:12 +0000267
Chris Lattner312531a2009-04-12 08:11:20 +0000268 if (!Expr->getType()->isPODType())
269 Diag(Expr->getLocStart(), diag::warn_cannot_pass_non_pod_arg_to_vararg)
270 << Expr->getType() << CT;
271
272 return false;
Anders Carlssondce5e2c2009-01-16 16:48:51 +0000273}
274
275
Chris Lattnere7a2e912008-07-25 21:10:04 +0000276/// UsualArithmeticConversions - Performs various conversions that are common to
277/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump1eb44332009-09-09 15:08:12 +0000278/// routine returns the first non-arithmetic type found. The client is
Chris Lattnere7a2e912008-07-25 21:10:04 +0000279/// responsible for emitting appropriate error diagnostics.
280/// FIXME: verify the conversion rules for "complex int" are consistent with
281/// GCC.
282QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
283 bool isCompAssign) {
Eli Friedmanab3a8522009-03-28 01:22:36 +0000284 if (!isCompAssign)
Chris Lattnere7a2e912008-07-25 21:10:04 +0000285 UsualUnaryConversions(lhsExpr);
Eli Friedmanab3a8522009-03-28 01:22:36 +0000286
287 UsualUnaryConversions(rhsExpr);
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000288
Mike Stump1eb44332009-09-09 15:08:12 +0000289 // For conversion purposes, we ignore any qualifiers.
Chris Lattnere7a2e912008-07-25 21:10:04 +0000290 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +0000291 QualType lhs =
292 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +0000293 QualType rhs =
Chris Lattnerb77792e2008-07-26 22:17:49 +0000294 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000295
296 // If both types are identical, no conversion is needed.
297 if (lhs == rhs)
298 return lhs;
299
300 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
301 // The caller can deal with this (e.g. pointer + int).
302 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
303 return lhs;
304
Douglas Gregor2d833e32009-05-02 00:36:19 +0000305 // Perform bitfield promotions.
Eli Friedman04e83572009-08-20 04:21:42 +0000306 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr);
Douglas Gregor2d833e32009-05-02 00:36:19 +0000307 if (!LHSBitfieldPromoteTy.isNull())
308 lhs = LHSBitfieldPromoteTy;
Eli Friedman04e83572009-08-20 04:21:42 +0000309 QualType RHSBitfieldPromoteTy = Context.isPromotableBitField(rhsExpr);
Douglas Gregor2d833e32009-05-02 00:36:19 +0000310 if (!RHSBitfieldPromoteTy.isNull())
311 rhs = RHSBitfieldPromoteTy;
312
Eli Friedmana95d7572009-08-19 07:44:53 +0000313 QualType destType = Context.UsualArithmeticConversionsType(lhs, rhs);
Eli Friedmanab3a8522009-03-28 01:22:36 +0000314 if (!isCompAssign)
Eli Friedman73c39ab2009-10-20 08:27:19 +0000315 ImpCastExprToType(lhsExpr, destType, CastExpr::CK_Unknown);
316 ImpCastExprToType(rhsExpr, destType, CastExpr::CK_Unknown);
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000317 return destType;
318}
319
Chris Lattnere7a2e912008-07-25 21:10:04 +0000320//===----------------------------------------------------------------------===//
321// Semantic Analysis for various Expression Types
322//===----------------------------------------------------------------------===//
323
324
Steve Narofff69936d2007-09-16 03:34:24 +0000325/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Reid Spencer5f016e22007-07-11 17:01:13 +0000326/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
327/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
328/// multiple tokens. However, the common case is that StringToks points to one
329/// string.
Sebastian Redlcd965b92009-01-18 18:53:16 +0000330///
331Action::OwningExprResult
Steve Narofff69936d2007-09-16 03:34:24 +0000332Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000333 assert(NumStringToks && "Must have at least one string!");
334
Chris Lattnerbbee00b2009-01-16 18:51:42 +0000335 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Reid Spencer5f016e22007-07-11 17:01:13 +0000336 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +0000337 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +0000338
339 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
340 for (unsigned i = 0; i != NumStringToks; ++i)
341 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000342
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000343 QualType StrTy = Context.CharTy;
Argyrios Kyrtzidis55f4b022008-08-09 17:20:01 +0000344 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000345 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregor77a52232008-09-12 00:47:35 +0000346
347 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
348 if (getLangOptions().CPlusPlus)
349 StrTy.addConst();
Sebastian Redlcd965b92009-01-18 18:53:16 +0000350
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000351 // Get an array type for the string, according to C99 6.4.5. This includes
352 // the nul terminator character as well as the string length for pascal
353 // strings.
354 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerdbb1ecc2009-02-26 23:01:51 +0000355 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000356 ArrayType::Normal, 0);
Mike Stump1eb44332009-09-09 15:08:12 +0000357
Reid Spencer5f016e22007-07-11 17:01:13 +0000358 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Mike Stump1eb44332009-09-09 15:08:12 +0000359 return Owned(StringLiteral::Create(Context, Literal.GetString(),
Chris Lattner2085fd62009-02-18 06:40:38 +0000360 Literal.GetStringLength(),
361 Literal.AnyWide, StrTy,
362 &StringTokLocs[0],
363 StringTokLocs.size()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000364}
365
Chris Lattner639e2d32008-10-20 05:16:36 +0000366/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
367/// CurBlock to VD should cause it to be snapshotted (as we do for auto
368/// variables defined outside the block) or false if this is not needed (e.g.
369/// for values inside the block or for globals).
370///
Chris Lattner17f3a6d2009-04-21 22:26:47 +0000371/// This also keeps the 'hasBlockDeclRefExprs' in the BlockSemaInfo records
372/// up-to-date.
373///
Chris Lattner639e2d32008-10-20 05:16:36 +0000374static bool ShouldSnapshotBlockValueReference(BlockSemaInfo *CurBlock,
375 ValueDecl *VD) {
376 // If the value is defined inside the block, we couldn't snapshot it even if
377 // we wanted to.
378 if (CurBlock->TheDecl == VD->getDeclContext())
379 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000380
Chris Lattner639e2d32008-10-20 05:16:36 +0000381 // If this is an enum constant or function, it is constant, don't snapshot.
382 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
383 return false;
384
385 // If this is a reference to an extern, static, or global variable, no need to
386 // snapshot it.
387 // FIXME: What about 'const' variables in C++?
388 if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
Chris Lattner17f3a6d2009-04-21 22:26:47 +0000389 if (!Var->hasLocalStorage())
390 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000391
Chris Lattner17f3a6d2009-04-21 22:26:47 +0000392 // Blocks that have these can't be constant.
393 CurBlock->hasBlockDeclRefExprs = true;
394
395 // If we have nested blocks, the decl may be declared in an outer block (in
396 // which case that outer block doesn't get "hasBlockDeclRefExprs") or it may
397 // be defined outside all of the current blocks (in which case the blocks do
398 // all get the bit). Walk the nesting chain.
399 for (BlockSemaInfo *NextBlock = CurBlock->PrevBlockInfo; NextBlock;
400 NextBlock = NextBlock->PrevBlockInfo) {
401 // If we found the defining block for the variable, don't mark the block as
402 // having a reference outside it.
403 if (NextBlock->TheDecl == VD->getDeclContext())
404 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000405
Chris Lattner17f3a6d2009-04-21 22:26:47 +0000406 // Otherwise, the DeclRef from the inner block causes the outer one to need
407 // a snapshot as well.
408 NextBlock->hasBlockDeclRefExprs = true;
409 }
Mike Stump1eb44332009-09-09 15:08:12 +0000410
Chris Lattner639e2d32008-10-20 05:16:36 +0000411 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000412}
413
Chris Lattner639e2d32008-10-20 05:16:36 +0000414
415
Douglas Gregora2813ce2009-10-23 18:54:35 +0000416/// BuildDeclRefExpr - Build a DeclRefExpr.
Anders Carlssone41590d2009-06-24 00:10:43 +0000417Sema::OwningExprResult
Sebastian Redlebc07d52009-02-03 20:19:35 +0000418Sema::BuildDeclRefExpr(NamedDecl *D, QualType Ty, SourceLocation Loc,
Sebastian Redlebc07d52009-02-03 20:19:35 +0000419 const CXXScopeSpec *SS) {
Anders Carlssone2bb2242009-06-26 19:16:07 +0000420 if (Context.getCanonicalType(Ty) == Context.UndeducedAutoTy) {
421 Diag(Loc,
Mike Stump1eb44332009-09-09 15:08:12 +0000422 diag::err_auto_variable_cannot_appear_in_own_initializer)
Anders Carlssone2bb2242009-06-26 19:16:07 +0000423 << D->getDeclName();
424 return ExprError();
425 }
Mike Stump1eb44332009-09-09 15:08:12 +0000426
Anders Carlssone41590d2009-06-24 00:10:43 +0000427 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
428 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
429 if (const FunctionDecl *FD = MD->getParent()->isLocalClass()) {
430 if (VD->hasLocalStorage() && VD->getDeclContext() != CurContext) {
Mike Stump1eb44332009-09-09 15:08:12 +0000431 Diag(Loc, diag::err_reference_to_local_var_in_enclosing_function)
Anders Carlssone41590d2009-06-24 00:10:43 +0000432 << D->getIdentifier() << FD->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +0000433 Diag(D->getLocation(), diag::note_local_variable_declared_here)
Anders Carlssone41590d2009-06-24 00:10:43 +0000434 << D->getIdentifier();
435 return ExprError();
436 }
437 }
438 }
439 }
Mike Stump1eb44332009-09-09 15:08:12 +0000440
Douglas Gregore0762c92009-06-19 23:52:42 +0000441 MarkDeclarationReferenced(Loc, D);
Mike Stump1eb44332009-09-09 15:08:12 +0000442
Douglas Gregora2813ce2009-10-23 18:54:35 +0000443 return Owned(DeclRefExpr::Create(Context,
444 SS? (NestedNameSpecifier *)SS->getScopeRep() : 0,
445 SS? SS->getRange() : SourceRange(),
Douglas Gregor0da76df2009-11-23 11:41:28 +0000446 D, Loc, Ty));
Douglas Gregor1a49af92009-01-06 05:10:23 +0000447}
448
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000449/// getObjectForAnonymousRecordDecl - Retrieve the (unnamed) field or
450/// variable corresponding to the anonymous union or struct whose type
451/// is Record.
Douglas Gregor6ab35242009-04-09 21:40:53 +0000452static Decl *getObjectForAnonymousRecordDecl(ASTContext &Context,
453 RecordDecl *Record) {
Mike Stump1eb44332009-09-09 15:08:12 +0000454 assert(Record->isAnonymousStructOrUnion() &&
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000455 "Record must be an anonymous struct or union!");
Mike Stump1eb44332009-09-09 15:08:12 +0000456
Mike Stump390b4cc2009-05-16 07:39:55 +0000457 // FIXME: Once Decls are directly linked together, this will be an O(1)
458 // operation rather than a slow walk through DeclContext's vector (which
459 // itself will be eliminated). DeclGroups might make this even better.
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000460 DeclContext *Ctx = Record->getDeclContext();
Mike Stump1eb44332009-09-09 15:08:12 +0000461 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000462 DEnd = Ctx->decls_end();
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000463 D != DEnd; ++D) {
464 if (*D == Record) {
465 // The object for the anonymous struct/union directly
466 // follows its type in the list of declarations.
467 ++D;
468 assert(D != DEnd && "Missing object for anonymous record");
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000469 assert(!cast<NamedDecl>(*D)->getDeclName() && "Decl should be unnamed");
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000470 return *D;
471 }
472 }
473
474 assert(false && "Missing object for anonymous record");
475 return 0;
476}
477
Douglas Gregorffb4b6e2009-04-15 06:41:24 +0000478/// \brief Given a field that represents a member of an anonymous
479/// struct/union, build the path from that field's context to the
480/// actual member.
481///
482/// Construct the sequence of field member references we'll have to
483/// perform to get to the field in the anonymous union/struct. The
484/// list of members is built from the field outward, so traverse it
485/// backwards to go from an object in the current context to the field
486/// we found.
487///
488/// \returns The variable from which the field access should begin,
489/// for an anonymous struct/union that is not a member of another
490/// class. Otherwise, returns NULL.
491VarDecl *Sema::BuildAnonymousStructUnionMemberPath(FieldDecl *Field,
492 llvm::SmallVectorImpl<FieldDecl *> &Path) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000493 assert(Field->getDeclContext()->isRecord() &&
494 cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion()
495 && "Field must be stored inside an anonymous struct or union");
496
Douglas Gregorffb4b6e2009-04-15 06:41:24 +0000497 Path.push_back(Field);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000498 VarDecl *BaseObject = 0;
499 DeclContext *Ctx = Field->getDeclContext();
500 do {
501 RecordDecl *Record = cast<RecordDecl>(Ctx);
Douglas Gregor6ab35242009-04-09 21:40:53 +0000502 Decl *AnonObject = getObjectForAnonymousRecordDecl(Context, Record);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000503 if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject))
Douglas Gregorffb4b6e2009-04-15 06:41:24 +0000504 Path.push_back(AnonField);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000505 else {
506 BaseObject = cast<VarDecl>(AnonObject);
507 break;
508 }
509 Ctx = Ctx->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +0000510 } while (Ctx->isRecord() &&
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000511 cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion());
Douglas Gregorffb4b6e2009-04-15 06:41:24 +0000512
513 return BaseObject;
514}
515
516Sema::OwningExprResult
517Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
518 FieldDecl *Field,
519 Expr *BaseObjectExpr,
520 SourceLocation OpLoc) {
521 llvm::SmallVector<FieldDecl *, 4> AnonFields;
Mike Stump1eb44332009-09-09 15:08:12 +0000522 VarDecl *BaseObject = BuildAnonymousStructUnionMemberPath(Field,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +0000523 AnonFields);
524
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000525 // Build the expression that refers to the base object, from
526 // which we will build a sequence of member references to each
527 // of the anonymous union objects and, eventually, the field we
528 // found via name lookup.
529 bool BaseObjectIsPointer = false;
John McCall0953e762009-09-24 19:53:00 +0000530 Qualifiers BaseQuals;
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000531 if (BaseObject) {
532 // BaseObject is an anonymous struct/union variable (and is,
533 // therefore, not part of another non-anonymous record).
Ted Kremenek8189cde2009-02-07 01:47:29 +0000534 if (BaseObjectExpr) BaseObjectExpr->Destroy(Context);
Douglas Gregore0762c92009-06-19 23:52:42 +0000535 MarkDeclarationReferenced(Loc, BaseObject);
Steve Naroff6ece14c2009-01-21 00:14:39 +0000536 BaseObjectExpr = new (Context) DeclRefExpr(BaseObject,BaseObject->getType(),
Mike Stumpeed9cac2009-02-19 03:04:26 +0000537 SourceLocation());
John McCall0953e762009-09-24 19:53:00 +0000538 BaseQuals
539 = Context.getCanonicalType(BaseObject->getType()).getQualifiers();
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000540 } else if (BaseObjectExpr) {
541 // The caller provided the base object expression. Determine
542 // whether its a pointer and whether it adds any qualifiers to the
543 // anonymous struct/union fields we're looking into.
544 QualType ObjectType = BaseObjectExpr->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000545 if (const PointerType *ObjectPtr = ObjectType->getAs<PointerType>()) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000546 BaseObjectIsPointer = true;
547 ObjectType = ObjectPtr->getPointeeType();
548 }
John McCall0953e762009-09-24 19:53:00 +0000549 BaseQuals
550 = Context.getCanonicalType(ObjectType).getQualifiers();
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000551 } else {
552 // We've found a member of an anonymous struct/union that is
553 // inside a non-anonymous struct/union, so in a well-formed
554 // program our base object expression is "this".
555 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
556 if (!MD->isStatic()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000557 QualType AnonFieldType
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000558 = Context.getTagDeclType(
559 cast<RecordDecl>(AnonFields.back()->getDeclContext()));
560 QualType ThisType = Context.getTagDeclType(MD->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +0000561 if ((Context.getCanonicalType(AnonFieldType)
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000562 == Context.getCanonicalType(ThisType)) ||
563 IsDerivedFrom(ThisType, AnonFieldType)) {
564 // Our base object expression is "this".
Steve Naroff6ece14c2009-01-21 00:14:39 +0000565 BaseObjectExpr = new (Context) CXXThisExpr(SourceLocation(),
Mike Stumpeed9cac2009-02-19 03:04:26 +0000566 MD->getThisType(Context));
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000567 BaseObjectIsPointer = true;
568 }
569 } else {
Sebastian Redlcd965b92009-01-18 18:53:16 +0000570 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
571 << Field->getDeclName());
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000572 }
John McCall0953e762009-09-24 19:53:00 +0000573 BaseQuals = Qualifiers::fromCVRMask(MD->getTypeQualifiers());
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000574 }
575
Mike Stump1eb44332009-09-09 15:08:12 +0000576 if (!BaseObjectExpr)
Sebastian Redlcd965b92009-01-18 18:53:16 +0000577 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
578 << Field->getDeclName());
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000579 }
580
581 // Build the implicit member references to the field of the
582 // anonymous struct/union.
583 Expr *Result = BaseObjectExpr;
John McCall0953e762009-09-24 19:53:00 +0000584 Qualifiers ResultQuals = BaseQuals;
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000585 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
586 FI = AnonFields.rbegin(), FIEnd = AnonFields.rend();
587 FI != FIEnd; ++FI) {
588 QualType MemberType = (*FI)->getType();
John McCall0953e762009-09-24 19:53:00 +0000589 Qualifiers MemberTypeQuals =
590 Context.getCanonicalType(MemberType).getQualifiers();
591
592 // CVR attributes from the base are picked up by members,
593 // except that 'mutable' members don't pick up 'const'.
594 if ((*FI)->isMutable())
595 ResultQuals.removeConst();
596
597 // GC attributes are never picked up by members.
598 ResultQuals.removeObjCGCAttr();
599
600 // TR 18037 does not allow fields to be declared with address spaces.
601 assert(!MemberTypeQuals.hasAddressSpace());
602
603 Qualifiers NewQuals = ResultQuals + MemberTypeQuals;
604 if (NewQuals != MemberTypeQuals)
605 MemberType = Context.getQualifiedType(MemberType, NewQuals);
606
Douglas Gregore0762c92009-06-19 23:52:42 +0000607 MarkDeclarationReferenced(Loc, *FI);
Eli Friedman16c53782009-12-04 07:18:51 +0000608 PerformObjectMemberConversion(Result, *FI);
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +0000609 // FIXME: Might this end up being a qualified name?
Steve Naroff6ece14c2009-01-21 00:14:39 +0000610 Result = new (Context) MemberExpr(Result, BaseObjectIsPointer, *FI,
611 OpLoc, MemberType);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000612 BaseObjectIsPointer = false;
John McCall0953e762009-09-24 19:53:00 +0000613 ResultQuals = NewQuals;
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000614 }
615
Sebastian Redlcd965b92009-01-18 18:53:16 +0000616 return Owned(Result);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000617}
618
John McCall129e2df2009-11-30 22:42:35 +0000619/// Decomposes the given name into a DeclarationName, its location, and
620/// possibly a list of template arguments.
621///
622/// If this produces template arguments, it is permitted to call
623/// DecomposeTemplateName.
624///
625/// This actually loses a lot of source location information for
626/// non-standard name kinds; we should consider preserving that in
627/// some way.
628static void DecomposeUnqualifiedId(Sema &SemaRef,
629 const UnqualifiedId &Id,
630 TemplateArgumentListInfo &Buffer,
631 DeclarationName &Name,
632 SourceLocation &NameLoc,
633 const TemplateArgumentListInfo *&TemplateArgs) {
634 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
635 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
636 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
637
638 ASTTemplateArgsPtr TemplateArgsPtr(SemaRef,
639 Id.TemplateId->getTemplateArgs(),
640 Id.TemplateId->NumArgs);
641 SemaRef.translateTemplateArguments(TemplateArgsPtr, Buffer);
642 TemplateArgsPtr.release();
643
644 TemplateName TName =
645 Sema::TemplateTy::make(Id.TemplateId->Template).getAsVal<TemplateName>();
646
647 Name = SemaRef.Context.getNameForTemplate(TName);
648 NameLoc = Id.TemplateId->TemplateNameLoc;
649 TemplateArgs = &Buffer;
650 } else {
651 Name = SemaRef.GetNameFromUnqualifiedId(Id);
652 NameLoc = Id.StartLocation;
653 TemplateArgs = 0;
654 }
655}
656
657/// Decompose the given template name into a list of lookup results.
658///
659/// The unqualified ID must name a non-dependent template, which can
660/// be more easily tested by checking whether DecomposeUnqualifiedId
661/// found template arguments.
662static void DecomposeTemplateName(LookupResult &R, const UnqualifiedId &Id) {
663 assert(Id.getKind() == UnqualifiedId::IK_TemplateId);
664 TemplateName TName =
665 Sema::TemplateTy::make(Id.TemplateId->Template).getAsVal<TemplateName>();
666
John McCallf7a1a742009-11-24 19:00:30 +0000667 if (TemplateDecl *TD = TName.getAsTemplateDecl())
668 R.addDecl(TD);
John McCall0bd6feb2009-12-02 08:04:21 +0000669 else if (OverloadedTemplateStorage *OT = TName.getAsOverloadedTemplate())
670 for (OverloadedTemplateStorage::iterator I = OT->begin(), E = OT->end();
671 I != E; ++I)
John McCallf7a1a742009-11-24 19:00:30 +0000672 R.addDecl(*I);
John McCallb681b612009-11-22 02:49:43 +0000673
John McCallf7a1a742009-11-24 19:00:30 +0000674 R.resolveKind();
Douglas Gregor02a24ee2009-11-03 16:56:39 +0000675}
676
John McCall129e2df2009-11-30 22:42:35 +0000677static bool IsFullyFormedScope(Sema &SemaRef, CXXRecordDecl *Record) {
678 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
679 E = Record->bases_end(); I != E; ++I) {
680 CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
681 CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
682 if (!BaseRT) return false;
683
684 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
685 if (!BaseRecord->isDefinition() ||
686 !IsFullyFormedScope(SemaRef, BaseRecord))
687 return false;
688 }
689
690 return true;
691}
692
John McCalle1599ce2009-11-30 23:50:49 +0000693/// Determines whether we can lookup this id-expression now or whether
694/// we have to wait until template instantiation is complete.
695static bool IsDependentIdExpression(Sema &SemaRef, const CXXScopeSpec &SS) {
John McCall129e2df2009-11-30 22:42:35 +0000696 DeclContext *DC = SemaRef.computeDeclContext(SS, false);
John McCall129e2df2009-11-30 22:42:35 +0000697
John McCalle1599ce2009-11-30 23:50:49 +0000698 // If the qualifier scope isn't computable, it's definitely dependent.
699 if (!DC) return true;
700
701 // If the qualifier scope doesn't name a record, we can always look into it.
702 if (!isa<CXXRecordDecl>(DC)) return false;
703
704 // We can't look into record types unless they're fully-formed.
705 if (!IsFullyFormedScope(SemaRef, cast<CXXRecordDecl>(DC))) return true;
706
John McCallaa81e162009-12-01 22:10:20 +0000707 return false;
708}
John McCalle1599ce2009-11-30 23:50:49 +0000709
John McCallaa81e162009-12-01 22:10:20 +0000710/// Determines if the given class is provably not derived from all of
711/// the prospective base classes.
712static bool IsProvablyNotDerivedFrom(Sema &SemaRef,
713 CXXRecordDecl *Record,
714 const llvm::SmallPtrSet<CXXRecordDecl*, 4> &Bases) {
John McCallb1b42562009-12-01 22:28:41 +0000715 if (Bases.count(Record->getCanonicalDecl()))
John McCallaa81e162009-12-01 22:10:20 +0000716 return false;
717
John McCallb1b42562009-12-01 22:28:41 +0000718 RecordDecl *RD = Record->getDefinition(SemaRef.Context);
719 if (!RD) return false;
720 Record = cast<CXXRecordDecl>(RD);
721
John McCallaa81e162009-12-01 22:10:20 +0000722 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
723 E = Record->bases_end(); I != E; ++I) {
724 CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
725 CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
726 if (!BaseRT) return false;
727
728 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCallaa81e162009-12-01 22:10:20 +0000729 if (!IsProvablyNotDerivedFrom(SemaRef, BaseRecord, Bases))
730 return false;
731 }
732
733 return true;
734}
735
John McCall144238e2009-12-02 20:26:00 +0000736/// Determines if this a C++ class member.
737static bool IsClassMember(NamedDecl *D) {
738 DeclContext *DC = D->getDeclContext();
John McCall336e7742009-12-02 19:59:55 +0000739
John McCall144238e2009-12-02 20:26:00 +0000740 // C++0x [class.mem]p1:
741 // The enumerators of an unscoped enumeration defined in
742 // the class are members of the class.
743 // FIXME: support C++0x scoped enumerations.
744 if (isa<EnumDecl>(DC))
745 DC = DC->getParent();
746
747 return DC->isRecord();
748}
749
750/// Determines if this is an instance member of a class.
751static bool IsInstanceMember(NamedDecl *D) {
752 assert(IsClassMember(D) &&
John McCallaa81e162009-12-01 22:10:20 +0000753 "checking whether non-member is instance member");
754
755 if (isa<FieldDecl>(D)) return true;
756
757 if (isa<CXXMethodDecl>(D))
758 return !cast<CXXMethodDecl>(D)->isStatic();
759
760 if (isa<FunctionTemplateDecl>(D)) {
761 D = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
762 return !cast<CXXMethodDecl>(D)->isStatic();
763 }
764
765 return false;
766}
767
768enum IMAKind {
769 /// The reference is definitely not an instance member access.
770 IMA_Static,
771
772 /// The reference may be an implicit instance member access.
773 IMA_Mixed,
774
775 /// The reference may be to an instance member, but it is invalid if
776 /// so, because the context is not an instance method.
777 IMA_Mixed_StaticContext,
778
779 /// The reference may be to an instance member, but it is invalid if
780 /// so, because the context is from an unrelated class.
781 IMA_Mixed_Unrelated,
782
783 /// The reference is definitely an implicit instance member access.
784 IMA_Instance,
785
786 /// The reference may be to an unresolved using declaration.
787 IMA_Unresolved,
788
789 /// The reference may be to an unresolved using declaration and the
790 /// context is not an instance method.
791 IMA_Unresolved_StaticContext,
792
793 /// The reference is to a member of an anonymous structure in a
794 /// non-class context.
795 IMA_AnonymousMember,
796
797 /// All possible referrents are instance members and the current
798 /// context is not an instance method.
799 IMA_Error_StaticContext,
800
801 /// All possible referrents are instance members of an unrelated
802 /// class.
803 IMA_Error_Unrelated
804};
805
806/// The given lookup names class member(s) and is not being used for
807/// an address-of-member expression. Classify the type of access
808/// according to whether it's possible that this reference names an
809/// instance member. This is best-effort; it is okay to
810/// conservatively answer "yes", in which case some errors will simply
811/// not be caught until template-instantiation.
812static IMAKind ClassifyImplicitMemberAccess(Sema &SemaRef,
813 const LookupResult &R) {
John McCall144238e2009-12-02 20:26:00 +0000814 assert(!R.empty() && IsClassMember(*R.begin()));
John McCallaa81e162009-12-01 22:10:20 +0000815
816 bool isStaticContext =
817 (!isa<CXXMethodDecl>(SemaRef.CurContext) ||
818 cast<CXXMethodDecl>(SemaRef.CurContext)->isStatic());
819
820 if (R.isUnresolvableResult())
821 return isStaticContext ? IMA_Unresolved_StaticContext : IMA_Unresolved;
822
823 // Collect all the declaring classes of instance members we find.
824 bool hasNonInstance = false;
825 llvm::SmallPtrSet<CXXRecordDecl*, 4> Classes;
826 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
827 NamedDecl *D = (*I)->getUnderlyingDecl();
828 if (IsInstanceMember(D)) {
829 CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext());
830
831 // If this is a member of an anonymous record, move out to the
832 // innermost non-anonymous struct or union. If there isn't one,
833 // that's a special case.
834 while (R->isAnonymousStructOrUnion()) {
835 R = dyn_cast<CXXRecordDecl>(R->getParent());
836 if (!R) return IMA_AnonymousMember;
837 }
838 Classes.insert(R->getCanonicalDecl());
839 }
840 else
841 hasNonInstance = true;
842 }
843
844 // If we didn't find any instance members, it can't be an implicit
845 // member reference.
846 if (Classes.empty())
847 return IMA_Static;
848
849 // If the current context is not an instance method, it can't be
850 // an implicit member reference.
851 if (isStaticContext)
852 return (hasNonInstance ? IMA_Mixed_StaticContext : IMA_Error_StaticContext);
853
854 // If we can prove that the current context is unrelated to all the
855 // declaring classes, it can't be an implicit member reference (in
856 // which case it's an error if any of those members are selected).
857 if (IsProvablyNotDerivedFrom(SemaRef,
858 cast<CXXMethodDecl>(SemaRef.CurContext)->getParent(),
859 Classes))
860 return (hasNonInstance ? IMA_Mixed_Unrelated : IMA_Error_Unrelated);
861
862 return (hasNonInstance ? IMA_Mixed : IMA_Instance);
863}
864
865/// Diagnose a reference to a field with no object available.
866static void DiagnoseInstanceReference(Sema &SemaRef,
867 const CXXScopeSpec &SS,
868 const LookupResult &R) {
869 SourceLocation Loc = R.getNameLoc();
870 SourceRange Range(Loc);
871 if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
872
873 if (R.getAsSingle<FieldDecl>()) {
874 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(SemaRef.CurContext)) {
875 if (MD->isStatic()) {
876 // "invalid use of member 'x' in static member function"
877 SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method)
878 << Range << R.getLookupName();
879 return;
880 }
881 }
882
883 SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
884 << R.getLookupName() << Range;
885 return;
886 }
887
888 SemaRef.Diag(Loc, diag::err_member_call_without_object) << Range;
John McCall129e2df2009-11-30 22:42:35 +0000889}
890
John McCallf7a1a742009-11-24 19:00:30 +0000891Sema::OwningExprResult Sema::ActOnIdExpression(Scope *S,
892 const CXXScopeSpec &SS,
893 UnqualifiedId &Id,
894 bool HasTrailingLParen,
895 bool isAddressOfOperand) {
896 assert(!(isAddressOfOperand && HasTrailingLParen) &&
897 "cannot be direct & operand and have a trailing lparen");
898
899 if (SS.isInvalid())
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000900 return ExprError();
Douglas Gregor5953d8b2009-03-19 17:26:29 +0000901
John McCall129e2df2009-11-30 22:42:35 +0000902 TemplateArgumentListInfo TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +0000903
904 // Decompose the UnqualifiedId into the following data.
905 DeclarationName Name;
906 SourceLocation NameLoc;
907 const TemplateArgumentListInfo *TemplateArgs;
John McCall129e2df2009-11-30 22:42:35 +0000908 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer,
909 Name, NameLoc, TemplateArgs);
Douglas Gregor5953d8b2009-03-19 17:26:29 +0000910
Douglas Gregor10c42622008-11-18 15:03:34 +0000911 IdentifierInfo *II = Name.getAsIdentifierInfo();
John McCallba135432009-11-21 08:51:07 +0000912
John McCallf7a1a742009-11-24 19:00:30 +0000913 // C++ [temp.dep.expr]p3:
914 // An id-expression is type-dependent if it contains:
915 // -- a nested-name-specifier that contains a class-name that
916 // names a dependent type.
917 // Determine whether this is a member of an unknown specialization;
918 // we need to handle these differently.
John McCalle1599ce2009-11-30 23:50:49 +0000919 if (SS.isSet() && IsDependentIdExpression(*this, SS)) {
John McCallf7a1a742009-11-24 19:00:30 +0000920 return ActOnDependentIdExpression(SS, Name, NameLoc,
John McCall2f841ba2009-12-02 03:53:29 +0000921 isAddressOfOperand,
John McCallf7a1a742009-11-24 19:00:30 +0000922 TemplateArgs);
923 }
John McCallba135432009-11-21 08:51:07 +0000924
John McCallf7a1a742009-11-24 19:00:30 +0000925 // Perform the required lookup.
926 LookupResult R(*this, Name, NameLoc, LookupOrdinaryName);
927 if (TemplateArgs) {
John McCallf7a1a742009-11-24 19:00:30 +0000928 // Just re-use the lookup done by isTemplateName.
John McCall129e2df2009-11-30 22:42:35 +0000929 DecomposeTemplateName(R, Id);
John McCallf7a1a742009-11-24 19:00:30 +0000930 } else {
931 LookupParsedName(R, S, &SS, true);
Mike Stump1eb44332009-09-09 15:08:12 +0000932
John McCallf7a1a742009-11-24 19:00:30 +0000933 // If this reference is in an Objective-C method, then we need to do
934 // some special Objective-C lookup, too.
935 if (!SS.isSet() && II && getCurMethodDecl()) {
936 OwningExprResult E(LookupInObjCMethod(R, S, II));
937 if (E.isInvalid())
938 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000939
John McCallf7a1a742009-11-24 19:00:30 +0000940 Expr *Ex = E.takeAs<Expr>();
941 if (Ex) return Owned(Ex);
Steve Naroffe3e9add2008-06-02 23:03:37 +0000942 }
Chris Lattner8a934232008-03-31 00:36:02 +0000943 }
Douglas Gregorc71e28c2009-02-16 19:28:42 +0000944
John McCallf7a1a742009-11-24 19:00:30 +0000945 if (R.isAmbiguous())
946 return ExprError();
947
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000948 // Determine whether this name might be a candidate for
949 // argument-dependent lookup.
John McCallf7a1a742009-11-24 19:00:30 +0000950 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000951
John McCallf7a1a742009-11-24 19:00:30 +0000952 if (R.empty() && !ADL) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000953 // Otherwise, this could be an implicitly declared function reference (legal
John McCallf7a1a742009-11-24 19:00:30 +0000954 // in C90, extension in C99, forbidden in C++).
955 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
956 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
957 if (D) R.addDecl(D);
958 }
959
960 // If this name wasn't predeclared and if this is not a function
961 // call, diagnose the problem.
962 if (R.empty()) {
963 if (!SS.isEmpty())
964 return ExprError(Diag(NameLoc, diag::err_no_member)
965 << Name << computeDeclContext(SS, false)
966 << SS.getRange());
Douglas Gregor3f093272009-10-13 21:16:44 +0000967 else if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
Sean Hunt3e518bd2009-11-29 07:34:05 +0000968 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregor10c42622008-11-18 15:03:34 +0000969 Name.getNameKind() == DeclarationName::CXXConversionFunctionName)
John McCallf7a1a742009-11-24 19:00:30 +0000970 return ExprError(Diag(NameLoc, diag::err_undeclared_use)
971 << Name);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000972 else
John McCallf7a1a742009-11-24 19:00:30 +0000973 return ExprError(Diag(NameLoc, diag::err_undeclared_var_use) << Name);
Reid Spencer5f016e22007-07-11 17:01:13 +0000974 }
975 }
Mike Stump1eb44332009-09-09 15:08:12 +0000976
John McCallf7a1a742009-11-24 19:00:30 +0000977 // This is guaranteed from this point on.
978 assert(!R.empty() || ADL);
979
980 if (VarDecl *Var = R.getAsSingle<VarDecl>()) {
Douglas Gregor751f9a42009-06-30 15:47:41 +0000981 // Warn about constructs like:
982 // if (void *X = foo()) { ... } else { X }.
983 // In the else block, the pointer is always false.
Mike Stump1eb44332009-09-09 15:08:12 +0000984
Douglas Gregor751f9a42009-06-30 15:47:41 +0000985 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
986 Scope *CheckS = S;
Douglas Gregor9c4b8382009-11-05 17:49:26 +0000987 while (CheckS && CheckS->getControlParent()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000988 if (CheckS->isWithinElse() &&
Douglas Gregor751f9a42009-06-30 15:47:41 +0000989 CheckS->getControlParent()->isDeclScope(DeclPtrTy::make(Var))) {
John McCallf7a1a742009-11-24 19:00:30 +0000990 ExprError(Diag(NameLoc, diag::warn_value_always_zero)
Douglas Gregor9c4b8382009-11-05 17:49:26 +0000991 << Var->getDeclName()
992 << (Var->getType()->isPointerType()? 2 :
993 Var->getType()->isBooleanType()? 1 : 0));
Douglas Gregor751f9a42009-06-30 15:47:41 +0000994 break;
995 }
Mike Stump1eb44332009-09-09 15:08:12 +0000996
Douglas Gregor9c4b8382009-11-05 17:49:26 +0000997 // Move to the parent of this scope.
998 CheckS = CheckS->getParent();
Douglas Gregor751f9a42009-06-30 15:47:41 +0000999 }
1000 }
John McCallf7a1a742009-11-24 19:00:30 +00001001 } else if (FunctionDecl *Func = R.getAsSingle<FunctionDecl>()) {
Douglas Gregor751f9a42009-06-30 15:47:41 +00001002 if (!getLangOptions().CPlusPlus && !Func->hasPrototype()) {
1003 // C99 DR 316 says that, if a function type comes from a
1004 // function definition (without a prototype), that type is only
1005 // used for checking compatibility. Therefore, when referencing
1006 // the function, we pretend that we don't have the full function
1007 // type.
John McCallf7a1a742009-11-24 19:00:30 +00001008 if (DiagnoseUseOfDecl(Func, NameLoc))
Douglas Gregor751f9a42009-06-30 15:47:41 +00001009 return ExprError();
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001010
Douglas Gregor751f9a42009-06-30 15:47:41 +00001011 QualType T = Func->getType();
1012 QualType NoProtoType = T;
John McCall183700f2009-09-21 23:43:11 +00001013 if (const FunctionProtoType *Proto = T->getAs<FunctionProtoType>())
Douglas Gregor751f9a42009-06-30 15:47:41 +00001014 NoProtoType = Context.getFunctionNoProtoType(Proto->getResultType());
John McCallf7a1a742009-11-24 19:00:30 +00001015 return BuildDeclRefExpr(Func, NoProtoType, NameLoc, &SS);
Douglas Gregor751f9a42009-06-30 15:47:41 +00001016 }
1017 }
Mike Stump1eb44332009-09-09 15:08:12 +00001018
John McCallaa81e162009-12-01 22:10:20 +00001019 // Check whether this might be a C++ implicit instance member access.
1020 // C++ [expr.prim.general]p6:
1021 // Within the definition of a non-static member function, an
1022 // identifier that names a non-static member is transformed to a
1023 // class member access expression.
1024 // But note that &SomeClass::foo is grammatically distinct, even
1025 // though we don't parse it that way.
John McCall144238e2009-12-02 20:26:00 +00001026 if (!R.empty() && IsClassMember(*R.begin())) {
John McCallf7a1a742009-11-24 19:00:30 +00001027 bool isAbstractMemberPointer = (isAddressOfOperand && !SS.isEmpty());
John McCall5b3f9132009-11-22 01:44:31 +00001028
John McCallaa81e162009-12-01 22:10:20 +00001029 if (!isAbstractMemberPointer) {
1030 switch (ClassifyImplicitMemberAccess(*this, R)) {
1031 case IMA_Instance:
1032 return BuildImplicitMemberExpr(SS, R, TemplateArgs, true);
1033
1034 case IMA_AnonymousMember:
1035 assert(R.isSingleResult());
1036 return BuildAnonymousStructUnionMemberReference(R.getNameLoc(),
1037 R.getAsSingle<FieldDecl>());
1038
1039 case IMA_Mixed:
1040 case IMA_Mixed_Unrelated:
1041 case IMA_Unresolved:
1042 return BuildImplicitMemberExpr(SS, R, TemplateArgs, false);
1043
1044 case IMA_Static:
1045 case IMA_Mixed_StaticContext:
1046 case IMA_Unresolved_StaticContext:
1047 break;
1048
1049 case IMA_Error_StaticContext:
1050 case IMA_Error_Unrelated:
1051 DiagnoseInstanceReference(*this, SS, R);
1052 return ExprError();
1053 }
John McCall5b3f9132009-11-22 01:44:31 +00001054 }
1055 }
1056
John McCallf7a1a742009-11-24 19:00:30 +00001057 if (TemplateArgs)
1058 return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
John McCall5b3f9132009-11-22 01:44:31 +00001059
John McCallf7a1a742009-11-24 19:00:30 +00001060 return BuildDeclarationNameExpr(SS, R, ADL);
1061}
1062
John McCall129e2df2009-11-30 22:42:35 +00001063/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1064/// declaration name, generally during template instantiation.
1065/// There's a large number of things which don't need to be done along
1066/// this path.
John McCallf7a1a742009-11-24 19:00:30 +00001067Sema::OwningExprResult
1068Sema::BuildQualifiedDeclarationNameExpr(const CXXScopeSpec &SS,
1069 DeclarationName Name,
1070 SourceLocation NameLoc) {
1071 DeclContext *DC;
1072 if (!(DC = computeDeclContext(SS, false)) ||
1073 DC->isDependentContext() ||
1074 RequireCompleteDeclContext(SS))
1075 return BuildDependentDeclRefExpr(SS, Name, NameLoc, 0);
1076
1077 LookupResult R(*this, Name, NameLoc, LookupOrdinaryName);
1078 LookupQualifiedName(R, DC);
1079
1080 if (R.isAmbiguous())
1081 return ExprError();
1082
1083 if (R.empty()) {
1084 Diag(NameLoc, diag::err_no_member) << Name << DC << SS.getRange();
1085 return ExprError();
1086 }
1087
1088 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1089}
1090
1091/// LookupInObjCMethod - The parser has read a name in, and Sema has
1092/// detected that we're currently inside an ObjC method. Perform some
1093/// additional lookup.
1094///
1095/// Ideally, most of this would be done by lookup, but there's
1096/// actually quite a lot of extra work involved.
1097///
1098/// Returns a null sentinel to indicate trivial success.
1099Sema::OwningExprResult
1100Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
1101 IdentifierInfo *II) {
1102 SourceLocation Loc = Lookup.getNameLoc();
1103
1104 // There are two cases to handle here. 1) scoped lookup could have failed,
1105 // in which case we should look for an ivar. 2) scoped lookup could have
1106 // found a decl, but that decl is outside the current instance method (i.e.
1107 // a global variable). In these two cases, we do a lookup for an ivar with
1108 // this name, if the lookup sucedes, we replace it our current decl.
1109
1110 // If we're in a class method, we don't normally want to look for
1111 // ivars. But if we don't find anything else, and there's an
1112 // ivar, that's an error.
1113 bool IsClassMethod = getCurMethodDecl()->isClassMethod();
1114
1115 bool LookForIvars;
1116 if (Lookup.empty())
1117 LookForIvars = true;
1118 else if (IsClassMethod)
1119 LookForIvars = false;
1120 else
1121 LookForIvars = (Lookup.isSingleResult() &&
1122 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
1123
1124 if (LookForIvars) {
1125 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
1126 ObjCInterfaceDecl *ClassDeclared;
1127 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1128 // Diagnose using an ivar in a class method.
1129 if (IsClassMethod)
1130 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1131 << IV->getDeclName());
1132
1133 // If we're referencing an invalid decl, just return this as a silent
1134 // error node. The error diagnostic was already emitted on the decl.
1135 if (IV->isInvalidDecl())
1136 return ExprError();
1137
1138 // Check if referencing a field with __attribute__((deprecated)).
1139 if (DiagnoseUseOfDecl(IV, Loc))
1140 return ExprError();
1141
1142 // Diagnose the use of an ivar outside of the declaring class.
1143 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
1144 ClassDeclared != IFace)
1145 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1146
1147 // FIXME: This should use a new expr for a direct reference, don't
1148 // turn this into Self->ivar, just return a BareIVarExpr or something.
1149 IdentifierInfo &II = Context.Idents.get("self");
1150 UnqualifiedId SelfName;
1151 SelfName.setIdentifier(&II, SourceLocation());
1152 CXXScopeSpec SelfScopeSpec;
1153 OwningExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
1154 SelfName, false, false);
1155 MarkDeclarationReferenced(Loc, IV);
1156 return Owned(new (Context)
1157 ObjCIvarRefExpr(IV, IV->getType(), Loc,
1158 SelfExpr.takeAs<Expr>(), true, true));
1159 }
1160 } else if (getCurMethodDecl()->isInstanceMethod()) {
1161 // We should warn if a local variable hides an ivar.
1162 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
1163 ObjCInterfaceDecl *ClassDeclared;
1164 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1165 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
1166 IFace == ClassDeclared)
1167 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
1168 }
1169 }
1170
1171 // Needed to implement property "super.method" notation.
1172 if (Lookup.empty() && II->isStr("super")) {
1173 QualType T;
1174
1175 if (getCurMethodDecl()->isInstanceMethod())
1176 T = Context.getObjCObjectPointerType(Context.getObjCInterfaceType(
1177 getCurMethodDecl()->getClassInterface()));
1178 else
1179 T = Context.getObjCClassType();
1180 return Owned(new (Context) ObjCSuperExpr(Loc, T));
1181 }
1182
1183 // Sentinel value saying that we didn't do anything special.
1184 return Owned((Expr*) 0);
Douglas Gregor751f9a42009-06-30 15:47:41 +00001185}
John McCallba135432009-11-21 08:51:07 +00001186
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00001187/// \brief Cast member's object to its own class if necessary.
Fariborz Jahanianf3e53d32009-07-29 19:40:11 +00001188bool
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00001189Sema::PerformObjectMemberConversion(Expr *&From, NamedDecl *Member) {
1190 if (FieldDecl *FD = dyn_cast<FieldDecl>(Member))
Mike Stump1eb44332009-09-09 15:08:12 +00001191 if (CXXRecordDecl *RD =
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00001192 dyn_cast<CXXRecordDecl>(FD->getDeclContext())) {
Mike Stump1eb44332009-09-09 15:08:12 +00001193 QualType DestType =
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00001194 Context.getCanonicalType(Context.getTypeDeclType(RD));
Fariborz Jahanian96e2fa92009-07-29 20:41:46 +00001195 if (DestType->isDependentType() || From->getType()->isDependentType())
1196 return false;
1197 QualType FromRecordType = From->getType();
1198 QualType DestRecordType = DestType;
Ted Kremenek6217b802009-07-29 21:53:49 +00001199 if (FromRecordType->getAs<PointerType>()) {
Fariborz Jahanian96e2fa92009-07-29 20:41:46 +00001200 DestType = Context.getPointerType(DestType);
1201 FromRecordType = FromRecordType->getPointeeType();
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00001202 }
Fariborz Jahanian96e2fa92009-07-29 20:41:46 +00001203 if (!Context.hasSameUnqualifiedType(FromRecordType, DestRecordType) &&
1204 CheckDerivedToBaseConversion(FromRecordType,
1205 DestRecordType,
1206 From->getSourceRange().getBegin(),
1207 From->getSourceRange()))
1208 return true;
Anders Carlsson3503d042009-07-31 01:23:52 +00001209 ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
1210 /*isLvalue=*/true);
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00001211 }
Fariborz Jahanianf3e53d32009-07-29 19:40:11 +00001212 return false;
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00001213}
Douglas Gregor751f9a42009-06-30 15:47:41 +00001214
Douglas Gregor83f6faf2009-08-31 23:41:50 +00001215/// \brief Build a MemberExpr AST node.
Mike Stump1eb44332009-09-09 15:08:12 +00001216static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow,
Eli Friedmanf595cc42009-12-04 06:40:45 +00001217 const CXXScopeSpec &SS, ValueDecl *Member,
John McCallf7a1a742009-11-24 19:00:30 +00001218 SourceLocation Loc, QualType Ty,
1219 const TemplateArgumentListInfo *TemplateArgs = 0) {
1220 NestedNameSpecifier *Qualifier = 0;
1221 SourceRange QualifierRange;
John McCall129e2df2009-11-30 22:42:35 +00001222 if (SS.isSet()) {
1223 Qualifier = (NestedNameSpecifier *) SS.getScopeRep();
1224 QualifierRange = SS.getRange();
John McCallf7a1a742009-11-24 19:00:30 +00001225 }
Mike Stump1eb44332009-09-09 15:08:12 +00001226
John McCallf7a1a742009-11-24 19:00:30 +00001227 return MemberExpr::Create(C, Base, isArrow, Qualifier, QualifierRange,
1228 Member, Loc, TemplateArgs, Ty);
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +00001229}
1230
John McCallaa81e162009-12-01 22:10:20 +00001231/// Builds an implicit member access expression. The current context
1232/// is known to be an instance method, and the given unqualified lookup
1233/// set is known to contain only instance members, at least one of which
1234/// is from an appropriate type.
John McCall5b3f9132009-11-22 01:44:31 +00001235Sema::OwningExprResult
John McCallaa81e162009-12-01 22:10:20 +00001236Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
1237 LookupResult &R,
1238 const TemplateArgumentListInfo *TemplateArgs,
1239 bool IsKnownInstance) {
John McCallf7a1a742009-11-24 19:00:30 +00001240 assert(!R.empty() && !R.isAmbiguous());
1241
John McCallba135432009-11-21 08:51:07 +00001242 SourceLocation Loc = R.getNameLoc();
Sebastian Redlebc07d52009-02-03 20:19:35 +00001243
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001244 // We may have found a field within an anonymous union or struct
1245 // (C++ [class.union]).
Douglas Gregore961afb2009-10-22 07:08:30 +00001246 // FIXME: This needs to happen post-isImplicitMemberReference?
John McCallf7a1a742009-11-24 19:00:30 +00001247 // FIXME: template-ids inside anonymous structs?
John McCall129e2df2009-11-30 22:42:35 +00001248 if (FieldDecl *FD = R.getAsSingle<FieldDecl>())
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001249 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
John McCall5b3f9132009-11-22 01:44:31 +00001250 return BuildAnonymousStructUnionMemberReference(Loc, FD);
Sebastian Redlcd965b92009-01-18 18:53:16 +00001251
John McCallaa81e162009-12-01 22:10:20 +00001252 // If this is known to be an instance access, go ahead and build a
1253 // 'this' expression now.
1254 QualType ThisType = cast<CXXMethodDecl>(CurContext)->getThisType(Context);
1255 Expr *This = 0; // null signifies implicit access
1256 if (IsKnownInstance) {
1257 This = new (Context) CXXThisExpr(SourceLocation(), ThisType);
Douglas Gregor88a35142008-12-22 05:46:06 +00001258 }
1259
John McCallaa81e162009-12-01 22:10:20 +00001260 return BuildMemberReferenceExpr(ExprArg(*this, This), ThisType,
1261 /*OpLoc*/ SourceLocation(),
1262 /*IsArrow*/ true,
1263 SS, R, TemplateArgs);
John McCallba135432009-11-21 08:51:07 +00001264}
1265
John McCallf7a1a742009-11-24 19:00:30 +00001266bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00001267 const LookupResult &R,
1268 bool HasTrailingLParen) {
John McCallba135432009-11-21 08:51:07 +00001269 // Only when used directly as the postfix-expression of a call.
1270 if (!HasTrailingLParen)
1271 return false;
1272
1273 // Never if a scope specifier was provided.
John McCallf7a1a742009-11-24 19:00:30 +00001274 if (SS.isSet())
John McCallba135432009-11-21 08:51:07 +00001275 return false;
1276
1277 // Only in C++ or ObjC++.
John McCall5b3f9132009-11-22 01:44:31 +00001278 if (!getLangOptions().CPlusPlus)
John McCallba135432009-11-21 08:51:07 +00001279 return false;
1280
1281 // Turn off ADL when we find certain kinds of declarations during
1282 // normal lookup:
1283 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
1284 NamedDecl *D = *I;
1285
1286 // C++0x [basic.lookup.argdep]p3:
1287 // -- a declaration of a class member
1288 // Since using decls preserve this property, we check this on the
1289 // original decl.
John McCall144238e2009-12-02 20:26:00 +00001290 if (IsClassMember(D))
John McCallba135432009-11-21 08:51:07 +00001291 return false;
1292
1293 // C++0x [basic.lookup.argdep]p3:
1294 // -- a block-scope function declaration that is not a
1295 // using-declaration
1296 // NOTE: we also trigger this for function templates (in fact, we
1297 // don't check the decl type at all, since all other decl types
1298 // turn off ADL anyway).
1299 if (isa<UsingShadowDecl>(D))
1300 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1301 else if (D->getDeclContext()->isFunctionOrMethod())
1302 return false;
1303
1304 // C++0x [basic.lookup.argdep]p3:
1305 // -- a declaration that is neither a function or a function
1306 // template
1307 // And also for builtin functions.
1308 if (isa<FunctionDecl>(D)) {
1309 FunctionDecl *FDecl = cast<FunctionDecl>(D);
1310
1311 // But also builtin functions.
1312 if (FDecl->getBuiltinID() && FDecl->isImplicit())
1313 return false;
1314 } else if (!isa<FunctionTemplateDecl>(D))
1315 return false;
1316 }
1317
1318 return true;
1319}
1320
1321
John McCallba135432009-11-21 08:51:07 +00001322/// Diagnoses obvious problems with the use of the given declaration
1323/// as an expression. This is only actually called for lookups that
1324/// were not overloaded, and it doesn't promise that the declaration
1325/// will in fact be used.
1326static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
1327 if (isa<TypedefDecl>(D)) {
1328 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
1329 return true;
1330 }
1331
1332 if (isa<ObjCInterfaceDecl>(D)) {
1333 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
1334 return true;
1335 }
1336
1337 if (isa<NamespaceDecl>(D)) {
1338 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
1339 return true;
1340 }
1341
1342 return false;
1343}
1344
1345Sema::OwningExprResult
John McCallf7a1a742009-11-24 19:00:30 +00001346Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00001347 LookupResult &R,
1348 bool NeedsADL) {
John McCallf7a1a742009-11-24 19:00:30 +00001349 // If this isn't an overloaded result and we don't need ADL, just
1350 // build an ordinary singleton decl ref.
John McCall5b3f9132009-11-22 01:44:31 +00001351 if (!NeedsADL && !R.isOverloadedResult())
1352 return BuildDeclarationNameExpr(SS, R.getNameLoc(), R.getFoundDecl());
John McCallba135432009-11-21 08:51:07 +00001353
1354 // We only need to check the declaration if there's exactly one
1355 // result, because in the overloaded case the results can only be
1356 // functions and function templates.
John McCall5b3f9132009-11-22 01:44:31 +00001357 if (R.isSingleResult() &&
1358 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCallba135432009-11-21 08:51:07 +00001359 return ExprError();
1360
John McCallf7a1a742009-11-24 19:00:30 +00001361 bool Dependent
1362 = UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(), 0);
John McCallba135432009-11-21 08:51:07 +00001363 UnresolvedLookupExpr *ULE
John McCallf7a1a742009-11-24 19:00:30 +00001364 = UnresolvedLookupExpr::Create(Context, Dependent,
1365 (NestedNameSpecifier*) SS.getScopeRep(),
1366 SS.getRange(),
John McCall5b3f9132009-11-22 01:44:31 +00001367 R.getLookupName(), R.getNameLoc(),
1368 NeedsADL, R.isOverloadedResult());
1369 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1370 ULE->addDecl(*I);
John McCallba135432009-11-21 08:51:07 +00001371
1372 return Owned(ULE);
1373}
1374
1375
1376/// \brief Complete semantic analysis for a reference to the given declaration.
1377Sema::OwningExprResult
John McCallf7a1a742009-11-24 19:00:30 +00001378Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCallba135432009-11-21 08:51:07 +00001379 SourceLocation Loc, NamedDecl *D) {
1380 assert(D && "Cannot refer to a NULL declaration");
John McCall7453ed42009-11-22 00:44:51 +00001381 assert(!isa<FunctionTemplateDecl>(D) &&
1382 "Cannot refer unambiguously to a function template");
John McCallba135432009-11-21 08:51:07 +00001383 DeclarationName Name = D->getDeclName();
1384
1385 if (CheckDeclInExpr(*this, Loc, D))
1386 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001387
Douglas Gregor9af2f522009-12-01 16:58:18 +00001388 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
1389 // Specifically diagnose references to class templates that are missing
1390 // a template argument list.
1391 Diag(Loc, diag::err_template_decl_ref)
1392 << Template << SS.getRange();
1393 Diag(Template->getLocation(), diag::note_template_decl_here);
1394 return ExprError();
1395 }
1396
1397 // Make sure that we're referring to a value.
1398 ValueDecl *VD = dyn_cast<ValueDecl>(D);
1399 if (!VD) {
1400 Diag(Loc, diag::err_ref_non_value)
1401 << D << SS.getRange();
1402 Diag(D->getLocation(), diag::note_previous_decl);
1403 return ExprError();
1404 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001405
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001406 // Check whether this declaration can be used. Note that we suppress
1407 // this check when we're going to perform argument-dependent lookup
1408 // on this function name, because this might not be the function
1409 // that overload resolution actually selects.
John McCallba135432009-11-21 08:51:07 +00001410 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001411 return ExprError();
1412
Steve Naroffdd972f22008-09-05 22:11:13 +00001413 // Only create DeclRefExpr's for valid Decl's.
1414 if (VD->isInvalidDecl())
Sebastian Redlcd965b92009-01-18 18:53:16 +00001415 return ExprError();
1416
Chris Lattner639e2d32008-10-20 05:16:36 +00001417 // If the identifier reference is inside a block, and it refers to a value
1418 // that is outside the block, create a BlockDeclRefExpr instead of a
1419 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
1420 // the block is formed.
Steve Naroffdd972f22008-09-05 22:11:13 +00001421 //
Chris Lattner639e2d32008-10-20 05:16:36 +00001422 // We do not do this for things like enum constants, global variables, etc,
1423 // as they do not get snapshotted.
1424 //
1425 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Douglas Gregore0762c92009-06-19 23:52:42 +00001426 MarkDeclarationReferenced(Loc, VD);
Eli Friedman5fdeae12009-03-22 23:00:19 +00001427 QualType ExprTy = VD->getType().getNonReferenceType();
Steve Naroff090276f2008-10-10 01:28:17 +00001428 // The BlocksAttr indicates the variable is bound by-reference.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001429 if (VD->getAttr<BlocksAttr>())
Eli Friedman5fdeae12009-03-22 23:00:19 +00001430 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, true));
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00001431 // This is to record that a 'const' was actually synthesize and added.
1432 bool constAdded = !ExprTy.isConstQualified();
Steve Naroff090276f2008-10-10 01:28:17 +00001433 // Variable will be bound by-copy, make it const within the closure.
Mike Stump1eb44332009-09-09 15:08:12 +00001434
Eli Friedman5fdeae12009-03-22 23:00:19 +00001435 ExprTy.addConst();
Mike Stump1eb44332009-09-09 15:08:12 +00001436 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, false,
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00001437 constAdded));
Steve Naroff090276f2008-10-10 01:28:17 +00001438 }
1439 // If this reference is not in a block or if the referenced variable is
1440 // within the block, create a normal DeclRefExpr.
Douglas Gregor898574e2008-12-05 23:32:09 +00001441
John McCallf7a1a742009-11-24 19:00:30 +00001442 return BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc, &SS);
Reid Spencer5f016e22007-07-11 17:01:13 +00001443}
1444
Sebastian Redlcd965b92009-01-18 18:53:16 +00001445Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
1446 tok::TokenKind Kind) {
Chris Lattnerd9f69102008-08-10 01:53:14 +00001447 PredefinedExpr::IdentType IT;
Sebastian Redlcd965b92009-01-18 18:53:16 +00001448
Reid Spencer5f016e22007-07-11 17:01:13 +00001449 switch (Kind) {
Chris Lattner1423ea42008-01-12 18:39:25 +00001450 default: assert(0 && "Unknown simple primary expr!");
Chris Lattnerd9f69102008-08-10 01:53:14 +00001451 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
1452 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
1453 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00001454 }
Chris Lattner1423ea42008-01-12 18:39:25 +00001455
Chris Lattnerfa28b302008-01-12 08:14:25 +00001456 // Pre-defined identifiers are of type char[x], where x is the length of the
1457 // string.
Mike Stump1eb44332009-09-09 15:08:12 +00001458
Anders Carlsson3a082d82009-09-08 18:24:21 +00001459 Decl *currentDecl = getCurFunctionOrMethodDecl();
1460 if (!currentDecl) {
Chris Lattnerb0da9232008-12-12 05:05:20 +00001461 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson3a082d82009-09-08 18:24:21 +00001462 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerb0da9232008-12-12 05:05:20 +00001463 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001464
Anders Carlsson773f3972009-09-11 01:22:35 +00001465 QualType ResTy;
1466 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
1467 ResTy = Context.DependentTy;
1468 } else {
1469 unsigned Length =
1470 PredefinedExpr::ComputeName(Context, IT, currentDecl).length();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001471
Anders Carlsson773f3972009-09-11 01:22:35 +00001472 llvm::APInt LengthI(32, Length + 1);
John McCall0953e762009-09-24 19:53:00 +00001473 ResTy = Context.CharTy.withConst();
Anders Carlsson773f3972009-09-11 01:22:35 +00001474 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
1475 }
Steve Naroff6ece14c2009-01-21 00:14:39 +00001476 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Reid Spencer5f016e22007-07-11 17:01:13 +00001477}
1478
Sebastian Redlcd965b92009-01-18 18:53:16 +00001479Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001480 llvm::SmallString<16> CharBuffer;
1481 CharBuffer.resize(Tok.getLength());
1482 const char *ThisTokBegin = &CharBuffer[0];
1483 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd965b92009-01-18 18:53:16 +00001484
Reid Spencer5f016e22007-07-11 17:01:13 +00001485 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1486 Tok.getLocation(), PP);
1487 if (Literal.hadError())
Sebastian Redlcd965b92009-01-18 18:53:16 +00001488 return ExprError();
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00001489
1490 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
1491
Sebastian Redle91b3bc2009-01-20 22:23:13 +00001492 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
1493 Literal.isWide(),
1494 type, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00001495}
1496
Sebastian Redlcd965b92009-01-18 18:53:16 +00001497Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
1498 // Fast path for a single digit (which is quite common). A single digit
Reid Spencer5f016e22007-07-11 17:01:13 +00001499 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
1500 if (Tok.getLength() == 1) {
Chris Lattner7216dc92009-01-26 22:36:52 +00001501 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattner0c21e842009-01-16 07:10:29 +00001502 unsigned IntSize = Context.Target.getIntWidth();
Steve Naroff6ece14c2009-01-21 00:14:39 +00001503 return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
Steve Naroff0a473932009-01-20 19:53:53 +00001504 Context.IntTy, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00001505 }
Ted Kremenek28396602009-01-13 23:19:12 +00001506
Reid Spencer5f016e22007-07-11 17:01:13 +00001507 llvm::SmallString<512> IntegerBuffer;
Chris Lattner2a299042008-09-30 20:53:45 +00001508 // Add padding so that NumericLiteralParser can overread by one character.
1509 IntegerBuffer.resize(Tok.getLength()+1);
Reid Spencer5f016e22007-07-11 17:01:13 +00001510 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd965b92009-01-18 18:53:16 +00001511
Reid Spencer5f016e22007-07-11 17:01:13 +00001512 // Get the spelling of the token, which eliminates trigraphs, etc.
1513 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd965b92009-01-18 18:53:16 +00001514
Mike Stump1eb44332009-09-09 15:08:12 +00001515 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Reid Spencer5f016e22007-07-11 17:01:13 +00001516 Tok.getLocation(), PP);
1517 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +00001518 return ExprError();
1519
Chris Lattner5d661452007-08-26 03:42:43 +00001520 Expr *Res;
Sebastian Redlcd965b92009-01-18 18:53:16 +00001521
Chris Lattner5d661452007-08-26 03:42:43 +00001522 if (Literal.isFloatingLiteral()) {
Chris Lattner525a0502007-09-22 18:29:59 +00001523 QualType Ty;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001524 if (Literal.isFloat)
Chris Lattner525a0502007-09-22 18:29:59 +00001525 Ty = Context.FloatTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001526 else if (!Literal.isLong)
Chris Lattner525a0502007-09-22 18:29:59 +00001527 Ty = Context.DoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001528 else
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001529 Ty = Context.LongDoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001530
1531 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
1532
Ted Kremenek720c4ec2007-11-29 00:56:49 +00001533 // isExact will be set by GetFloatValue().
1534 bool isExact = false;
Chris Lattner001d64d2009-06-29 17:34:55 +00001535 llvm::APFloat Val = Literal.GetFloatValue(Format, &isExact);
1536 Res = new (Context) FloatingLiteral(Val, isExact, Ty, Tok.getLocation());
Sebastian Redlcd965b92009-01-18 18:53:16 +00001537
Chris Lattner5d661452007-08-26 03:42:43 +00001538 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00001539 return ExprError();
Chris Lattner5d661452007-08-26 03:42:43 +00001540 } else {
Chris Lattnerf0467b32008-04-02 04:24:33 +00001541 QualType Ty;
Reid Spencer5f016e22007-07-11 17:01:13 +00001542
Neil Boothb9449512007-08-29 22:00:19 +00001543 // long long is a C99 feature.
1544 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth79859c32007-08-29 22:13:52 +00001545 Literal.isLongLong)
Neil Boothb9449512007-08-29 22:00:19 +00001546 Diag(Tok.getLocation(), diag::ext_longlong);
1547
Reid Spencer5f016e22007-07-11 17:01:13 +00001548 // Get the value in the widest-possible width.
Chris Lattner98be4942008-03-05 18:54:05 +00001549 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlcd965b92009-01-18 18:53:16 +00001550
Reid Spencer5f016e22007-07-11 17:01:13 +00001551 if (Literal.GetIntegerValue(ResultVal)) {
1552 // If this value didn't fit into uintmax_t, warn and force to ull.
1553 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattnerf0467b32008-04-02 04:24:33 +00001554 Ty = Context.UnsignedLongLongTy;
1555 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner98be4942008-03-05 18:54:05 +00001556 "long long is not intmax_t?");
Reid Spencer5f016e22007-07-11 17:01:13 +00001557 } else {
1558 // If this value fits into a ULL, try to figure out what else it fits into
1559 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd965b92009-01-18 18:53:16 +00001560
Reid Spencer5f016e22007-07-11 17:01:13 +00001561 // Octal, Hexadecimal, and integers with a U suffix are allowed to
1562 // be an unsigned int.
1563 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
1564
1565 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001566 unsigned Width = 0;
Chris Lattner97c51562007-08-23 21:58:08 +00001567 if (!Literal.isLong && !Literal.isLongLong) {
1568 // Are int/unsigned possibilities?
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001569 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001570
Reid Spencer5f016e22007-07-11 17:01:13 +00001571 // Does it fit in a unsigned int?
1572 if (ResultVal.isIntN(IntSize)) {
1573 // Does it fit in a signed int?
1574 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001575 Ty = Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001576 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001577 Ty = Context.UnsignedIntTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001578 Width = IntSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00001579 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001580 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001581
Reid Spencer5f016e22007-07-11 17:01:13 +00001582 // Are long/unsigned long possibilities?
Chris Lattnerf0467b32008-04-02 04:24:33 +00001583 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001584 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001585
Reid Spencer5f016e22007-07-11 17:01:13 +00001586 // Does it fit in a unsigned long?
1587 if (ResultVal.isIntN(LongSize)) {
1588 // Does it fit in a signed long?
1589 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001590 Ty = Context.LongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001591 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001592 Ty = Context.UnsignedLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001593 Width = LongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00001594 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001595 }
1596
Reid Spencer5f016e22007-07-11 17:01:13 +00001597 // Finally, check long long if needed.
Chris Lattnerf0467b32008-04-02 04:24:33 +00001598 if (Ty.isNull()) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001599 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001600
Reid Spencer5f016e22007-07-11 17:01:13 +00001601 // Does it fit in a unsigned long long?
1602 if (ResultVal.isIntN(LongLongSize)) {
1603 // Does it fit in a signed long long?
1604 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001605 Ty = Context.LongLongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001606 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001607 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001608 Width = LongLongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00001609 }
1610 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001611
Reid Spencer5f016e22007-07-11 17:01:13 +00001612 // If we still couldn't decide a type, we probably have something that
1613 // does not fit in a signed long long, but has no U suffix.
Chris Lattnerf0467b32008-04-02 04:24:33 +00001614 if (Ty.isNull()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001615 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattnerf0467b32008-04-02 04:24:33 +00001616 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001617 Width = Context.Target.getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +00001618 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001619
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001620 if (ResultVal.getBitWidth() != Width)
1621 ResultVal.trunc(Width);
Reid Spencer5f016e22007-07-11 17:01:13 +00001622 }
Sebastian Redle91b3bc2009-01-20 22:23:13 +00001623 Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00001624 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001625
Chris Lattner5d661452007-08-26 03:42:43 +00001626 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
1627 if (Literal.isImaginary)
Mike Stump1eb44332009-09-09 15:08:12 +00001628 Res = new (Context) ImaginaryLiteral(Res,
Steve Naroff6ece14c2009-01-21 00:14:39 +00001629 Context.getComplexType(Res->getType()));
Sebastian Redlcd965b92009-01-18 18:53:16 +00001630
1631 return Owned(Res);
Reid Spencer5f016e22007-07-11 17:01:13 +00001632}
1633
Sebastian Redlcd965b92009-01-18 18:53:16 +00001634Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1635 SourceLocation R, ExprArg Val) {
Anders Carlssone9146f22009-05-01 19:49:17 +00001636 Expr *E = Val.takeAs<Expr>();
Chris Lattnerf0467b32008-04-02 04:24:33 +00001637 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff6ece14c2009-01-21 00:14:39 +00001638 return Owned(new (Context) ParenExpr(L, R, E));
Reid Spencer5f016e22007-07-11 17:01:13 +00001639}
1640
1641/// The UsualUnaryConversions() function is *not* called by this routine.
1642/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl28507842009-02-26 14:39:58 +00001643bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Sebastian Redl05189992008-11-11 17:56:53 +00001644 SourceLocation OpLoc,
1645 const SourceRange &ExprRange,
1646 bool isSizeof) {
Sebastian Redl28507842009-02-26 14:39:58 +00001647 if (exprType->isDependentType())
1648 return false;
1649
Sebastian Redl5d484e82009-11-23 17:18:46 +00001650 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
1651 // the result is the size of the referenced type."
1652 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
1653 // result shall be the alignment of the referenced type."
1654 if (const ReferenceType *Ref = exprType->getAs<ReferenceType>())
1655 exprType = Ref->getPointeeType();
1656
Reid Spencer5f016e22007-07-11 17:01:13 +00001657 // C99 6.5.3.4p1:
John McCall5ab75172009-11-04 07:28:41 +00001658 if (exprType->isFunctionType()) {
Chris Lattner1efaa952009-04-24 00:30:45 +00001659 // alignof(function) is allowed as an extension.
Chris Lattner01072922009-01-24 19:46:37 +00001660 if (isSizeof)
1661 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
1662 return false;
1663 }
Mike Stump1eb44332009-09-09 15:08:12 +00001664
Chris Lattner1efaa952009-04-24 00:30:45 +00001665 // Allow sizeof(void)/alignof(void) as an extension.
Chris Lattner01072922009-01-24 19:46:37 +00001666 if (exprType->isVoidType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001667 Diag(OpLoc, diag::ext_sizeof_void_type)
1668 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattner01072922009-01-24 19:46:37 +00001669 return false;
1670 }
Mike Stump1eb44332009-09-09 15:08:12 +00001671
Chris Lattner1efaa952009-04-24 00:30:45 +00001672 if (RequireCompleteType(OpLoc, exprType,
Mike Stump1eb44332009-09-09 15:08:12 +00001673 isSizeof ? diag::err_sizeof_incomplete_type :
Anders Carlssonb7906612009-08-26 23:45:07 +00001674 PDiag(diag::err_alignof_incomplete_type)
1675 << ExprRange))
Chris Lattner1efaa952009-04-24 00:30:45 +00001676 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001677
Chris Lattner1efaa952009-04-24 00:30:45 +00001678 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
Fariborz Jahanianced1e282009-04-24 17:34:33 +00001679 if (LangOpts.ObjCNonFragileABI && exprType->isObjCInterfaceType()) {
Chris Lattner1efaa952009-04-24 00:30:45 +00001680 Diag(OpLoc, diag::err_sizeof_nonfragile_interface)
Chris Lattner5cb10d32009-04-24 22:30:50 +00001681 << exprType << isSizeof << ExprRange;
1682 return true;
Chris Lattnerca790922009-04-21 19:55:16 +00001683 }
Mike Stump1eb44332009-09-09 15:08:12 +00001684
Chris Lattner1efaa952009-04-24 00:30:45 +00001685 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001686}
1687
Chris Lattner31e21e02009-01-24 20:17:12 +00001688bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
1689 const SourceRange &ExprRange) {
1690 E = E->IgnoreParens();
Sebastian Redl28507842009-02-26 14:39:58 +00001691
Mike Stump1eb44332009-09-09 15:08:12 +00001692 // alignof decl is always ok.
Chris Lattner31e21e02009-01-24 20:17:12 +00001693 if (isa<DeclRefExpr>(E))
1694 return false;
Sebastian Redl28507842009-02-26 14:39:58 +00001695
1696 // Cannot know anything else if the expression is dependent.
1697 if (E->isTypeDependent())
1698 return false;
1699
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001700 if (E->getBitField()) {
1701 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
1702 return true;
Chris Lattner31e21e02009-01-24 20:17:12 +00001703 }
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001704
1705 // Alignment of a field access is always okay, so long as it isn't a
1706 // bit-field.
1707 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump8e1fab22009-07-22 18:58:19 +00001708 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001709 return false;
1710
Chris Lattner31e21e02009-01-24 20:17:12 +00001711 return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
1712}
1713
Douglas Gregorba498172009-03-13 21:01:28 +00001714/// \brief Build a sizeof or alignof expression given a type operand.
Mike Stump1eb44332009-09-09 15:08:12 +00001715Action::OwningExprResult
John McCalla93c9342009-12-07 02:54:59 +00001716Sema::CreateSizeOfAlignOfExpr(TypeSourceInfo *TInfo,
John McCall5ab75172009-11-04 07:28:41 +00001717 SourceLocation OpLoc,
Douglas Gregorba498172009-03-13 21:01:28 +00001718 bool isSizeOf, SourceRange R) {
John McCalla93c9342009-12-07 02:54:59 +00001719 if (!TInfo)
Douglas Gregorba498172009-03-13 21:01:28 +00001720 return ExprError();
1721
John McCalla93c9342009-12-07 02:54:59 +00001722 QualType T = TInfo->getType();
John McCall5ab75172009-11-04 07:28:41 +00001723
Douglas Gregorba498172009-03-13 21:01:28 +00001724 if (!T->isDependentType() &&
1725 CheckSizeOfAlignOfOperand(T, OpLoc, R, isSizeOf))
1726 return ExprError();
1727
1728 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
John McCalla93c9342009-12-07 02:54:59 +00001729 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, TInfo,
Douglas Gregorba498172009-03-13 21:01:28 +00001730 Context.getSizeType(), OpLoc,
1731 R.getEnd()));
1732}
1733
1734/// \brief Build a sizeof or alignof expression given an expression
1735/// operand.
Mike Stump1eb44332009-09-09 15:08:12 +00001736Action::OwningExprResult
1737Sema::CreateSizeOfAlignOfExpr(Expr *E, SourceLocation OpLoc,
Douglas Gregorba498172009-03-13 21:01:28 +00001738 bool isSizeOf, SourceRange R) {
1739 // Verify that the operand is valid.
1740 bool isInvalid = false;
1741 if (E->isTypeDependent()) {
1742 // Delay type-checking for type-dependent expressions.
1743 } else if (!isSizeOf) {
1744 isInvalid = CheckAlignOfExpr(E, OpLoc, R);
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001745 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Douglas Gregorba498172009-03-13 21:01:28 +00001746 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
1747 isInvalid = true;
1748 } else {
1749 isInvalid = CheckSizeOfAlignOfOperand(E->getType(), OpLoc, R, true);
1750 }
1751
1752 if (isInvalid)
1753 return ExprError();
1754
1755 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1756 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, E,
1757 Context.getSizeType(), OpLoc,
1758 R.getEnd()));
1759}
1760
Sebastian Redl05189992008-11-11 17:56:53 +00001761/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1762/// the same for @c alignof and @c __alignof
1763/// Note that the ArgRange is invalid if isType is false.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001764Action::OwningExprResult
Sebastian Redl05189992008-11-11 17:56:53 +00001765Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1766 void *TyOrEx, const SourceRange &ArgRange) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001767 // If error parsing type, ignore.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001768 if (TyOrEx == 0) return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001769
Sebastian Redl05189992008-11-11 17:56:53 +00001770 if (isType) {
John McCalla93c9342009-12-07 02:54:59 +00001771 TypeSourceInfo *TInfo;
1772 (void) GetTypeFromParser(TyOrEx, &TInfo);
1773 return CreateSizeOfAlignOfExpr(TInfo, OpLoc, isSizeof, ArgRange);
Mike Stump1eb44332009-09-09 15:08:12 +00001774 }
Sebastian Redl05189992008-11-11 17:56:53 +00001775
Douglas Gregorba498172009-03-13 21:01:28 +00001776 Expr *ArgEx = (Expr *)TyOrEx;
1777 Action::OwningExprResult Result
1778 = CreateSizeOfAlignOfExpr(ArgEx, OpLoc, isSizeof, ArgEx->getSourceRange());
1779
1780 if (Result.isInvalid())
1781 DeleteExpr(ArgEx);
1782
1783 return move(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00001784}
1785
Chris Lattnerba27e2a2009-02-17 08:12:06 +00001786QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc, bool isReal) {
Sebastian Redl28507842009-02-26 14:39:58 +00001787 if (V->isTypeDependent())
1788 return Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00001789
Chris Lattnercc26ed72007-08-26 05:39:26 +00001790 // These operators return the element type of a complex type.
John McCall183700f2009-09-21 23:43:11 +00001791 if (const ComplexType *CT = V->getType()->getAs<ComplexType>())
Chris Lattnerdbb36972007-08-24 21:16:53 +00001792 return CT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00001793
Chris Lattnercc26ed72007-08-26 05:39:26 +00001794 // Otherwise they pass through real integer and floating point types here.
1795 if (V->getType()->isArithmeticType())
1796 return V->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001797
Chris Lattnercc26ed72007-08-26 05:39:26 +00001798 // Reject anything else.
Chris Lattnerba27e2a2009-02-17 08:12:06 +00001799 Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
1800 << (isReal ? "__real" : "__imag");
Chris Lattnercc26ed72007-08-26 05:39:26 +00001801 return QualType();
Chris Lattnerdbb36972007-08-24 21:16:53 +00001802}
1803
1804
Reid Spencer5f016e22007-07-11 17:01:13 +00001805
Sebastian Redl0eb23302009-01-19 00:08:26 +00001806Action::OwningExprResult
1807Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
1808 tok::TokenKind Kind, ExprArg Input) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001809 UnaryOperator::Opcode Opc;
1810 switch (Kind) {
1811 default: assert(0 && "Unknown unary op!");
1812 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
1813 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1814 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00001815
Eli Friedmane4216e92009-11-18 03:38:04 +00001816 return BuildUnaryOp(S, OpLoc, Opc, move(Input));
Reid Spencer5f016e22007-07-11 17:01:13 +00001817}
1818
Sebastian Redl0eb23302009-01-19 00:08:26 +00001819Action::OwningExprResult
1820Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
1821 ExprArg Idx, SourceLocation RLoc) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00001822 // Since this might be a postfix expression, get rid of ParenListExprs.
1823 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
1824
Sebastian Redl0eb23302009-01-19 00:08:26 +00001825 Expr *LHSExp = static_cast<Expr*>(Base.get()),
1826 *RHSExp = static_cast<Expr*>(Idx.get());
Mike Stump1eb44332009-09-09 15:08:12 +00001827
Douglas Gregor337c6b92008-11-19 17:17:41 +00001828 if (getLangOptions().CPlusPlus &&
Douglas Gregor3384c9c2009-05-19 00:01:19 +00001829 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
1830 Base.release();
1831 Idx.release();
1832 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
1833 Context.DependentTy, RLoc));
1834 }
1835
Mike Stump1eb44332009-09-09 15:08:12 +00001836 if (getLangOptions().CPlusPlus &&
Sebastian Redl0eb23302009-01-19 00:08:26 +00001837 (LHSExp->getType()->isRecordType() ||
Eli Friedman03f332a2008-12-15 22:34:21 +00001838 LHSExp->getType()->isEnumeralType() ||
1839 RHSExp->getType()->isRecordType() ||
1840 RHSExp->getType()->isEnumeralType())) {
Sebastian Redlf322ed62009-10-29 20:17:01 +00001841 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, move(Base),move(Idx));
Douglas Gregor337c6b92008-11-19 17:17:41 +00001842 }
1843
Sebastian Redlf322ed62009-10-29 20:17:01 +00001844 return CreateBuiltinArraySubscriptExpr(move(Base), LLoc, move(Idx), RLoc);
1845}
1846
1847
1848Action::OwningExprResult
1849Sema::CreateBuiltinArraySubscriptExpr(ExprArg Base, SourceLocation LLoc,
1850 ExprArg Idx, SourceLocation RLoc) {
1851 Expr *LHSExp = static_cast<Expr*>(Base.get());
1852 Expr *RHSExp = static_cast<Expr*>(Idx.get());
1853
Chris Lattner12d9ff62007-07-16 00:14:47 +00001854 // Perform default conversions.
1855 DefaultFunctionArrayConversion(LHSExp);
1856 DefaultFunctionArrayConversion(RHSExp);
Sebastian Redl0eb23302009-01-19 00:08:26 +00001857
Chris Lattner12d9ff62007-07-16 00:14:47 +00001858 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001859
Reid Spencer5f016e22007-07-11 17:01:13 +00001860 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner73d0d4f2007-08-30 17:45:32 +00001861 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stumpeed9cac2009-02-19 03:04:26 +00001862 // in the subscript position. As a result, we need to derive the array base
Reid Spencer5f016e22007-07-11 17:01:13 +00001863 // and index from the expression types.
Chris Lattner12d9ff62007-07-16 00:14:47 +00001864 Expr *BaseExpr, *IndexExpr;
1865 QualType ResultType;
Sebastian Redl28507842009-02-26 14:39:58 +00001866 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
1867 BaseExpr = LHSExp;
1868 IndexExpr = RHSExp;
1869 ResultType = Context.DependentTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00001870 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner12d9ff62007-07-16 00:14:47 +00001871 BaseExpr = LHSExp;
1872 IndexExpr = RHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00001873 ResultType = PTy->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001874 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattner7a2e0472007-07-16 00:23:25 +00001875 // Handle the uncommon case of "123[Ptr]".
Chris Lattner12d9ff62007-07-16 00:14:47 +00001876 BaseExpr = RHSExp;
1877 IndexExpr = LHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00001878 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00001879 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00001880 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00001881 BaseExpr = LHSExp;
1882 IndexExpr = RHSExp;
1883 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00001884 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00001885 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00001886 // Handle the uncommon case of "123[Ptr]".
1887 BaseExpr = RHSExp;
1888 IndexExpr = LHSExp;
1889 ResultType = PTy->getPointeeType();
John McCall183700f2009-09-21 23:43:11 +00001890 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattnerc8629632007-07-31 19:29:30 +00001891 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner12d9ff62007-07-16 00:14:47 +00001892 IndexExpr = RHSExp;
Nate Begeman334a8022009-01-18 00:45:31 +00001893
Chris Lattner12d9ff62007-07-16 00:14:47 +00001894 // FIXME: need to deal with const...
1895 ResultType = VTy->getElementType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00001896 } else if (LHSTy->isArrayType()) {
1897 // If we see an array that wasn't promoted by
1898 // DefaultFunctionArrayConversion, it must be an array that
1899 // wasn't promoted because of the C90 rule that doesn't
1900 // allow promoting non-lvalue arrays. Warn, then
1901 // force the promotion here.
1902 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
1903 LHSExp->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00001904 ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
1905 CastExpr::CK_ArrayToPointerDecay);
Eli Friedman7c32f8e2009-04-25 23:46:54 +00001906 LHSTy = LHSExp->getType();
1907
1908 BaseExpr = LHSExp;
1909 IndexExpr = RHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00001910 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00001911 } else if (RHSTy->isArrayType()) {
1912 // Same as previous, except for 123[f().a] case
1913 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
1914 RHSExp->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00001915 ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
1916 CastExpr::CK_ArrayToPointerDecay);
Eli Friedman7c32f8e2009-04-25 23:46:54 +00001917 RHSTy = RHSExp->getType();
1918
1919 BaseExpr = RHSExp;
1920 IndexExpr = LHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00001921 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001922 } else {
Chris Lattner338395d2009-04-25 22:50:55 +00001923 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
1924 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00001925 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001926 // C99 6.5.2.1p1
Nate Begeman2ef13e52009-08-10 23:49:36 +00001927 if (!(IndexExpr->getType()->isIntegerType() &&
1928 IndexExpr->getType()->isScalarType()) && !IndexExpr->isTypeDependent())
Chris Lattner338395d2009-04-25 22:50:55 +00001929 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
1930 << IndexExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00001931
Daniel Dunbar7e88a602009-09-17 06:31:17 +00001932 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinig0f9a5b52009-09-14 20:14:57 +00001933 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
1934 && !IndexExpr->isTypeDependent())
Sam Weinig76e2b712009-09-14 01:58:58 +00001935 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
1936
Douglas Gregore7450f52009-03-24 19:52:54 +00001937 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump1eb44332009-09-09 15:08:12 +00001938 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
1939 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregore7450f52009-03-24 19:52:54 +00001940 // incomplete types are not object types.
1941 if (ResultType->isFunctionType()) {
1942 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
1943 << ResultType << BaseExpr->getSourceRange();
1944 return ExprError();
1945 }
Mike Stump1eb44332009-09-09 15:08:12 +00001946
Douglas Gregore7450f52009-03-24 19:52:54 +00001947 if (!ResultType->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00001948 RequireCompleteType(LLoc, ResultType,
Anders Carlssonb7906612009-08-26 23:45:07 +00001949 PDiag(diag::err_subscript_incomplete_type)
1950 << BaseExpr->getSourceRange()))
Douglas Gregore7450f52009-03-24 19:52:54 +00001951 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001952
Chris Lattner1efaa952009-04-24 00:30:45 +00001953 // Diagnose bad cases where we step over interface counts.
1954 if (ResultType->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
1955 Diag(LLoc, diag::err_subscript_nonfragile_interface)
1956 << ResultType << BaseExpr->getSourceRange();
1957 return ExprError();
1958 }
Mike Stump1eb44332009-09-09 15:08:12 +00001959
Sebastian Redl0eb23302009-01-19 00:08:26 +00001960 Base.release();
1961 Idx.release();
Mike Stumpeed9cac2009-02-19 03:04:26 +00001962 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
Steve Naroff6ece14c2009-01-21 00:14:39 +00001963 ResultType, RLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00001964}
1965
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001966QualType Sema::
Nate Begeman213541a2008-04-18 23:10:10 +00001967CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00001968 const IdentifierInfo *CompName,
Anders Carlsson8f28f992009-08-26 18:25:21 +00001969 SourceLocation CompLoc) {
Daniel Dunbar2ad32892009-10-18 02:09:38 +00001970 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
1971 // see FIXME there.
1972 //
1973 // FIXME: This logic can be greatly simplified by splitting it along
1974 // halving/not halving and reworking the component checking.
John McCall183700f2009-09-21 23:43:11 +00001975 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
Nate Begeman8a997642008-05-09 06:41:27 +00001976
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001977 // The vector accessor can't exceed the number of elements.
Daniel Dunbare013d682009-10-18 20:26:12 +00001978 const char *compStr = CompName->getNameStart();
Nate Begeman353417a2009-01-18 01:47:54 +00001979
Mike Stumpeed9cac2009-02-19 03:04:26 +00001980 // This flag determines whether or not the component is one of the four
Nate Begeman353417a2009-01-18 01:47:54 +00001981 // special names that indicate a subset of exactly half the elements are
1982 // to be selected.
1983 bool HalvingSwizzle = false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00001984
Nate Begeman353417a2009-01-18 01:47:54 +00001985 // This flag determines whether or not CompName has an 's' char prefix,
1986 // indicating that it is a string of hex values to be used as vector indices.
Nate Begeman131f4652009-06-25 21:06:09 +00001987 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
Nate Begeman8a997642008-05-09 06:41:27 +00001988
1989 // Check that we've found one of the special components, or that the component
1990 // names must come from the same set.
Mike Stumpeed9cac2009-02-19 03:04:26 +00001991 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begeman353417a2009-01-18 01:47:54 +00001992 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
1993 HalvingSwizzle = true;
Nate Begeman8a997642008-05-09 06:41:27 +00001994 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner88dca042007-08-02 22:33:49 +00001995 do
1996 compStr++;
1997 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
Nate Begeman353417a2009-01-18 01:47:54 +00001998 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
Chris Lattner88dca042007-08-02 22:33:49 +00001999 do
2000 compStr++;
Nate Begeman353417a2009-01-18 01:47:54 +00002001 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
Chris Lattner88dca042007-08-02 22:33:49 +00002002 }
Nate Begeman353417a2009-01-18 01:47:54 +00002003
Mike Stumpeed9cac2009-02-19 03:04:26 +00002004 if (!HalvingSwizzle && *compStr) {
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002005 // We didn't get to the end of the string. This means the component names
2006 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002007 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
2008 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002009 return QualType();
2010 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00002011
Nate Begeman353417a2009-01-18 01:47:54 +00002012 // Ensure no component accessor exceeds the width of the vector type it
2013 // operates on.
2014 if (!HalvingSwizzle) {
Daniel Dunbare013d682009-10-18 20:26:12 +00002015 compStr = CompName->getNameStart();
Nate Begeman353417a2009-01-18 01:47:54 +00002016
2017 if (HexSwizzle)
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002018 compStr++;
Nate Begeman353417a2009-01-18 01:47:54 +00002019
2020 while (*compStr) {
2021 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
2022 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
2023 << baseType << SourceRange(CompLoc);
2024 return QualType();
2025 }
2026 }
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002027 }
Nate Begeman8a997642008-05-09 06:41:27 +00002028
Nate Begeman353417a2009-01-18 01:47:54 +00002029 // If this is a halving swizzle, verify that the base type has an even
2030 // number of elements.
2031 if (HalvingSwizzle && (vecType->getNumElements() & 1U)) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002032 Diag(OpLoc, diag::err_ext_vector_component_requires_even)
Chris Lattnerd1625842008-11-24 06:25:27 +00002033 << baseType << SourceRange(CompLoc);
Nate Begeman8a997642008-05-09 06:41:27 +00002034 return QualType();
2035 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00002036
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002037 // The component accessor looks fine - now we need to compute the actual type.
Mike Stumpeed9cac2009-02-19 03:04:26 +00002038 // The vector type is implied by the component accessor. For example,
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002039 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman353417a2009-01-18 01:47:54 +00002040 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begeman8a997642008-05-09 06:41:27 +00002041 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begeman353417a2009-01-18 01:47:54 +00002042 unsigned CompSize = HalvingSwizzle ? vecType->getNumElements() / 2
Anders Carlsson8f28f992009-08-26 18:25:21 +00002043 : CompName->getLength();
Nate Begeman353417a2009-01-18 01:47:54 +00002044 if (HexSwizzle)
2045 CompSize--;
2046
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002047 if (CompSize == 1)
2048 return vecType->getElementType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00002049
Nate Begeman213541a2008-04-18 23:10:10 +00002050 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stumpeed9cac2009-02-19 03:04:26 +00002051 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begeman213541a2008-04-18 23:10:10 +00002052 // diagostics look bad. We want extended vector types to appear built-in.
2053 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
2054 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
2055 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroffbea0b342007-07-29 16:33:31 +00002056 }
2057 return VT; // should never get here (a typedef type should always be found).
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002058}
2059
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002060static Decl *FindGetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
Anders Carlsson8f28f992009-08-26 18:25:21 +00002061 IdentifierInfo *Member,
Douglas Gregor6ab35242009-04-09 21:40:53 +00002062 const Selector &Sel,
2063 ASTContext &Context) {
Mike Stump1eb44332009-09-09 15:08:12 +00002064
Anders Carlsson8f28f992009-08-26 18:25:21 +00002065 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002066 return PD;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002067 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002068 return OMD;
Mike Stump1eb44332009-09-09 15:08:12 +00002069
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002070 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
2071 E = PDecl->protocol_end(); I != E; ++I) {
Mike Stump1eb44332009-09-09 15:08:12 +00002072 if (Decl *D = FindGetterNameDeclFromProtocolList(*I, Member, Sel,
Douglas Gregor6ab35242009-04-09 21:40:53 +00002073 Context))
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002074 return D;
2075 }
2076 return 0;
2077}
2078
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002079static Decl *FindGetterNameDecl(const ObjCObjectPointerType *QIdTy,
Anders Carlsson8f28f992009-08-26 18:25:21 +00002080 IdentifierInfo *Member,
Douglas Gregor6ab35242009-04-09 21:40:53 +00002081 const Selector &Sel,
2082 ASTContext &Context) {
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002083 // Check protocols on qualified interfaces.
2084 Decl *GDecl = 0;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002085 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002086 E = QIdTy->qual_end(); I != E; ++I) {
Anders Carlsson8f28f992009-08-26 18:25:21 +00002087 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002088 GDecl = PD;
2089 break;
2090 }
2091 // Also must look for a getter name which uses property syntax.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002092 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002093 GDecl = OMD;
2094 break;
2095 }
2096 }
2097 if (!GDecl) {
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002098 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002099 E = QIdTy->qual_end(); I != E; ++I) {
2100 // Search in the protocol-qualifier list of current protocol.
Douglas Gregor6ab35242009-04-09 21:40:53 +00002101 GDecl = FindGetterNameDeclFromProtocolList(*I, Member, Sel, Context);
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002102 if (GDecl)
2103 return GDecl;
2104 }
2105 }
2106 return GDecl;
2107}
Chris Lattner76a642f2009-02-15 22:43:40 +00002108
John McCall129e2df2009-11-30 22:42:35 +00002109Sema::OwningExprResult
John McCallaa81e162009-12-01 22:10:20 +00002110Sema::ActOnDependentMemberExpr(ExprArg Base, QualType BaseType,
2111 bool IsArrow, SourceLocation OpLoc,
John McCall129e2df2009-11-30 22:42:35 +00002112 const CXXScopeSpec &SS,
2113 NamedDecl *FirstQualifierInScope,
2114 DeclarationName Name, SourceLocation NameLoc,
2115 const TemplateArgumentListInfo *TemplateArgs) {
2116 Expr *BaseExpr = Base.takeAs<Expr>();
2117
2118 // Even in dependent contexts, try to diagnose base expressions with
2119 // obviously wrong types, e.g.:
2120 //
2121 // T* t;
2122 // t.f;
2123 //
2124 // In Obj-C++, however, the above expression is valid, since it could be
2125 // accessing the 'f' property if T is an Obj-C interface. The extra check
2126 // allows this, while still reporting an error if T is a struct pointer.
2127 if (!IsArrow) {
John McCallaa81e162009-12-01 22:10:20 +00002128 const PointerType *PT = BaseType->getAs<PointerType>();
John McCall129e2df2009-11-30 22:42:35 +00002129 if (PT && (!getLangOptions().ObjC1 ||
2130 PT->getPointeeType()->isRecordType())) {
John McCallaa81e162009-12-01 22:10:20 +00002131 assert(BaseExpr && "cannot happen with implicit member accesses");
John McCall129e2df2009-11-30 22:42:35 +00002132 Diag(NameLoc, diag::err_typecheck_member_reference_struct_union)
John McCallaa81e162009-12-01 22:10:20 +00002133 << BaseType << BaseExpr->getSourceRange();
John McCall129e2df2009-11-30 22:42:35 +00002134 return ExprError();
2135 }
2136 }
2137
John McCallaa81e162009-12-01 22:10:20 +00002138 assert(BaseType->isDependentType());
John McCall129e2df2009-11-30 22:42:35 +00002139
2140 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
2141 // must have pointer type, and the accessed type is the pointee.
John McCallaa81e162009-12-01 22:10:20 +00002142 return Owned(CXXDependentScopeMemberExpr::Create(Context, BaseExpr, BaseType,
John McCall129e2df2009-11-30 22:42:35 +00002143 IsArrow, OpLoc,
2144 static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
2145 SS.getRange(),
2146 FirstQualifierInScope,
2147 Name, NameLoc,
2148 TemplateArgs));
2149}
2150
2151/// We know that the given qualified member reference points only to
2152/// declarations which do not belong to the static type of the base
2153/// expression. Diagnose the problem.
2154static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
2155 Expr *BaseExpr,
2156 QualType BaseType,
John McCall2f841ba2009-12-02 03:53:29 +00002157 const CXXScopeSpec &SS,
John McCall129e2df2009-11-30 22:42:35 +00002158 const LookupResult &R) {
John McCall2f841ba2009-12-02 03:53:29 +00002159 // If this is an implicit member access, use a different set of
2160 // diagnostics.
2161 if (!BaseExpr)
2162 return DiagnoseInstanceReference(SemaRef, SS, R);
John McCall129e2df2009-11-30 22:42:35 +00002163
2164 // FIXME: this is an exceedingly lame diagnostic for some of the more
2165 // complicated cases here.
John McCall2f841ba2009-12-02 03:53:29 +00002166 DeclContext *DC = R.getRepresentativeDecl()->getDeclContext();
John McCall129e2df2009-11-30 22:42:35 +00002167 SemaRef.Diag(R.getNameLoc(), diag::err_not_direct_base_or_virtual)
John McCall2f841ba2009-12-02 03:53:29 +00002168 << SS.getRange() << DC << BaseType;
John McCall129e2df2009-11-30 22:42:35 +00002169}
2170
2171// Check whether the declarations we found through a nested-name
2172// specifier in a member expression are actually members of the base
2173// type. The restriction here is:
2174//
2175// C++ [expr.ref]p2:
2176// ... In these cases, the id-expression shall name a
2177// member of the class or of one of its base classes.
2178//
2179// So it's perfectly legitimate for the nested-name specifier to name
2180// an unrelated class, and for us to find an overload set including
2181// decls from classes which are not superclasses, as long as the decl
2182// we actually pick through overload resolution is from a superclass.
2183bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
2184 QualType BaseType,
John McCall2f841ba2009-12-02 03:53:29 +00002185 const CXXScopeSpec &SS,
John McCall129e2df2009-11-30 22:42:35 +00002186 const LookupResult &R) {
John McCallaa81e162009-12-01 22:10:20 +00002187 const RecordType *BaseRT = BaseType->getAs<RecordType>();
2188 if (!BaseRT) {
2189 // We can't check this yet because the base type is still
2190 // dependent.
2191 assert(BaseType->isDependentType());
2192 return false;
2193 }
2194 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall129e2df2009-11-30 22:42:35 +00002195
2196 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
John McCallaa81e162009-12-01 22:10:20 +00002197 // If this is an implicit member reference and we find a
2198 // non-instance member, it's not an error.
2199 if (!BaseExpr && !IsInstanceMember((*I)->getUnderlyingDecl()))
2200 return false;
John McCall129e2df2009-11-30 22:42:35 +00002201
John McCallaa81e162009-12-01 22:10:20 +00002202 // Note that we use the DC of the decl, not the underlying decl.
2203 CXXRecordDecl *RecordD = cast<CXXRecordDecl>((*I)->getDeclContext());
2204 while (RecordD->isAnonymousStructOrUnion())
2205 RecordD = cast<CXXRecordDecl>(RecordD->getParent());
2206
2207 llvm::SmallPtrSet<CXXRecordDecl*,4> MemberRecord;
2208 MemberRecord.insert(RecordD->getCanonicalDecl());
2209
2210 if (!IsProvablyNotDerivedFrom(*this, BaseRecord, MemberRecord))
2211 return false;
2212 }
2213
John McCall2f841ba2009-12-02 03:53:29 +00002214 DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS, R);
John McCallaa81e162009-12-01 22:10:20 +00002215 return true;
2216}
2217
2218static bool
2219LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
2220 SourceRange BaseRange, const RecordType *RTy,
2221 SourceLocation OpLoc, const CXXScopeSpec &SS) {
2222 RecordDecl *RDecl = RTy->getDecl();
2223 if (SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
2224 PDiag(diag::err_typecheck_incomplete_tag)
2225 << BaseRange))
2226 return true;
2227
2228 DeclContext *DC = RDecl;
2229 if (SS.isSet()) {
2230 // If the member name was a qualified-id, look into the
2231 // nested-name-specifier.
2232 DC = SemaRef.computeDeclContext(SS, false);
2233
John McCall2f841ba2009-12-02 03:53:29 +00002234 if (SemaRef.RequireCompleteDeclContext(SS)) {
2235 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
2236 << SS.getRange() << DC;
2237 return true;
2238 }
2239
John McCallaa81e162009-12-01 22:10:20 +00002240 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
2241
2242 if (!isa<TypeDecl>(DC)) {
2243 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
2244 << DC << SS.getRange();
2245 return true;
John McCall129e2df2009-11-30 22:42:35 +00002246 }
2247 }
2248
John McCallaa81e162009-12-01 22:10:20 +00002249 // The record definition is complete, now look up the member.
2250 SemaRef.LookupQualifiedName(R, DC);
John McCall129e2df2009-11-30 22:42:35 +00002251
2252 return false;
2253}
2254
2255Sema::OwningExprResult
John McCallaa81e162009-12-01 22:10:20 +00002256Sema::BuildMemberReferenceExpr(ExprArg BaseArg, QualType BaseType,
John McCall129e2df2009-11-30 22:42:35 +00002257 SourceLocation OpLoc, bool IsArrow,
2258 const CXXScopeSpec &SS,
2259 NamedDecl *FirstQualifierInScope,
2260 DeclarationName Name, SourceLocation NameLoc,
2261 const TemplateArgumentListInfo *TemplateArgs) {
2262 Expr *Base = BaseArg.takeAs<Expr>();
2263
John McCall2f841ba2009-12-02 03:53:29 +00002264 if (BaseType->isDependentType() ||
2265 (SS.isSet() && isDependentScopeSpecifier(SS)))
John McCallaa81e162009-12-01 22:10:20 +00002266 return ActOnDependentMemberExpr(ExprArg(*this, Base), BaseType,
John McCall129e2df2009-11-30 22:42:35 +00002267 IsArrow, OpLoc,
2268 SS, FirstQualifierInScope,
2269 Name, NameLoc,
2270 TemplateArgs);
2271
2272 LookupResult R(*this, Name, NameLoc, LookupMemberName);
John McCall129e2df2009-11-30 22:42:35 +00002273
John McCallaa81e162009-12-01 22:10:20 +00002274 // Implicit member accesses.
2275 if (!Base) {
2276 QualType RecordTy = BaseType;
2277 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
2278 if (LookupMemberExprInRecord(*this, R, SourceRange(),
2279 RecordTy->getAs<RecordType>(),
2280 OpLoc, SS))
2281 return ExprError();
2282
2283 // Explicit member accesses.
2284 } else {
2285 OwningExprResult Result =
2286 LookupMemberExpr(R, Base, IsArrow, OpLoc,
2287 SS, FirstQualifierInScope,
2288 /*ObjCImpDecl*/ DeclPtrTy());
2289
2290 if (Result.isInvalid()) {
2291 Owned(Base);
2292 return ExprError();
2293 }
2294
2295 if (Result.get())
2296 return move(Result);
John McCall129e2df2009-11-30 22:42:35 +00002297 }
2298
John McCallaa81e162009-12-01 22:10:20 +00002299 return BuildMemberReferenceExpr(ExprArg(*this, Base), BaseType,
2300 OpLoc, IsArrow, SS, R, TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00002301}
2302
2303Sema::OwningExprResult
John McCallaa81e162009-12-01 22:10:20 +00002304Sema::BuildMemberReferenceExpr(ExprArg Base, QualType BaseExprType,
2305 SourceLocation OpLoc, bool IsArrow,
2306 const CXXScopeSpec &SS,
John McCall129e2df2009-11-30 22:42:35 +00002307 LookupResult &R,
2308 const TemplateArgumentListInfo *TemplateArgs) {
2309 Expr *BaseExpr = Base.takeAs<Expr>();
John McCallaa81e162009-12-01 22:10:20 +00002310 QualType BaseType = BaseExprType;
John McCall129e2df2009-11-30 22:42:35 +00002311 if (IsArrow) {
2312 assert(BaseType->isPointerType());
2313 BaseType = BaseType->getAs<PointerType>()->getPointeeType();
2314 }
2315
2316 NestedNameSpecifier *Qualifier =
2317 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
2318 DeclarationName MemberName = R.getLookupName();
2319 SourceLocation MemberLoc = R.getNameLoc();
2320
2321 if (R.isAmbiguous())
Douglas Gregorfe85ced2009-08-06 03:17:00 +00002322 return ExprError();
2323
John McCall129e2df2009-11-30 22:42:35 +00002324 if (R.empty()) {
2325 // Rederive where we looked up.
2326 DeclContext *DC = (SS.isSet()
2327 ? computeDeclContext(SS, false)
2328 : BaseType->getAs<RecordType>()->getDecl());
Nate Begeman2ef13e52009-08-10 23:49:36 +00002329
John McCall129e2df2009-11-30 22:42:35 +00002330 Diag(R.getNameLoc(), diag::err_no_member)
John McCallaa81e162009-12-01 22:10:20 +00002331 << MemberName << DC
2332 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
John McCall129e2df2009-11-30 22:42:35 +00002333 return ExprError();
2334 }
2335
John McCall2f841ba2009-12-02 03:53:29 +00002336 // Diagnose qualified lookups that find only declarations from a
2337 // non-base type. Note that it's okay for lookup to find
2338 // declarations from a non-base type as long as those aren't the
2339 // ones picked by overload resolution.
2340 if (SS.isSet() && CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
John McCall129e2df2009-11-30 22:42:35 +00002341 return ExprError();
2342
2343 // Construct an unresolved result if we in fact got an unresolved
2344 // result.
2345 if (R.isOverloadedResult() || R.isUnresolvableResult()) {
John McCallaa81e162009-12-01 22:10:20 +00002346 bool Dependent =
2347 R.isUnresolvableResult() ||
2348 UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(), TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00002349
2350 UnresolvedMemberExpr *MemExpr
2351 = UnresolvedMemberExpr::Create(Context, Dependent,
2352 R.isUnresolvableResult(),
John McCallaa81e162009-12-01 22:10:20 +00002353 BaseExpr, BaseExprType,
2354 IsArrow, OpLoc,
John McCall129e2df2009-11-30 22:42:35 +00002355 Qualifier, SS.getRange(),
2356 MemberName, MemberLoc,
2357 TemplateArgs);
2358 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
2359 MemExpr->addDecl(*I);
2360
2361 return Owned(MemExpr);
2362 }
2363
2364 assert(R.isSingleResult());
2365 NamedDecl *MemberDecl = R.getFoundDecl();
2366
2367 // FIXME: diagnose the presence of template arguments now.
2368
2369 // If the decl being referenced had an error, return an error for this
2370 // sub-expr without emitting another error, in order to avoid cascading
2371 // error cases.
2372 if (MemberDecl->isInvalidDecl())
2373 return ExprError();
2374
John McCallaa81e162009-12-01 22:10:20 +00002375 // Handle the implicit-member-access case.
2376 if (!BaseExpr) {
2377 // If this is not an instance member, convert to a non-member access.
2378 if (!IsInstanceMember(MemberDecl))
2379 return BuildDeclarationNameExpr(SS, R.getNameLoc(), MemberDecl);
2380
2381 BaseExpr = new (Context) CXXThisExpr(SourceLocation(), BaseExprType);
2382 }
2383
John McCall129e2df2009-11-30 22:42:35 +00002384 bool ShouldCheckUse = true;
2385 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
2386 // Don't diagnose the use of a virtual member function unless it's
2387 // explicitly qualified.
2388 if (MD->isVirtual() && !SS.isSet())
2389 ShouldCheckUse = false;
2390 }
2391
2392 // Check the use of this member.
2393 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc)) {
2394 Owned(BaseExpr);
2395 return ExprError();
2396 }
2397
2398 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
2399 // We may have found a field within an anonymous union or struct
2400 // (C++ [class.union]).
Eli Friedman16c53782009-12-04 07:18:51 +00002401 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion() &&
2402 !BaseType->getAs<RecordType>()->getDecl()->isAnonymousStructOrUnion())
John McCall129e2df2009-11-30 22:42:35 +00002403 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
2404 BaseExpr, OpLoc);
2405
2406 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
2407 QualType MemberType = FD->getType();
2408 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>())
2409 MemberType = Ref->getPointeeType();
2410 else {
2411 Qualifiers BaseQuals = BaseType.getQualifiers();
2412 BaseQuals.removeObjCGCAttr();
2413 if (FD->isMutable()) BaseQuals.removeConst();
2414
2415 Qualifiers MemberQuals
2416 = Context.getCanonicalType(MemberType).getQualifiers();
2417
2418 Qualifiers Combined = BaseQuals + MemberQuals;
2419 if (Combined != MemberQuals)
2420 MemberType = Context.getQualifiedType(MemberType, Combined);
2421 }
2422
2423 MarkDeclarationReferenced(MemberLoc, FD);
2424 if (PerformObjectMemberConversion(BaseExpr, FD))
2425 return ExprError();
2426 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
2427 FD, MemberLoc, MemberType));
2428 }
2429
2430 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
2431 MarkDeclarationReferenced(MemberLoc, Var);
2432 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
2433 Var, MemberLoc,
2434 Var->getType().getNonReferenceType()));
2435 }
2436
2437 if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl)) {
2438 MarkDeclarationReferenced(MemberLoc, MemberDecl);
2439 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
2440 MemberFn, MemberLoc,
2441 MemberFn->getType()));
2442 }
2443
2444 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
2445 MarkDeclarationReferenced(MemberLoc, MemberDecl);
2446 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
2447 Enum, MemberLoc, Enum->getType()));
2448 }
2449
2450 Owned(BaseExpr);
2451
2452 if (isa<TypeDecl>(MemberDecl))
2453 return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
2454 << MemberName << int(IsArrow));
2455
2456 // We found a declaration kind that we didn't expect. This is a
2457 // generic error message that tells the user that she can't refer
2458 // to this member with '.' or '->'.
2459 return ExprError(Diag(MemberLoc,
2460 diag::err_typecheck_member_reference_unknown)
2461 << MemberName << int(IsArrow));
2462}
2463
2464/// Look up the given member of the given non-type-dependent
2465/// expression. This can return in one of two ways:
2466/// * If it returns a sentinel null-but-valid result, the caller will
2467/// assume that lookup was performed and the results written into
2468/// the provided structure. It will take over from there.
2469/// * Otherwise, the returned expression will be produced in place of
2470/// an ordinary member expression.
2471///
2472/// The ObjCImpDecl bit is a gross hack that will need to be properly
2473/// fixed for ObjC++.
2474Sema::OwningExprResult
2475Sema::LookupMemberExpr(LookupResult &R, Expr *&BaseExpr,
2476 bool IsArrow, SourceLocation OpLoc,
2477 const CXXScopeSpec &SS,
2478 NamedDecl *FirstQualifierInScope,
2479 DeclPtrTy ObjCImpDecl) {
Douglas Gregora71d8192009-09-04 17:36:40 +00002480 assert(BaseExpr && "no base expression");
Mike Stump1eb44332009-09-09 15:08:12 +00002481
Steve Naroff3cc4af82007-12-16 21:42:28 +00002482 // Perform default conversions.
2483 DefaultFunctionArrayConversion(BaseExpr);
Sebastian Redl0eb23302009-01-19 00:08:26 +00002484
Steve Naroffdfa6aae2007-07-26 03:11:44 +00002485 QualType BaseType = BaseExpr->getType();
John McCall129e2df2009-11-30 22:42:35 +00002486 assert(!BaseType->isDependentType());
2487
2488 DeclarationName MemberName = R.getLookupName();
2489 SourceLocation MemberLoc = R.getNameLoc();
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00002490
2491 // If the user is trying to apply -> or . to a function pointer
John McCall129e2df2009-11-30 22:42:35 +00002492 // type, it's probably because they forgot parentheses to call that
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00002493 // function. Suggest the addition of those parentheses, build the
2494 // call, and continue on.
2495 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
2496 if (const FunctionProtoType *Fun
2497 = Ptr->getPointeeType()->getAs<FunctionProtoType>()) {
2498 QualType ResultTy = Fun->getResultType();
2499 if (Fun->getNumArgs() == 0 &&
John McCall129e2df2009-11-30 22:42:35 +00002500 ((!IsArrow && ResultTy->isRecordType()) ||
2501 (IsArrow && ResultTy->isPointerType() &&
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00002502 ResultTy->getAs<PointerType>()->getPointeeType()
2503 ->isRecordType()))) {
2504 SourceLocation Loc = PP.getLocForEndOfToken(BaseExpr->getLocEnd());
2505 Diag(Loc, diag::err_member_reference_needs_call)
2506 << QualType(Fun, 0)
2507 << CodeModificationHint::CreateInsertion(Loc, "()");
2508
2509 OwningExprResult NewBase
John McCall129e2df2009-11-30 22:42:35 +00002510 = ActOnCallExpr(0, ExprArg(*this, BaseExpr), Loc,
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00002511 MultiExprArg(*this, 0, 0), 0, Loc);
2512 if (NewBase.isInvalid())
John McCall129e2df2009-11-30 22:42:35 +00002513 return ExprError();
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00002514
2515 BaseExpr = NewBase.takeAs<Expr>();
2516 DefaultFunctionArrayConversion(BaseExpr);
2517 BaseType = BaseExpr->getType();
2518 }
2519 }
2520 }
2521
David Chisnall0f436562009-08-17 16:35:33 +00002522 // If this is an Objective-C pseudo-builtin and a definition is provided then
2523 // use that.
2524 if (BaseType->isObjCIdType()) {
2525 // We have an 'id' type. Rather than fall through, we check if this
2526 // is a reference to 'isa'.
2527 if (BaseType != Context.ObjCIdRedefinitionType) {
2528 BaseType = Context.ObjCIdRedefinitionType;
Eli Friedman73c39ab2009-10-20 08:27:19 +00002529 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
David Chisnall0f436562009-08-17 16:35:33 +00002530 }
David Chisnall0f436562009-08-17 16:35:33 +00002531 }
John McCall129e2df2009-11-30 22:42:35 +00002532
Fariborz Jahanian369a3bd2009-11-25 23:07:42 +00002533 // If this is an Objective-C pseudo-builtin and a definition is provided then
2534 // use that.
2535 if (Context.isObjCSelType(BaseType)) {
2536 // We have an 'SEL' type. Rather than fall through, we check if this
2537 // is a reference to 'sel_id'.
2538 if (BaseType != Context.ObjCSelRedefinitionType) {
2539 BaseType = Context.ObjCSelRedefinitionType;
2540 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
2541 }
2542 }
John McCall129e2df2009-11-30 22:42:35 +00002543
Steve Naroffdfa6aae2007-07-26 03:11:44 +00002544 assert(!BaseType.isNull() && "no type for member expression");
Sebastian Redl0eb23302009-01-19 00:08:26 +00002545
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00002546 // Handle properties on ObjC 'Class' types.
John McCall129e2df2009-11-30 22:42:35 +00002547 if (!IsArrow && BaseType->isObjCClassType()) {
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00002548 // Also must look for a getter name which uses property syntax.
2549 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
2550 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
2551 if (ObjCMethodDecl *MD = getCurMethodDecl()) {
2552 ObjCInterfaceDecl *IFace = MD->getClassInterface();
2553 ObjCMethodDecl *Getter;
2554 // FIXME: need to also look locally in the implementation.
2555 if ((Getter = IFace->lookupClassMethod(Sel))) {
2556 // Check the use of this method.
2557 if (DiagnoseUseOfDecl(Getter, MemberLoc))
2558 return ExprError();
2559 }
2560 // If we found a getter then this may be a valid dot-reference, we
2561 // will look for the matching setter, in case it is needed.
2562 Selector SetterSel =
2563 SelectorTable::constructSetterName(PP.getIdentifierTable(),
2564 PP.getSelectorTable(), Member);
2565 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
2566 if (!Setter) {
2567 // If this reference is in an @implementation, also check for 'private'
2568 // methods.
Steve Naroffd789d3d2009-10-01 23:46:04 +00002569 Setter = IFace->lookupPrivateInstanceMethod(SetterSel);
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00002570 }
2571 // Look through local category implementations associated with the class.
2572 if (!Setter)
2573 Setter = IFace->getCategoryClassMethod(SetterSel);
2574
2575 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2576 return ExprError();
2577
2578 if (Getter || Setter) {
2579 QualType PType;
2580
2581 if (Getter)
2582 PType = Getter->getResultType();
2583 else
2584 // Get the expression type from Setter's incoming parameter.
2585 PType = (*(Setter->param_end() -1))->getType();
2586 // FIXME: we must check that the setter has property type.
2587 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter,
2588 PType,
2589 Setter, MemberLoc, BaseExpr));
2590 }
2591 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
2592 << MemberName << BaseType);
2593 }
2594 }
2595
2596 if (BaseType->isObjCClassType() &&
2597 BaseType != Context.ObjCClassRedefinitionType) {
2598 BaseType = Context.ObjCClassRedefinitionType;
Eli Friedman73c39ab2009-10-20 08:27:19 +00002599 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00002600 }
Mike Stump1eb44332009-09-09 15:08:12 +00002601
John McCall129e2df2009-11-30 22:42:35 +00002602 if (IsArrow) {
2603 if (const PointerType *PT = BaseType->getAs<PointerType>())
Steve Naroffdfa6aae2007-07-26 03:11:44 +00002604 BaseType = PT->getPointeeType();
Steve Naroff14108da2009-07-10 23:34:53 +00002605 else if (BaseType->isObjCObjectPointerType())
2606 ;
John McCall129e2df2009-11-30 22:42:35 +00002607 else {
2608 Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
2609 << BaseType << BaseExpr->getSourceRange();
2610 return ExprError();
Anders Carlsson4ef27702009-05-16 20:31:20 +00002611 }
John McCall129e2df2009-11-30 22:42:35 +00002612 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002613
John McCall129e2df2009-11-30 22:42:35 +00002614 // Handle field access to simple records. This also handles access
2615 // to fields of the ObjC 'id' struct.
Ted Kremenek6217b802009-07-29 21:53:49 +00002616 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
John McCallaa81e162009-12-01 22:10:20 +00002617 if (LookupMemberExprInRecord(*this, R, BaseExpr->getSourceRange(),
2618 RTy, OpLoc, SS))
Douglas Gregor4ec339f2009-01-19 19:26:10 +00002619 return ExprError();
John McCall129e2df2009-11-30 22:42:35 +00002620 return Owned((Expr*) 0);
Chris Lattnerfb173ec2008-07-21 04:28:12 +00002621 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002622
Douglas Gregora71d8192009-09-04 17:36:40 +00002623 // Handle pseudo-destructors (C++ [expr.pseudo]). Since anything referring
2624 // into a record type was handled above, any destructor we see here is a
2625 // pseudo-destructor.
2626 if (MemberName.getNameKind() == DeclarationName::CXXDestructorName) {
2627 // C++ [expr.pseudo]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00002628 // The left hand side of the dot operator shall be of scalar type. The
2629 // left hand side of the arrow operator shall be of pointer to scalar
Douglas Gregora71d8192009-09-04 17:36:40 +00002630 // type.
2631 if (!BaseType->isScalarType())
2632 return Owned(Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
2633 << BaseType << BaseExpr->getSourceRange());
Mike Stump1eb44332009-09-09 15:08:12 +00002634
Douglas Gregora71d8192009-09-04 17:36:40 +00002635 // [...] The type designated by the pseudo-destructor-name shall be the
2636 // same as the object type.
2637 if (!MemberName.getCXXNameType()->isDependentType() &&
2638 !Context.hasSameUnqualifiedType(BaseType, MemberName.getCXXNameType()))
2639 return Owned(Diag(OpLoc, diag::err_pseudo_dtor_type_mismatch)
2640 << BaseType << MemberName.getCXXNameType()
2641 << BaseExpr->getSourceRange() << SourceRange(MemberLoc));
Mike Stump1eb44332009-09-09 15:08:12 +00002642
2643 // [...] Furthermore, the two type-names in a pseudo-destructor-name of
Douglas Gregora71d8192009-09-04 17:36:40 +00002644 // the form
2645 //
Mike Stump1eb44332009-09-09 15:08:12 +00002646 // ::[opt] nested-name-specifier[opt] type-name :: ̃ type-name
2647 //
Douglas Gregora71d8192009-09-04 17:36:40 +00002648 // shall designate the same scalar type.
2649 //
2650 // FIXME: DPG can't see any way to trigger this particular clause, so it
2651 // isn't checked here.
Mike Stump1eb44332009-09-09 15:08:12 +00002652
Douglas Gregora71d8192009-09-04 17:36:40 +00002653 // FIXME: We've lost the precise spelling of the type by going through
2654 // DeclarationName. Can we do better?
2655 return Owned(new (Context) CXXPseudoDestructorExpr(Context, BaseExpr,
John McCall129e2df2009-11-30 22:42:35 +00002656 IsArrow, OpLoc,
2657 (NestedNameSpecifier *) SS.getScopeRep(),
2658 SS.getRange(),
Douglas Gregora71d8192009-09-04 17:36:40 +00002659 MemberName.getCXXNameType(),
2660 MemberLoc));
2661 }
Mike Stump1eb44332009-09-09 15:08:12 +00002662
Chris Lattnera38e6b12008-07-21 04:59:05 +00002663 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
2664 // (*Obj).ivar.
John McCall129e2df2009-11-30 22:42:35 +00002665 if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
2666 (!IsArrow && BaseType->isObjCInterfaceType())) {
John McCall183700f2009-09-21 23:43:11 +00002667 const ObjCObjectPointerType *OPT = BaseType->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00002668 const ObjCInterfaceType *IFaceT =
John McCall183700f2009-09-21 23:43:11 +00002669 OPT ? OPT->getInterfaceType() : BaseType->getAs<ObjCInterfaceType>();
Steve Naroffc70e8d92009-07-16 00:25:06 +00002670 if (IFaceT) {
Anders Carlsson8f28f992009-08-26 18:25:21 +00002671 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
2672
Steve Naroffc70e8d92009-07-16 00:25:06 +00002673 ObjCInterfaceDecl *IDecl = IFaceT->getDecl();
2674 ObjCInterfaceDecl *ClassDeclared;
Anders Carlsson8f28f992009-08-26 18:25:21 +00002675 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
Mike Stump1eb44332009-09-09 15:08:12 +00002676
Steve Naroffc70e8d92009-07-16 00:25:06 +00002677 if (IV) {
2678 // If the decl being referenced had an error, return an error for this
2679 // sub-expr without emitting another error, in order to avoid cascading
2680 // error cases.
2681 if (IV->isInvalidDecl())
2682 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002683
Steve Naroffc70e8d92009-07-16 00:25:06 +00002684 // Check whether we can reference this field.
2685 if (DiagnoseUseOfDecl(IV, MemberLoc))
2686 return ExprError();
2687 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
2688 IV->getAccessControl() != ObjCIvarDecl::Package) {
2689 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
2690 if (ObjCMethodDecl *MD = getCurMethodDecl())
2691 ClassOfMethodDecl = MD->getClassInterface();
2692 else if (ObjCImpDecl && getCurFunctionDecl()) {
2693 // Case of a c-function declared inside an objc implementation.
2694 // FIXME: For a c-style function nested inside an objc implementation
2695 // class, there is no implementation context available, so we pass
2696 // down the context as argument to this routine. Ideally, this context
2697 // need be passed down in the AST node and somehow calculated from the
2698 // AST for a function decl.
2699 Decl *ImplDecl = ObjCImpDecl.getAs<Decl>();
Mike Stump1eb44332009-09-09 15:08:12 +00002700 if (ObjCImplementationDecl *IMPD =
Steve Naroffc70e8d92009-07-16 00:25:06 +00002701 dyn_cast<ObjCImplementationDecl>(ImplDecl))
2702 ClassOfMethodDecl = IMPD->getClassInterface();
2703 else if (ObjCCategoryImplDecl* CatImplClass =
2704 dyn_cast<ObjCCategoryImplDecl>(ImplDecl))
2705 ClassOfMethodDecl = CatImplClass->getClassInterface();
2706 }
Mike Stump1eb44332009-09-09 15:08:12 +00002707
2708 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
2709 if (ClassDeclared != IDecl ||
Steve Naroffc70e8d92009-07-16 00:25:06 +00002710 ClassOfMethodDecl != ClassDeclared)
Mike Stump1eb44332009-09-09 15:08:12 +00002711 Diag(MemberLoc, diag::error_private_ivar_access)
Steve Naroffc70e8d92009-07-16 00:25:06 +00002712 << IV->getDeclName();
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002713 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
2714 // @protected
Mike Stump1eb44332009-09-09 15:08:12 +00002715 Diag(MemberLoc, diag::error_protected_ivar_access)
Steve Naroffc70e8d92009-07-16 00:25:06 +00002716 << IV->getDeclName();
Steve Naroffb06d8752009-03-04 18:34:24 +00002717 }
Steve Naroffc70e8d92009-07-16 00:25:06 +00002718
2719 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
2720 MemberLoc, BaseExpr,
John McCall129e2df2009-11-30 22:42:35 +00002721 IsArrow));
Fariborz Jahanian935fd762009-03-03 01:21:12 +00002722 }
Steve Naroffc70e8d92009-07-16 00:25:06 +00002723 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
Anders Carlsson8f28f992009-08-26 18:25:21 +00002724 << IDecl->getDeclName() << MemberName
Steve Naroffc70e8d92009-07-16 00:25:06 +00002725 << BaseExpr->getSourceRange());
Fariborz Jahanianaaa63a72008-12-13 22:20:28 +00002726 }
Chris Lattnerfb173ec2008-07-21 04:28:12 +00002727 }
Steve Naroffde2e22d2009-07-15 18:40:39 +00002728 // Handle properties on 'id' and qualified "id".
John McCall129e2df2009-11-30 22:42:35 +00002729 if (!IsArrow && (BaseType->isObjCIdType() ||
2730 BaseType->isObjCQualifiedIdType())) {
John McCall183700f2009-09-21 23:43:11 +00002731 const ObjCObjectPointerType *QIdTy = BaseType->getAs<ObjCObjectPointerType>();
Anders Carlsson8f28f992009-08-26 18:25:21 +00002732 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Mike Stump1eb44332009-09-09 15:08:12 +00002733
Steve Naroff14108da2009-07-10 23:34:53 +00002734 // Check protocols on qualified interfaces.
Anders Carlsson8f28f992009-08-26 18:25:21 +00002735 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Steve Naroff14108da2009-07-10 23:34:53 +00002736 if (Decl *PMDecl = FindGetterNameDecl(QIdTy, Member, Sel, Context)) {
2737 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
2738 // Check the use of this declaration
2739 if (DiagnoseUseOfDecl(PD, MemberLoc))
2740 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00002741
Steve Naroff14108da2009-07-10 23:34:53 +00002742 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
2743 MemberLoc, BaseExpr));
2744 }
2745 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
2746 // Check the use of this method.
2747 if (DiagnoseUseOfDecl(OMD, MemberLoc))
2748 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00002749
Steve Naroff14108da2009-07-10 23:34:53 +00002750 return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel,
Mike Stump1eb44332009-09-09 15:08:12 +00002751 OMD->getResultType(),
2752 OMD, OpLoc, MemberLoc,
Steve Naroff14108da2009-07-10 23:34:53 +00002753 NULL, 0));
2754 }
2755 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002756
Steve Naroff14108da2009-07-10 23:34:53 +00002757 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlsson8f28f992009-08-26 18:25:21 +00002758 << MemberName << BaseType);
Steve Naroff14108da2009-07-10 23:34:53 +00002759 }
Chris Lattnera38e6b12008-07-21 04:59:05 +00002760 // Handle Objective-C property access, which is "Obj.property" where Obj is a
2761 // pointer to a (potentially qualified) interface type.
Steve Naroff14108da2009-07-10 23:34:53 +00002762 const ObjCObjectPointerType *OPT;
John McCall129e2df2009-11-30 22:42:35 +00002763 if (!IsArrow && (OPT = BaseType->getAsObjCInterfacePointerType())) {
Steve Naroff14108da2009-07-10 23:34:53 +00002764 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
2765 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
Anders Carlsson8f28f992009-08-26 18:25:21 +00002766 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Mike Stump1eb44332009-09-09 15:08:12 +00002767
Daniel Dunbar2307d312008-09-03 01:05:41 +00002768 // Search for a declared property first.
Anders Carlsson8f28f992009-08-26 18:25:21 +00002769 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002770 // Check whether we can reference this property.
2771 if (DiagnoseUseOfDecl(PD, MemberLoc))
2772 return ExprError();
Fariborz Jahanian4c2743f2009-05-08 19:36:34 +00002773 QualType ResTy = PD->getType();
Anders Carlsson8f28f992009-08-26 18:25:21 +00002774 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002775 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Fariborz Jahanianc001e892009-05-08 20:20:55 +00002776 if (DiagnosePropertyAccessorMismatch(PD, Getter, MemberLoc))
2777 ResTy = Getter->getResultType();
Fariborz Jahanian4c2743f2009-05-08 19:36:34 +00002778 return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
Chris Lattner7eba82e2009-02-16 18:35:08 +00002779 MemberLoc, BaseExpr));
2780 }
Daniel Dunbar2307d312008-09-03 01:05:41 +00002781 // Check protocols on qualified interfaces.
Steve Naroff67ef8ea2009-07-20 17:56:53 +00002782 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
2783 E = OPT->qual_end(); I != E; ++I)
Anders Carlsson8f28f992009-08-26 18:25:21 +00002784 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002785 // Check whether we can reference this property.
2786 if (DiagnoseUseOfDecl(PD, MemberLoc))
2787 return ExprError();
Chris Lattner7eba82e2009-02-16 18:35:08 +00002788
Steve Naroff6ece14c2009-01-21 00:14:39 +00002789 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner7eba82e2009-02-16 18:35:08 +00002790 MemberLoc, BaseExpr));
2791 }
Daniel Dunbar2307d312008-09-03 01:05:41 +00002792 // If that failed, look for an "implicit" property by seeing if the nullary
2793 // selector is implemented.
2794
2795 // FIXME: The logic for looking up nullary and unary selectors should be
2796 // shared with the code in ActOnInstanceMessage.
2797
Anders Carlsson8f28f992009-08-26 18:25:21 +00002798 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002799 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Sebastian Redl0eb23302009-01-19 00:08:26 +00002800
Daniel Dunbar2307d312008-09-03 01:05:41 +00002801 // If this reference is in an @implementation, check for 'private' methods.
2802 if (!Getter)
Steve Naroffd789d3d2009-10-01 23:46:04 +00002803 Getter = IFace->lookupPrivateInstanceMethod(Sel);
Daniel Dunbar2307d312008-09-03 01:05:41 +00002804
Steve Naroff7692ed62008-10-22 19:16:27 +00002805 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +00002806 if (!Getter)
2807 Getter = IFace->getCategoryInstanceMethod(Sel);
Daniel Dunbar2307d312008-09-03 01:05:41 +00002808 if (Getter) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002809 // Check if we can reference this property.
2810 if (DiagnoseUseOfDecl(Getter, MemberLoc))
2811 return ExprError();
Steve Naroff1ca66942009-03-11 13:48:17 +00002812 }
2813 // If we found a getter then this may be a valid dot-reference, we
2814 // will look for the matching setter, in case it is needed.
Mike Stump1eb44332009-09-09 15:08:12 +00002815 Selector SetterSel =
2816 SelectorTable::constructSetterName(PP.getIdentifierTable(),
Anders Carlsson8f28f992009-08-26 18:25:21 +00002817 PP.getSelectorTable(), Member);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002818 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
Steve Naroff1ca66942009-03-11 13:48:17 +00002819 if (!Setter) {
2820 // If this reference is in an @implementation, also check for 'private'
2821 // methods.
Steve Naroffd789d3d2009-10-01 23:46:04 +00002822 Setter = IFace->lookupPrivateInstanceMethod(SetterSel);
Steve Naroff1ca66942009-03-11 13:48:17 +00002823 }
2824 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +00002825 if (!Setter)
2826 Setter = IFace->getCategoryInstanceMethod(SetterSel);
Sebastian Redl0eb23302009-01-19 00:08:26 +00002827
Steve Naroff1ca66942009-03-11 13:48:17 +00002828 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2829 return ExprError();
2830
2831 if (Getter || Setter) {
2832 QualType PType;
2833
2834 if (Getter)
2835 PType = Getter->getResultType();
Fariborz Jahanian154440e2009-08-18 20:50:23 +00002836 else
2837 // Get the expression type from Setter's incoming parameter.
2838 PType = (*(Setter->param_end() -1))->getType();
Steve Naroff1ca66942009-03-11 13:48:17 +00002839 // FIXME: we must check that the setter has property type.
Fariborz Jahanian09105f52009-08-20 17:02:02 +00002840 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter, PType,
Steve Naroff1ca66942009-03-11 13:48:17 +00002841 Setter, MemberLoc, BaseExpr));
2842 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002843 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlsson8f28f992009-08-26 18:25:21 +00002844 << MemberName << BaseType);
Fariborz Jahanian232220c2007-11-12 22:29:28 +00002845 }
Mike Stump1eb44332009-09-09 15:08:12 +00002846
Steve Narofff242b1b2009-07-24 17:54:45 +00002847 // Handle the following exceptional case (*Obj).isa.
John McCall129e2df2009-11-30 22:42:35 +00002848 if (!IsArrow &&
Steve Narofff242b1b2009-07-24 17:54:45 +00002849 BaseType->isSpecificBuiltinType(BuiltinType::ObjCId) &&
Anders Carlsson8f28f992009-08-26 18:25:21 +00002850 MemberName.getAsIdentifierInfo()->isStr("isa"))
Steve Narofff242b1b2009-07-24 17:54:45 +00002851 return Owned(new (Context) ObjCIsaExpr(BaseExpr, false, MemberLoc,
2852 Context.getObjCIdType()));
2853
Chris Lattnerfb173ec2008-07-21 04:28:12 +00002854 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner73525de2009-02-16 21:11:58 +00002855 if (BaseType->isExtVectorType()) {
Anders Carlsson8f28f992009-08-26 18:25:21 +00002856 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Chris Lattnerfb173ec2008-07-21 04:28:12 +00002857 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
2858 if (ret.isNull())
Sebastian Redl0eb23302009-01-19 00:08:26 +00002859 return ExprError();
Anders Carlsson8f28f992009-08-26 18:25:21 +00002860 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, *Member,
Steve Naroff6ece14c2009-01-21 00:14:39 +00002861 MemberLoc));
Chris Lattnerfb173ec2008-07-21 04:28:12 +00002862 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002863
Douglas Gregor214f31a2009-03-27 06:00:30 +00002864 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
2865 << BaseType << BaseExpr->getSourceRange();
2866
Douglas Gregor214f31a2009-03-27 06:00:30 +00002867 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00002868}
2869
John McCall129e2df2009-11-30 22:42:35 +00002870static Sema::OwningExprResult DiagnoseDtorReference(Sema &SemaRef,
2871 SourceLocation NameLoc,
2872 Sema::ExprArg MemExpr) {
2873 Expr *E = (Expr *) MemExpr.get();
2874 SourceLocation ExpectedLParenLoc = SemaRef.PP.getLocForEndOfToken(NameLoc);
2875 SemaRef.Diag(E->getLocStart(), diag::err_dtor_expr_without_call)
Douglas Gregor2d1c2142009-11-03 19:44:04 +00002876 << isa<CXXPseudoDestructorExpr>(E)
2877 << CodeModificationHint::CreateInsertion(ExpectedLParenLoc, "()");
2878
John McCall129e2df2009-11-30 22:42:35 +00002879 return SemaRef.ActOnCallExpr(/*Scope*/ 0,
2880 move(MemExpr),
2881 /*LPLoc*/ ExpectedLParenLoc,
2882 Sema::MultiExprArg(SemaRef, 0, 0),
2883 /*CommaLocs*/ 0,
2884 /*RPLoc*/ ExpectedLParenLoc);
2885}
2886
2887/// The main callback when the parser finds something like
2888/// expression . [nested-name-specifier] identifier
2889/// expression -> [nested-name-specifier] identifier
2890/// where 'identifier' encompasses a fairly broad spectrum of
2891/// possibilities, including destructor and operator references.
2892///
2893/// \param OpKind either tok::arrow or tok::period
2894/// \param HasTrailingLParen whether the next token is '(', which
2895/// is used to diagnose mis-uses of special members that can
2896/// only be called
2897/// \param ObjCImpDecl the current ObjC @implementation decl;
2898/// this is an ugly hack around the fact that ObjC @implementations
2899/// aren't properly put in the context chain
2900Sema::OwningExprResult Sema::ActOnMemberAccessExpr(Scope *S, ExprArg BaseArg,
2901 SourceLocation OpLoc,
2902 tok::TokenKind OpKind,
2903 const CXXScopeSpec &SS,
2904 UnqualifiedId &Id,
2905 DeclPtrTy ObjCImpDecl,
2906 bool HasTrailingLParen) {
2907 if (SS.isSet() && SS.isInvalid())
2908 return ExprError();
2909
2910 TemplateArgumentListInfo TemplateArgsBuffer;
2911
2912 // Decompose the name into its component parts.
2913 DeclarationName Name;
2914 SourceLocation NameLoc;
2915 const TemplateArgumentListInfo *TemplateArgs;
2916 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer,
2917 Name, NameLoc, TemplateArgs);
2918
2919 bool IsArrow = (OpKind == tok::arrow);
2920
2921 NamedDecl *FirstQualifierInScope
2922 = (!SS.isSet() ? 0 : FindFirstQualifierInScope(S,
2923 static_cast<NestedNameSpecifier*>(SS.getScopeRep())));
2924
2925 // This is a postfix expression, so get rid of ParenListExprs.
2926 BaseArg = MaybeConvertParenListExprToParenExpr(S, move(BaseArg));
2927
2928 Expr *Base = BaseArg.takeAs<Expr>();
2929 OwningExprResult Result(*this);
2930 if (Base->getType()->isDependentType()) {
John McCallaa81e162009-12-01 22:10:20 +00002931 Result = ActOnDependentMemberExpr(ExprArg(*this, Base), Base->getType(),
John McCall129e2df2009-11-30 22:42:35 +00002932 IsArrow, OpLoc,
2933 SS, FirstQualifierInScope,
2934 Name, NameLoc,
2935 TemplateArgs);
2936 } else {
2937 LookupResult R(*this, Name, NameLoc, LookupMemberName);
2938 if (TemplateArgs) {
2939 // Re-use the lookup done for the template name.
2940 DecomposeTemplateName(R, Id);
2941 } else {
2942 Result = LookupMemberExpr(R, Base, IsArrow, OpLoc,
2943 SS, FirstQualifierInScope,
2944 ObjCImpDecl);
2945
2946 if (Result.isInvalid()) {
2947 Owned(Base);
2948 return ExprError();
2949 }
2950
2951 if (Result.get()) {
2952 // The only way a reference to a destructor can be used is to
2953 // immediately call it, which falls into this case. If the
2954 // next token is not a '(', produce a diagnostic and build the
2955 // call now.
2956 if (!HasTrailingLParen &&
2957 Id.getKind() == UnqualifiedId::IK_DestructorName)
2958 return DiagnoseDtorReference(*this, NameLoc, move(Result));
2959
2960 return move(Result);
2961 }
2962 }
2963
John McCallaa81e162009-12-01 22:10:20 +00002964 Result = BuildMemberReferenceExpr(ExprArg(*this, Base), Base->getType(),
2965 OpLoc, IsArrow, SS, R, TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00002966 }
2967
2968 return move(Result);
Anders Carlsson8f28f992009-08-26 18:25:21 +00002969}
2970
Anders Carlsson56c5e332009-08-25 03:49:14 +00002971Sema::OwningExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
2972 FunctionDecl *FD,
2973 ParmVarDecl *Param) {
2974 if (Param->hasUnparsedDefaultArg()) {
2975 Diag (CallLoc,
2976 diag::err_use_of_default_argument_to_function_declared_later) <<
2977 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00002978 Diag(UnparsedDefaultArgLocs[Param],
Anders Carlsson56c5e332009-08-25 03:49:14 +00002979 diag::note_default_argument_declared_here);
2980 } else {
2981 if (Param->hasUninstantiatedDefaultArg()) {
2982 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
2983
2984 // Instantiate the expression.
Douglas Gregord6350ae2009-08-28 20:31:08 +00002985 MultiLevelTemplateArgumentList ArgList = getTemplateInstantiationArgs(FD);
Anders Carlsson25cae7f2009-09-05 05:14:19 +00002986
Mike Stump1eb44332009-09-09 15:08:12 +00002987 InstantiatingTemplate Inst(*this, CallLoc, Param,
2988 ArgList.getInnermost().getFlatArgumentList(),
Douglas Gregord6350ae2009-08-28 20:31:08 +00002989 ArgList.getInnermost().flat_size());
Anders Carlsson56c5e332009-08-25 03:49:14 +00002990
John McCallce3ff2b2009-08-25 22:02:44 +00002991 OwningExprResult Result = SubstExpr(UninstExpr, ArgList);
Mike Stump1eb44332009-09-09 15:08:12 +00002992 if (Result.isInvalid())
Anders Carlsson56c5e332009-08-25 03:49:14 +00002993 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00002994
2995 if (SetParamDefaultArgument(Param, move(Result),
Anders Carlsson56c5e332009-08-25 03:49:14 +00002996 /*FIXME:EqualLoc*/
2997 UninstExpr->getSourceRange().getBegin()))
2998 return ExprError();
2999 }
Mike Stump1eb44332009-09-09 15:08:12 +00003000
Anders Carlsson56c5e332009-08-25 03:49:14 +00003001 Expr *DefaultExpr = Param->getDefaultArg();
Mike Stump1eb44332009-09-09 15:08:12 +00003002
Anders Carlsson56c5e332009-08-25 03:49:14 +00003003 // If the default expression creates temporaries, we need to
3004 // push them to the current stack of expression temporaries so they'll
3005 // be properly destroyed.
Mike Stump1eb44332009-09-09 15:08:12 +00003006 if (CXXExprWithTemporaries *E
Anders Carlsson56c5e332009-08-25 03:49:14 +00003007 = dyn_cast_or_null<CXXExprWithTemporaries>(DefaultExpr)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003008 assert(!E->shouldDestroyTemporaries() &&
Anders Carlsson56c5e332009-08-25 03:49:14 +00003009 "Can't destroy temporaries in a default argument expr!");
3010 for (unsigned I = 0, N = E->getNumTemporaries(); I != N; ++I)
3011 ExprTemporaries.push_back(E->getTemporary(I));
3012 }
3013 }
3014
3015 // We already type-checked the argument, so we know it works.
3016 return Owned(CXXDefaultArgExpr::Create(Context, Param));
3017}
3018
Douglas Gregor88a35142008-12-22 05:46:06 +00003019/// ConvertArgumentsForCall - Converts the arguments specified in
3020/// Args/NumArgs to the parameter types of the function FDecl with
3021/// function prototype Proto. Call is the call expression itself, and
3022/// Fn is the function expression. For a C++ member function, this
3023/// routine does not attempt to convert the object argument. Returns
3024/// true if the call is ill-formed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003025bool
3026Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor88a35142008-12-22 05:46:06 +00003027 FunctionDecl *FDecl,
Douglas Gregor72564e72009-02-26 23:50:07 +00003028 const FunctionProtoType *Proto,
Douglas Gregor88a35142008-12-22 05:46:06 +00003029 Expr **Args, unsigned NumArgs,
3030 SourceLocation RParenLoc) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00003031 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor88a35142008-12-22 05:46:06 +00003032 // assignment, to the types of the corresponding parameter, ...
3033 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor3fd56d72009-01-23 21:30:56 +00003034 bool Invalid = false;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003035
Douglas Gregor88a35142008-12-22 05:46:06 +00003036 // If too few arguments are available (and we don't have default
3037 // arguments for the remaining parameters), don't make the call.
3038 if (NumArgs < NumArgsInProto) {
3039 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
3040 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
3041 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
Ted Kremenek8189cde2009-02-07 01:47:29 +00003042 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor88a35142008-12-22 05:46:06 +00003043 }
3044
3045 // If too many are passed and not variadic, error on the extras and drop
3046 // them.
3047 if (NumArgs > NumArgsInProto) {
3048 if (!Proto->isVariadic()) {
3049 Diag(Args[NumArgsInProto]->getLocStart(),
3050 diag::err_typecheck_call_too_many_args)
3051 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
3052 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3053 Args[NumArgs-1]->getLocEnd());
3054 // This deletes the extra arguments.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003055 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003056 return true;
Douglas Gregor88a35142008-12-22 05:46:06 +00003057 }
Douglas Gregor88a35142008-12-22 05:46:06 +00003058 }
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003059 llvm::SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00003060 VariadicCallType CallType =
3061 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
3062 if (Fn->getType()->isBlockPointerType())
3063 CallType = VariadicBlock; // Block
3064 else if (isa<MemberExpr>(Fn))
3065 CallType = VariadicMethod;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003066 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00003067 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003068 if (Invalid)
3069 return true;
3070 unsigned TotalNumArgs = AllArgs.size();
3071 for (unsigned i = 0; i < TotalNumArgs; ++i)
3072 Call->setArg(i, AllArgs[i]);
3073
3074 return false;
3075}
Mike Stumpeed9cac2009-02-19 03:04:26 +00003076
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003077bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
3078 FunctionDecl *FDecl,
3079 const FunctionProtoType *Proto,
3080 unsigned FirstProtoArg,
3081 Expr **Args, unsigned NumArgs,
3082 llvm::SmallVector<Expr *, 8> &AllArgs,
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00003083 VariadicCallType CallType) {
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003084 unsigned NumArgsInProto = Proto->getNumArgs();
3085 unsigned NumArgsToCheck = NumArgs;
3086 bool Invalid = false;
3087 if (NumArgs != NumArgsInProto)
3088 // Use default arguments for missing arguments
3089 NumArgsToCheck = NumArgsInProto;
3090 unsigned ArgIx = 0;
Douglas Gregor88a35142008-12-22 05:46:06 +00003091 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003092 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor88a35142008-12-22 05:46:06 +00003093 QualType ProtoArgType = Proto->getArgType(i);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003094
Douglas Gregor88a35142008-12-22 05:46:06 +00003095 Expr *Arg;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003096 if (ArgIx < NumArgs) {
3097 Arg = Args[ArgIx++];
3098
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003099 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3100 ProtoArgType,
Anders Carlssonb7906612009-08-26 23:45:07 +00003101 PDiag(diag::err_call_incomplete_argument)
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003102 << Arg->getSourceRange()))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003103 return true;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003104
Douglas Gregor61366e92008-12-24 00:01:03 +00003105 // Pass the argument.
3106 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
3107 return true;
Anders Carlsson03d8ed42009-11-13 04:34:45 +00003108
Anders Carlsson4b3cbea2009-11-13 17:04:35 +00003109 if (!ProtoArgType->isReferenceType())
3110 Arg = MaybeBindToTemporary(Arg).takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00003111 } else {
Anders Carlssoned961f92009-08-25 02:29:20 +00003112 ParmVarDecl *Param = FDecl->getParamDecl(i);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003113
Mike Stump1eb44332009-09-09 15:08:12 +00003114 OwningExprResult ArgExpr =
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003115 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson56c5e332009-08-25 03:49:14 +00003116 if (ArgExpr.isInvalid())
3117 return true;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003118
Anders Carlsson56c5e332009-08-25 03:49:14 +00003119 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00003120 }
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003121 AllArgs.push_back(Arg);
Douglas Gregor88a35142008-12-22 05:46:06 +00003122 }
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003123
Douglas Gregor88a35142008-12-22 05:46:06 +00003124 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00003125 if (CallType != VariadicDoesNotApply) {
Douglas Gregor88a35142008-12-22 05:46:06 +00003126 // Promote the arguments (C99 6.5.2.2p7).
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003127 for (unsigned i = ArgIx; i < NumArgs; i++) {
Douglas Gregor88a35142008-12-22 05:46:06 +00003128 Expr *Arg = Args[i];
Chris Lattner312531a2009-04-12 08:11:20 +00003129 Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003130 AllArgs.push_back(Arg);
Douglas Gregor88a35142008-12-22 05:46:06 +00003131 }
3132 }
Douglas Gregor3fd56d72009-01-23 21:30:56 +00003133 return Invalid;
Douglas Gregor88a35142008-12-22 05:46:06 +00003134}
3135
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003136/// \brief "Deconstruct" the function argument of a call expression to find
3137/// the underlying declaration (if any), the name of the called function,
3138/// whether argument-dependent lookup is available, whether it has explicit
3139/// template arguments, etc.
3140void Sema::DeconstructCallFunction(Expr *FnExpr,
John McCallba135432009-11-21 08:51:07 +00003141 llvm::SmallVectorImpl<NamedDecl*> &Fns,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003142 DeclarationName &Name,
3143 NestedNameSpecifier *&Qualifier,
3144 SourceRange &QualifierRange,
3145 bool &ArgumentDependentLookup,
John McCall7453ed42009-11-22 00:44:51 +00003146 bool &Overloaded,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003147 bool &HasExplicitTemplateArguments,
John McCalld5532b62009-11-23 01:53:49 +00003148 TemplateArgumentListInfo &ExplicitTemplateArgs) {
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003149 // Set defaults for all of the output parameters.
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003150 Name = DeclarationName();
3151 Qualifier = 0;
3152 QualifierRange = SourceRange();
John McCallf7a1a742009-11-24 19:00:30 +00003153 ArgumentDependentLookup = false;
John McCall7453ed42009-11-22 00:44:51 +00003154 Overloaded = false;
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003155 HasExplicitTemplateArguments = false;
John McCall7453ed42009-11-22 00:44:51 +00003156
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003157 // If we're directly calling a function, get the appropriate declaration.
3158 // Also, in C++, keep track of whether we should perform argument-dependent
3159 // lookup and whether there were any explicitly-specified template arguments.
3160 while (true) {
3161 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(FnExpr))
3162 FnExpr = IcExpr->getSubExpr();
3163 else if (ParenExpr *PExpr = dyn_cast<ParenExpr>(FnExpr)) {
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003164 FnExpr = PExpr->getSubExpr();
3165 } else if (isa<UnaryOperator>(FnExpr) &&
3166 cast<UnaryOperator>(FnExpr)->getOpcode()
3167 == UnaryOperator::AddrOf) {
3168 FnExpr = cast<UnaryOperator>(FnExpr)->getSubExpr();
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003169 } else if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(FnExpr)) {
John McCallba135432009-11-21 08:51:07 +00003170 Fns.push_back(cast<NamedDecl>(DRExpr->getDecl()));
3171 ArgumentDependentLookup = false;
3172 if ((Qualifier = DRExpr->getQualifier()))
Douglas Gregora2813ce2009-10-23 18:54:35 +00003173 QualifierRange = DRExpr->getQualifierRange();
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003174 break;
John McCallba135432009-11-21 08:51:07 +00003175 } else if (UnresolvedLookupExpr *UnresLookup
3176 = dyn_cast<UnresolvedLookupExpr>(FnExpr)) {
3177 Name = UnresLookup->getName();
3178 Fns.append(UnresLookup->decls_begin(), UnresLookup->decls_end());
3179 ArgumentDependentLookup = UnresLookup->requiresADL();
John McCall7453ed42009-11-22 00:44:51 +00003180 Overloaded = UnresLookup->isOverloaded();
John McCallba135432009-11-21 08:51:07 +00003181 if ((Qualifier = UnresLookup->getQualifier()))
3182 QualifierRange = UnresLookup->getQualifierRange();
John McCallf7a1a742009-11-24 19:00:30 +00003183 if (UnresLookup->hasExplicitTemplateArgs()) {
3184 HasExplicitTemplateArguments = true;
3185 UnresLookup->copyTemplateArgumentsInto(ExplicitTemplateArgs);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003186 }
3187 break;
3188 } else {
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003189 break;
3190 }
3191 }
3192}
3193
Steve Narofff69936d2007-09-16 03:34:24 +00003194/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Reid Spencer5f016e22007-07-11 17:01:13 +00003195/// This provides the location of the left/right parens and a list of comma
3196/// locations.
Sebastian Redl0eb23302009-01-19 00:08:26 +00003197Action::OwningExprResult
3198Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
3199 MultiExprArg args,
Douglas Gregor88a35142008-12-22 05:46:06 +00003200 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Sebastian Redl0eb23302009-01-19 00:08:26 +00003201 unsigned NumArgs = args.size();
Nate Begeman2ef13e52009-08-10 23:49:36 +00003202
3203 // Since this might be a postfix expression, get rid of ParenListExprs.
3204 fn = MaybeConvertParenListExprToParenExpr(S, move(fn));
Mike Stump1eb44332009-09-09 15:08:12 +00003205
Anders Carlssonf1b1d592009-05-01 19:30:39 +00003206 Expr *Fn = fn.takeAs<Expr>();
Sebastian Redl0eb23302009-01-19 00:08:26 +00003207 Expr **Args = reinterpret_cast<Expr**>(args.release());
Chris Lattner74c469f2007-07-21 03:03:59 +00003208 assert(Fn && "no function call expression");
Mike Stump1eb44332009-09-09 15:08:12 +00003209
Douglas Gregor88a35142008-12-22 05:46:06 +00003210 if (getLangOptions().CPlusPlus) {
Douglas Gregora71d8192009-09-04 17:36:40 +00003211 // If this is a pseudo-destructor expression, build the call immediately.
3212 if (isa<CXXPseudoDestructorExpr>(Fn)) {
3213 if (NumArgs > 0) {
3214 // Pseudo-destructor calls should not have any arguments.
3215 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
3216 << CodeModificationHint::CreateRemoval(
3217 SourceRange(Args[0]->getLocStart(),
3218 Args[NumArgs-1]->getLocEnd()));
Mike Stump1eb44332009-09-09 15:08:12 +00003219
Douglas Gregora71d8192009-09-04 17:36:40 +00003220 for (unsigned I = 0; I != NumArgs; ++I)
3221 Args[I]->Destroy(Context);
Mike Stump1eb44332009-09-09 15:08:12 +00003222
Douglas Gregora71d8192009-09-04 17:36:40 +00003223 NumArgs = 0;
3224 }
Mike Stump1eb44332009-09-09 15:08:12 +00003225
Douglas Gregora71d8192009-09-04 17:36:40 +00003226 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
3227 RParenLoc));
3228 }
Mike Stump1eb44332009-09-09 15:08:12 +00003229
Douglas Gregor17330012009-02-04 15:01:18 +00003230 // Determine whether this is a dependent call inside a C++ template,
Mike Stumpeed9cac2009-02-19 03:04:26 +00003231 // in which case we won't do any semantic analysis now.
Mike Stump390b4cc2009-05-16 07:39:55 +00003232 // FIXME: Will need to cache the results of name lookup (including ADL) in
3233 // Fn.
Douglas Gregor17330012009-02-04 15:01:18 +00003234 bool Dependent = false;
3235 if (Fn->isTypeDependent())
3236 Dependent = true;
3237 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
3238 Dependent = true;
3239
3240 if (Dependent)
Ted Kremenek668bf912009-02-09 20:51:47 +00003241 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
Douglas Gregor17330012009-02-04 15:01:18 +00003242 Context.DependentTy, RParenLoc));
3243
3244 // Determine whether this is a call to an object (C++ [over.call.object]).
3245 if (Fn->getType()->isRecordType())
3246 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
3247 CommaLocs, RParenLoc));
3248
John McCall129e2df2009-11-30 22:42:35 +00003249 Expr *NakedFn = Fn->IgnoreParens();
3250
3251 // Determine whether this is a call to an unresolved member function.
3252 if (UnresolvedMemberExpr *MemE = dyn_cast<UnresolvedMemberExpr>(NakedFn)) {
3253 // If lookup was unresolved but not dependent (i.e. didn't find
3254 // an unresolved using declaration), it has to be an overloaded
3255 // function set, which means it must contain either multiple
3256 // declarations (all methods or method templates) or a single
3257 // method template.
3258 assert((MemE->getNumDecls() > 1) ||
3259 isa<FunctionTemplateDecl>(*MemE->decls_begin()));
Douglas Gregor958aeb02009-12-01 03:34:29 +00003260 (void)MemE;
John McCall129e2df2009-11-30 22:42:35 +00003261
John McCallaa81e162009-12-01 22:10:20 +00003262 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
3263 CommaLocs, RParenLoc);
John McCall129e2df2009-11-30 22:42:35 +00003264 }
3265
Douglas Gregorfa047642009-02-04 00:32:51 +00003266 // Determine whether this is a call to a member function.
John McCall129e2df2009-11-30 22:42:35 +00003267 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(NakedFn)) {
Douglas Gregore53060f2009-06-25 22:08:12 +00003268 NamedDecl *MemDecl = MemExpr->getMemberDecl();
John McCall129e2df2009-11-30 22:42:35 +00003269 if (isa<CXXMethodDecl>(MemDecl))
John McCallaa81e162009-12-01 22:10:20 +00003270 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
3271 CommaLocs, RParenLoc);
Douglas Gregore53060f2009-06-25 22:08:12 +00003272 }
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003273
3274 // Determine whether this is a call to a pointer-to-member function.
John McCall129e2df2009-11-30 22:42:35 +00003275 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(NakedFn)) {
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003276 if (BO->getOpcode() == BinaryOperator::PtrMemD ||
3277 BO->getOpcode() == BinaryOperator::PtrMemI) {
Fariborz Jahanian5de24502009-10-28 16:49:46 +00003278 if (const FunctionProtoType *FPT =
3279 dyn_cast<FunctionProtoType>(BO->getType())) {
3280 QualType ResultTy = FPT->getResultType().getNonReferenceType();
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003281
Fariborz Jahanian5de24502009-10-28 16:49:46 +00003282 ExprOwningPtr<CXXMemberCallExpr>
3283 TheCall(this, new (Context) CXXMemberCallExpr(Context, BO, Args,
3284 NumArgs, ResultTy,
3285 RParenLoc));
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003286
Fariborz Jahanian5de24502009-10-28 16:49:46 +00003287 if (CheckCallReturnType(FPT->getResultType(),
3288 BO->getRHS()->getSourceRange().getBegin(),
3289 TheCall.get(), 0))
3290 return ExprError();
Anders Carlsson8d6d90d2009-10-15 00:41:48 +00003291
Fariborz Jahanian5de24502009-10-28 16:49:46 +00003292 if (ConvertArgumentsForCall(&*TheCall, BO, 0, FPT, Args, NumArgs,
3293 RParenLoc))
3294 return ExprError();
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003295
Fariborz Jahanian5de24502009-10-28 16:49:46 +00003296 return Owned(MaybeBindToTemporary(TheCall.release()).release());
3297 }
3298 return ExprError(Diag(Fn->getLocStart(),
3299 diag::err_typecheck_call_not_function)
3300 << Fn->getType() << Fn->getSourceRange());
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003301 }
3302 }
Douglas Gregor88a35142008-12-22 05:46:06 +00003303 }
3304
Douglas Gregorfa047642009-02-04 00:32:51 +00003305 // If we're directly calling a function, get the appropriate declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003306 // Also, in C++, keep track of whether we should perform argument-dependent
Douglas Gregor6db8ed42009-06-30 23:57:56 +00003307 // lookup and whether there were any explicitly-specified template arguments.
John McCallba135432009-11-21 08:51:07 +00003308 llvm::SmallVector<NamedDecl*,8> Fns;
3309 DeclarationName UnqualifiedName;
John McCall7453ed42009-11-22 00:44:51 +00003310 bool Overloaded;
3311 bool ADL;
Douglas Gregor6db8ed42009-06-30 23:57:56 +00003312 bool HasExplicitTemplateArgs = 0;
John McCalld5532b62009-11-23 01:53:49 +00003313 TemplateArgumentListInfo ExplicitTemplateArgs;
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003314 NestedNameSpecifier *Qualifier = 0;
3315 SourceRange QualifierRange;
John McCallba135432009-11-21 08:51:07 +00003316 DeconstructCallFunction(Fn, Fns, UnqualifiedName, Qualifier, QualifierRange,
John McCall7453ed42009-11-22 00:44:51 +00003317 ADL, Overloaded, HasExplicitTemplateArgs,
John McCalld5532b62009-11-23 01:53:49 +00003318 ExplicitTemplateArgs);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003319
John McCall7453ed42009-11-22 00:44:51 +00003320 NamedDecl *NDecl; // the specific declaration we're calling, if applicable
3321 FunctionDecl *FDecl; // same, if it's known to be a function
John McCallba135432009-11-21 08:51:07 +00003322
John McCall7453ed42009-11-22 00:44:51 +00003323 if (Overloaded || ADL) {
3324#ifndef NDEBUG
3325 if (ADL) {
3326 // To do ADL, we must have found an unqualified name.
3327 assert(UnqualifiedName && "found no unqualified name for ADL");
3328
3329 // We don't perform ADL for implicit declarations of builtins.
3330 // Verify that this was correctly set up.
3331 if (Fns.size() == 1 && (FDecl = dyn_cast<FunctionDecl>(Fns[0])) &&
3332 FDecl->getBuiltinID() && FDecl->isImplicit())
3333 assert(0 && "performing ADL for builtin");
3334
3335 // We don't perform ADL in C.
3336 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
3337 }
3338
3339 if (Overloaded) {
3340 // To be overloaded, we must either have multiple functions or
3341 // at least one function template (which is effectively an
3342 // infinite set of functions).
3343 assert((Fns.size() > 1 ||
3344 (Fns.size() == 1 &&
3345 isa<FunctionTemplateDecl>(Fns[0]->getUnderlyingDecl())))
3346 && "unrecognized overload situation");
3347 }
3348#endif
3349
3350 FDecl = ResolveOverloadedCallFn(Fn, Fns, UnqualifiedName,
John McCalld5532b62009-11-23 01:53:49 +00003351 (HasExplicitTemplateArgs ? &ExplicitTemplateArgs : 0),
John McCall7453ed42009-11-22 00:44:51 +00003352 LParenLoc, Args, NumArgs, CommaLocs,
3353 RParenLoc, ADL);
3354 if (!FDecl)
3355 return ExprError();
3356
3357 Fn = FixOverloadedFunctionReference(Fn, FDecl);
3358
3359 NDecl = FDecl;
3360 } else {
3361 assert(Fns.size() <= 1 && "overloaded without Overloaded flag");
3362 if (Fns.empty())
John McCallaa81e162009-12-01 22:10:20 +00003363 NDecl = 0;
John McCall7453ed42009-11-22 00:44:51 +00003364 else {
3365 NDecl = Fns[0];
Douglas Gregorfa047642009-02-04 00:32:51 +00003366 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003367 }
Chris Lattner04421082008-04-08 04:40:51 +00003368
John McCallaa81e162009-12-01 22:10:20 +00003369 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc);
3370}
3371
3372/// BuildCallExpr - Build a call to a resolved expression, i.e. an
3373/// expression not of \p OverloadTy. The expression should
3374/// unary-convert to an expression of function-pointer or
3375/// block-pointer type.
3376///
3377/// \param NDecl the declaration being called, if available
3378Sema::OwningExprResult
3379Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
3380 SourceLocation LParenLoc,
3381 Expr **Args, unsigned NumArgs,
3382 SourceLocation RParenLoc) {
3383 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
3384
Chris Lattner04421082008-04-08 04:40:51 +00003385 // Promote the function operand.
3386 UsualUnaryConversions(Fn);
3387
Chris Lattner925e60d2007-12-28 05:29:59 +00003388 // Make the call expr early, before semantic checks. This guarantees cleanup
3389 // of arguments and function on error.
Ted Kremenek668bf912009-02-09 20:51:47 +00003390 ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
3391 Args, NumArgs,
3392 Context.BoolTy,
3393 RParenLoc));
Sebastian Redl0eb23302009-01-19 00:08:26 +00003394
Steve Naroffdd972f22008-09-05 22:11:13 +00003395 const FunctionType *FuncT;
3396 if (!Fn->getType()->isBlockPointerType()) {
3397 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
3398 // have type pointer to function".
Ted Kremenek6217b802009-07-29 21:53:49 +00003399 const PointerType *PT = Fn->getType()->getAs<PointerType>();
Steve Naroffdd972f22008-09-05 22:11:13 +00003400 if (PT == 0)
Sebastian Redl0eb23302009-01-19 00:08:26 +00003401 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3402 << Fn->getType() << Fn->getSourceRange());
John McCall183700f2009-09-21 23:43:11 +00003403 FuncT = PT->getPointeeType()->getAs<FunctionType>();
Steve Naroffdd972f22008-09-05 22:11:13 +00003404 } else { // This is a block call.
Ted Kremenek6217b802009-07-29 21:53:49 +00003405 FuncT = Fn->getType()->getAs<BlockPointerType>()->getPointeeType()->
John McCall183700f2009-09-21 23:43:11 +00003406 getAs<FunctionType>();
Steve Naroffdd972f22008-09-05 22:11:13 +00003407 }
Chris Lattner925e60d2007-12-28 05:29:59 +00003408 if (FuncT == 0)
Sebastian Redl0eb23302009-01-19 00:08:26 +00003409 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3410 << Fn->getType() << Fn->getSourceRange());
3411
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003412 // Check for a valid return type
Anders Carlsson8c8d9192009-10-09 23:51:55 +00003413 if (CheckCallReturnType(FuncT->getResultType(),
3414 Fn->getSourceRange().getBegin(), TheCall.get(),
3415 FDecl))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003416 return ExprError();
3417
Chris Lattner925e60d2007-12-28 05:29:59 +00003418 // We know the result type of the call, set it.
Douglas Gregor15da57e2008-10-29 02:00:59 +00003419 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Sebastian Redl0eb23302009-01-19 00:08:26 +00003420
Douglas Gregor72564e72009-02-26 23:50:07 +00003421 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00003422 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00003423 RParenLoc))
Sebastian Redl0eb23302009-01-19 00:08:26 +00003424 return ExprError();
Chris Lattner925e60d2007-12-28 05:29:59 +00003425 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00003426 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redl0eb23302009-01-19 00:08:26 +00003427
Douglas Gregor74734d52009-04-02 15:37:10 +00003428 if (FDecl) {
3429 // Check if we have too few/too many template arguments, based
3430 // on our knowledge of the function definition.
3431 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00003432 if (FDecl->getBody(Def) && NumArgs != Def->param_size()) {
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00003433 const FunctionProtoType *Proto =
John McCall183700f2009-09-21 23:43:11 +00003434 Def->getType()->getAs<FunctionProtoType>();
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00003435 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size())) {
3436 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
3437 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
3438 }
3439 }
Douglas Gregor74734d52009-04-02 15:37:10 +00003440 }
3441
Steve Naroffb291ab62007-08-28 23:30:39 +00003442 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner925e60d2007-12-28 05:29:59 +00003443 for (unsigned i = 0; i != NumArgs; i++) {
3444 Expr *Arg = Args[i];
3445 DefaultArgumentPromotion(Arg);
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003446 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3447 Arg->getType(),
Anders Carlssonb7906612009-08-26 23:45:07 +00003448 PDiag(diag::err_call_incomplete_argument)
3449 << Arg->getSourceRange()))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003450 return ExprError();
Chris Lattner925e60d2007-12-28 05:29:59 +00003451 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +00003452 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003453 }
Chris Lattner925e60d2007-12-28 05:29:59 +00003454
Douglas Gregor88a35142008-12-22 05:46:06 +00003455 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3456 if (!Method->isStatic())
Sebastian Redl0eb23302009-01-19 00:08:26 +00003457 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
3458 << Fn->getSourceRange());
Douglas Gregor88a35142008-12-22 05:46:06 +00003459
Fariborz Jahaniandaf04152009-05-15 20:33:25 +00003460 // Check for sentinels
3461 if (NDecl)
3462 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00003463
Chris Lattner59907c42007-08-10 20:18:51 +00003464 // Do special checking on direct calls to functions.
Anders Carlssond406bf02009-08-16 01:56:34 +00003465 if (FDecl) {
3466 if (CheckFunctionCall(FDecl, TheCall.get()))
3467 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003468
Douglas Gregor7814e6d2009-09-12 00:22:50 +00003469 if (unsigned BuiltinID = FDecl->getBuiltinID())
Anders Carlssond406bf02009-08-16 01:56:34 +00003470 return CheckBuiltinFunctionCall(BuiltinID, TheCall.take());
3471 } else if (NDecl) {
3472 if (CheckBlockCall(NDecl, TheCall.get()))
3473 return ExprError();
3474 }
Chris Lattner59907c42007-08-10 20:18:51 +00003475
Anders Carlssonec74c592009-08-16 03:06:32 +00003476 return MaybeBindToTemporary(TheCall.take());
Reid Spencer5f016e22007-07-11 17:01:13 +00003477}
3478
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003479Action::OwningExprResult
3480Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
3481 SourceLocation RParenLoc, ExprArg InitExpr) {
Steve Narofff69936d2007-09-16 03:34:24 +00003482 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00003483 //FIXME: Preserve type source info.
3484 QualType literalType = GetTypeFromParser(Ty);
Steve Naroffaff1edd2007-07-19 21:32:11 +00003485 // FIXME: put back this assert when initializers are worked out.
Steve Narofff69936d2007-09-16 03:34:24 +00003486 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003487 Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
Anders Carlssond35c8322007-12-05 07:24:19 +00003488
Eli Friedman6223c222008-05-20 05:22:08 +00003489 if (literalType->isArrayType()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003490 if (literalType->isVariableArrayType())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003491 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
3492 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor690dc7f2009-05-21 23:48:18 +00003493 } else if (!literalType->isDependentType() &&
3494 RequireCompleteType(LParenLoc, literalType,
Anders Carlssonb7906612009-08-26 23:45:07 +00003495 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump1eb44332009-09-09 15:08:12 +00003496 << SourceRange(LParenLoc,
Anders Carlssonb7906612009-08-26 23:45:07 +00003497 literalExpr->getSourceRange().getEnd())))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003498 return ExprError();
Eli Friedman6223c222008-05-20 05:22:08 +00003499
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003500 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003501 DeclarationName(), /*FIXME:DirectInit=*/false))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003502 return ExprError();
Steve Naroffe9b12192008-01-14 18:19:28 +00003503
Chris Lattner371f2582008-12-04 23:50:19 +00003504 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffe9b12192008-01-14 18:19:28 +00003505 if (isFileScope) { // 6.5.2.5p3
Steve Naroffd0091aa2008-01-10 22:15:12 +00003506 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003507 return ExprError();
Steve Naroffd0091aa2008-01-10 22:15:12 +00003508 }
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003509 InitExpr.release();
Mike Stumpeed9cac2009-02-19 03:04:26 +00003510 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType,
Steve Naroff6ece14c2009-01-21 00:14:39 +00003511 literalExpr, isFileScope));
Steve Naroff4aa88f82007-07-19 01:06:55 +00003512}
3513
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003514Action::OwningExprResult
3515Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003516 SourceLocation RBraceLoc) {
3517 unsigned NumInit = initlist.size();
3518 Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00003519
Steve Naroff08d92e42007-09-15 18:49:24 +00003520 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stumpeed9cac2009-02-19 03:04:26 +00003521 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003522
Mike Stumpeed9cac2009-02-19 03:04:26 +00003523 InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
Douglas Gregor4c678342009-01-28 21:54:33 +00003524 RBraceLoc);
Chris Lattnerf0467b32008-04-02 04:24:33 +00003525 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003526 return Owned(E);
Steve Naroff4aa88f82007-07-19 01:06:55 +00003527}
3528
Anders Carlsson82debc72009-10-18 18:12:03 +00003529static CastExpr::CastKind getScalarCastKind(ASTContext &Context,
3530 QualType SrcTy, QualType DestTy) {
Douglas Gregora4923eb2009-11-16 21:35:15 +00003531 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
Anders Carlsson82debc72009-10-18 18:12:03 +00003532 return CastExpr::CK_NoOp;
3533
3534 if (SrcTy->hasPointerRepresentation()) {
3535 if (DestTy->hasPointerRepresentation())
3536 return CastExpr::CK_BitCast;
3537 if (DestTy->isIntegerType())
3538 return CastExpr::CK_PointerToIntegral;
3539 }
3540
3541 if (SrcTy->isIntegerType()) {
3542 if (DestTy->isIntegerType())
3543 return CastExpr::CK_IntegralCast;
3544 if (DestTy->hasPointerRepresentation())
3545 return CastExpr::CK_IntegralToPointer;
3546 if (DestTy->isRealFloatingType())
3547 return CastExpr::CK_IntegralToFloating;
3548 }
3549
3550 if (SrcTy->isRealFloatingType()) {
3551 if (DestTy->isRealFloatingType())
3552 return CastExpr::CK_FloatingCast;
3553 if (DestTy->isIntegerType())
3554 return CastExpr::CK_FloatingToIntegral;
3555 }
3556
3557 // FIXME: Assert here.
3558 // assert(false && "Unhandled cast combination!");
3559 return CastExpr::CK_Unknown;
3560}
3561
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003562/// CheckCastTypes - Check type constraints for casting between types.
Sebastian Redlef0cb8e2009-07-29 13:50:23 +00003563bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr,
Mike Stump1eb44332009-09-09 15:08:12 +00003564 CastExpr::CastKind& Kind,
Fariborz Jahaniane9f42082009-08-26 18:55:36 +00003565 CXXMethodDecl *& ConversionDecl,
3566 bool FunctionalStyle) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00003567 if (getLangOptions().CPlusPlus)
Fariborz Jahaniane9f42082009-08-26 18:55:36 +00003568 return CXXCheckCStyleCast(TyR, castType, castExpr, Kind, FunctionalStyle,
3569 ConversionDecl);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00003570
Eli Friedman199ea952009-08-15 19:02:19 +00003571 DefaultFunctionArrayConversion(castExpr);
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003572
3573 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
3574 // type needs to be scalar.
3575 if (castType->isVoidType()) {
3576 // Cast to void allows any expr type.
Anders Carlssonebeaf202009-10-16 02:35:04 +00003577 Kind = CastExpr::CK_ToVoid;
3578 return false;
3579 }
3580
3581 if (!castType->isScalarType() && !castType->isVectorType()) {
Douglas Gregora4923eb2009-11-16 21:35:15 +00003582 if (Context.hasSameUnqualifiedType(castType, castExpr->getType()) &&
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003583 (castType->isStructureType() || castType->isUnionType())) {
3584 // GCC struct/union extension: allow cast to self.
Eli Friedmanb1d796d2009-03-23 00:24:07 +00003585 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003586 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
3587 << castType << castExpr->getSourceRange();
Anders Carlsson4d8673b2009-08-07 23:22:37 +00003588 Kind = CastExpr::CK_NoOp;
Anders Carlssonc3516322009-10-16 02:48:28 +00003589 return false;
3590 }
3591
3592 if (castType->isUnionType()) {
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003593 // GCC cast to union extension
Ted Kremenek6217b802009-07-29 21:53:49 +00003594 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003595 RecordDecl::field_iterator Field, FieldEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003596 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003597 Field != FieldEnd; ++Field) {
Douglas Gregora4923eb2009-11-16 21:35:15 +00003598 if (Context.hasSameUnqualifiedType(Field->getType(),
3599 castExpr->getType())) {
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003600 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
3601 << castExpr->getSourceRange();
3602 break;
3603 }
3604 }
3605 if (Field == FieldEnd)
3606 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
3607 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlsson4d8673b2009-08-07 23:22:37 +00003608 Kind = CastExpr::CK_ToUnion;
Anders Carlssonc3516322009-10-16 02:48:28 +00003609 return false;
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003610 }
Anders Carlssonc3516322009-10-16 02:48:28 +00003611
3612 // Reject any other conversions to non-scalar types.
3613 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
3614 << castType << castExpr->getSourceRange();
3615 }
3616
3617 if (!castExpr->getType()->isScalarType() &&
3618 !castExpr->getType()->isVectorType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003619 return Diag(castExpr->getLocStart(),
3620 diag::err_typecheck_expect_scalar_operand)
Chris Lattnerd1625842008-11-24 06:25:27 +00003621 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlssonc3516322009-10-16 02:48:28 +00003622 }
3623
Anders Carlsson16a89042009-10-16 05:23:41 +00003624 if (castType->isExtVectorType())
3625 return CheckExtVectorCast(TyR, castType, castExpr, Kind);
3626
Anders Carlssonc3516322009-10-16 02:48:28 +00003627 if (castType->isVectorType())
3628 return CheckVectorCast(TyR, castType, castExpr->getType(), Kind);
3629 if (castExpr->getType()->isVectorType())
3630 return CheckVectorCast(TyR, castExpr->getType(), castType, Kind);
3631
3632 if (getLangOptions().ObjC1 && isa<ObjCSuperExpr>(castExpr))
Steve Naroffa0c3e9c2009-04-08 23:52:26 +00003633 return Diag(castExpr->getLocStart(), diag::err_illegal_super_cast) << TyR;
Anders Carlssonc3516322009-10-16 02:48:28 +00003634
Anders Carlsson16a89042009-10-16 05:23:41 +00003635 if (isa<ObjCSelectorExpr>(castExpr))
3636 return Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
3637
Anders Carlssonc3516322009-10-16 02:48:28 +00003638 if (!castType->isArithmeticType()) {
Eli Friedman41826bb2009-05-01 02:23:58 +00003639 QualType castExprType = castExpr->getType();
3640 if (!castExprType->isIntegralType() && castExprType->isArithmeticType())
3641 return Diag(castExpr->getLocStart(),
3642 diag::err_cast_pointer_from_non_pointer_int)
3643 << castExprType << castExpr->getSourceRange();
3644 } else if (!castExpr->getType()->isArithmeticType()) {
3645 if (!castType->isIntegralType() && castType->isArithmeticType())
3646 return Diag(castExpr->getLocStart(),
3647 diag::err_cast_pointer_to_non_pointer_int)
3648 << castType << castExpr->getSourceRange();
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003649 }
Anders Carlsson82debc72009-10-18 18:12:03 +00003650
3651 Kind = getScalarCastKind(Context, castExpr->getType(), castType);
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003652 return false;
3653}
3654
Anders Carlssonc3516322009-10-16 02:48:28 +00003655bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
3656 CastExpr::CastKind &Kind) {
Anders Carlssona64db8f2007-11-27 05:51:55 +00003657 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00003658
Anders Carlssona64db8f2007-11-27 05:51:55 +00003659 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner98be4942008-03-05 18:54:05 +00003660 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssona64db8f2007-11-27 05:51:55 +00003661 return Diag(R.getBegin(),
Mike Stumpeed9cac2009-02-19 03:04:26 +00003662 Ty->isVectorType() ?
Anders Carlssona64db8f2007-11-27 05:51:55 +00003663 diag::err_invalid_conversion_between_vectors :
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003664 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00003665 << VectorTy << Ty << R;
Anders Carlssona64db8f2007-11-27 05:51:55 +00003666 } else
3667 return Diag(R.getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003668 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattnerd1625842008-11-24 06:25:27 +00003669 << VectorTy << Ty << R;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003670
Anders Carlssonc3516322009-10-16 02:48:28 +00003671 Kind = CastExpr::CK_BitCast;
Anders Carlssona64db8f2007-11-27 05:51:55 +00003672 return false;
3673}
3674
Anders Carlsson16a89042009-10-16 05:23:41 +00003675bool Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *&CastExpr,
3676 CastExpr::CastKind &Kind) {
Nate Begeman58d29a42009-06-26 00:50:28 +00003677 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Anders Carlsson16a89042009-10-16 05:23:41 +00003678
3679 QualType SrcTy = CastExpr->getType();
3680
Nate Begeman9b10da62009-06-27 22:05:55 +00003681 // If SrcTy is a VectorType, the total size must match to explicitly cast to
3682 // an ExtVectorType.
Nate Begeman58d29a42009-06-26 00:50:28 +00003683 if (SrcTy->isVectorType()) {
3684 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
3685 return Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
3686 << DestTy << SrcTy << R;
Anders Carlsson16a89042009-10-16 05:23:41 +00003687 Kind = CastExpr::CK_BitCast;
Nate Begeman58d29a42009-06-26 00:50:28 +00003688 return false;
3689 }
3690
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00003691 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begeman58d29a42009-06-26 00:50:28 +00003692 // conversion will take place first from scalar to elt type, and then
3693 // splat from elt type to vector.
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00003694 if (SrcTy->isPointerType())
3695 return Diag(R.getBegin(),
3696 diag::err_invalid_conversion_between_vector_and_scalar)
3697 << DestTy << SrcTy << R;
Eli Friedman73c39ab2009-10-20 08:27:19 +00003698
3699 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
3700 ImpCastExprToType(CastExpr, DestElemTy,
3701 getScalarCastKind(Context, SrcTy, DestElemTy));
Anders Carlsson16a89042009-10-16 05:23:41 +00003702
3703 Kind = CastExpr::CK_VectorSplat;
Nate Begeman58d29a42009-06-26 00:50:28 +00003704 return false;
3705}
3706
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003707Action::OwningExprResult
Nate Begeman2ef13e52009-08-10 23:49:36 +00003708Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, TypeTy *Ty,
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003709 SourceLocation RParenLoc, ExprArg Op) {
Anders Carlssoncdb61972009-08-07 22:21:05 +00003710 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Mike Stump1eb44332009-09-09 15:08:12 +00003711
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003712 assert((Ty != 0) && (Op.get() != 0) &&
3713 "ActOnCastExpr(): missing type or expr");
Steve Naroff16beff82007-07-16 23:25:18 +00003714
Nate Begeman2ef13e52009-08-10 23:49:36 +00003715 Expr *castExpr = (Expr *)Op.get();
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00003716 //FIXME: Preserve type source info.
3717 QualType castType = GetTypeFromParser(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00003718
Nate Begeman2ef13e52009-08-10 23:49:36 +00003719 // If the Expr being casted is a ParenListExpr, handle it specially.
3720 if (isa<ParenListExpr>(castExpr))
3721 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, move(Op),castType);
Anders Carlsson0aebc812009-09-09 21:33:21 +00003722 CXXMethodDecl *Method = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003723 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr,
Anders Carlsson0aebc812009-09-09 21:33:21 +00003724 Kind, Method))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003725 return ExprError();
Anders Carlsson0aebc812009-09-09 21:33:21 +00003726
3727 if (Method) {
Daniel Dunbar7e88a602009-09-17 06:31:17 +00003728 OwningExprResult CastArg = BuildCXXCastArgument(LParenLoc, castType, Kind,
Anders Carlsson0aebc812009-09-09 21:33:21 +00003729 Method, move(Op));
Daniel Dunbar7e88a602009-09-17 06:31:17 +00003730
Anders Carlsson0aebc812009-09-09 21:33:21 +00003731 if (CastArg.isInvalid())
3732 return ExprError();
Daniel Dunbar7e88a602009-09-17 06:31:17 +00003733
Anders Carlsson0aebc812009-09-09 21:33:21 +00003734 castExpr = CastArg.takeAs<Expr>();
3735 } else {
3736 Op.release();
Fariborz Jahanian31976592009-08-29 19:15:16 +00003737 }
Mike Stump1eb44332009-09-09 15:08:12 +00003738
Sebastian Redl9cc11e72009-07-25 15:41:38 +00003739 return Owned(new (Context) CStyleCastExpr(castType.getNonReferenceType(),
Mike Stump1eb44332009-09-09 15:08:12 +00003740 Kind, castExpr, castType,
Anders Carlssoncdb61972009-08-07 22:21:05 +00003741 LParenLoc, RParenLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00003742}
3743
Nate Begeman2ef13e52009-08-10 23:49:36 +00003744/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
3745/// of comma binary operators.
3746Action::OwningExprResult
3747Sema::MaybeConvertParenListExprToParenExpr(Scope *S, ExprArg EA) {
3748 Expr *expr = EA.takeAs<Expr>();
3749 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
3750 if (!E)
3751 return Owned(expr);
Mike Stump1eb44332009-09-09 15:08:12 +00003752
Nate Begeman2ef13e52009-08-10 23:49:36 +00003753 OwningExprResult Result(*this, E->getExpr(0));
Mike Stump1eb44332009-09-09 15:08:12 +00003754
Nate Begeman2ef13e52009-08-10 23:49:36 +00003755 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
3756 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, move(Result),
3757 Owned(E->getExpr(i)));
Mike Stump1eb44332009-09-09 15:08:12 +00003758
Nate Begeman2ef13e52009-08-10 23:49:36 +00003759 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), move(Result));
3760}
3761
3762Action::OwningExprResult
3763Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
3764 SourceLocation RParenLoc, ExprArg Op,
3765 QualType Ty) {
3766 ParenListExpr *PE = (ParenListExpr *)Op.get();
Mike Stump1eb44332009-09-09 15:08:12 +00003767
3768 // If this is an altivec initializer, '(' type ')' '(' init, ..., init ')'
Nate Begeman2ef13e52009-08-10 23:49:36 +00003769 // then handle it as such.
3770 if (getLangOptions().AltiVec && Ty->isVectorType()) {
3771 if (PE->getNumExprs() == 0) {
3772 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
3773 return ExprError();
3774 }
3775
3776 llvm::SmallVector<Expr *, 8> initExprs;
3777 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
3778 initExprs.push_back(PE->getExpr(i));
3779
3780 // FIXME: This means that pretty-printing the final AST will produce curly
3781 // braces instead of the original commas.
3782 Op.release();
Mike Stump1eb44332009-09-09 15:08:12 +00003783 InitListExpr *E = new (Context) InitListExpr(LParenLoc, &initExprs[0],
Nate Begeman2ef13e52009-08-10 23:49:36 +00003784 initExprs.size(), RParenLoc);
3785 E->setType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00003786 return ActOnCompoundLiteral(LParenLoc, Ty.getAsOpaquePtr(), RParenLoc,
Nate Begeman2ef13e52009-08-10 23:49:36 +00003787 Owned(E));
3788 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00003789 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
Nate Begeman2ef13e52009-08-10 23:49:36 +00003790 // sequence of BinOp comma operators.
3791 Op = MaybeConvertParenListExprToParenExpr(S, move(Op));
3792 return ActOnCastExpr(S, LParenLoc, Ty.getAsOpaquePtr(), RParenLoc,move(Op));
3793 }
3794}
3795
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00003796Action::OwningExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
Nate Begeman2ef13e52009-08-10 23:49:36 +00003797 SourceLocation R,
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00003798 MultiExprArg Val,
3799 TypeTy *TypeOfCast) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00003800 unsigned nexprs = Val.size();
3801 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00003802 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
3803 Expr *expr;
3804 if (nexprs == 1 && TypeOfCast && !TypeIsVectorType(TypeOfCast))
3805 expr = new (Context) ParenExpr(L, R, exprs[0]);
3806 else
3807 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
Nate Begeman2ef13e52009-08-10 23:49:36 +00003808 return Owned(expr);
3809}
3810
Sebastian Redl28507842009-02-26 14:39:58 +00003811/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
3812/// In that case, lhs = cond.
Chris Lattnera119a3b2009-02-18 04:38:20 +00003813/// C99 6.5.15
3814QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
3815 SourceLocation QuestionLoc) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003816 // C++ is sufficiently different to merit its own checker.
3817 if (getLangOptions().CPlusPlus)
3818 return CXXCheckConditionalOperands(Cond, LHS, RHS, QuestionLoc);
3819
John McCallb13c87f2009-11-05 09:23:39 +00003820 CheckSignCompare(LHS, RHS, QuestionLoc, diag::warn_mixed_sign_conditional);
3821
Chris Lattnerefdc39d2009-02-18 04:28:32 +00003822 UsualUnaryConversions(Cond);
3823 UsualUnaryConversions(LHS);
3824 UsualUnaryConversions(RHS);
3825 QualType CondTy = Cond->getType();
3826 QualType LHSTy = LHS->getType();
3827 QualType RHSTy = RHS->getType();
Steve Naroffc80b4ee2007-07-16 21:54:35 +00003828
Reid Spencer5f016e22007-07-11 17:01:13 +00003829 // first, check the condition.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003830 if (!CondTy->isScalarType()) { // C99 6.5.15p2
3831 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
3832 << CondTy;
3833 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003834 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003835
Chris Lattner70d67a92008-01-06 22:42:25 +00003836 // Now check the two expressions.
Nate Begeman2ef13e52009-08-10 23:49:36 +00003837 if (LHSTy->isVectorType() || RHSTy->isVectorType())
3838 return CheckVectorOperands(QuestionLoc, LHS, RHS);
Douglas Gregor898574e2008-12-05 23:32:09 +00003839
Chris Lattner70d67a92008-01-06 22:42:25 +00003840 // If both operands have arithmetic type, do the usual arithmetic conversions
3841 // to find a common type: C99 6.5.15p3,5.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00003842 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
3843 UsualArithmeticConversions(LHS, RHS);
3844 return LHS->getType();
Steve Naroffa4332e22007-07-17 00:58:39 +00003845 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003846
Chris Lattner70d67a92008-01-06 22:42:25 +00003847 // If both operands are the same structure or union type, the result is that
3848 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00003849 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
3850 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattnera21ddb32007-11-26 01:40:58 +00003851 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stumpeed9cac2009-02-19 03:04:26 +00003852 // "If both the operands have structure or union type, the result has
Chris Lattner70d67a92008-01-06 22:42:25 +00003853 // that type." This implies that CV qualifiers are dropped.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00003854 return LHSTy.getUnqualifiedType();
Eli Friedmanb1d796d2009-03-23 00:24:07 +00003855 // FIXME: Type of conditional expression must be complete in C mode.
Reid Spencer5f016e22007-07-11 17:01:13 +00003856 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003857
Chris Lattner70d67a92008-01-06 22:42:25 +00003858 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffe701c0a2008-05-12 21:44:38 +00003859 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnerefdc39d2009-02-18 04:28:32 +00003860 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
3861 if (!LHSTy->isVoidType())
3862 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
3863 << RHS->getSourceRange();
3864 if (!RHSTy->isVoidType())
3865 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
3866 << LHS->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00003867 ImpCastExprToType(LHS, Context.VoidTy, CastExpr::CK_ToVoid);
3868 ImpCastExprToType(RHS, Context.VoidTy, CastExpr::CK_ToVoid);
Eli Friedman0e724012008-06-04 19:47:51 +00003869 return Context.VoidTy;
Steve Naroffe701c0a2008-05-12 21:44:38 +00003870 }
Steve Naroffb6d54e52008-01-08 01:11:38 +00003871 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
3872 // the type of the other operand."
Steve Naroff58f9f2c2009-07-14 18:25:06 +00003873 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
Douglas Gregorce940492009-09-25 04:25:58 +00003874 RHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003875 // promote the null to a pointer.
3876 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_Unknown);
Chris Lattnerefdc39d2009-02-18 04:28:32 +00003877 return LHSTy;
Steve Naroffb6d54e52008-01-08 01:11:38 +00003878 }
Steve Naroff58f9f2c2009-07-14 18:25:06 +00003879 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
Douglas Gregorce940492009-09-25 04:25:58 +00003880 LHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003881 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_Unknown);
Chris Lattnerefdc39d2009-02-18 04:28:32 +00003882 return RHSTy;
Steve Naroffb6d54e52008-01-08 01:11:38 +00003883 }
David Chisnall0f436562009-08-17 16:35:33 +00003884 // Handle things like Class and struct objc_class*. Here we case the result
3885 // to the pseudo-builtin, because that will be implicitly cast back to the
3886 // redefinition type if an attempt is made to access its fields.
3887 if (LHSTy->isObjCClassType() &&
3888 (RHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003889 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
David Chisnall0f436562009-08-17 16:35:33 +00003890 return LHSTy;
3891 }
3892 if (RHSTy->isObjCClassType() &&
3893 (LHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003894 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
David Chisnall0f436562009-08-17 16:35:33 +00003895 return RHSTy;
3896 }
3897 // And the same for struct objc_object* / id
3898 if (LHSTy->isObjCIdType() &&
3899 (RHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003900 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
David Chisnall0f436562009-08-17 16:35:33 +00003901 return LHSTy;
3902 }
3903 if (RHSTy->isObjCIdType() &&
3904 (LHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003905 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
David Chisnall0f436562009-08-17 16:35:33 +00003906 return RHSTy;
3907 }
Fariborz Jahanian369a3bd2009-11-25 23:07:42 +00003908 // And the same for struct objc_selector* / SEL
3909 if (Context.isObjCSelType(LHSTy) &&
3910 (RHSTy.getDesugaredType() == Context.ObjCSelRedefinitionType)) {
3911 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
3912 return LHSTy;
3913 }
3914 if (Context.isObjCSelType(RHSTy) &&
3915 (LHSTy.getDesugaredType() == Context.ObjCSelRedefinitionType)) {
3916 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
3917 return RHSTy;
3918 }
Steve Naroff7154a772009-07-01 14:36:47 +00003919 // Handle block pointer types.
3920 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
3921 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
3922 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
3923 QualType destType = Context.getPointerType(Context.VoidTy);
Eli Friedman73c39ab2009-10-20 08:27:19 +00003924 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
3925 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00003926 return destType;
3927 }
3928 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3929 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3930 return QualType();
Mike Stumpdd3e1662009-05-07 03:14:14 +00003931 }
Steve Naroff7154a772009-07-01 14:36:47 +00003932 // We have 2 block pointer types.
3933 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3934 // Two identical block pointer types are always compatible.
Mike Stumpdd3e1662009-05-07 03:14:14 +00003935 return LHSTy;
3936 }
Steve Naroff7154a772009-07-01 14:36:47 +00003937 // The block pointer types aren't identical, continue checking.
Ted Kremenek6217b802009-07-29 21:53:49 +00003938 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
3939 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00003940
Steve Naroff7154a772009-07-01 14:36:47 +00003941 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
3942 rhptee.getUnqualifiedType())) {
Mike Stumpdd3e1662009-05-07 03:14:14 +00003943 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
3944 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3945 // In this situation, we assume void* type. No especially good
3946 // reason, but this is what gcc does, and we do have to pick
3947 // to get a consistent AST.
3948 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Eli Friedman73c39ab2009-10-20 08:27:19 +00003949 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
3950 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
Mike Stumpdd3e1662009-05-07 03:14:14 +00003951 return incompatTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00003952 }
Steve Naroff7154a772009-07-01 14:36:47 +00003953 // The block pointer types are compatible.
Eli Friedman73c39ab2009-10-20 08:27:19 +00003954 ImpCastExprToType(LHS, LHSTy, CastExpr::CK_BitCast);
3955 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
Steve Naroff91588042009-04-08 17:05:15 +00003956 return LHSTy;
3957 }
Steve Naroff7154a772009-07-01 14:36:47 +00003958 // Check constraints for Objective-C object pointers types.
Steve Naroff14108da2009-07-10 23:34:53 +00003959 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003960
Steve Naroff7154a772009-07-01 14:36:47 +00003961 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3962 // Two identical object pointer types are always compatible.
3963 return LHSTy;
3964 }
John McCall183700f2009-09-21 23:43:11 +00003965 const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>();
3966 const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>();
Steve Naroff7154a772009-07-01 14:36:47 +00003967 QualType compositeType = LHSTy;
Mike Stump1eb44332009-09-09 15:08:12 +00003968
Steve Naroff7154a772009-07-01 14:36:47 +00003969 // If both operands are interfaces and either operand can be
3970 // assigned to the other, use that type as the composite
3971 // type. This allows
3972 // xxx ? (A*) a : (B*) b
3973 // where B is a subclass of A.
3974 //
3975 // Additionally, as for assignment, if either type is 'id'
3976 // allow silent coercion. Finally, if the types are
3977 // incompatible then make sure to use 'id' as the composite
3978 // type so the result is acceptable for sending messages to.
3979
3980 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
3981 // It could return the composite type.
Steve Naroff14108da2009-07-10 23:34:53 +00003982 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
Fariborz Jahanian9ec22a32009-08-22 22:27:17 +00003983 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
Steve Naroff14108da2009-07-10 23:34:53 +00003984 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
Fariborz Jahanian9ec22a32009-08-22 22:27:17 +00003985 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
Mike Stump1eb44332009-09-09 15:08:12 +00003986 } else if ((LHSTy->isObjCQualifiedIdType() ||
Steve Naroff14108da2009-07-10 23:34:53 +00003987 RHSTy->isObjCQualifiedIdType()) &&
Steve Naroff4084c302009-07-23 01:01:38 +00003988 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003989 // Need to handle "id<xx>" explicitly.
Steve Naroff14108da2009-07-10 23:34:53 +00003990 // GCC allows qualified id and any Objective-C type to devolve to
3991 // id. Currently localizing to here until clear this should be
3992 // part of ObjCQualifiedIdTypesAreCompatible.
3993 compositeType = Context.getObjCIdType();
3994 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
Steve Naroff7154a772009-07-01 14:36:47 +00003995 compositeType = Context.getObjCIdType();
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00003996 } else if (!(compositeType =
3997 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
3998 ;
3999 else {
Steve Naroff7154a772009-07-01 14:36:47 +00004000 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
4001 << LHSTy << RHSTy
4002 << LHS->getSourceRange() << RHS->getSourceRange();
4003 QualType incompatTy = Context.getObjCIdType();
Eli Friedman73c39ab2009-10-20 08:27:19 +00004004 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
4005 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00004006 return incompatTy;
4007 }
4008 // The object pointer types are compatible.
Eli Friedman73c39ab2009-10-20 08:27:19 +00004009 ImpCastExprToType(LHS, compositeType, CastExpr::CK_BitCast);
4010 ImpCastExprToType(RHS, compositeType, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00004011 return compositeType;
4012 }
Steve Naroffc715e782009-07-29 15:09:39 +00004013 // Check Objective-C object pointer types and 'void *'
4014 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004015 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
John McCall183700f2009-09-21 23:43:11 +00004016 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00004017 QualType destPointee
4018 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
Steve Naroffc715e782009-07-29 15:09:39 +00004019 QualType destType = Context.getPointerType(destPointee);
Eli Friedman73c39ab2009-10-20 08:27:19 +00004020 // Add qualifiers if necessary.
4021 ImpCastExprToType(LHS, destType, CastExpr::CK_NoOp);
4022 // Promote to void*.
4023 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
Steve Naroffc715e782009-07-29 15:09:39 +00004024 return destType;
4025 }
4026 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
John McCall183700f2009-09-21 23:43:11 +00004027 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00004028 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00004029 QualType destPointee
4030 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
Steve Naroffc715e782009-07-29 15:09:39 +00004031 QualType destType = Context.getPointerType(destPointee);
Eli Friedman73c39ab2009-10-20 08:27:19 +00004032 // Add qualifiers if necessary.
4033 ImpCastExprToType(RHS, destType, CastExpr::CK_NoOp);
4034 // Promote to void*.
4035 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
Steve Naroffc715e782009-07-29 15:09:39 +00004036 return destType;
4037 }
Steve Naroff7154a772009-07-01 14:36:47 +00004038 // Check constraints for C object pointers types (C99 6.5.15p3,6).
4039 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
4040 // get the "pointed to" types
Ted Kremenek6217b802009-07-29 21:53:49 +00004041 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4042 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff7154a772009-07-01 14:36:47 +00004043
4044 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
4045 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
4046 // Figure out necessary qualifiers (C99 6.5.15p6)
John McCall0953e762009-09-24 19:53:00 +00004047 QualType destPointee
4048 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
Steve Naroff7154a772009-07-01 14:36:47 +00004049 QualType destType = Context.getPointerType(destPointee);
Eli Friedman73c39ab2009-10-20 08:27:19 +00004050 // Add qualifiers if necessary.
4051 ImpCastExprToType(LHS, destType, CastExpr::CK_NoOp);
4052 // Promote to void*.
4053 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00004054 return destType;
4055 }
4056 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
John McCall0953e762009-09-24 19:53:00 +00004057 QualType destPointee
4058 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
Steve Naroff7154a772009-07-01 14:36:47 +00004059 QualType destType = Context.getPointerType(destPointee);
Eli Friedman73c39ab2009-10-20 08:27:19 +00004060 // Add qualifiers if necessary.
Eli Friedman16fea9b2009-11-17 01:22:05 +00004061 ImpCastExprToType(RHS, destType, CastExpr::CK_NoOp);
Eli Friedman73c39ab2009-10-20 08:27:19 +00004062 // Promote to void*.
Eli Friedman16fea9b2009-11-17 01:22:05 +00004063 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00004064 return destType;
4065 }
4066
4067 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4068 // Two identical pointer types are always compatible.
4069 return LHSTy;
4070 }
4071 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
4072 rhptee.getUnqualifiedType())) {
4073 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
4074 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
4075 // In this situation, we assume void* type. No especially good
4076 // reason, but this is what gcc does, and we do have to pick
4077 // to get a consistent AST.
4078 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Eli Friedman73c39ab2009-10-20 08:27:19 +00004079 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
4080 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00004081 return incompatTy;
4082 }
4083 // The pointer types are compatible.
4084 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
4085 // differently qualified versions of compatible types, the result type is
4086 // a pointer to an appropriately qualified version of the *composite*
4087 // type.
4088 // FIXME: Need to calculate the composite type.
4089 // FIXME: Need to add qualifiers
Eli Friedman73c39ab2009-10-20 08:27:19 +00004090 ImpCastExprToType(LHS, LHSTy, CastExpr::CK_BitCast);
4091 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00004092 return LHSTy;
4093 }
Mike Stump1eb44332009-09-09 15:08:12 +00004094
Steve Naroff7154a772009-07-01 14:36:47 +00004095 // GCC compatibility: soften pointer/integer mismatch.
4096 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
4097 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4098 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00004099 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_IntegralToPointer);
Steve Naroff7154a772009-07-01 14:36:47 +00004100 return RHSTy;
4101 }
4102 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
4103 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4104 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00004105 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_IntegralToPointer);
Steve Naroff7154a772009-07-01 14:36:47 +00004106 return LHSTy;
4107 }
Daniel Dunbar5e155f02008-09-11 23:12:46 +00004108
Chris Lattner70d67a92008-01-06 22:42:25 +00004109 // Otherwise, the operands are not compatible.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004110 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
4111 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00004112 return QualType();
4113}
4114
Steve Narofff69936d2007-09-16 03:34:24 +00004115/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Reid Spencer5f016e22007-07-11 17:01:13 +00004116/// in the case of a the GNU conditional expr extension.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004117Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
4118 SourceLocation ColonLoc,
4119 ExprArg Cond, ExprArg LHS,
4120 ExprArg RHS) {
4121 Expr *CondExpr = (Expr *) Cond.get();
4122 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
Chris Lattnera21ddb32007-11-26 01:40:58 +00004123
4124 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
4125 // was the condition.
4126 bool isLHSNull = LHSExpr == 0;
4127 if (isLHSNull)
4128 LHSExpr = CondExpr;
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004129
4130 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
Chris Lattner26824902007-07-16 21:39:03 +00004131 RHSExpr, QuestionLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00004132 if (result.isNull())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004133 return ExprError();
4134
4135 Cond.release();
4136 LHS.release();
4137 RHS.release();
Douglas Gregor47e1f7c2009-08-26 14:37:04 +00004138 return Owned(new (Context) ConditionalOperator(CondExpr, QuestionLoc,
Steve Naroff6ece14c2009-01-21 00:14:39 +00004139 isLHSNull ? 0 : LHSExpr,
Douglas Gregor47e1f7c2009-08-26 14:37:04 +00004140 ColonLoc, RHSExpr, result));
Reid Spencer5f016e22007-07-11 17:01:13 +00004141}
4142
Reid Spencer5f016e22007-07-11 17:01:13 +00004143// CheckPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stumpeed9cac2009-02-19 03:04:26 +00004144// being closely modeled after the C99 spec:-). The odd characteristic of this
Reid Spencer5f016e22007-07-11 17:01:13 +00004145// routine is it effectively iqnores the qualifiers on the top level pointee.
4146// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
4147// FIXME: add a couple examples in this comment.
Mike Stumpeed9cac2009-02-19 03:04:26 +00004148Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00004149Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
4150 QualType lhptee, rhptee;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004151
David Chisnall0f436562009-08-17 16:35:33 +00004152 if ((lhsType->isObjCClassType() &&
4153 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
4154 (rhsType->isObjCClassType() &&
4155 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
4156 return Compatible;
4157 }
4158
Reid Spencer5f016e22007-07-11 17:01:13 +00004159 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenek6217b802009-07-29 21:53:49 +00004160 lhptee = lhsType->getAs<PointerType>()->getPointeeType();
4161 rhptee = rhsType->getAs<PointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004162
Reid Spencer5f016e22007-07-11 17:01:13 +00004163 // make sure we operate on the canonical type
Chris Lattnerb77792e2008-07-26 22:17:49 +00004164 lhptee = Context.getCanonicalType(lhptee);
4165 rhptee = Context.getCanonicalType(rhptee);
Reid Spencer5f016e22007-07-11 17:01:13 +00004166
Chris Lattner5cf216b2008-01-04 18:04:52 +00004167 AssignConvertType ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004168
4169 // C99 6.5.16.1p1: This following citation is common to constraints
4170 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
4171 // qualifiers of the type *pointed to* by the right;
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00004172 // FIXME: Handle ExtQualType
Douglas Gregor98cd5992008-10-21 23:43:52 +00004173 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner5cf216b2008-01-04 18:04:52 +00004174 ConvTy = CompatiblePointerDiscardsQualifiers;
Reid Spencer5f016e22007-07-11 17:01:13 +00004175
Mike Stumpeed9cac2009-02-19 03:04:26 +00004176 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
4177 // incomplete type and the other is a pointer to a qualified or unqualified
Reid Spencer5f016e22007-07-11 17:01:13 +00004178 // version of void...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00004179 if (lhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00004180 if (rhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00004181 return ConvTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004182
Chris Lattnerbfe639e2008-01-03 22:56:36 +00004183 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00004184 assert(rhptee->isFunctionType());
4185 return FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00004186 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004187
Chris Lattnerbfe639e2008-01-03 22:56:36 +00004188 if (rhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00004189 if (lhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00004190 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00004191
4192 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00004193 assert(lhptee->isFunctionType());
4194 return FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00004195 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004196 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Reid Spencer5f016e22007-07-11 17:01:13 +00004197 // unqualified versions of compatible types, ...
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004198 lhptee = lhptee.getUnqualifiedType();
4199 rhptee = rhptee.getUnqualifiedType();
4200 if (!Context.typesAreCompatible(lhptee, rhptee)) {
4201 // Check if the pointee types are compatible ignoring the sign.
4202 // We explicitly check for char so that we catch "char" vs
4203 // "unsigned char" on systems where "char" is unsigned.
Chris Lattner6a2b9262009-10-17 20:33:28 +00004204 if (lhptee->isCharType())
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004205 lhptee = Context.UnsignedCharTy;
Chris Lattner6a2b9262009-10-17 20:33:28 +00004206 else if (lhptee->isSignedIntegerType())
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004207 lhptee = Context.getCorrespondingUnsignedType(lhptee);
Chris Lattner6a2b9262009-10-17 20:33:28 +00004208
4209 if (rhptee->isCharType())
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004210 rhptee = Context.UnsignedCharTy;
Chris Lattner6a2b9262009-10-17 20:33:28 +00004211 else if (rhptee->isSignedIntegerType())
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004212 rhptee = Context.getCorrespondingUnsignedType(rhptee);
Chris Lattner6a2b9262009-10-17 20:33:28 +00004213
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004214 if (lhptee == rhptee) {
4215 // Types are compatible ignoring the sign. Qualifier incompatibility
4216 // takes priority over sign incompatibility because the sign
4217 // warning can be disabled.
4218 if (ConvTy != Compatible)
4219 return ConvTy;
4220 return IncompatiblePointerSign;
4221 }
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00004222
4223 // If we are a multi-level pointer, it's possible that our issue is simply
4224 // one of qualification - e.g. char ** -> const char ** is not allowed. If
4225 // the eventual target type is the same and the pointers have the same
4226 // level of indirection, this must be the issue.
4227 if (lhptee->isPointerType() && rhptee->isPointerType()) {
4228 do {
4229 lhptee = lhptee->getAs<PointerType>()->getPointeeType();
4230 rhptee = rhptee->getAs<PointerType>()->getPointeeType();
4231
4232 lhptee = Context.getCanonicalType(lhptee);
4233 rhptee = Context.getCanonicalType(rhptee);
4234 } while (lhptee->isPointerType() && rhptee->isPointerType());
4235
Douglas Gregora4923eb2009-11-16 21:35:15 +00004236 if (Context.hasSameUnqualifiedType(lhptee, rhptee))
Sean Huntc9132b62009-11-08 07:46:34 +00004237 return IncompatibleNestedPointerQualifiers;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00004238 }
4239
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004240 // General pointer incompatibility takes priority over qualifiers.
Mike Stump1eb44332009-09-09 15:08:12 +00004241 return IncompatiblePointer;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004242 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00004243 return ConvTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00004244}
4245
Steve Naroff1c7d0672008-09-04 15:10:53 +00004246/// CheckBlockPointerTypesForAssignment - This routine determines whether two
4247/// block pointer types are compatible or whether a block and normal pointer
4248/// are compatible. It is more restrict than comparing two function pointer
4249// types.
Mike Stumpeed9cac2009-02-19 03:04:26 +00004250Sema::AssignConvertType
4251Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
Steve Naroff1c7d0672008-09-04 15:10:53 +00004252 QualType rhsType) {
4253 QualType lhptee, rhptee;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004254
Steve Naroff1c7d0672008-09-04 15:10:53 +00004255 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenek6217b802009-07-29 21:53:49 +00004256 lhptee = lhsType->getAs<BlockPointerType>()->getPointeeType();
4257 rhptee = rhsType->getAs<BlockPointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004258
Steve Naroff1c7d0672008-09-04 15:10:53 +00004259 // make sure we operate on the canonical type
4260 lhptee = Context.getCanonicalType(lhptee);
4261 rhptee = Context.getCanonicalType(rhptee);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004262
Steve Naroff1c7d0672008-09-04 15:10:53 +00004263 AssignConvertType ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004264
Steve Naroff1c7d0672008-09-04 15:10:53 +00004265 // For blocks we enforce that qualifiers are identical.
Douglas Gregora4923eb2009-11-16 21:35:15 +00004266 if (lhptee.getLocalCVRQualifiers() != rhptee.getLocalCVRQualifiers())
Steve Naroff1c7d0672008-09-04 15:10:53 +00004267 ConvTy = CompatiblePointerDiscardsQualifiers;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004268
Eli Friedman26784c12009-06-08 05:08:54 +00004269 if (!Context.typesAreCompatible(lhptee, rhptee))
Mike Stumpeed9cac2009-02-19 03:04:26 +00004270 return IncompatibleBlockPointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00004271 return ConvTy;
4272}
4273
Mike Stumpeed9cac2009-02-19 03:04:26 +00004274/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
4275/// has code to accommodate several GCC extensions when type checking
Reid Spencer5f016e22007-07-11 17:01:13 +00004276/// pointers. Here are some objectionable examples that GCC considers warnings:
4277///
4278/// int a, *pint;
4279/// short *pshort;
4280/// struct foo *pfoo;
4281///
4282/// pint = pshort; // warning: assignment from incompatible pointer type
4283/// a = pint; // warning: assignment makes integer from pointer without a cast
4284/// pint = a; // warning: assignment makes pointer from integer without a cast
4285/// pint = pfoo; // warning: assignment from incompatible pointer type
4286///
4287/// As a result, the code for dealing with pointers is more complex than the
Mike Stumpeed9cac2009-02-19 03:04:26 +00004288/// C99 spec dictates.
Reid Spencer5f016e22007-07-11 17:01:13 +00004289///
Chris Lattner5cf216b2008-01-04 18:04:52 +00004290Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00004291Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattnerfc144e22008-01-04 23:18:45 +00004292 // Get canonical types. We're not formatting these types, just comparing
4293 // them.
Chris Lattnerb77792e2008-07-26 22:17:49 +00004294 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
4295 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedmanf8f873d2008-05-30 18:07:22 +00004296
4297 if (lhsType == rhsType)
Chris Lattnerd2656dd2008-01-07 17:51:46 +00004298 return Compatible; // Common case: fast path an exact match.
Steve Naroff700204c2007-07-24 21:46:40 +00004299
David Chisnall0f436562009-08-17 16:35:33 +00004300 if ((lhsType->isObjCClassType() &&
4301 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
4302 (rhsType->isObjCClassType() &&
4303 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
4304 return Compatible;
4305 }
4306
Douglas Gregor9d293df2008-10-28 00:22:11 +00004307 // If the left-hand side is a reference type, then we are in a
4308 // (rare!) case where we've allowed the use of references in C,
4309 // e.g., as a parameter type in a built-in function. In this case,
4310 // just make sure that the type referenced is compatible with the
4311 // right-hand side type. The caller is responsible for adjusting
4312 // lhsType so that the resulting expression does not have reference
4313 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00004314 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
Douglas Gregor9d293df2008-10-28 00:22:11 +00004315 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlsson793680e2007-10-12 23:56:29 +00004316 return Compatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00004317 return Incompatible;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00004318 }
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004319 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
4320 // to the same ExtVector type.
4321 if (lhsType->isExtVectorType()) {
4322 if (rhsType->isExtVectorType())
4323 return lhsType == rhsType ? Compatible : Incompatible;
4324 if (!rhsType->isVectorType() && rhsType->isArithmeticType())
4325 return Compatible;
4326 }
Mike Stump1eb44332009-09-09 15:08:12 +00004327
Nate Begemanbe2341d2008-07-14 18:02:46 +00004328 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00004329 // If we are allowing lax vector conversions, and LHS and RHS are both
Mike Stumpeed9cac2009-02-19 03:04:26 +00004330 // vectors, the total size only needs to be the same. This is a bitcast;
Nate Begemanbe2341d2008-07-14 18:02:46 +00004331 // no bits are changed but the result type is different.
Chris Lattnere8b3e962008-01-04 23:32:24 +00004332 if (getLangOptions().LaxVectorConversions &&
4333 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00004334 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00004335 return IncompatibleVectors;
Chris Lattnere8b3e962008-01-04 23:32:24 +00004336 }
4337 return Incompatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004338 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00004339
Chris Lattnere8b3e962008-01-04 23:32:24 +00004340 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Reid Spencer5f016e22007-07-11 17:01:13 +00004341 return Compatible;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00004342
Chris Lattner78eca282008-04-07 06:49:41 +00004343 if (isa<PointerType>(lhsType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00004344 if (rhsType->isIntegerType())
Chris Lattnerb7b61152008-01-04 18:22:42 +00004345 return IntToPointer;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00004346
Chris Lattner78eca282008-04-07 06:49:41 +00004347 if (isa<PointerType>(rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00004348 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004349
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004350 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff14108da2009-07-10 23:34:53 +00004351 if (isa<ObjCObjectPointerType>(rhsType)) {
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004352 if (lhsType->isVoidPointerType()) // an exception to the rule.
4353 return Compatible;
4354 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00004355 }
Ted Kremenek6217b802009-07-29 21:53:49 +00004356 if (rhsType->getAs<BlockPointerType>()) {
4357 if (lhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00004358 return Compatible;
Steve Naroffb4406862008-09-29 18:10:17 +00004359
4360 // Treat block pointers as objects.
Steve Naroff14108da2009-07-10 23:34:53 +00004361 if (getLangOptions().ObjC1 && lhsType->isObjCIdType())
Steve Naroffb4406862008-09-29 18:10:17 +00004362 return Compatible;
4363 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00004364 return Incompatible;
4365 }
4366
4367 if (isa<BlockPointerType>(lhsType)) {
4368 if (rhsType->isIntegerType())
Eli Friedmand8f4f432009-02-25 04:20:42 +00004369 return IntToBlockPointer;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004370
Steve Naroffb4406862008-09-29 18:10:17 +00004371 // Treat block pointers as objects.
Steve Naroff14108da2009-07-10 23:34:53 +00004372 if (getLangOptions().ObjC1 && rhsType->isObjCIdType())
Steve Naroffb4406862008-09-29 18:10:17 +00004373 return Compatible;
4374
Steve Naroff1c7d0672008-09-04 15:10:53 +00004375 if (rhsType->isBlockPointerType())
4376 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004377
Ted Kremenek6217b802009-07-29 21:53:49 +00004378 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff1c7d0672008-09-04 15:10:53 +00004379 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00004380 return Compatible;
Steve Naroff1c7d0672008-09-04 15:10:53 +00004381 }
Chris Lattnerfc144e22008-01-04 23:18:45 +00004382 return Incompatible;
4383 }
4384
Steve Naroff14108da2009-07-10 23:34:53 +00004385 if (isa<ObjCObjectPointerType>(lhsType)) {
4386 if (rhsType->isIntegerType())
4387 return IntToPointer;
Mike Stump1eb44332009-09-09 15:08:12 +00004388
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004389 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff14108da2009-07-10 23:34:53 +00004390 if (isa<PointerType>(rhsType)) {
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004391 if (rhsType->isVoidPointerType()) // an exception to the rule.
4392 return Compatible;
4393 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00004394 }
4395 if (rhsType->isObjCObjectPointerType()) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00004396 if (lhsType->isObjCBuiltinType() || rhsType->isObjCBuiltinType())
4397 return Compatible;
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004398 if (Context.typesAreCompatible(lhsType, rhsType))
4399 return Compatible;
Steve Naroff4084c302009-07-23 01:01:38 +00004400 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
4401 return IncompatibleObjCQualifiedId;
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004402 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00004403 }
Ted Kremenek6217b802009-07-29 21:53:49 +00004404 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00004405 if (RHSPT->getPointeeType()->isVoidType())
4406 return Compatible;
4407 }
4408 // Treat block pointers as objects.
4409 if (rhsType->isBlockPointerType())
4410 return Compatible;
4411 return Incompatible;
4412 }
Chris Lattner78eca282008-04-07 06:49:41 +00004413 if (isa<PointerType>(rhsType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00004414 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedmanf8f873d2008-05-30 18:07:22 +00004415 if (lhsType == Context.BoolTy)
4416 return Compatible;
4417
4418 if (lhsType->isIntegerType())
Chris Lattnerb7b61152008-01-04 18:22:42 +00004419 return PointerToInt;
Reid Spencer5f016e22007-07-11 17:01:13 +00004420
Mike Stumpeed9cac2009-02-19 03:04:26 +00004421 if (isa<PointerType>(lhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00004422 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004423
4424 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenek6217b802009-07-29 21:53:49 +00004425 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00004426 return Compatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00004427 return Incompatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00004428 }
Steve Naroff14108da2009-07-10 23:34:53 +00004429 if (isa<ObjCObjectPointerType>(rhsType)) {
4430 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
4431 if (lhsType == Context.BoolTy)
4432 return Compatible;
4433
4434 if (lhsType->isIntegerType())
4435 return PointerToInt;
4436
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004437 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff14108da2009-07-10 23:34:53 +00004438 if (isa<PointerType>(lhsType)) {
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004439 if (lhsType->isVoidPointerType()) // an exception to the rule.
4440 return Compatible;
4441 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00004442 }
4443 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenek6217b802009-07-29 21:53:49 +00004444 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Steve Naroff14108da2009-07-10 23:34:53 +00004445 return Compatible;
4446 return Incompatible;
4447 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00004448
Chris Lattnerfc144e22008-01-04 23:18:45 +00004449 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner78eca282008-04-07 06:49:41 +00004450 if (Context.typesAreCompatible(lhsType, rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00004451 return Compatible;
Reid Spencer5f016e22007-07-11 17:01:13 +00004452 }
4453 return Incompatible;
4454}
4455
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004456/// \brief Constructs a transparent union from an expression that is
4457/// used to initialize the transparent union.
Mike Stump1eb44332009-09-09 15:08:12 +00004458static void ConstructTransparentUnion(ASTContext &C, Expr *&E,
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004459 QualType UnionType, FieldDecl *Field) {
4460 // Build an initializer list that designates the appropriate member
4461 // of the transparent union.
4462 InitListExpr *Initializer = new (C) InitListExpr(SourceLocation(),
4463 &E, 1,
4464 SourceLocation());
4465 Initializer->setType(UnionType);
4466 Initializer->setInitializedFieldInUnion(Field);
4467
4468 // Build a compound literal constructing a value of the transparent
4469 // union type from this initializer list.
4470 E = new (C) CompoundLiteralExpr(SourceLocation(), UnionType, Initializer,
4471 false);
4472}
4473
4474Sema::AssignConvertType
4475Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) {
4476 QualType FromType = rExpr->getType();
4477
Mike Stump1eb44332009-09-09 15:08:12 +00004478 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004479 // transparent_union GCC extension.
4480 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00004481 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004482 return Incompatible;
4483
4484 // The field to initialize within the transparent union.
4485 RecordDecl *UD = UT->getDecl();
4486 FieldDecl *InitField = 0;
4487 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004488 for (RecordDecl::field_iterator it = UD->field_begin(),
4489 itend = UD->field_end();
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004490 it != itend; ++it) {
4491 if (it->getType()->isPointerType()) {
4492 // If the transparent union contains a pointer type, we allow:
4493 // 1) void pointer
4494 // 2) null pointer constant
4495 if (FromType->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +00004496 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004497 ImpCastExprToType(rExpr, it->getType(), CastExpr::CK_BitCast);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004498 InitField = *it;
4499 break;
4500 }
Mike Stump1eb44332009-09-09 15:08:12 +00004501
Douglas Gregorce940492009-09-25 04:25:58 +00004502 if (rExpr->isNullPointerConstant(Context,
4503 Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004504 ImpCastExprToType(rExpr, it->getType(), CastExpr::CK_IntegralToPointer);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004505 InitField = *it;
4506 break;
4507 }
4508 }
4509
4510 if (CheckAssignmentConstraints(it->getType(), rExpr->getType())
4511 == Compatible) {
4512 InitField = *it;
4513 break;
4514 }
4515 }
4516
4517 if (!InitField)
4518 return Incompatible;
4519
4520 ConstructTransparentUnion(Context, rExpr, ArgType, InitField);
4521 return Compatible;
4522}
4523
Chris Lattner5cf216b2008-01-04 18:04:52 +00004524Sema::AssignConvertType
Steve Naroff90045e82007-07-13 23:32:42 +00004525Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00004526 if (getLangOptions().CPlusPlus) {
4527 if (!lhsType->isRecordType()) {
4528 // C++ 5.17p3: If the left operand is not of class type, the
4529 // expression is implicitly converted (C++ 4) to the
4530 // cv-unqualified type of the left operand.
Douglas Gregor45920e82008-12-19 17:40:08 +00004531 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
4532 "assigning"))
Douglas Gregor98cd5992008-10-21 23:43:52 +00004533 return Incompatible;
Chris Lattner2c4463f2009-04-12 09:02:39 +00004534 return Compatible;
Douglas Gregor98cd5992008-10-21 23:43:52 +00004535 }
4536
4537 // FIXME: Currently, we fall through and treat C++ classes like C
4538 // structures.
4539 }
4540
Steve Naroff529a4ad2007-11-27 17:58:44 +00004541 // C99 6.5.16.1p1: the left operand is a pointer and the right is
4542 // a null pointer constant.
Mike Stump1eb44332009-09-09 15:08:12 +00004543 if ((lhsType->isPointerType() ||
4544 lhsType->isObjCObjectPointerType() ||
Mike Stumpeed9cac2009-02-19 03:04:26 +00004545 lhsType->isBlockPointerType())
Douglas Gregorce940492009-09-25 04:25:58 +00004546 && rExpr->isNullPointerConstant(Context,
4547 Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004548 ImpCastExprToType(rExpr, lhsType, CastExpr::CK_Unknown);
Steve Naroff529a4ad2007-11-27 17:58:44 +00004549 return Compatible;
4550 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004551
Chris Lattner943140e2007-10-16 02:55:40 +00004552 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroff90045e82007-07-13 23:32:42 +00004553 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregor02a24ee2009-11-03 16:56:39 +00004554 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Steve Naroff90045e82007-07-13 23:32:42 +00004555 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner943140e2007-10-16 02:55:40 +00004556 //
Mike Stumpeed9cac2009-02-19 03:04:26 +00004557 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner943140e2007-10-16 02:55:40 +00004558 if (!lhsType->isReferenceType())
4559 DefaultFunctionArrayConversion(rExpr);
Steve Narofff1120de2007-08-24 22:33:52 +00004560
Chris Lattner5cf216b2008-01-04 18:04:52 +00004561 Sema::AssignConvertType result =
4562 CheckAssignmentConstraints(lhsType, rExpr->getType());
Mike Stumpeed9cac2009-02-19 03:04:26 +00004563
Steve Narofff1120de2007-08-24 22:33:52 +00004564 // C99 6.5.16.1p2: The value of the right operand is converted to the
4565 // type of the assignment expression.
Douglas Gregor9d293df2008-10-28 00:22:11 +00004566 // CheckAssignmentConstraints allows the left-hand side to be a reference,
4567 // so that we can use references in built-in functions even in C.
4568 // The getNonReferenceType() call makes sure that the resulting expression
4569 // does not have reference type.
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004570 if (result != Incompatible && rExpr->getType() != lhsType)
Eli Friedman73c39ab2009-10-20 08:27:19 +00004571 ImpCastExprToType(rExpr, lhsType.getNonReferenceType(),
4572 CastExpr::CK_Unknown);
Steve Narofff1120de2007-08-24 22:33:52 +00004573 return result;
Steve Naroff90045e82007-07-13 23:32:42 +00004574}
4575
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004576QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004577 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattner22caddc2008-11-23 09:13:29 +00004578 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004579 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerca5eede2007-12-12 05:47:28 +00004580 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00004581}
4582
Mike Stumpeed9cac2009-02-19 03:04:26 +00004583inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Steve Naroff49b45262007-07-13 16:58:59 +00004584 Expr *&rex) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00004585 // For conversion purposes, we ignore any qualifiers.
Nate Begeman1330b0e2008-04-04 01:30:25 +00004586 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +00004587 QualType lhsType =
4588 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
4589 QualType rhsType =
4590 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004591
Nate Begemanbe2341d2008-07-14 18:02:46 +00004592 // If the vector types are identical, return.
Nate Begeman1330b0e2008-04-04 01:30:25 +00004593 if (lhsType == rhsType)
Reid Spencer5f016e22007-07-11 17:01:13 +00004594 return lhsType;
Nate Begeman4119d1a2007-12-30 02:59:45 +00004595
Nate Begemanbe2341d2008-07-14 18:02:46 +00004596 // Handle the case of a vector & extvector type of the same size and element
4597 // type. It would be nice if we only had one vector type someday.
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00004598 if (getLangOptions().LaxVectorConversions) {
4599 // FIXME: Should we warn here?
John McCall183700f2009-09-21 23:43:11 +00004600 if (const VectorType *LV = lhsType->getAs<VectorType>()) {
4601 if (const VectorType *RV = rhsType->getAs<VectorType>())
Nate Begemanbe2341d2008-07-14 18:02:46 +00004602 if (LV->getElementType() == RV->getElementType() &&
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00004603 LV->getNumElements() == RV->getNumElements()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00004604 return lhsType->isExtVectorType() ? lhsType : rhsType;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00004605 }
4606 }
4607 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004608
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004609 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
4610 // swap back (so that we don't reverse the inputs to a subtract, for instance.
4611 bool swapped = false;
4612 if (rhsType->isExtVectorType()) {
4613 swapped = true;
4614 std::swap(rex, lex);
4615 std::swap(rhsType, lhsType);
4616 }
Mike Stump1eb44332009-09-09 15:08:12 +00004617
Nate Begemandde25982009-06-28 19:12:57 +00004618 // Handle the case of an ext vector and scalar.
John McCall183700f2009-09-21 23:43:11 +00004619 if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) {
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004620 QualType EltTy = LV->getElementType();
4621 if (EltTy->isIntegralType() && rhsType->isIntegralType()) {
4622 if (Context.getIntegerTypeOrder(EltTy, rhsType) >= 0) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004623 ImpCastExprToType(rex, lhsType, CastExpr::CK_IntegralCast);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004624 if (swapped) std::swap(rex, lex);
4625 return lhsType;
4626 }
4627 }
4628 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
4629 rhsType->isRealFloatingType()) {
4630 if (Context.getFloatingTypeOrder(EltTy, rhsType) >= 0) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004631 ImpCastExprToType(rex, lhsType, CastExpr::CK_FloatingCast);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004632 if (swapped) std::swap(rex, lex);
4633 return lhsType;
4634 }
Nate Begeman4119d1a2007-12-30 02:59:45 +00004635 }
4636 }
Mike Stump1eb44332009-09-09 15:08:12 +00004637
Nate Begemandde25982009-06-28 19:12:57 +00004638 // Vectors of different size or scalar and non-ext-vector are errors.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004639 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattnerd1625842008-11-24 06:25:27 +00004640 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004641 << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00004642 return QualType();
Sebastian Redl22460502009-02-07 00:15:38 +00004643}
4644
Reid Spencer5f016e22007-07-11 17:01:13 +00004645inline QualType Sema::CheckMultiplyDivideOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00004646 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Daniel Dunbar69d1d002009-01-05 22:42:10 +00004647 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004648 return CheckVectorOperands(Loc, lex, rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004649
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004650 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004651
Steve Naroffa4332e22007-07-17 00:58:39 +00004652 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004653 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004654 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00004655}
4656
4657inline QualType Sema::CheckRemainderOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00004658 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Daniel Dunbar523aa602009-01-05 22:55:36 +00004659 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4660 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
4661 return CheckVectorOperands(Loc, lex, rex);
4662 return InvalidOperands(Loc, lex, rex);
4663 }
Steve Naroff90045e82007-07-13 23:32:42 +00004664
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004665 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004666
Steve Naroffa4332e22007-07-17 00:58:39 +00004667 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004668 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004669 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00004670}
4671
4672inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Mike Stump1eb44332009-09-09 15:08:12 +00004673 Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00004674 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4675 QualType compType = CheckVectorOperands(Loc, lex, rex);
4676 if (CompLHSTy) *CompLHSTy = compType;
4677 return compType;
4678 }
Steve Naroff49b45262007-07-13 16:58:59 +00004679
Eli Friedmanab3a8522009-03-28 01:22:36 +00004680 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Eli Friedmand72d16e2008-05-18 18:08:51 +00004681
Reid Spencer5f016e22007-07-11 17:01:13 +00004682 // handle the common case first (both operands are arithmetic).
Eli Friedmanab3a8522009-03-28 01:22:36 +00004683 if (lex->getType()->isArithmeticType() &&
4684 rex->getType()->isArithmeticType()) {
4685 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004686 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00004687 }
Reid Spencer5f016e22007-07-11 17:01:13 +00004688
Eli Friedmand72d16e2008-05-18 18:08:51 +00004689 // Put any potential pointer into PExp
4690 Expr* PExp = lex, *IExp = rex;
Steve Naroff58f9f2c2009-07-14 18:25:06 +00004691 if (IExp->getType()->isAnyPointerType())
Eli Friedmand72d16e2008-05-18 18:08:51 +00004692 std::swap(PExp, IExp);
4693
Steve Naroff58f9f2c2009-07-14 18:25:06 +00004694 if (PExp->getType()->isAnyPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004695
Eli Friedmand72d16e2008-05-18 18:08:51 +00004696 if (IExp->getType()->isIntegerType()) {
Steve Naroff760e3c42009-07-13 21:20:41 +00004697 QualType PointeeTy = PExp->getType()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00004698
Chris Lattnerb5f15622009-04-24 23:50:08 +00004699 // Check for arithmetic on pointers to incomplete types.
4700 if (PointeeTy->isVoidType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +00004701 if (getLangOptions().CPlusPlus) {
4702 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004703 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004704 return QualType();
Eli Friedmand72d16e2008-05-18 18:08:51 +00004705 }
Douglas Gregore7450f52009-03-24 19:52:54 +00004706
4707 // GNU extension: arithmetic on pointer to void
4708 Diag(Loc, diag::ext_gnu_void_ptr)
4709 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerb5f15622009-04-24 23:50:08 +00004710 } else if (PointeeTy->isFunctionType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +00004711 if (getLangOptions().CPlusPlus) {
4712 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
4713 << lex->getType() << lex->getSourceRange();
4714 return QualType();
4715 }
4716
4717 // GNU extension: arithmetic on pointer to function
4718 Diag(Loc, diag::ext_gnu_ptr_func_arith)
4719 << lex->getType() << lex->getSourceRange();
Steve Naroff9deaeca2009-07-13 21:32:29 +00004720 } else {
Steve Naroff760e3c42009-07-13 21:20:41 +00004721 // Check if we require a complete type.
Mike Stump1eb44332009-09-09 15:08:12 +00004722 if (((PExp->getType()->isPointerType() &&
Steve Naroff9deaeca2009-07-13 21:32:29 +00004723 !PExp->getType()->isDependentType()) ||
Steve Naroff760e3c42009-07-13 21:20:41 +00004724 PExp->getType()->isObjCObjectPointerType()) &&
4725 RequireCompleteType(Loc, PointeeTy,
Mike Stump1eb44332009-09-09 15:08:12 +00004726 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
4727 << PExp->getSourceRange()
Anders Carlssond497ba72009-08-26 22:59:12 +00004728 << PExp->getType()))
Steve Naroff760e3c42009-07-13 21:20:41 +00004729 return QualType();
4730 }
Chris Lattnerb5f15622009-04-24 23:50:08 +00004731 // Diagnose bad cases where we step over interface counts.
4732 if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4733 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
4734 << PointeeTy << PExp->getSourceRange();
4735 return QualType();
4736 }
Mike Stump1eb44332009-09-09 15:08:12 +00004737
Eli Friedmanab3a8522009-03-28 01:22:36 +00004738 if (CompLHSTy) {
Eli Friedman04e83572009-08-20 04:21:42 +00004739 QualType LHSTy = Context.isPromotableBitField(lex);
4740 if (LHSTy.isNull()) {
4741 LHSTy = lex->getType();
4742 if (LHSTy->isPromotableIntegerType())
4743 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregor2d833e32009-05-02 00:36:19 +00004744 }
Eli Friedmanab3a8522009-03-28 01:22:36 +00004745 *CompLHSTy = LHSTy;
4746 }
Eli Friedmand72d16e2008-05-18 18:08:51 +00004747 return PExp->getType();
4748 }
4749 }
4750
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004751 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00004752}
4753
Chris Lattnereca7be62008-04-07 05:30:13 +00004754// C99 6.5.6
4755QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Eli Friedmanab3a8522009-03-28 01:22:36 +00004756 SourceLocation Loc, QualType* CompLHSTy) {
4757 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4758 QualType compType = CheckVectorOperands(Loc, lex, rex);
4759 if (CompLHSTy) *CompLHSTy = compType;
4760 return compType;
4761 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004762
Eli Friedmanab3a8522009-03-28 01:22:36 +00004763 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004764
Chris Lattner6e4ab612007-12-09 21:53:25 +00004765 // Enforce type constraints: C99 6.5.6p3.
Mike Stumpeed9cac2009-02-19 03:04:26 +00004766
Chris Lattner6e4ab612007-12-09 21:53:25 +00004767 // Handle the common case first (both operands are arithmetic).
Mike Stumpaf199f32009-05-07 18:43:07 +00004768 if (lex->getType()->isArithmeticType()
4769 && rex->getType()->isArithmeticType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00004770 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004771 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00004772 }
Mike Stump1eb44332009-09-09 15:08:12 +00004773
Chris Lattner6e4ab612007-12-09 21:53:25 +00004774 // Either ptr - int or ptr - ptr.
Steve Naroff58f9f2c2009-07-14 18:25:06 +00004775 if (lex->getType()->isAnyPointerType()) {
Steve Naroff430ee5a2009-07-13 17:19:15 +00004776 QualType lpointee = lex->getType()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004777
Douglas Gregore7450f52009-03-24 19:52:54 +00004778 // The LHS must be an completely-defined object type.
Douglas Gregorc983b862009-01-23 00:36:41 +00004779
Douglas Gregore7450f52009-03-24 19:52:54 +00004780 bool ComplainAboutVoid = false;
4781 Expr *ComplainAboutFunc = 0;
4782 if (lpointee->isVoidType()) {
4783 if (getLangOptions().CPlusPlus) {
4784 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
4785 << lex->getSourceRange() << rex->getSourceRange();
4786 return QualType();
4787 }
4788
4789 // GNU C extension: arithmetic on pointer to void
4790 ComplainAboutVoid = true;
4791 } else if (lpointee->isFunctionType()) {
4792 if (getLangOptions().CPlusPlus) {
4793 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattnerd1625842008-11-24 06:25:27 +00004794 << lex->getType() << lex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00004795 return QualType();
4796 }
Douglas Gregore7450f52009-03-24 19:52:54 +00004797
4798 // GNU C extension: arithmetic on pointer to function
4799 ComplainAboutFunc = lex;
4800 } else if (!lpointee->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00004801 RequireCompleteType(Loc, lpointee,
Anders Carlssond497ba72009-08-26 22:59:12 +00004802 PDiag(diag::err_typecheck_sub_ptr_object)
Mike Stump1eb44332009-09-09 15:08:12 +00004803 << lex->getSourceRange()
Anders Carlssond497ba72009-08-26 22:59:12 +00004804 << lex->getType()))
Douglas Gregore7450f52009-03-24 19:52:54 +00004805 return QualType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00004806
Chris Lattnerb5f15622009-04-24 23:50:08 +00004807 // Diagnose bad cases where we step over interface counts.
4808 if (lpointee->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4809 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
4810 << lpointee << lex->getSourceRange();
4811 return QualType();
4812 }
Mike Stump1eb44332009-09-09 15:08:12 +00004813
Chris Lattner6e4ab612007-12-09 21:53:25 +00004814 // The result type of a pointer-int computation is the pointer type.
Douglas Gregore7450f52009-03-24 19:52:54 +00004815 if (rex->getType()->isIntegerType()) {
4816 if (ComplainAboutVoid)
4817 Diag(Loc, diag::ext_gnu_void_ptr)
4818 << lex->getSourceRange() << rex->getSourceRange();
4819 if (ComplainAboutFunc)
4820 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump1eb44332009-09-09 15:08:12 +00004821 << ComplainAboutFunc->getType()
Douglas Gregore7450f52009-03-24 19:52:54 +00004822 << ComplainAboutFunc->getSourceRange();
4823
Eli Friedmanab3a8522009-03-28 01:22:36 +00004824 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00004825 return lex->getType();
Douglas Gregore7450f52009-03-24 19:52:54 +00004826 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004827
Chris Lattner6e4ab612007-12-09 21:53:25 +00004828 // Handle pointer-pointer subtractions.
Ted Kremenek6217b802009-07-29 21:53:49 +00004829 if (const PointerType *RHSPTy = rex->getType()->getAs<PointerType>()) {
Eli Friedman8e54ad02008-02-08 01:19:44 +00004830 QualType rpointee = RHSPTy->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004831
Douglas Gregore7450f52009-03-24 19:52:54 +00004832 // RHS must be a completely-type object type.
4833 // Handle the GNU void* extension.
4834 if (rpointee->isVoidType()) {
4835 if (getLangOptions().CPlusPlus) {
4836 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
4837 << lex->getSourceRange() << rex->getSourceRange();
4838 return QualType();
4839 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004840
Douglas Gregore7450f52009-03-24 19:52:54 +00004841 ComplainAboutVoid = true;
4842 } else if (rpointee->isFunctionType()) {
4843 if (getLangOptions().CPlusPlus) {
4844 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattnerd1625842008-11-24 06:25:27 +00004845 << rex->getType() << rex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00004846 return QualType();
4847 }
Douglas Gregore7450f52009-03-24 19:52:54 +00004848
4849 // GNU extension: arithmetic on pointer to function
4850 if (!ComplainAboutFunc)
4851 ComplainAboutFunc = rex;
4852 } else if (!rpointee->isDependentType() &&
4853 RequireCompleteType(Loc, rpointee,
Anders Carlssond497ba72009-08-26 22:59:12 +00004854 PDiag(diag::err_typecheck_sub_ptr_object)
4855 << rex->getSourceRange()
4856 << rex->getType()))
Douglas Gregore7450f52009-03-24 19:52:54 +00004857 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004858
Eli Friedman88d936b2009-05-16 13:54:38 +00004859 if (getLangOptions().CPlusPlus) {
4860 // Pointee types must be the same: C++ [expr.add]
4861 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
4862 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
4863 << lex->getType() << rex->getType()
4864 << lex->getSourceRange() << rex->getSourceRange();
4865 return QualType();
4866 }
4867 } else {
4868 // Pointee types must be compatible C99 6.5.6p3
4869 if (!Context.typesAreCompatible(
4870 Context.getCanonicalType(lpointee).getUnqualifiedType(),
4871 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
4872 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
4873 << lex->getType() << rex->getType()
4874 << lex->getSourceRange() << rex->getSourceRange();
4875 return QualType();
4876 }
Chris Lattner6e4ab612007-12-09 21:53:25 +00004877 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004878
Douglas Gregore7450f52009-03-24 19:52:54 +00004879 if (ComplainAboutVoid)
4880 Diag(Loc, diag::ext_gnu_void_ptr)
4881 << lex->getSourceRange() << rex->getSourceRange();
4882 if (ComplainAboutFunc)
4883 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump1eb44332009-09-09 15:08:12 +00004884 << ComplainAboutFunc->getType()
Douglas Gregore7450f52009-03-24 19:52:54 +00004885 << ComplainAboutFunc->getSourceRange();
Eli Friedmanab3a8522009-03-28 01:22:36 +00004886
4887 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00004888 return Context.getPointerDiffType();
4889 }
4890 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004891
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004892 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00004893}
4894
Chris Lattnereca7be62008-04-07 05:30:13 +00004895// C99 6.5.7
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004896QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnereca7be62008-04-07 05:30:13 +00004897 bool isCompAssign) {
Chris Lattnerca5eede2007-12-12 05:47:28 +00004898 // C99 6.5.7p2: Each of the operands shall have integer type.
4899 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004900 return InvalidOperands(Loc, lex, rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004901
Nate Begeman2207d792009-10-25 02:26:48 +00004902 // Vector shifts promote their scalar inputs to vector type.
4903 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
4904 return CheckVectorOperands(Loc, lex, rex);
4905
Chris Lattnerca5eede2007-12-12 05:47:28 +00004906 // Shifts don't perform usual arithmetic conversions, they just do integer
4907 // promotions on each operand. C99 6.5.7p3
Eli Friedman04e83572009-08-20 04:21:42 +00004908 QualType LHSTy = Context.isPromotableBitField(lex);
4909 if (LHSTy.isNull()) {
4910 LHSTy = lex->getType();
4911 if (LHSTy->isPromotableIntegerType())
4912 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregor2d833e32009-05-02 00:36:19 +00004913 }
Chris Lattner1dcf2c82007-12-13 07:28:16 +00004914 if (!isCompAssign)
Eli Friedman73c39ab2009-10-20 08:27:19 +00004915 ImpCastExprToType(lex, LHSTy, CastExpr::CK_IntegralCast);
Eli Friedmanab3a8522009-03-28 01:22:36 +00004916
Chris Lattnerca5eede2007-12-12 05:47:28 +00004917 UsualUnaryConversions(rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004918
Ryan Flynnd0439682009-08-07 16:20:20 +00004919 // Sanity-check shift operands
4920 llvm::APSInt Right;
4921 // Check right/shifter operand
Daniel Dunbar3f180c62009-09-17 06:31:27 +00004922 if (!rex->isValueDependent() &&
4923 rex->isIntegerConstantExpr(Right, Context)) {
Ryan Flynn8045c732009-08-08 19:18:23 +00004924 if (Right.isNegative())
Ryan Flynnd0439682009-08-07 16:20:20 +00004925 Diag(Loc, diag::warn_shift_negative) << rex->getSourceRange();
4926 else {
4927 llvm::APInt LeftBits(Right.getBitWidth(),
4928 Context.getTypeSize(lex->getType()));
4929 if (Right.uge(LeftBits))
4930 Diag(Loc, diag::warn_shift_gt_typewidth) << rex->getSourceRange();
4931 }
4932 }
4933
Chris Lattnerca5eede2007-12-12 05:47:28 +00004934 // "The type of the result is that of the promoted left operand."
Eli Friedmanab3a8522009-03-28 01:22:36 +00004935 return LHSTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00004936}
4937
John McCall5dbad3d2009-11-06 08:49:08 +00004938/// \brief Implements -Wsign-compare.
4939///
4940/// \param lex the left-hand expression
4941/// \param rex the right-hand expression
4942/// \param OpLoc the location of the joining operator
John McCall48f5e632009-11-06 08:53:51 +00004943/// \param Equality whether this is an "equality-like" join, which
4944/// suppresses the warning in some cases
John McCallb13c87f2009-11-05 09:23:39 +00004945void Sema::CheckSignCompare(Expr *lex, Expr *rex, SourceLocation OpLoc,
John McCall5dbad3d2009-11-06 08:49:08 +00004946 const PartialDiagnostic &PD, bool Equality) {
John McCall7d62a8f2009-11-06 18:16:06 +00004947 // Don't warn if we're in an unevaluated context.
Douglas Gregor2afce722009-11-26 00:44:06 +00004948 if (ExprEvalContexts.back().Context == Unevaluated)
John McCall7d62a8f2009-11-06 18:16:06 +00004949 return;
4950
John McCall45aa4552009-11-05 00:40:04 +00004951 QualType lt = lex->getType(), rt = rex->getType();
4952
4953 // Only warn if both operands are integral.
4954 if (!lt->isIntegerType() || !rt->isIntegerType())
4955 return;
4956
Sebastian Redl732429c2009-11-05 21:09:23 +00004957 // If either expression is value-dependent, don't warn. We'll get another
4958 // chance at instantiation time.
4959 if (lex->isValueDependent() || rex->isValueDependent())
4960 return;
4961
John McCall45aa4552009-11-05 00:40:04 +00004962 // The rule is that the signed operand becomes unsigned, so isolate the
4963 // signed operand.
John McCall5dbad3d2009-11-06 08:49:08 +00004964 Expr *signedOperand, *unsignedOperand;
John McCall45aa4552009-11-05 00:40:04 +00004965 if (lt->isSignedIntegerType()) {
4966 if (rt->isSignedIntegerType()) return;
4967 signedOperand = lex;
John McCall5dbad3d2009-11-06 08:49:08 +00004968 unsignedOperand = rex;
John McCall45aa4552009-11-05 00:40:04 +00004969 } else {
4970 if (!rt->isSignedIntegerType()) return;
4971 signedOperand = rex;
John McCall5dbad3d2009-11-06 08:49:08 +00004972 unsignedOperand = lex;
John McCall45aa4552009-11-05 00:40:04 +00004973 }
4974
John McCall5dbad3d2009-11-06 08:49:08 +00004975 // If the unsigned type is strictly smaller than the signed type,
John McCall48f5e632009-11-06 08:53:51 +00004976 // then (1) the result type will be signed and (2) the unsigned
4977 // value will fit fully within the signed type, and thus the result
John McCall5dbad3d2009-11-06 08:49:08 +00004978 // of the comparison will be exact.
4979 if (Context.getIntWidth(signedOperand->getType()) >
4980 Context.getIntWidth(unsignedOperand->getType()))
4981 return;
4982
John McCall45aa4552009-11-05 00:40:04 +00004983 // If the value is a non-negative integer constant, then the
4984 // signed->unsigned conversion won't change it.
4985 llvm::APSInt value;
John McCallb13c87f2009-11-05 09:23:39 +00004986 if (signedOperand->isIntegerConstantExpr(value, Context)) {
John McCall45aa4552009-11-05 00:40:04 +00004987 assert(value.isSigned() && "result of signed expression not signed");
4988
4989 if (value.isNonNegative())
4990 return;
4991 }
4992
John McCall5dbad3d2009-11-06 08:49:08 +00004993 if (Equality) {
4994 // For (in)equality comparisons, if the unsigned operand is a
John McCall48f5e632009-11-06 08:53:51 +00004995 // constant which cannot collide with a overflowed signed operand,
4996 // then reinterpreting the signed operand as unsigned will not
4997 // change the result of the comparison.
John McCall5dbad3d2009-11-06 08:49:08 +00004998 if (unsignedOperand->isIntegerConstantExpr(value, Context)) {
4999 assert(!value.isSigned() && "result of unsigned expression is signed");
5000
5001 // 2's complement: test the top bit.
5002 if (value.isNonNegative())
5003 return;
5004 }
5005 }
5006
John McCallb13c87f2009-11-05 09:23:39 +00005007 Diag(OpLoc, PD)
John McCall45aa4552009-11-05 00:40:04 +00005008 << lex->getType() << rex->getType()
5009 << lex->getSourceRange() << rex->getSourceRange();
5010}
5011
Douglas Gregor0c6db942009-05-04 06:07:12 +00005012// C99 6.5.8, C++ [expr.rel]
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005013QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Douglas Gregora86b8322009-04-06 18:45:53 +00005014 unsigned OpaqueOpc, bool isRelational) {
5015 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)OpaqueOpc;
5016
Chris Lattner02dd4b12009-12-05 05:40:13 +00005017 // Handle vector comparisons separately.
Nate Begemanbe2341d2008-07-14 18:02:46 +00005018 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005019 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005020
John McCall5dbad3d2009-11-06 08:49:08 +00005021 CheckSignCompare(lex, rex, Loc, diag::warn_mixed_sign_comparison,
5022 (Opc == BinaryOperator::EQ || Opc == BinaryOperator::NE));
John McCall45aa4552009-11-05 00:40:04 +00005023
Chris Lattnera5937dd2007-08-26 01:18:55 +00005024 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroff30bf7712007-08-10 18:26:40 +00005025 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
5026 UsualArithmeticConversions(lex, rex);
5027 else {
5028 UsualUnaryConversions(lex);
5029 UsualUnaryConversions(rex);
5030 }
Steve Naroffc80b4ee2007-07-16 21:54:35 +00005031 QualType lType = lex->getType();
5032 QualType rType = rex->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005033
Mike Stumpaf199f32009-05-07 18:43:07 +00005034 if (!lType->isFloatingType()
5035 && !(lType->isBlockPointerType() && isRelational)) {
Chris Lattner55660a72009-03-08 19:39:53 +00005036 // For non-floating point types, check for self-comparisons of the form
5037 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
5038 // often indicate logic errors in the program.
Mike Stump1eb44332009-09-09 15:08:12 +00005039 // NOTE: Don't warn about comparisons of enum constants. These can arise
Ted Kremenek9ecede72009-03-20 19:57:37 +00005040 // from macro expansions, and are usually quite deliberate.
Chris Lattner55660a72009-03-08 19:39:53 +00005041 Expr *LHSStripped = lex->IgnoreParens();
5042 Expr *RHSStripped = rex->IgnoreParens();
5043 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped))
5044 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped))
Ted Kremenekb82dcd82009-03-20 18:35:45 +00005045 if (DRL->getDecl() == DRR->getDecl() &&
5046 !isa<EnumConstantDecl>(DRL->getDecl()))
Mike Stumpeed9cac2009-02-19 03:04:26 +00005047 Diag(Loc, diag::warn_selfcomparison);
Mike Stump1eb44332009-09-09 15:08:12 +00005048
Chris Lattner55660a72009-03-08 19:39:53 +00005049 if (isa<CastExpr>(LHSStripped))
5050 LHSStripped = LHSStripped->IgnoreParenCasts();
5051 if (isa<CastExpr>(RHSStripped))
5052 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00005053
Chris Lattner55660a72009-03-08 19:39:53 +00005054 // Warn about comparisons against a string constant (unless the other
5055 // operand is null), the user probably wants strcmp.
Douglas Gregora86b8322009-04-06 18:45:53 +00005056 Expr *literalString = 0;
5057 Expr *literalStringStripped = 0;
Chris Lattner55660a72009-03-08 19:39:53 +00005058 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Douglas Gregorce940492009-09-25 04:25:58 +00005059 !RHSStripped->isNullPointerConstant(Context,
5060 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregora86b8322009-04-06 18:45:53 +00005061 literalString = lex;
5062 literalStringStripped = LHSStripped;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00005063 } else if ((isa<StringLiteral>(RHSStripped) ||
5064 isa<ObjCEncodeExpr>(RHSStripped)) &&
Douglas Gregorce940492009-09-25 04:25:58 +00005065 !LHSStripped->isNullPointerConstant(Context,
5066 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregora86b8322009-04-06 18:45:53 +00005067 literalString = rex;
5068 literalStringStripped = RHSStripped;
5069 }
5070
5071 if (literalString) {
5072 std::string resultComparison;
5073 switch (Opc) {
5074 case BinaryOperator::LT: resultComparison = ") < 0"; break;
5075 case BinaryOperator::GT: resultComparison = ") > 0"; break;
5076 case BinaryOperator::LE: resultComparison = ") <= 0"; break;
5077 case BinaryOperator::GE: resultComparison = ") >= 0"; break;
5078 case BinaryOperator::EQ: resultComparison = ") == 0"; break;
5079 case BinaryOperator::NE: resultComparison = ") != 0"; break;
5080 default: assert(false && "Invalid comparison operator");
5081 }
5082 Diag(Loc, diag::warn_stringcompare)
5083 << isa<ObjCEncodeExpr>(literalStringStripped)
5084 << literalString->getSourceRange()
Douglas Gregora3a83512009-04-01 23:51:29 +00005085 << CodeModificationHint::CreateReplacement(SourceRange(Loc), ", ")
5086 << CodeModificationHint::CreateInsertion(lex->getLocStart(),
5087 "strcmp(")
5088 << CodeModificationHint::CreateInsertion(
5089 PP.getLocForEndOfToken(rex->getLocEnd()),
Douglas Gregora86b8322009-04-06 18:45:53 +00005090 resultComparison);
5091 }
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00005092 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005093
Douglas Gregor447b69e2008-11-19 03:25:36 +00005094 // The result of comparisons is 'bool' in C++, 'int' in C.
Chris Lattner02dd4b12009-12-05 05:40:13 +00005095 QualType ResultTy = getLangOptions().CPlusPlus ? Context.BoolTy:Context.IntTy;
Douglas Gregor447b69e2008-11-19 03:25:36 +00005096
Chris Lattnera5937dd2007-08-26 01:18:55 +00005097 if (isRelational) {
5098 if (lType->isRealType() && rType->isRealType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00005099 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00005100 } else {
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00005101 // Check for comparisons of floating point operands using != and ==.
Chris Lattner02dd4b12009-12-05 05:40:13 +00005102 if (lType->isFloatingType() && rType->isFloatingType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005103 CheckFloatComparison(Loc,lex,rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005104
Chris Lattnera5937dd2007-08-26 01:18:55 +00005105 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00005106 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00005107 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005108
Douglas Gregorce940492009-09-25 04:25:58 +00005109 bool LHSIsNull = lex->isNullPointerConstant(Context,
5110 Expr::NPC_ValueDependentIsNull);
5111 bool RHSIsNull = rex->isNullPointerConstant(Context,
5112 Expr::NPC_ValueDependentIsNull);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005113
Chris Lattnera5937dd2007-08-26 01:18:55 +00005114 // All of the following pointer related warnings are GCC extensions, except
5115 // when handling null pointer constants. One day, we can consider making them
5116 // errors (when -pedantic-errors is enabled).
Steve Naroff77878cc2007-08-27 04:08:11 +00005117 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00005118 QualType LCanPointeeTy =
Ted Kremenek6217b802009-07-29 21:53:49 +00005119 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattnerbc896f52008-04-03 05:07:25 +00005120 QualType RCanPointeeTy =
Ted Kremenek6217b802009-07-29 21:53:49 +00005121 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stumpeed9cac2009-02-19 03:04:26 +00005122
Douglas Gregor0c6db942009-05-04 06:07:12 +00005123 if (getLangOptions().CPlusPlus) {
Eli Friedman3075e762009-08-23 00:27:47 +00005124 if (LCanPointeeTy == RCanPointeeTy)
5125 return ResultTy;
5126
Douglas Gregor0c6db942009-05-04 06:07:12 +00005127 // C++ [expr.rel]p2:
5128 // [...] Pointer conversions (4.10) and qualification
5129 // conversions (4.4) are performed on pointer operands (or on
5130 // a pointer operand and a null pointer constant) to bring
5131 // them to their composite pointer type. [...]
5132 //
Douglas Gregor20b3e992009-08-24 17:42:35 +00005133 // C++ [expr.eq]p1 uses the same notion for (in)equality
Douglas Gregor0c6db942009-05-04 06:07:12 +00005134 // comparisons of pointers.
Douglas Gregorde866f32009-05-05 04:50:50 +00005135 QualType T = FindCompositePointerType(lex, rex);
Douglas Gregor0c6db942009-05-04 06:07:12 +00005136 if (T.isNull()) {
5137 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
5138 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5139 return QualType();
5140 }
5141
Eli Friedman73c39ab2009-10-20 08:27:19 +00005142 ImpCastExprToType(lex, T, CastExpr::CK_BitCast);
5143 ImpCastExprToType(rex, T, CastExpr::CK_BitCast);
Douglas Gregor0c6db942009-05-04 06:07:12 +00005144 return ResultTy;
5145 }
Eli Friedman3075e762009-08-23 00:27:47 +00005146 // C99 6.5.9p2 and C99 6.5.8p2
5147 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
5148 RCanPointeeTy.getUnqualifiedType())) {
5149 // Valid unless a relational comparison of function pointers
5150 if (isRelational && LCanPointeeTy->isFunctionType()) {
5151 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
5152 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5153 }
5154 } else if (!isRelational &&
5155 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
5156 // Valid unless comparison between non-null pointer and function pointer
5157 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
5158 && !LHSIsNull && !RHSIsNull) {
5159 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
5160 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5161 }
5162 } else {
5163 // Invalid
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00005164 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattnerd1625842008-11-24 06:25:27 +00005165 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00005166 }
Eli Friedman3075e762009-08-23 00:27:47 +00005167 if (LCanPointeeTy != RCanPointeeTy)
Eli Friedman73c39ab2009-10-20 08:27:19 +00005168 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005169 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00005170 }
Mike Stump1eb44332009-09-09 15:08:12 +00005171
Sebastian Redl6e8ed162009-05-10 18:38:11 +00005172 if (getLangOptions().CPlusPlus) {
Mike Stump1eb44332009-09-09 15:08:12 +00005173 // Comparison of pointers with null pointer constants and equality
Douglas Gregor20b3e992009-08-24 17:42:35 +00005174 // comparisons of member pointers to null pointer constants.
Mike Stump1eb44332009-09-09 15:08:12 +00005175 if (RHSIsNull &&
Douglas Gregor20b3e992009-08-24 17:42:35 +00005176 (lType->isPointerType() ||
5177 (!isRelational && lType->isMemberPointerType()))) {
Anders Carlsson26ba8502009-08-24 18:03:14 +00005178 ImpCastExprToType(rex, lType, CastExpr::CK_NullToMemberPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00005179 return ResultTy;
5180 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00005181 if (LHSIsNull &&
5182 (rType->isPointerType() ||
5183 (!isRelational && rType->isMemberPointerType()))) {
Anders Carlsson26ba8502009-08-24 18:03:14 +00005184 ImpCastExprToType(lex, rType, CastExpr::CK_NullToMemberPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00005185 return ResultTy;
5186 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00005187
5188 // Comparison of member pointers.
Mike Stump1eb44332009-09-09 15:08:12 +00005189 if (!isRelational &&
Douglas Gregor20b3e992009-08-24 17:42:35 +00005190 lType->isMemberPointerType() && rType->isMemberPointerType()) {
5191 // C++ [expr.eq]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00005192 // In addition, pointers to members can be compared, or a pointer to
5193 // member and a null pointer constant. Pointer to member conversions
5194 // (4.11) and qualification conversions (4.4) are performed to bring
5195 // them to a common type. If one operand is a null pointer constant,
5196 // the common type is the type of the other operand. Otherwise, the
5197 // common type is a pointer to member type similar (4.4) to the type
5198 // of one of the operands, with a cv-qualification signature (4.4)
5199 // that is the union of the cv-qualification signatures of the operand
Douglas Gregor20b3e992009-08-24 17:42:35 +00005200 // types.
5201 QualType T = FindCompositePointerType(lex, rex);
5202 if (T.isNull()) {
5203 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
5204 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5205 return QualType();
5206 }
Mike Stump1eb44332009-09-09 15:08:12 +00005207
Eli Friedman73c39ab2009-10-20 08:27:19 +00005208 ImpCastExprToType(lex, T, CastExpr::CK_BitCast);
5209 ImpCastExprToType(rex, T, CastExpr::CK_BitCast);
Douglas Gregor20b3e992009-08-24 17:42:35 +00005210 return ResultTy;
5211 }
Mike Stump1eb44332009-09-09 15:08:12 +00005212
Douglas Gregor20b3e992009-08-24 17:42:35 +00005213 // Comparison of nullptr_t with itself.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00005214 if (lType->isNullPtrType() && rType->isNullPtrType())
5215 return ResultTy;
5216 }
Mike Stump1eb44332009-09-09 15:08:12 +00005217
Steve Naroff1c7d0672008-09-04 15:10:53 +00005218 // Handle block pointer types.
Mike Stumpdd3e1662009-05-07 03:14:14 +00005219 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00005220 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
5221 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005222
Steve Naroff1c7d0672008-09-04 15:10:53 +00005223 if (!LHSIsNull && !RHSIsNull &&
Eli Friedman26784c12009-06-08 05:08:54 +00005224 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00005225 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattnerd1625842008-11-24 06:25:27 +00005226 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff1c7d0672008-09-04 15:10:53 +00005227 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00005228 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005229 return ResultTy;
Steve Naroff1c7d0672008-09-04 15:10:53 +00005230 }
Steve Naroff59f53942008-09-28 01:11:11 +00005231 // Allow block pointers to be compared with null pointer constants.
Mike Stumpdd3e1662009-05-07 03:14:14 +00005232 if (!isRelational
5233 && ((lType->isBlockPointerType() && rType->isPointerType())
5234 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Naroff59f53942008-09-28 01:11:11 +00005235 if (!LHSIsNull && !RHSIsNull) {
Ted Kremenek6217b802009-07-29 21:53:49 +00005236 if (!((rType->isPointerType() && rType->getAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00005237 ->getPointeeType()->isVoidType())
Ted Kremenek6217b802009-07-29 21:53:49 +00005238 || (lType->isPointerType() && lType->getAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00005239 ->getPointeeType()->isVoidType())))
5240 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
5241 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff59f53942008-09-28 01:11:11 +00005242 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00005243 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005244 return ResultTy;
Steve Naroff59f53942008-09-28 01:11:11 +00005245 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00005246
Steve Naroff14108da2009-07-10 23:34:53 +00005247 if ((lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType())) {
Steve Naroffa5ad8632008-10-27 10:33:19 +00005248 if (lType->isPointerType() || rType->isPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00005249 const PointerType *LPT = lType->getAs<PointerType>();
5250 const PointerType *RPT = rType->getAs<PointerType>();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005251 bool LPtrToVoid = LPT ?
Steve Naroffa8069f12008-11-17 19:49:16 +00005252 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005253 bool RPtrToVoid = RPT ?
Steve Naroffa8069f12008-11-17 19:49:16 +00005254 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005255
Steve Naroffa8069f12008-11-17 19:49:16 +00005256 if (!LPtrToVoid && !RPtrToVoid &&
5257 !Context.typesAreCompatible(lType, rType)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00005258 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattnerd1625842008-11-24 06:25:27 +00005259 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroffa5ad8632008-10-27 10:33:19 +00005260 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00005261 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005262 return ResultTy;
Steve Naroff87f3b932008-10-20 18:19:10 +00005263 }
Steve Naroff14108da2009-07-10 23:34:53 +00005264 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00005265 if (!Context.areComparableObjCPointerTypes(lType, rType))
Steve Naroff14108da2009-07-10 23:34:53 +00005266 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
5267 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00005268 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005269 return ResultTy;
Steve Naroff20373222008-06-03 14:04:54 +00005270 }
Fariborz Jahanian7359f042007-12-20 01:06:58 +00005271 }
Steve Naroff58f9f2c2009-07-14 18:25:06 +00005272 if (lType->isAnyPointerType() && rType->isIntegerType()) {
Chris Lattner06c0f5b2009-08-23 00:03:44 +00005273 unsigned DiagID = 0;
5274 if (RHSIsNull) {
5275 if (isRelational)
5276 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
5277 } else if (isRelational)
5278 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
5279 else
5280 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump1eb44332009-09-09 15:08:12 +00005281
Chris Lattner06c0f5b2009-08-23 00:03:44 +00005282 if (DiagID) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00005283 Diag(Loc, DiagID)
Chris Lattner149f1382009-06-30 06:24:05 +00005284 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner6365e3e2009-08-22 18:58:31 +00005285 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00005286 ImpCastExprToType(rex, lType, CastExpr::CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005287 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00005288 }
Steve Naroff58f9f2c2009-07-14 18:25:06 +00005289 if (lType->isIntegerType() && rType->isAnyPointerType()) {
Chris Lattner06c0f5b2009-08-23 00:03:44 +00005290 unsigned DiagID = 0;
5291 if (LHSIsNull) {
5292 if (isRelational)
5293 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
5294 } else if (isRelational)
5295 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
5296 else
5297 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump1eb44332009-09-09 15:08:12 +00005298
Chris Lattner06c0f5b2009-08-23 00:03:44 +00005299 if (DiagID) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00005300 Diag(Loc, DiagID)
Chris Lattner149f1382009-06-30 06:24:05 +00005301 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner6365e3e2009-08-22 18:58:31 +00005302 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00005303 ImpCastExprToType(lex, rType, CastExpr::CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005304 return ResultTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00005305 }
Steve Naroff39218df2008-09-04 16:56:14 +00005306 // Handle block pointers.
Mike Stumpaf199f32009-05-07 18:43:07 +00005307 if (!isRelational && RHSIsNull
5308 && lType->isBlockPointerType() && rType->isIntegerType()) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00005309 ImpCastExprToType(rex, lType, CastExpr::CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005310 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00005311 }
Mike Stumpaf199f32009-05-07 18:43:07 +00005312 if (!isRelational && LHSIsNull
5313 && lType->isIntegerType() && rType->isBlockPointerType()) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00005314 ImpCastExprToType(lex, rType, CastExpr::CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005315 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00005316 }
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005317 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00005318}
5319
Nate Begemanbe2341d2008-07-14 18:02:46 +00005320/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stumpeed9cac2009-02-19 03:04:26 +00005321/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begemanbe2341d2008-07-14 18:02:46 +00005322/// like a scalar comparison, a vector comparison produces a vector of integer
5323/// types.
5324QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005325 SourceLocation Loc,
Nate Begemanbe2341d2008-07-14 18:02:46 +00005326 bool isRelational) {
5327 // Check to make sure we're operating on vectors of the same type and width,
5328 // Allowing one side to be a scalar of element type.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005329 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanbe2341d2008-07-14 18:02:46 +00005330 if (vType.isNull())
5331 return vType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005332
Nate Begemanbe2341d2008-07-14 18:02:46 +00005333 QualType lType = lex->getType();
5334 QualType rType = rex->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005335
Nate Begemanbe2341d2008-07-14 18:02:46 +00005336 // For non-floating point types, check for self-comparisons of the form
5337 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
5338 // often indicate logic errors in the program.
5339 if (!lType->isFloatingType()) {
5340 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
5341 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
5342 if (DRL->getDecl() == DRR->getDecl())
Mike Stumpeed9cac2009-02-19 03:04:26 +00005343 Diag(Loc, diag::warn_selfcomparison);
Nate Begemanbe2341d2008-07-14 18:02:46 +00005344 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005345
Nate Begemanbe2341d2008-07-14 18:02:46 +00005346 // Check for comparisons of floating point operands using != and ==.
5347 if (!isRelational && lType->isFloatingType()) {
5348 assert (rType->isFloatingType());
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005349 CheckFloatComparison(Loc,lex,rex);
Nate Begemanbe2341d2008-07-14 18:02:46 +00005350 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005351
Nate Begemanbe2341d2008-07-14 18:02:46 +00005352 // Return the type for the comparison, which is the same as vector type for
5353 // integer vectors, or an integer type of identical size and number of
5354 // elements for floating point vectors.
5355 if (lType->isIntegerType())
5356 return lType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005357
John McCall183700f2009-09-21 23:43:11 +00005358 const VectorType *VTy = lType->getAs<VectorType>();
Nate Begemanbe2341d2008-07-14 18:02:46 +00005359 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman59b5da62009-01-18 03:20:47 +00005360 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanbe2341d2008-07-14 18:02:46 +00005361 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattnerd013aa12009-03-31 07:46:52 +00005362 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman59b5da62009-01-18 03:20:47 +00005363 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
5364
Mike Stumpeed9cac2009-02-19 03:04:26 +00005365 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman59b5da62009-01-18 03:20:47 +00005366 "Unhandled vector element size in vector compare");
Nate Begemanbe2341d2008-07-14 18:02:46 +00005367 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
5368}
5369
Reid Spencer5f016e22007-07-11 17:01:13 +00005370inline QualType Sema::CheckBitwiseOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00005371 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Steve Naroff3e5e5562007-07-16 22:23:01 +00005372 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005373 return CheckVectorOperands(Loc, lex, rex);
Steve Naroff90045e82007-07-13 23:32:42 +00005374
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00005375 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005376
Steve Naroffa4332e22007-07-17 00:58:39 +00005377 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00005378 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005379 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00005380}
5381
5382inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Mike Stump1eb44332009-09-09 15:08:12 +00005383 Expr *&lex, Expr *&rex, SourceLocation Loc) {
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005384 if (!Context.getLangOptions().CPlusPlus) {
5385 UsualUnaryConversions(lex);
5386 UsualUnaryConversions(rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005387
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005388 if (!lex->getType()->isScalarType() || !rex->getType()->isScalarType())
5389 return InvalidOperands(Loc, lex, rex);
Anders Carlsson04905012009-10-16 01:44:21 +00005390
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005391 return Context.IntTy;
Anders Carlsson04905012009-10-16 01:44:21 +00005392 }
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005393
5394 // C++ [expr.log.and]p1
5395 // C++ [expr.log.or]p1
5396 // The operands are both implicitly converted to type bool (clause 4).
5397 StandardConversionSequence LHS;
5398 if (!IsStandardConversion(lex, Context.BoolTy,
5399 /*InOverloadResolution=*/false, LHS))
5400 return InvalidOperands(Loc, lex, rex);
Anders Carlsson04905012009-10-16 01:44:21 +00005401
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005402 if (PerformImplicitConversion(lex, Context.BoolTy, LHS,
5403 "passing", /*IgnoreBaseAccess=*/false))
5404 return InvalidOperands(Loc, lex, rex);
5405
5406 StandardConversionSequence RHS;
5407 if (!IsStandardConversion(rex, Context.BoolTy,
5408 /*InOverloadResolution=*/false, RHS))
5409 return InvalidOperands(Loc, lex, rex);
5410
5411 if (PerformImplicitConversion(rex, Context.BoolTy, RHS,
5412 "passing", /*IgnoreBaseAccess=*/false))
5413 return InvalidOperands(Loc, lex, rex);
5414
5415 // C++ [expr.log.and]p2
5416 // C++ [expr.log.or]p2
5417 // The result is a bool.
5418 return Context.BoolTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00005419}
5420
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00005421/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
5422/// is a read-only property; return true if so. A readonly property expression
5423/// depends on various declarations and thus must be treated specially.
5424///
Mike Stump1eb44332009-09-09 15:08:12 +00005425static bool IsReadonlyProperty(Expr *E, Sema &S) {
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00005426 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
5427 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
5428 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
5429 QualType BaseType = PropExpr->getBase()->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00005430 if (const ObjCObjectPointerType *OPT =
Steve Naroff14108da2009-07-10 23:34:53 +00005431 BaseType->getAsObjCInterfacePointerType())
5432 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
5433 if (S.isPropertyReadonly(PDecl, IFace))
5434 return true;
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00005435 }
5436 }
5437 return false;
5438}
5439
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005440/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
5441/// emit an error and return true. If so, return false.
5442static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbar44e35f72009-04-15 00:08:05 +00005443 SourceLocation OrigLoc = Loc;
Mike Stump1eb44332009-09-09 15:08:12 +00005444 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbar44e35f72009-04-15 00:08:05 +00005445 &Loc);
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00005446 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
5447 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005448 if (IsLV == Expr::MLV_Valid)
5449 return false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005450
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005451 unsigned Diag = 0;
5452 bool NeedType = false;
5453 switch (IsLV) { // C99 6.5.16p2
5454 default: assert(0 && "Unknown result from isModifiableLvalue!");
5455 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005456 case Expr::MLV_ArrayType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005457 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
5458 NeedType = true;
5459 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005460 case Expr::MLV_NotObjectType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005461 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
5462 NeedType = true;
5463 break;
Chris Lattnerca354fa2008-11-17 19:51:54 +00005464 case Expr::MLV_LValueCast:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005465 Diag = diag::err_typecheck_lvalue_casts_not_supported;
5466 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00005467 case Expr::MLV_InvalidExpression:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005468 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
5469 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00005470 case Expr::MLV_IncompleteType:
5471 case Expr::MLV_IncompleteVoidType:
Douglas Gregor86447ec2009-03-09 16:13:40 +00005472 return S.RequireCompleteType(Loc, E->getType(),
Anders Carlssonb7906612009-08-26 23:45:07 +00005473 PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
5474 << E->getSourceRange());
Chris Lattner5cf216b2008-01-04 18:04:52 +00005475 case Expr::MLV_DuplicateVectorComponents:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005476 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
5477 break;
Steve Naroff4f6a7d72008-09-26 14:41:28 +00005478 case Expr::MLV_NotBlockQualified:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005479 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
5480 break;
Fariborz Jahanian5daf5702008-11-22 18:39:36 +00005481 case Expr::MLV_ReadonlyProperty:
5482 Diag = diag::error_readonly_property_assignment;
5483 break;
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00005484 case Expr::MLV_NoSetterProperty:
5485 Diag = diag::error_nosetter_property_assignment;
5486 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00005487 }
Steve Naroffd1861fd2007-07-31 12:34:36 +00005488
Daniel Dunbar44e35f72009-04-15 00:08:05 +00005489 SourceRange Assign;
5490 if (Loc != OrigLoc)
5491 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005492 if (NeedType)
Daniel Dunbar44e35f72009-04-15 00:08:05 +00005493 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005494 else
Mike Stump1eb44332009-09-09 15:08:12 +00005495 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005496 return true;
5497}
5498
5499
5500
5501// C99 6.5.16.1
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005502QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
5503 SourceLocation Loc,
5504 QualType CompoundType) {
5505 // Verify that LHS is a modifiable lvalue, and emit error if not.
5506 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005507 return QualType();
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005508
5509 QualType LHSType = LHS->getType();
5510 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005511
Chris Lattner5cf216b2008-01-04 18:04:52 +00005512 AssignConvertType ConvTy;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005513 if (CompoundType.isNull()) {
Chris Lattner2c156472008-08-21 18:04:13 +00005514 // Simple assignment "x = y".
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005515 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00005516 // Special case of NSObject attributes on c-style pointer types.
5517 if (ConvTy == IncompatiblePointer &&
5518 ((Context.isObjCNSObjectType(LHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00005519 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00005520 (Context.isObjCNSObjectType(RHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00005521 LHSType->isObjCObjectPointerType())))
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00005522 ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005523
Chris Lattner2c156472008-08-21 18:04:13 +00005524 // If the RHS is a unary plus or minus, check to see if they = and + are
5525 // right next to each other. If so, the user may have typo'd "x =+ 4"
5526 // instead of "x += 4".
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005527 Expr *RHSCheck = RHS;
Chris Lattner2c156472008-08-21 18:04:13 +00005528 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
5529 RHSCheck = ICE->getSubExpr();
5530 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
5531 if ((UO->getOpcode() == UnaryOperator::Plus ||
5532 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005533 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner2c156472008-08-21 18:04:13 +00005534 // Only if the two operators are exactly adjacent.
Chris Lattner399bd1b2009-03-08 06:51:10 +00005535 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
5536 // And there is a space or other character before the subexpr of the
5537 // unary +/-. We don't want to warn on "x=-1".
Chris Lattner3e872092009-03-09 07:11:10 +00005538 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
5539 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00005540 Diag(Loc, diag::warn_not_compound_assign)
5541 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
5542 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner399bd1b2009-03-08 06:51:10 +00005543 }
Chris Lattner2c156472008-08-21 18:04:13 +00005544 }
5545 } else {
5546 // Compound assignment "x += y"
Eli Friedman623712b2009-05-16 05:56:02 +00005547 ConvTy = CheckAssignmentConstraints(LHSType, RHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00005548 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00005549
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005550 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
5551 RHS, "assigning"))
Chris Lattner5cf216b2008-01-04 18:04:52 +00005552 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005553
Reid Spencer5f016e22007-07-11 17:01:13 +00005554 // C99 6.5.16p3: The type of an assignment expression is the type of the
5555 // left operand unless the left operand has qualified type, in which case
Mike Stumpeed9cac2009-02-19 03:04:26 +00005556 // it is the unqualified version of the type of the left operand.
Reid Spencer5f016e22007-07-11 17:01:13 +00005557 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
5558 // is converted to the type of the assignment expression (above).
Chris Lattner73d0d4f2007-08-30 17:45:32 +00005559 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregor2d833e32009-05-02 00:36:19 +00005560 // operand.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005561 return LHSType.getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +00005562}
5563
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005564// C99 6.5.17
5565QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
Chris Lattner53fcaa92008-07-25 20:54:07 +00005566 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005567 DefaultFunctionArrayConversion(RHS);
Eli Friedmanb1d796d2009-03-23 00:24:07 +00005568
5569 // FIXME: Check that RHS type is complete in C mode (it's legal for it to be
5570 // incomplete in C++).
5571
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005572 return RHS->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00005573}
5574
Steve Naroff49b45262007-07-13 16:58:59 +00005575/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
5576/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00005577QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
5578 bool isInc) {
Sebastian Redl28507842009-02-26 14:39:58 +00005579 if (Op->isTypeDependent())
5580 return Context.DependentTy;
5581
Chris Lattner3528d352008-11-21 07:05:48 +00005582 QualType ResType = Op->getType();
5583 assert(!ResType.isNull() && "no type for increment/decrement expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00005584
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00005585 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
5586 // Decrement of bool is not allowed.
5587 if (!isInc) {
5588 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
5589 return QualType();
5590 }
5591 // Increment of bool sets it to true, but is deprecated.
5592 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
5593 } else if (ResType->isRealType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00005594 // OK!
Steve Naroff58f9f2c2009-07-14 18:25:06 +00005595 } else if (ResType->isAnyPointerType()) {
5596 QualType PointeeTy = ResType->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00005597
Chris Lattner3528d352008-11-21 07:05:48 +00005598 // C99 6.5.2.4p2, 6.5.6p2
Steve Naroff14108da2009-07-10 23:34:53 +00005599 if (PointeeTy->isVoidType()) {
Douglas Gregorc983b862009-01-23 00:36:41 +00005600 if (getLangOptions().CPlusPlus) {
5601 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
5602 << Op->getSourceRange();
5603 return QualType();
5604 }
5605
5606 // Pointer to void is a GNU extension in C.
Chris Lattner3528d352008-11-21 07:05:48 +00005607 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Steve Naroff14108da2009-07-10 23:34:53 +00005608 } else if (PointeeTy->isFunctionType()) {
Douglas Gregorc983b862009-01-23 00:36:41 +00005609 if (getLangOptions().CPlusPlus) {
5610 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
5611 << Op->getType() << Op->getSourceRange();
5612 return QualType();
5613 }
5614
5615 Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattnerd1625842008-11-24 06:25:27 +00005616 << ResType << Op->getSourceRange();
Steve Naroff14108da2009-07-10 23:34:53 +00005617 } else if (RequireCompleteType(OpLoc, PointeeTy,
Anders Carlssond497ba72009-08-26 22:59:12 +00005618 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
Mike Stump1eb44332009-09-09 15:08:12 +00005619 << Op->getSourceRange()
Anders Carlssond497ba72009-08-26 22:59:12 +00005620 << ResType))
Douglas Gregor4ec339f2009-01-19 19:26:10 +00005621 return QualType();
Fariborz Jahanian9f8a04f2009-07-16 17:59:14 +00005622 // Diagnose bad cases where we step over interface counts.
5623 else if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
5624 Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
5625 << PointeeTy << Op->getSourceRange();
5626 return QualType();
5627 }
Chris Lattner3528d352008-11-21 07:05:48 +00005628 } else if (ResType->isComplexType()) {
5629 // C99 does not support ++/-- on complex types, we allow as an extension.
5630 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00005631 << ResType << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00005632 } else {
5633 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Chris Lattnerd1625842008-11-24 06:25:27 +00005634 << ResType << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00005635 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00005636 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005637 // At this point, we know we have a real, complex or pointer type.
Steve Naroffdd10e022007-08-23 21:37:33 +00005638 // Now make sure the operand is a modifiable lvalue.
Chris Lattner3528d352008-11-21 07:05:48 +00005639 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Reid Spencer5f016e22007-07-11 17:01:13 +00005640 return QualType();
Chris Lattner3528d352008-11-21 07:05:48 +00005641 return ResType;
Reid Spencer5f016e22007-07-11 17:01:13 +00005642}
5643
Anders Carlsson369dee42008-02-01 07:15:58 +00005644/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Reid Spencer5f016e22007-07-11 17:01:13 +00005645/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00005646/// where the declaration is needed for type checking. We only need to
5647/// handle cases when the expression references a function designator
5648/// or is an lvalue. Here are some examples:
5649/// - &(x) => x
5650/// - &*****f => f for f a function designator.
5651/// - &s.xx => s
5652/// - &s.zz[1].yy -> s, if zz is an array
5653/// - *(x + 1) -> x, if x is an array
5654/// - &"123"[2] -> 0
5655/// - & __real__ x -> x
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005656static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00005657 switch (E->getStmtClass()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00005658 case Stmt::DeclRefExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00005659 return cast<DeclRefExpr>(E)->getDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00005660 case Stmt::MemberExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00005661 // If this is an arrow operator, the address is an offset from
5662 // the base's value, so the object the base refers to is
5663 // irrelevant.
Chris Lattnerf0467b32008-04-02 04:24:33 +00005664 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnerf82228f2007-11-16 17:46:48 +00005665 return 0;
Eli Friedman23d58ce2009-04-20 08:23:18 +00005666 // Otherwise, the expression refers to a part of the base
Chris Lattnerf0467b32008-04-02 04:24:33 +00005667 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson369dee42008-02-01 07:15:58 +00005668 case Stmt::ArraySubscriptExprClass: {
Mike Stump390b4cc2009-05-16 07:39:55 +00005669 // FIXME: This code shouldn't be necessary! We should catch the implicit
5670 // promotion of register arrays earlier.
Eli Friedman23d58ce2009-04-20 08:23:18 +00005671 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
5672 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
5673 if (ICE->getSubExpr()->getType()->isArrayType())
5674 return getPrimaryDecl(ICE->getSubExpr());
5675 }
5676 return 0;
Anders Carlsson369dee42008-02-01 07:15:58 +00005677 }
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00005678 case Stmt::UnaryOperatorClass: {
5679 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005680
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00005681 switch(UO->getOpcode()) {
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00005682 case UnaryOperator::Real:
5683 case UnaryOperator::Imag:
5684 case UnaryOperator::Extension:
5685 return getPrimaryDecl(UO->getSubExpr());
5686 default:
5687 return 0;
5688 }
5689 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005690 case Stmt::ParenExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00005691 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnerf82228f2007-11-16 17:46:48 +00005692 case Stmt::ImplicitCastExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00005693 // If the result of an implicit cast is an l-value, we care about
5694 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattnerf0467b32008-04-02 04:24:33 +00005695 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Reid Spencer5f016e22007-07-11 17:01:13 +00005696 default:
5697 return 0;
5698 }
5699}
5700
5701/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stumpeed9cac2009-02-19 03:04:26 +00005702/// designator or an lvalue designating an object. If it is an lvalue, the
Reid Spencer5f016e22007-07-11 17:01:13 +00005703/// object cannot be declared with storage class register or be a bit field.
Mike Stumpeed9cac2009-02-19 03:04:26 +00005704/// Note: The usual conversions are *not* applied to the operand of the &
Reid Spencer5f016e22007-07-11 17:01:13 +00005705/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stumpeed9cac2009-02-19 03:04:26 +00005706/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregor904eed32008-11-10 20:40:00 +00005707/// we allow the '&' but retain the overloaded-function type.
Reid Spencer5f016e22007-07-11 17:01:13 +00005708QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Eli Friedman23d58ce2009-04-20 08:23:18 +00005709 // Make sure to ignore parentheses in subsequent checks
5710 op = op->IgnoreParens();
5711
Douglas Gregor9103bb22008-12-17 22:52:20 +00005712 if (op->isTypeDependent())
5713 return Context.DependentTy;
5714
Steve Naroff08f19672008-01-13 17:10:08 +00005715 if (getLangOptions().C99) {
5716 // Implement C99-only parts of addressof rules.
5717 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
5718 if (uOp->getOpcode() == UnaryOperator::Deref)
5719 // Per C99 6.5.3.2, the address of a deref always returns a valid result
5720 // (assuming the deref expression is valid).
5721 return uOp->getSubExpr()->getType();
5722 }
5723 // Technically, there should be a check for array subscript
5724 // expressions here, but the result of one is always an lvalue anyway.
5725 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005726 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner28be73f2008-07-26 21:30:36 +00005727 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes6b6609f2008-12-16 22:59:47 +00005728
Eli Friedman441cf102009-05-16 23:27:50 +00005729 if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
5730 // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00005731 // The operand must be either an l-value or a function designator
Eli Friedman441cf102009-05-16 23:27:50 +00005732 if (!op->getType()->isFunctionType()) {
Chris Lattnerf82228f2007-11-16 17:46:48 +00005733 // FIXME: emit more specific diag...
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00005734 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
5735 << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00005736 return QualType();
5737 }
Douglas Gregor33bbbc52009-05-02 02:18:30 +00005738 } else if (op->getBitField()) { // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00005739 // The operand cannot be a bit-field
5740 Diag(OpLoc, diag::err_typecheck_address_of)
5741 << "bit-field" << op->getSourceRange();
Douglas Gregor86f19402008-12-20 23:49:58 +00005742 return QualType();
Nate Begemanb104b1f2009-02-15 22:45:20 +00005743 } else if (isa<ExtVectorElementExpr>(op) || (isa<ArraySubscriptExpr>(op) &&
5744 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType())){
Eli Friedman23d58ce2009-04-20 08:23:18 +00005745 // The operand cannot be an element of a vector
Chris Lattnerd3a94e22008-11-20 06:06:08 +00005746 Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemanb104b1f2009-02-15 22:45:20 +00005747 << "vector element" << op->getSourceRange();
Steve Naroffbcb2b612008-02-29 23:30:25 +00005748 return QualType();
Fariborz Jahanian0337f212009-07-07 18:50:52 +00005749 } else if (isa<ObjCPropertyRefExpr>(op)) {
5750 // cannot take address of a property expression.
5751 Diag(OpLoc, diag::err_typecheck_address_of)
5752 << "property expression" << op->getSourceRange();
5753 return QualType();
Anders Carlsson1d524c32009-09-14 23:15:26 +00005754 } else if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(op)) {
5755 // FIXME: Can LHS ever be null here?
Anders Carlsson474e1022009-09-15 16:03:44 +00005756 if (!CheckAddressOfOperand(CO->getTrueExpr(), OpLoc).isNull())
5757 return CheckAddressOfOperand(CO->getFalseExpr(), OpLoc);
John McCallba135432009-11-21 08:51:07 +00005758 } else if (isa<UnresolvedLookupExpr>(op)) {
5759 return Context.OverloadTy;
Steve Naroffbcb2b612008-02-29 23:30:25 +00005760 } else if (dcl) { // C99 6.5.3.2p1
Mike Stumpeed9cac2009-02-19 03:04:26 +00005761 // We have an lvalue with a decl. Make sure the decl is not declared
Reid Spencer5f016e22007-07-11 17:01:13 +00005762 // with the register storage-class specifier.
5763 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
5764 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00005765 Diag(OpLoc, diag::err_typecheck_address_of)
5766 << "register variable" << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00005767 return QualType();
5768 }
John McCallba135432009-11-21 08:51:07 +00005769 } else if (isa<FunctionTemplateDecl>(dcl)) {
Douglas Gregor904eed32008-11-10 20:40:00 +00005770 return Context.OverloadTy;
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00005771 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(dcl)) {
Douglas Gregor29882052008-12-10 21:26:49 +00005772 // Okay: we can take the address of a field.
Sebastian Redlebc07d52009-02-03 20:19:35 +00005773 // Could be a pointer to member, though, if there is an explicit
5774 // scope qualifier for the class.
Douglas Gregora2813ce2009-10-23 18:54:35 +00005775 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redlebc07d52009-02-03 20:19:35 +00005776 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00005777 if (Ctx && Ctx->isRecord()) {
5778 if (FD->getType()->isReferenceType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00005779 Diag(OpLoc,
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00005780 diag::err_cannot_form_pointer_to_member_of_reference_type)
5781 << FD->getDeclName() << FD->getType();
5782 return QualType();
5783 }
Mike Stump1eb44332009-09-09 15:08:12 +00005784
Sebastian Redlebc07d52009-02-03 20:19:35 +00005785 return Context.getMemberPointerType(op->getType(),
5786 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00005787 }
Sebastian Redlebc07d52009-02-03 20:19:35 +00005788 }
Anders Carlsson196f7d02009-05-16 21:43:42 +00005789 } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(dcl)) {
Nuno Lopes6fea8d22008-12-16 22:58:26 +00005790 // Okay: we can take the address of a function.
Sebastian Redl33b399a2009-02-04 21:23:32 +00005791 // As above.
Douglas Gregora2813ce2009-10-23 18:54:35 +00005792 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier() &&
5793 MD->isInstance())
Anders Carlsson196f7d02009-05-16 21:43:42 +00005794 return Context.getMemberPointerType(op->getType(),
5795 Context.getTypeDeclType(MD->getParent()).getTypePtr());
5796 } else if (!isa<FunctionDecl>(dcl))
Reid Spencer5f016e22007-07-11 17:01:13 +00005797 assert(0 && "Unknown/unexpected decl type");
Reid Spencer5f016e22007-07-11 17:01:13 +00005798 }
Sebastian Redl33b399a2009-02-04 21:23:32 +00005799
Eli Friedman441cf102009-05-16 23:27:50 +00005800 if (lval == Expr::LV_IncompleteVoidType) {
5801 // Taking the address of a void variable is technically illegal, but we
5802 // allow it in cases which are otherwise valid.
5803 // Example: "extern void x; void* y = &x;".
5804 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
5805 }
5806
Reid Spencer5f016e22007-07-11 17:01:13 +00005807 // If the operand has type "type", the result has type "pointer to type".
5808 return Context.getPointerType(op->getType());
5809}
5810
Chris Lattner22caddc2008-11-23 09:13:29 +00005811QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
Sebastian Redl28507842009-02-26 14:39:58 +00005812 if (Op->isTypeDependent())
5813 return Context.DependentTy;
5814
Chris Lattner22caddc2008-11-23 09:13:29 +00005815 UsualUnaryConversions(Op);
5816 QualType Ty = Op->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005817
Chris Lattner22caddc2008-11-23 09:13:29 +00005818 // Note that per both C89 and C99, this is always legal, even if ptype is an
5819 // incomplete type or void. It would be possible to warn about dereferencing
5820 // a void pointer, but it's completely well-defined, and such a warning is
5821 // unlikely to catch any mistakes.
Ted Kremenek6217b802009-07-29 21:53:49 +00005822 if (const PointerType *PT = Ty->getAs<PointerType>())
Steve Naroff08f19672008-01-13 17:10:08 +00005823 return PT->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005824
John McCall183700f2009-09-21 23:43:11 +00005825 if (const ObjCObjectPointerType *OPT = Ty->getAs<ObjCObjectPointerType>())
Fariborz Jahanian16b10372009-09-03 00:43:07 +00005826 return OPT->getPointeeType();
Steve Naroff14108da2009-07-10 23:34:53 +00005827
Chris Lattnerd3a94e22008-11-20 06:06:08 +00005828 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner22caddc2008-11-23 09:13:29 +00005829 << Ty << Op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00005830 return QualType();
5831}
5832
5833static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
5834 tok::TokenKind Kind) {
5835 BinaryOperator::Opcode Opc;
5836 switch (Kind) {
5837 default: assert(0 && "Unknown binop!");
Sebastian Redl22460502009-02-07 00:15:38 +00005838 case tok::periodstar: Opc = BinaryOperator::PtrMemD; break;
5839 case tok::arrowstar: Opc = BinaryOperator::PtrMemI; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00005840 case tok::star: Opc = BinaryOperator::Mul; break;
5841 case tok::slash: Opc = BinaryOperator::Div; break;
5842 case tok::percent: Opc = BinaryOperator::Rem; break;
5843 case tok::plus: Opc = BinaryOperator::Add; break;
5844 case tok::minus: Opc = BinaryOperator::Sub; break;
5845 case tok::lessless: Opc = BinaryOperator::Shl; break;
5846 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
5847 case tok::lessequal: Opc = BinaryOperator::LE; break;
5848 case tok::less: Opc = BinaryOperator::LT; break;
5849 case tok::greaterequal: Opc = BinaryOperator::GE; break;
5850 case tok::greater: Opc = BinaryOperator::GT; break;
5851 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
5852 case tok::equalequal: Opc = BinaryOperator::EQ; break;
5853 case tok::amp: Opc = BinaryOperator::And; break;
5854 case tok::caret: Opc = BinaryOperator::Xor; break;
5855 case tok::pipe: Opc = BinaryOperator::Or; break;
5856 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
5857 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
5858 case tok::equal: Opc = BinaryOperator::Assign; break;
5859 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
5860 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
5861 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
5862 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
5863 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
5864 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
5865 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
5866 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
5867 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
5868 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
5869 case tok::comma: Opc = BinaryOperator::Comma; break;
5870 }
5871 return Opc;
5872}
5873
5874static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
5875 tok::TokenKind Kind) {
5876 UnaryOperator::Opcode Opc;
5877 switch (Kind) {
5878 default: assert(0 && "Unknown unary op!");
5879 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
5880 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
5881 case tok::amp: Opc = UnaryOperator::AddrOf; break;
5882 case tok::star: Opc = UnaryOperator::Deref; break;
5883 case tok::plus: Opc = UnaryOperator::Plus; break;
5884 case tok::minus: Opc = UnaryOperator::Minus; break;
5885 case tok::tilde: Opc = UnaryOperator::Not; break;
5886 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00005887 case tok::kw___real: Opc = UnaryOperator::Real; break;
5888 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
5889 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
5890 }
5891 return Opc;
5892}
5893
Douglas Gregoreaebc752008-11-06 23:29:22 +00005894/// CreateBuiltinBinOp - Creates a new built-in binary operation with
5895/// operator @p Opc at location @c TokLoc. This routine only supports
5896/// built-in operations; ActOnBinOp handles overloaded operators.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005897Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
5898 unsigned Op,
5899 Expr *lhs, Expr *rhs) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00005900 QualType ResultTy; // Result type of the binary operator.
Douglas Gregoreaebc752008-11-06 23:29:22 +00005901 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
Eli Friedmanab3a8522009-03-28 01:22:36 +00005902 // The following two variables are used for compound assignment operators
5903 QualType CompLHSTy; // Type of LHS after promotions for computation
5904 QualType CompResultTy; // Type of computation result
Douglas Gregoreaebc752008-11-06 23:29:22 +00005905
5906 switch (Opc) {
Douglas Gregoreaebc752008-11-06 23:29:22 +00005907 case BinaryOperator::Assign:
5908 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
5909 break;
Sebastian Redl22460502009-02-07 00:15:38 +00005910 case BinaryOperator::PtrMemD:
5911 case BinaryOperator::PtrMemI:
5912 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
5913 Opc == BinaryOperator::PtrMemI);
5914 break;
5915 case BinaryOperator::Mul:
Douglas Gregoreaebc752008-11-06 23:29:22 +00005916 case BinaryOperator::Div:
5917 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
5918 break;
5919 case BinaryOperator::Rem:
5920 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
5921 break;
5922 case BinaryOperator::Add:
5923 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
5924 break;
5925 case BinaryOperator::Sub:
5926 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
5927 break;
Sebastian Redl22460502009-02-07 00:15:38 +00005928 case BinaryOperator::Shl:
Douglas Gregoreaebc752008-11-06 23:29:22 +00005929 case BinaryOperator::Shr:
5930 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
5931 break;
5932 case BinaryOperator::LE:
5933 case BinaryOperator::LT:
5934 case BinaryOperator::GE:
5935 case BinaryOperator::GT:
Douglas Gregora86b8322009-04-06 18:45:53 +00005936 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregoreaebc752008-11-06 23:29:22 +00005937 break;
5938 case BinaryOperator::EQ:
5939 case BinaryOperator::NE:
Douglas Gregora86b8322009-04-06 18:45:53 +00005940 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregoreaebc752008-11-06 23:29:22 +00005941 break;
5942 case BinaryOperator::And:
5943 case BinaryOperator::Xor:
5944 case BinaryOperator::Or:
5945 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
5946 break;
5947 case BinaryOperator::LAnd:
5948 case BinaryOperator::LOr:
5949 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
5950 break;
5951 case BinaryOperator::MulAssign:
5952 case BinaryOperator::DivAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00005953 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
5954 CompLHSTy = CompResultTy;
5955 if (!CompResultTy.isNull())
5956 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00005957 break;
5958 case BinaryOperator::RemAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00005959 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
5960 CompLHSTy = CompResultTy;
5961 if (!CompResultTy.isNull())
5962 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00005963 break;
5964 case BinaryOperator::AddAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00005965 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
5966 if (!CompResultTy.isNull())
5967 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00005968 break;
5969 case BinaryOperator::SubAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00005970 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
5971 if (!CompResultTy.isNull())
5972 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00005973 break;
5974 case BinaryOperator::ShlAssign:
5975 case BinaryOperator::ShrAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00005976 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
5977 CompLHSTy = CompResultTy;
5978 if (!CompResultTy.isNull())
5979 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00005980 break;
5981 case BinaryOperator::AndAssign:
5982 case BinaryOperator::XorAssign:
5983 case BinaryOperator::OrAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00005984 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
5985 CompLHSTy = CompResultTy;
5986 if (!CompResultTy.isNull())
5987 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00005988 break;
5989 case BinaryOperator::Comma:
5990 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
5991 break;
5992 }
5993 if (ResultTy.isNull())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005994 return ExprError();
Eli Friedmanab3a8522009-03-28 01:22:36 +00005995 if (CompResultTy.isNull())
Steve Naroff6ece14c2009-01-21 00:14:39 +00005996 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
5997 else
5998 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
Eli Friedmanab3a8522009-03-28 01:22:36 +00005999 CompLHSTy, CompResultTy,
6000 OpLoc));
Douglas Gregoreaebc752008-11-06 23:29:22 +00006001}
6002
Sebastian Redlaee3c932009-10-27 12:10:02 +00006003/// SuggestParentheses - Emit a diagnostic together with a fixit hint that wraps
6004/// ParenRange in parentheses.
Sebastian Redl6b169ac2009-10-26 17:01:32 +00006005static void SuggestParentheses(Sema &Self, SourceLocation Loc,
6006 const PartialDiagnostic &PD,
6007 SourceRange ParenRange)
6008{
6009 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
6010 if (!ParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
6011 // We can't display the parentheses, so just dig the
6012 // warning/error and return.
6013 Self.Diag(Loc, PD);
6014 return;
6015 }
6016
6017 Self.Diag(Loc, PD)
6018 << CodeModificationHint::CreateInsertion(ParenRange.getBegin(), "(")
6019 << CodeModificationHint::CreateInsertion(EndLoc, ")");
6020}
6021
Sebastian Redlaee3c932009-10-27 12:10:02 +00006022/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
6023/// operators are mixed in a way that suggests that the programmer forgot that
6024/// comparison operators have higher precedence. The most typical example of
6025/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006026static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperator::Opcode Opc,
6027 SourceLocation OpLoc,Expr *lhs,Expr *rhs){
Sebastian Redlaee3c932009-10-27 12:10:02 +00006028 typedef BinaryOperator BinOp;
6029 BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1),
6030 rhsopc = static_cast<BinOp::Opcode>(-1);
6031 if (BinOp *BO = dyn_cast<BinOp>(lhs))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006032 lhsopc = BO->getOpcode();
Sebastian Redlaee3c932009-10-27 12:10:02 +00006033 if (BinOp *BO = dyn_cast<BinOp>(rhs))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006034 rhsopc = BO->getOpcode();
6035
6036 // Subs are not binary operators.
6037 if (lhsopc == -1 && rhsopc == -1)
6038 return;
6039
6040 // Bitwise operations are sometimes used as eager logical ops.
6041 // Don't diagnose this.
Sebastian Redlaee3c932009-10-27 12:10:02 +00006042 if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) &&
6043 (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc)))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006044 return;
6045
Sebastian Redlaee3c932009-10-27 12:10:02 +00006046 if (BinOp::isComparisonOp(lhsopc))
Sebastian Redl6b169ac2009-10-26 17:01:32 +00006047 SuggestParentheses(Self, OpLoc,
6048 PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redlaee3c932009-10-27 12:10:02 +00006049 << SourceRange(lhs->getLocStart(), OpLoc)
6050 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(lhsopc),
6051 SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(), rhs->getLocEnd()));
6052 else if (BinOp::isComparisonOp(rhsopc))
Sebastian Redl6b169ac2009-10-26 17:01:32 +00006053 SuggestParentheses(Self, OpLoc,
6054 PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redlaee3c932009-10-27 12:10:02 +00006055 << SourceRange(OpLoc, rhs->getLocEnd())
6056 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(rhsopc),
6057 SourceRange(lhs->getLocEnd(), cast<BinOp>(rhs)->getLHS()->getLocStart()));
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006058}
6059
6060/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
6061/// precedence. This currently diagnoses only "arg1 'bitwise' arg2 'eq' arg3".
6062/// But it could also warn about arg1 && arg2 || arg3, as GCC 4.3+ does.
6063static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperator::Opcode Opc,
6064 SourceLocation OpLoc, Expr *lhs, Expr *rhs){
Sebastian Redlaee3c932009-10-27 12:10:02 +00006065 if (BinaryOperator::isBitwiseOp(Opc))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006066 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs);
6067}
6068
Reid Spencer5f016e22007-07-11 17:01:13 +00006069// Binary Operators. 'Tok' is the token for the operator.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00006070Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
6071 tok::TokenKind Kind,
6072 ExprArg LHS, ExprArg RHS) {
Reid Spencer5f016e22007-07-11 17:01:13 +00006073 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
Anders Carlssone9146f22009-05-01 19:49:17 +00006074 Expr *lhs = LHS.takeAs<Expr>(), *rhs = RHS.takeAs<Expr>();
Reid Spencer5f016e22007-07-11 17:01:13 +00006075
Steve Narofff69936d2007-09-16 03:34:24 +00006076 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
6077 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00006078
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006079 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
6080 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs);
6081
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006082 return BuildBinOp(S, TokLoc, Opc, lhs, rhs);
6083}
6084
6085Action::OwningExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
6086 BinaryOperator::Opcode Opc,
6087 Expr *lhs, Expr *rhs) {
Douglas Gregor063daf62009-03-13 18:40:31 +00006088 if (getLangOptions().CPlusPlus &&
Mike Stump1eb44332009-09-09 15:08:12 +00006089 (lhs->getType()->isOverloadableType() ||
Douglas Gregor063daf62009-03-13 18:40:31 +00006090 rhs->getType()->isOverloadableType())) {
6091 // Find all of the overloaded operators visible from this
6092 // point. We perform both an operator-name lookup from the local
6093 // scope and an argument-dependent lookup based on the types of
6094 // the arguments.
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00006095 FunctionSet Functions;
Douglas Gregor063daf62009-03-13 18:40:31 +00006096 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
6097 if (OverOp != OO_None) {
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006098 if (S)
6099 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
6100 Functions);
Douglas Gregor063daf62009-03-13 18:40:31 +00006101 Expr *Args[2] = { lhs, rhs };
Mike Stump1eb44332009-09-09 15:08:12 +00006102 DeclarationName OpName
Douglas Gregor063daf62009-03-13 18:40:31 +00006103 = Context.DeclarationNames.getCXXOperatorName(OverOp);
Sebastian Redl644be852009-10-23 19:23:15 +00006104 ArgumentDependentLookup(OpName, /*Operator*/true, Args, 2, Functions);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006105 }
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006106
Douglas Gregor063daf62009-03-13 18:40:31 +00006107 // Build the (potentially-overloaded, potentially-dependent)
6108 // binary operation.
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006109 return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs);
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00006110 }
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006111
Douglas Gregoreaebc752008-11-06 23:29:22 +00006112 // Build a built-in binary operation.
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006113 return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs);
Reid Spencer5f016e22007-07-11 17:01:13 +00006114}
6115
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006116Action::OwningExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00006117 unsigned OpcIn,
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006118 ExprArg InputArg) {
6119 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor74253732008-11-19 15:42:04 +00006120
Mike Stump390b4cc2009-05-16 07:39:55 +00006121 // FIXME: Input is modified below, but InputArg is not updated appropriately.
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006122 Expr *Input = (Expr *)InputArg.get();
Reid Spencer5f016e22007-07-11 17:01:13 +00006123 QualType resultType;
6124 switch (Opc) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006125 case UnaryOperator::OffsetOf:
6126 assert(false && "Invalid unary operator");
6127 break;
6128
Reid Spencer5f016e22007-07-11 17:01:13 +00006129 case UnaryOperator::PreInc:
6130 case UnaryOperator::PreDec:
Eli Friedmande99a452009-07-22 22:25:00 +00006131 case UnaryOperator::PostInc:
6132 case UnaryOperator::PostDec:
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00006133 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
Eli Friedmande99a452009-07-22 22:25:00 +00006134 Opc == UnaryOperator::PreInc ||
6135 Opc == UnaryOperator::PostInc);
Reid Spencer5f016e22007-07-11 17:01:13 +00006136 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006137 case UnaryOperator::AddrOf:
Reid Spencer5f016e22007-07-11 17:01:13 +00006138 resultType = CheckAddressOfOperand(Input, OpLoc);
6139 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006140 case UnaryOperator::Deref:
Steve Naroff1ca9b112007-12-18 04:06:57 +00006141 DefaultFunctionArrayConversion(Input);
Reid Spencer5f016e22007-07-11 17:01:13 +00006142 resultType = CheckIndirectionOperand(Input, OpLoc);
6143 break;
6144 case UnaryOperator::Plus:
6145 case UnaryOperator::Minus:
Steve Naroffc80b4ee2007-07-16 21:54:35 +00006146 UsualUnaryConversions(Input);
6147 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00006148 if (resultType->isDependentType())
6149 break;
Douglas Gregor74253732008-11-19 15:42:04 +00006150 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
6151 break;
6152 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
6153 resultType->isEnumeralType())
6154 break;
6155 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
6156 Opc == UnaryOperator::Plus &&
6157 resultType->isPointerType())
6158 break;
6159
Sebastian Redl0eb23302009-01-19 00:08:26 +00006160 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
6161 << resultType << Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00006162 case UnaryOperator::Not: // bitwise complement
Steve Naroffc80b4ee2007-07-16 21:54:35 +00006163 UsualUnaryConversions(Input);
6164 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00006165 if (resultType->isDependentType())
6166 break;
Chris Lattner02a65142008-07-25 23:52:49 +00006167 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
6168 if (resultType->isComplexType() || resultType->isComplexIntegerType())
6169 // C99 does not support '~' for complex conjugation.
Chris Lattnerd3a94e22008-11-20 06:06:08 +00006170 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00006171 << resultType << Input->getSourceRange();
Chris Lattner02a65142008-07-25 23:52:49 +00006172 else if (!resultType->isIntegerType())
Sebastian Redl0eb23302009-01-19 00:08:26 +00006173 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
6174 << resultType << Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00006175 break;
6176 case UnaryOperator::LNot: // logical negation
6177 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Steve Naroffc80b4ee2007-07-16 21:54:35 +00006178 DefaultFunctionArrayConversion(Input);
6179 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00006180 if (resultType->isDependentType())
6181 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00006182 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redl0eb23302009-01-19 00:08:26 +00006183 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
6184 << resultType << Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00006185 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl0eb23302009-01-19 00:08:26 +00006186 // In C++, it's bool. C++ 5.3.1p8
6187 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00006188 break;
Chris Lattnerdbb36972007-08-24 21:16:53 +00006189 case UnaryOperator::Real:
Chris Lattnerdbb36972007-08-24 21:16:53 +00006190 case UnaryOperator::Imag:
Chris Lattnerba27e2a2009-02-17 08:12:06 +00006191 resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real);
Chris Lattnerdbb36972007-08-24 21:16:53 +00006192 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00006193 case UnaryOperator::Extension:
Reid Spencer5f016e22007-07-11 17:01:13 +00006194 resultType = Input->getType();
6195 break;
6196 }
6197 if (resultType.isNull())
Sebastian Redl0eb23302009-01-19 00:08:26 +00006198 return ExprError();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006199
6200 InputArg.release();
Steve Naroff6ece14c2009-01-21 00:14:39 +00006201 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00006202}
6203
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006204Action::OwningExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
6205 UnaryOperator::Opcode Opc,
6206 ExprArg input) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006207 Expr *Input = (Expr*)input.get();
Anders Carlssona8a1e3d2009-11-14 21:26:41 +00006208 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
6209 Opc != UnaryOperator::Extension) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006210 // Find all of the overloaded operators visible from this
6211 // point. We perform both an operator-name lookup from the local
6212 // scope and an argument-dependent lookup based on the types of
6213 // the arguments.
6214 FunctionSet Functions;
6215 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
6216 if (OverOp != OO_None) {
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006217 if (S)
6218 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
6219 Functions);
Mike Stump1eb44332009-09-09 15:08:12 +00006220 DeclarationName OpName
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006221 = Context.DeclarationNames.getCXXOperatorName(OverOp);
Sebastian Redl644be852009-10-23 19:23:15 +00006222 ArgumentDependentLookup(OpName, /*Operator*/true, &Input, 1, Functions);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006223 }
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006224
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006225 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, move(input));
6226 }
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006227
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006228 return CreateBuiltinUnaryOp(OpLoc, Opc, move(input));
6229}
6230
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006231// Unary Operators. 'Tok' is the token for the operator.
6232Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
6233 tok::TokenKind Op, ExprArg input) {
6234 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), move(input));
6235}
6236
Steve Naroff1b273c42007-09-16 14:56:35 +00006237/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Sebastian Redlf53597f2009-03-15 17:47:39 +00006238Sema::OwningExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
6239 SourceLocation LabLoc,
6240 IdentifierInfo *LabelII) {
Reid Spencer5f016e22007-07-11 17:01:13 +00006241 // Look up the record for this label identifier.
Chris Lattnerea29a3a2009-04-18 20:01:55 +00006242 LabelStmt *&LabelDecl = getLabelMap()[LabelII];
Mike Stumpeed9cac2009-02-19 03:04:26 +00006243
Daniel Dunbar0ffb1252008-08-04 16:51:22 +00006244 // If we haven't seen this label yet, create a forward reference. It
6245 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Steve Naroffcaaacec2009-03-13 15:38:40 +00006246 if (LabelDecl == 0)
Steve Naroff6ece14c2009-01-21 00:14:39 +00006247 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006248
Reid Spencer5f016e22007-07-11 17:01:13 +00006249 // Create the AST node. The address of a label always has type 'void*'.
Sebastian Redlf53597f2009-03-15 17:47:39 +00006250 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
6251 Context.getPointerType(Context.VoidTy)));
Reid Spencer5f016e22007-07-11 17:01:13 +00006252}
6253
Sebastian Redlf53597f2009-03-15 17:47:39 +00006254Sema::OwningExprResult
6255Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtArg substmt,
6256 SourceLocation RPLoc) { // "({..})"
6257 Stmt *SubStmt = static_cast<Stmt*>(substmt.get());
Chris Lattnerab18c4c2007-07-24 16:58:17 +00006258 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
6259 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
6260
Eli Friedmandca2b732009-01-24 23:09:00 +00006261 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Chris Lattner4a049f02009-04-25 19:11:05 +00006262 if (isFileScope)
Sebastian Redlf53597f2009-03-15 17:47:39 +00006263 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedmandca2b732009-01-24 23:09:00 +00006264
Chris Lattnerab18c4c2007-07-24 16:58:17 +00006265 // FIXME: there are a variety of strange constraints to enforce here, for
6266 // example, it is not possible to goto into a stmt expression apparently.
6267 // More semantic analysis is needed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00006268
Chris Lattnerab18c4c2007-07-24 16:58:17 +00006269 // If there are sub stmts in the compound stmt, take the type of the last one
6270 // as the type of the stmtexpr.
6271 QualType Ty = Context.VoidTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006272
Chris Lattner611b2ec2008-07-26 19:51:01 +00006273 if (!Compound->body_empty()) {
6274 Stmt *LastStmt = Compound->body_back();
6275 // If LastStmt is a label, skip down through into the body.
6276 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
6277 LastStmt = Label->getSubStmt();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006278
Chris Lattner611b2ec2008-07-26 19:51:01 +00006279 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattnerab18c4c2007-07-24 16:58:17 +00006280 Ty = LastExpr->getType();
Chris Lattner611b2ec2008-07-26 19:51:01 +00006281 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006282
Eli Friedmanb1d796d2009-03-23 00:24:07 +00006283 // FIXME: Check that expression type is complete/non-abstract; statement
6284 // expressions are not lvalues.
6285
Sebastian Redlf53597f2009-03-15 17:47:39 +00006286 substmt.release();
6287 return Owned(new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc));
Chris Lattnerab18c4c2007-07-24 16:58:17 +00006288}
Steve Naroffd34e9152007-08-01 22:05:33 +00006289
Sebastian Redlf53597f2009-03-15 17:47:39 +00006290Sema::OwningExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
6291 SourceLocation BuiltinLoc,
6292 SourceLocation TypeLoc,
6293 TypeTy *argty,
6294 OffsetOfComponent *CompPtr,
6295 unsigned NumComponents,
6296 SourceLocation RPLoc) {
6297 // FIXME: This function leaks all expressions in the offset components on
6298 // error.
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00006299 // FIXME: Preserve type source info.
6300 QualType ArgTy = GetTypeFromParser(argty);
Chris Lattner73d0d4f2007-08-30 17:45:32 +00006301 assert(!ArgTy.isNull() && "Missing type argument!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00006302
Sebastian Redl28507842009-02-26 14:39:58 +00006303 bool Dependent = ArgTy->isDependentType();
6304
Chris Lattner73d0d4f2007-08-30 17:45:32 +00006305 // We must have at least one component that refers to the type, and the first
6306 // one is known to be a field designator. Verify that the ArgTy represents
6307 // a struct/union/class.
Sebastian Redl28507842009-02-26 14:39:58 +00006308 if (!Dependent && !ArgTy->isRecordType())
Sebastian Redlf53597f2009-03-15 17:47:39 +00006309 return ExprError(Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006310
Eli Friedmanb1d796d2009-03-23 00:24:07 +00006311 // FIXME: Type must be complete per C99 7.17p3 because a declaring a variable
6312 // with an incomplete type would be illegal.
Douglas Gregor4fdf1fa2009-03-11 16:48:53 +00006313
Eli Friedman35183ac2009-02-27 06:44:11 +00006314 // Otherwise, create a null pointer as the base, and iteratively process
6315 // the offsetof designators.
6316 QualType ArgTyPtr = Context.getPointerType(ArgTy);
6317 Expr* Res = new (Context) ImplicitValueInitExpr(ArgTyPtr);
Sebastian Redlf53597f2009-03-15 17:47:39 +00006318 Res = new (Context) UnaryOperator(Res, UnaryOperator::Deref,
Eli Friedman35183ac2009-02-27 06:44:11 +00006319 ArgTy, SourceLocation());
Eli Friedman1d242592009-01-26 01:33:06 +00006320
Chris Lattner9e2b75c2007-08-31 21:49:13 +00006321 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
6322 // GCC extension, diagnose them.
Eli Friedman35183ac2009-02-27 06:44:11 +00006323 // FIXME: This diagnostic isn't actually visible because the location is in
6324 // a system header!
Chris Lattner9e2b75c2007-08-31 21:49:13 +00006325 if (NumComponents != 1)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00006326 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
6327 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006328
Sebastian Redl28507842009-02-26 14:39:58 +00006329 if (!Dependent) {
Eli Friedmanc0d600c2009-05-03 21:22:18 +00006330 bool DidWarnAboutNonPOD = false;
Mike Stump1eb44332009-09-09 15:08:12 +00006331
John McCalld00f2002009-11-04 03:03:43 +00006332 if (RequireCompleteType(TypeLoc, Res->getType(),
6333 diag::err_offsetof_incomplete_type))
6334 return ExprError();
6335
Sebastian Redl28507842009-02-26 14:39:58 +00006336 // FIXME: Dependent case loses a lot of information here. And probably
6337 // leaks like a sieve.
6338 for (unsigned i = 0; i != NumComponents; ++i) {
6339 const OffsetOfComponent &OC = CompPtr[i];
6340 if (OC.isBrackets) {
6341 // Offset of an array sub-field. TODO: Should we allow vector elements?
6342 const ArrayType *AT = Context.getAsArrayType(Res->getType());
6343 if (!AT) {
6344 Res->Destroy(Context);
Sebastian Redlf53597f2009-03-15 17:47:39 +00006345 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
6346 << Res->getType());
Sebastian Redl28507842009-02-26 14:39:58 +00006347 }
6348
6349 // FIXME: C++: Verify that operator[] isn't overloaded.
6350
Eli Friedman35183ac2009-02-27 06:44:11 +00006351 // Promote the array so it looks more like a normal array subscript
6352 // expression.
6353 DefaultFunctionArrayConversion(Res);
6354
Sebastian Redl28507842009-02-26 14:39:58 +00006355 // C99 6.5.2.1p1
6356 Expr *Idx = static_cast<Expr*>(OC.U.E);
Sebastian Redlf53597f2009-03-15 17:47:39 +00006357 // FIXME: Leaks Res
Sebastian Redl28507842009-02-26 14:39:58 +00006358 if (!Idx->isTypeDependent() && !Idx->getType()->isIntegerType())
Sebastian Redlf53597f2009-03-15 17:47:39 +00006359 return ExprError(Diag(Idx->getLocStart(),
Chris Lattner338395d2009-04-25 22:50:55 +00006360 diag::err_typecheck_subscript_not_integer)
Sebastian Redlf53597f2009-03-15 17:47:39 +00006361 << Idx->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +00006362
6363 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
6364 OC.LocEnd);
6365 continue;
Chris Lattner73d0d4f2007-08-30 17:45:32 +00006366 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006367
Ted Kremenek6217b802009-07-29 21:53:49 +00006368 const RecordType *RC = Res->getType()->getAs<RecordType>();
Sebastian Redl28507842009-02-26 14:39:58 +00006369 if (!RC) {
6370 Res->Destroy(Context);
Sebastian Redlf53597f2009-03-15 17:47:39 +00006371 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
6372 << Res->getType());
Sebastian Redl28507842009-02-26 14:39:58 +00006373 }
Chris Lattner704fe352007-08-30 17:59:59 +00006374
Sebastian Redl28507842009-02-26 14:39:58 +00006375 // Get the decl corresponding to this.
6376 RecordDecl *RD = RC->getDecl();
Anders Carlsson6d7f1492009-05-01 23:20:30 +00006377 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
Anders Carlsson5992e4a2009-05-02 18:36:10 +00006378 if (!CRD->isPOD() && !DidWarnAboutNonPOD) {
Anders Carlssonf9b8bc62009-05-02 17:45:47 +00006379 ExprError(Diag(BuiltinLoc, diag::warn_offsetof_non_pod_type)
6380 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
6381 << Res->getType());
Anders Carlsson5992e4a2009-05-02 18:36:10 +00006382 DidWarnAboutNonPOD = true;
6383 }
Anders Carlsson6d7f1492009-05-01 23:20:30 +00006384 }
Mike Stump1eb44332009-09-09 15:08:12 +00006385
John McCalla24dc2e2009-11-17 02:14:36 +00006386 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
6387 LookupQualifiedName(R, RD);
John McCallf36e02d2009-10-09 21:13:30 +00006388
John McCall1bcee0a2009-12-02 08:25:40 +00006389 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Sebastian Redlf53597f2009-03-15 17:47:39 +00006390 // FIXME: Leaks Res
Sebastian Redl28507842009-02-26 14:39:58 +00006391 if (!MemberDecl)
Douglas Gregor3f093272009-10-13 21:16:44 +00006392 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
6393 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, OC.LocEnd));
Mike Stumpeed9cac2009-02-19 03:04:26 +00006394
Sebastian Redl28507842009-02-26 14:39:58 +00006395 // FIXME: C++: Verify that MemberDecl isn't a static field.
6396 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedmane9356962009-04-26 20:50:44 +00006397 if (cast<RecordDecl>(MemberDecl->getDeclContext())->isAnonymousStructOrUnion()) {
Anders Carlssonf1b1d592009-05-01 19:30:39 +00006398 Res = BuildAnonymousStructUnionMemberReference(
John McCall09b6d0e2009-11-11 03:23:23 +00006399 OC.LocEnd, MemberDecl, Res, OC.LocEnd).takeAs<Expr>();
Eli Friedmane9356962009-04-26 20:50:44 +00006400 } else {
Eli Friedman16c53782009-12-04 07:18:51 +00006401 PerformObjectMemberConversion(Res, MemberDecl);
Eli Friedmane9356962009-04-26 20:50:44 +00006402 // MemberDecl->getType() doesn't get the right qualifiers, but it
6403 // doesn't matter here.
6404 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
6405 MemberDecl->getType().getNonReferenceType());
6406 }
Sebastian Redl28507842009-02-26 14:39:58 +00006407 }
Chris Lattner73d0d4f2007-08-30 17:45:32 +00006408 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006409
Sebastian Redlf53597f2009-03-15 17:47:39 +00006410 return Owned(new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
6411 Context.getSizeType(), BuiltinLoc));
Chris Lattner73d0d4f2007-08-30 17:45:32 +00006412}
6413
6414
Sebastian Redlf53597f2009-03-15 17:47:39 +00006415Sema::OwningExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
6416 TypeTy *arg1,TypeTy *arg2,
6417 SourceLocation RPLoc) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00006418 // FIXME: Preserve type source info.
6419 QualType argT1 = GetTypeFromParser(arg1);
6420 QualType argT2 = GetTypeFromParser(arg2);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006421
Steve Naroffd34e9152007-08-01 22:05:33 +00006422 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
Mike Stumpeed9cac2009-02-19 03:04:26 +00006423
Douglas Gregorc12a9c52009-05-19 22:28:02 +00006424 if (getLangOptions().CPlusPlus) {
6425 Diag(BuiltinLoc, diag::err_types_compatible_p_in_cplusplus)
6426 << SourceRange(BuiltinLoc, RPLoc);
6427 return ExprError();
6428 }
6429
Sebastian Redlf53597f2009-03-15 17:47:39 +00006430 return Owned(new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc,
6431 argT1, argT2, RPLoc));
Steve Naroffd34e9152007-08-01 22:05:33 +00006432}
6433
Sebastian Redlf53597f2009-03-15 17:47:39 +00006434Sema::OwningExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
6435 ExprArg cond,
6436 ExprArg expr1, ExprArg expr2,
6437 SourceLocation RPLoc) {
6438 Expr *CondExpr = static_cast<Expr*>(cond.get());
6439 Expr *LHSExpr = static_cast<Expr*>(expr1.get());
6440 Expr *RHSExpr = static_cast<Expr*>(expr2.get());
Mike Stumpeed9cac2009-02-19 03:04:26 +00006441
Steve Naroffd04fdd52007-08-03 21:21:27 +00006442 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
6443
Sebastian Redl28507842009-02-26 14:39:58 +00006444 QualType resType;
Douglas Gregorce940492009-09-25 04:25:58 +00006445 bool ValueDependent = false;
Douglas Gregorc9ecc572009-05-19 22:43:30 +00006446 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl28507842009-02-26 14:39:58 +00006447 resType = Context.DependentTy;
Douglas Gregorce940492009-09-25 04:25:58 +00006448 ValueDependent = true;
Sebastian Redl28507842009-02-26 14:39:58 +00006449 } else {
6450 // The conditional expression is required to be a constant expression.
6451 llvm::APSInt condEval(32);
6452 SourceLocation ExpLoc;
6453 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redlf53597f2009-03-15 17:47:39 +00006454 return ExprError(Diag(ExpLoc,
6455 diag::err_typecheck_choose_expr_requires_constant)
6456 << CondExpr->getSourceRange());
Steve Naroffd04fdd52007-08-03 21:21:27 +00006457
Sebastian Redl28507842009-02-26 14:39:58 +00006458 // If the condition is > zero, then the AST type is the same as the LSHExpr.
6459 resType = condEval.getZExtValue() ? LHSExpr->getType() : RHSExpr->getType();
Douglas Gregorce940492009-09-25 04:25:58 +00006460 ValueDependent = condEval.getZExtValue() ? LHSExpr->isValueDependent()
6461 : RHSExpr->isValueDependent();
Sebastian Redl28507842009-02-26 14:39:58 +00006462 }
6463
Sebastian Redlf53597f2009-03-15 17:47:39 +00006464 cond.release(); expr1.release(); expr2.release();
6465 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
Douglas Gregorce940492009-09-25 04:25:58 +00006466 resType, RPLoc,
6467 resType->isDependentType(),
6468 ValueDependent));
Steve Naroffd04fdd52007-08-03 21:21:27 +00006469}
6470
Steve Naroff4eb206b2008-09-03 18:15:37 +00006471//===----------------------------------------------------------------------===//
6472// Clang Extensions.
6473//===----------------------------------------------------------------------===//
6474
6475/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff090276f2008-10-10 01:28:17 +00006476void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00006477 // Analyze block parameters.
6478 BlockSemaInfo *BSI = new BlockSemaInfo();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006479
Steve Naroff4eb206b2008-09-03 18:15:37 +00006480 // Add BSI to CurBlock.
6481 BSI->PrevBlockInfo = CurBlock;
6482 CurBlock = BSI;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006483
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00006484 BSI->ReturnType = QualType();
Steve Naroff4eb206b2008-09-03 18:15:37 +00006485 BSI->TheScope = BlockScope;
Mike Stumpb83d2872009-02-19 22:01:56 +00006486 BSI->hasBlockDeclRefExprs = false;
Daniel Dunbar1d2154c2009-07-29 01:59:17 +00006487 BSI->hasPrototype = false;
Chris Lattner17a78302009-04-19 05:28:12 +00006488 BSI->SavedFunctionNeedsScopeChecking = CurFunctionNeedsScopeChecking;
6489 CurFunctionNeedsScopeChecking = false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006490
Steve Naroff090276f2008-10-10 01:28:17 +00006491 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Douglas Gregor44b43212008-12-11 16:49:14 +00006492 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff090276f2008-10-10 01:28:17 +00006493}
6494
Mike Stump98eb8a72009-02-04 22:31:32 +00006495void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpaf199f32009-05-07 18:43:07 +00006496 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
Mike Stump98eb8a72009-02-04 22:31:32 +00006497
6498 if (ParamInfo.getNumTypeObjects() == 0
6499 || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) {
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00006500 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
Mike Stump98eb8a72009-02-04 22:31:32 +00006501 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
6502
Mike Stump4eeab842009-04-28 01:10:27 +00006503 if (T->isArrayType()) {
6504 Diag(ParamInfo.getSourceRange().getBegin(),
6505 diag::err_block_returns_array);
6506 return;
6507 }
6508
Mike Stump98eb8a72009-02-04 22:31:32 +00006509 // The parameter list is optional, if there was none, assume ().
6510 if (!T->isFunctionType())
6511 T = Context.getFunctionType(T, NULL, 0, 0, 0);
6512
6513 CurBlock->hasPrototype = true;
6514 CurBlock->isVariadic = false;
Fariborz Jahanian2f7c3922009-05-14 20:53:39 +00006515 // Check for a valid sentinel attribute on this block.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00006516 if (CurBlock->TheDecl->getAttr<SentinelAttr>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00006517 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian3bba33d2009-05-15 21:18:04 +00006518 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian2f7c3922009-05-14 20:53:39 +00006519 // FIXME: remove the attribute.
6520 }
John McCall183700f2009-09-21 23:43:11 +00006521 QualType RetTy = T.getTypePtr()->getAs<FunctionType>()->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00006522
Chris Lattner9097af12009-04-11 19:27:54 +00006523 // Do not allow returning a objc interface by-value.
6524 if (RetTy->isObjCInterfaceType()) {
6525 Diag(ParamInfo.getSourceRange().getBegin(),
6526 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
6527 return;
6528 }
Mike Stump98eb8a72009-02-04 22:31:32 +00006529 return;
6530 }
6531
Steve Naroff4eb206b2008-09-03 18:15:37 +00006532 // Analyze arguments to block.
6533 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
6534 "Not a function declarator!");
6535 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006536
Steve Naroff090276f2008-10-10 01:28:17 +00006537 CurBlock->hasPrototype = FTI.hasPrototype;
6538 CurBlock->isVariadic = true;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006539
Steve Naroff4eb206b2008-09-03 18:15:37 +00006540 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
6541 // no arguments, not a function that takes a single void argument.
6542 if (FTI.hasPrototype &&
6543 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
Chris Lattnerb28317a2009-03-28 19:18:32 +00006544 (!FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType().getCVRQualifiers()&&
6545 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType())) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00006546 // empty arg list, don't push any params.
Steve Naroff090276f2008-10-10 01:28:17 +00006547 CurBlock->isVariadic = false;
Steve Naroff4eb206b2008-09-03 18:15:37 +00006548 } else if (FTI.hasPrototype) {
6549 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Chris Lattnerb28317a2009-03-28 19:18:32 +00006550 CurBlock->Params.push_back(FTI.ArgInfo[i].Param.getAs<ParmVarDecl>());
Steve Naroff090276f2008-10-10 01:28:17 +00006551 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroff4eb206b2008-09-03 18:15:37 +00006552 }
Jay Foadbeaaccd2009-05-21 09:52:38 +00006553 CurBlock->TheDecl->setParams(Context, CurBlock->Params.data(),
Chris Lattner9097af12009-04-11 19:27:54 +00006554 CurBlock->Params.size());
Fariborz Jahaniand66f22d2009-05-19 17:08:59 +00006555 CurBlock->TheDecl->setIsVariadic(CurBlock->isVariadic);
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00006556 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
Steve Naroff090276f2008-10-10 01:28:17 +00006557 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
6558 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
6559 // If this has an identifier, add it to the scope stack.
6560 if ((*AI)->getIdentifier())
6561 PushOnScopeChains(*AI, CurBlock->TheScope);
Chris Lattner9097af12009-04-11 19:27:54 +00006562
Fariborz Jahanian2f7c3922009-05-14 20:53:39 +00006563 // Check for a valid sentinel attribute on this block.
Mike Stump1eb44332009-09-09 15:08:12 +00006564 if (!CurBlock->isVariadic &&
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00006565 CurBlock->TheDecl->getAttr<SentinelAttr>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00006566 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian3bba33d2009-05-15 21:18:04 +00006567 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian2f7c3922009-05-14 20:53:39 +00006568 // FIXME: remove the attribute.
6569 }
Mike Stump1eb44332009-09-09 15:08:12 +00006570
Chris Lattner9097af12009-04-11 19:27:54 +00006571 // Analyze the return type.
6572 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
John McCall183700f2009-09-21 23:43:11 +00006573 QualType RetTy = T->getAs<FunctionType>()->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00006574
Chris Lattner9097af12009-04-11 19:27:54 +00006575 // Do not allow returning a objc interface by-value.
6576 if (RetTy->isObjCInterfaceType()) {
6577 Diag(ParamInfo.getSourceRange().getBegin(),
6578 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
6579 } else if (!RetTy->isDependentType())
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00006580 CurBlock->ReturnType = RetTy;
Steve Naroff4eb206b2008-09-03 18:15:37 +00006581}
6582
6583/// ActOnBlockError - If there is an error parsing a block, this callback
6584/// is invoked to pop the information about the block from the action impl.
6585void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
6586 // Ensure that CurBlock is deleted.
6587 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006588
Chris Lattner17a78302009-04-19 05:28:12 +00006589 CurFunctionNeedsScopeChecking = CurBlock->SavedFunctionNeedsScopeChecking;
6590
Steve Naroff4eb206b2008-09-03 18:15:37 +00006591 // Pop off CurBlock, handle nested blocks.
Chris Lattner5c59e2b2009-04-21 22:38:46 +00006592 PopDeclContext();
Steve Naroff4eb206b2008-09-03 18:15:37 +00006593 CurBlock = CurBlock->PrevBlockInfo;
Steve Naroff4eb206b2008-09-03 18:15:37 +00006594 // FIXME: Delete the ParmVarDecl objects as well???
Steve Naroff4eb206b2008-09-03 18:15:37 +00006595}
6596
6597/// ActOnBlockStmtExpr - This is called when the body of a block statement
6598/// literal was successfully completed. ^(int x){...}
Sebastian Redlf53597f2009-03-15 17:47:39 +00006599Sema::OwningExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
6600 StmtArg body, Scope *CurScope) {
Chris Lattner9af55002009-03-27 04:18:06 +00006601 // If blocks are disabled, emit an error.
6602 if (!LangOpts.Blocks)
6603 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump1eb44332009-09-09 15:08:12 +00006604
Steve Naroff4eb206b2008-09-03 18:15:37 +00006605 // Ensure that CurBlock is deleted.
6606 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
Steve Naroff4eb206b2008-09-03 18:15:37 +00006607
Steve Naroff090276f2008-10-10 01:28:17 +00006608 PopDeclContext();
6609
Steve Naroff4eb206b2008-09-03 18:15:37 +00006610 // Pop off CurBlock, handle nested blocks.
6611 CurBlock = CurBlock->PrevBlockInfo;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006612
Steve Naroff4eb206b2008-09-03 18:15:37 +00006613 QualType RetTy = Context.VoidTy;
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00006614 if (!BSI->ReturnType.isNull())
6615 RetTy = BSI->ReturnType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006616
Steve Naroff4eb206b2008-09-03 18:15:37 +00006617 llvm::SmallVector<QualType, 8> ArgTypes;
6618 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
6619 ArgTypes.push_back(BSI->Params[i]->getType());
Mike Stumpeed9cac2009-02-19 03:04:26 +00006620
Mike Stump56925862009-07-28 22:04:01 +00006621 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroff4eb206b2008-09-03 18:15:37 +00006622 QualType BlockTy;
6623 if (!BSI->hasPrototype)
Mike Stump56925862009-07-28 22:04:01 +00006624 BlockTy = Context.getFunctionType(RetTy, 0, 0, false, 0, false, false, 0, 0,
6625 NoReturn);
Steve Naroff4eb206b2008-09-03 18:15:37 +00006626 else
Jay Foadbeaaccd2009-05-21 09:52:38 +00006627 BlockTy = Context.getFunctionType(RetTy, ArgTypes.data(), ArgTypes.size(),
Mike Stump56925862009-07-28 22:04:01 +00006628 BSI->isVariadic, 0, false, false, 0, 0,
6629 NoReturn);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006630
Eli Friedmanb1d796d2009-03-23 00:24:07 +00006631 // FIXME: Check that return/parameter types are complete/non-abstract
Douglas Gregore0762c92009-06-19 23:52:42 +00006632 DiagnoseUnusedParameters(BSI->Params.begin(), BSI->Params.end());
Steve Naroff4eb206b2008-09-03 18:15:37 +00006633 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006634
Chris Lattner17a78302009-04-19 05:28:12 +00006635 // If needed, diagnose invalid gotos and switches in the block.
6636 if (CurFunctionNeedsScopeChecking)
6637 DiagnoseInvalidJumps(static_cast<CompoundStmt*>(body.get()));
6638 CurFunctionNeedsScopeChecking = BSI->SavedFunctionNeedsScopeChecking;
Mike Stump1eb44332009-09-09 15:08:12 +00006639
Anders Carlssone9146f22009-05-01 19:49:17 +00006640 BSI->TheDecl->setBody(body.takeAs<CompoundStmt>());
Mike Stump56925862009-07-28 22:04:01 +00006641 CheckFallThroughForBlock(BlockTy, BSI->TheDecl->getBody());
Sebastian Redlf53597f2009-03-15 17:47:39 +00006642 return Owned(new (Context) BlockExpr(BSI->TheDecl, BlockTy,
6643 BSI->hasBlockDeclRefExprs));
Steve Naroff4eb206b2008-09-03 18:15:37 +00006644}
6645
Sebastian Redlf53597f2009-03-15 17:47:39 +00006646Sema::OwningExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
6647 ExprArg expr, TypeTy *type,
6648 SourceLocation RPLoc) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00006649 QualType T = GetTypeFromParser(type);
Chris Lattner0d20b8a2009-04-05 15:49:53 +00006650 Expr *E = static_cast<Expr*>(expr.get());
6651 Expr *OrigExpr = E;
Mike Stump1eb44332009-09-09 15:08:12 +00006652
Anders Carlsson7c50aca2007-10-15 20:28:48 +00006653 InitBuiltinVaListType();
Eli Friedmanc34bcde2008-08-09 23:32:40 +00006654
6655 // Get the va_list type
6656 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedman5c091ba2009-05-16 12:46:54 +00006657 if (VaListType->isArrayType()) {
6658 // Deal with implicit array decay; for example, on x86-64,
6659 // va_list is an array, but it's supposed to decay to
6660 // a pointer for va_arg.
Eli Friedmanc34bcde2008-08-09 23:32:40 +00006661 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman5c091ba2009-05-16 12:46:54 +00006662 // Make sure the input expression also decays appropriately.
6663 UsualUnaryConversions(E);
6664 } else {
6665 // Otherwise, the va_list argument must be an l-value because
6666 // it is modified by va_arg.
Mike Stump1eb44332009-09-09 15:08:12 +00006667 if (!E->isTypeDependent() &&
Douglas Gregordd027302009-05-19 23:10:31 +00006668 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedman5c091ba2009-05-16 12:46:54 +00006669 return ExprError();
6670 }
Eli Friedmanc34bcde2008-08-09 23:32:40 +00006671
Douglas Gregordd027302009-05-19 23:10:31 +00006672 if (!E->isTypeDependent() &&
6673 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redlf53597f2009-03-15 17:47:39 +00006674 return ExprError(Diag(E->getLocStart(),
6675 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner0d20b8a2009-04-05 15:49:53 +00006676 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner9dc8f192009-04-05 00:59:53 +00006677 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006678
Eli Friedmanb1d796d2009-03-23 00:24:07 +00006679 // FIXME: Check that type is complete/non-abstract
Anders Carlsson7c50aca2007-10-15 20:28:48 +00006680 // FIXME: Warn if a non-POD type is passed in.
Mike Stumpeed9cac2009-02-19 03:04:26 +00006681
Sebastian Redlf53597f2009-03-15 17:47:39 +00006682 expr.release();
6683 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(),
6684 RPLoc));
Anders Carlsson7c50aca2007-10-15 20:28:48 +00006685}
6686
Sebastian Redlf53597f2009-03-15 17:47:39 +00006687Sema::OwningExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor2d8b2732008-11-29 04:51:27 +00006688 // The type of __null will be int or long, depending on the size of
6689 // pointers on the target.
6690 QualType Ty;
6691 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
6692 Ty = Context.IntTy;
6693 else
6694 Ty = Context.LongTy;
6695
Sebastian Redlf53597f2009-03-15 17:47:39 +00006696 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor2d8b2732008-11-29 04:51:27 +00006697}
6698
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00006699static void
6700MakeObjCStringLiteralCodeModificationHint(Sema& SemaRef,
6701 QualType DstType,
6702 Expr *SrcExpr,
6703 CodeModificationHint &Hint) {
6704 if (!SemaRef.getLangOptions().ObjC1)
6705 return;
6706
6707 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
6708 if (!PT)
6709 return;
6710
6711 // Check if the destination is of type 'id'.
6712 if (!PT->isObjCIdType()) {
6713 // Check if the destination is the 'NSString' interface.
6714 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
6715 if (!ID || !ID->getIdentifier()->isStr("NSString"))
6716 return;
6717 }
6718
6719 // Strip off any parens and casts.
6720 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
6721 if (!SL || SL->isWide())
6722 return;
6723
6724 Hint = CodeModificationHint::CreateInsertion(SL->getLocStart(), "@");
6725}
6726
Chris Lattner5cf216b2008-01-04 18:04:52 +00006727bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
6728 SourceLocation Loc,
6729 QualType DstType, QualType SrcType,
6730 Expr *SrcExpr, const char *Flavor) {
6731 // Decode the result (notice that AST's are still created for extensions).
6732 bool isInvalid = false;
6733 unsigned DiagKind;
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00006734 CodeModificationHint Hint;
6735
Chris Lattner5cf216b2008-01-04 18:04:52 +00006736 switch (ConvTy) {
6737 default: assert(0 && "Unknown conversion type");
6738 case Compatible: return false;
Chris Lattnerb7b61152008-01-04 18:22:42 +00006739 case PointerToInt:
Chris Lattner5cf216b2008-01-04 18:04:52 +00006740 DiagKind = diag::ext_typecheck_convert_pointer_int;
6741 break;
Chris Lattnerb7b61152008-01-04 18:22:42 +00006742 case IntToPointer:
6743 DiagKind = diag::ext_typecheck_convert_int_pointer;
6744 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00006745 case IncompatiblePointer:
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00006746 MakeObjCStringLiteralCodeModificationHint(*this, DstType, SrcExpr, Hint);
Chris Lattner5cf216b2008-01-04 18:04:52 +00006747 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
6748 break;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00006749 case IncompatiblePointerSign:
6750 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
6751 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00006752 case FunctionVoidPointer:
6753 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
6754 break;
6755 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor77a52232008-09-12 00:47:35 +00006756 // If the qualifiers lost were because we were applying the
6757 // (deprecated) C++ conversion from a string literal to a char*
6758 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
6759 // Ideally, this check would be performed in
6760 // CheckPointerTypesForAssignment. However, that would require a
6761 // bit of refactoring (so that the second argument is an
6762 // expression, rather than a type), which should be done as part
6763 // of a larger effort to fix CheckPointerTypesForAssignment for
6764 // C++ semantics.
6765 if (getLangOptions().CPlusPlus &&
6766 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
6767 return false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00006768 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
6769 break;
Sean Huntc9132b62009-11-08 07:46:34 +00006770 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanian3451e922009-11-09 22:16:37 +00006771 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00006772 break;
Steve Naroff1c7d0672008-09-04 15:10:53 +00006773 case IntToBlockPointer:
6774 DiagKind = diag::err_int_to_block_pointer;
6775 break;
6776 case IncompatibleBlockPointer:
Mike Stump25efa102009-04-21 22:51:42 +00006777 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00006778 break;
Steve Naroff39579072008-10-14 22:18:38 +00006779 case IncompatibleObjCQualifiedId:
Mike Stumpeed9cac2009-02-19 03:04:26 +00006780 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff39579072008-10-14 22:18:38 +00006781 // it can give a more specific diagnostic.
6782 DiagKind = diag::warn_incompatible_qualified_id;
6783 break;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00006784 case IncompatibleVectors:
6785 DiagKind = diag::warn_incompatible_vectors;
6786 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00006787 case Incompatible:
6788 DiagKind = diag::err_typecheck_convert_incompatible;
6789 isInvalid = true;
6790 break;
6791 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006792
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00006793 Diag(Loc, DiagKind) << DstType << SrcType << Flavor
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00006794 << SrcExpr->getSourceRange() << Hint;
Chris Lattner5cf216b2008-01-04 18:04:52 +00006795 return isInvalid;
6796}
Anders Carlssone21555e2008-11-30 19:50:32 +00006797
Chris Lattner3bf68932009-04-25 21:59:05 +00006798bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedman3b5ccca2009-04-25 22:26:58 +00006799 llvm::APSInt ICEResult;
6800 if (E->isIntegerConstantExpr(ICEResult, Context)) {
6801 if (Result)
6802 *Result = ICEResult;
6803 return false;
6804 }
6805
Anders Carlssone21555e2008-11-30 19:50:32 +00006806 Expr::EvalResult EvalResult;
6807
Mike Stumpeed9cac2009-02-19 03:04:26 +00006808 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone21555e2008-11-30 19:50:32 +00006809 EvalResult.HasSideEffects) {
6810 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
6811
6812 if (EvalResult.Diag) {
6813 // We only show the note if it's not the usual "invalid subexpression"
6814 // or if it's actually in a subexpression.
6815 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
6816 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
6817 Diag(EvalResult.DiagLoc, EvalResult.Diag);
6818 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006819
Anders Carlssone21555e2008-11-30 19:50:32 +00006820 return true;
6821 }
6822
Eli Friedman3b5ccca2009-04-25 22:26:58 +00006823 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
6824 E->getSourceRange();
Anders Carlssone21555e2008-11-30 19:50:32 +00006825
Eli Friedman3b5ccca2009-04-25 22:26:58 +00006826 if (EvalResult.Diag &&
6827 Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
6828 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006829
Anders Carlssone21555e2008-11-30 19:50:32 +00006830 if (Result)
6831 *Result = EvalResult.Val.getInt();
6832 return false;
6833}
Douglas Gregore0762c92009-06-19 23:52:42 +00006834
Douglas Gregor2afce722009-11-26 00:44:06 +00006835void
Mike Stump1eb44332009-09-09 15:08:12 +00006836Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregor2afce722009-11-26 00:44:06 +00006837 ExprEvalContexts.push_back(
6838 ExpressionEvaluationContextRecord(NewContext, ExprTemporaries.size()));
Douglas Gregorac7610d2009-06-22 20:57:11 +00006839}
6840
Mike Stump1eb44332009-09-09 15:08:12 +00006841void
Douglas Gregor2afce722009-11-26 00:44:06 +00006842Sema::PopExpressionEvaluationContext() {
6843 // Pop the current expression evaluation context off the stack.
6844 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
6845 ExprEvalContexts.pop_back();
Douglas Gregorac7610d2009-06-22 20:57:11 +00006846
Douglas Gregor2afce722009-11-26 00:44:06 +00006847 if (Rec.Context == PotentiallyPotentiallyEvaluated &&
6848 Rec.PotentiallyReferenced) {
Douglas Gregorac7610d2009-06-22 20:57:11 +00006849 // Mark any remaining declarations in the current position of the stack
6850 // as "referenced". If they were not meant to be referenced, semantic
6851 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
Douglas Gregor2afce722009-11-26 00:44:06 +00006852 for (PotentiallyReferencedDecls::iterator
6853 I = Rec.PotentiallyReferenced->begin(),
6854 IEnd = Rec.PotentiallyReferenced->end();
Douglas Gregorac7610d2009-06-22 20:57:11 +00006855 I != IEnd; ++I)
6856 MarkDeclarationReferenced(I->first, I->second);
Douglas Gregor2afce722009-11-26 00:44:06 +00006857 }
6858
6859 // When are coming out of an unevaluated context, clear out any
6860 // temporaries that we may have created as part of the evaluation of
6861 // the expression in that context: they aren't relevant because they
6862 // will never be constructed.
6863 if (Rec.Context == Unevaluated &&
6864 ExprTemporaries.size() > Rec.NumTemporaries)
6865 ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
6866 ExprTemporaries.end());
6867
6868 // Destroy the popped expression evaluation record.
6869 Rec.Destroy();
Douglas Gregorac7610d2009-06-22 20:57:11 +00006870}
Douglas Gregore0762c92009-06-19 23:52:42 +00006871
6872/// \brief Note that the given declaration was referenced in the source code.
6873///
6874/// This routine should be invoke whenever a given declaration is referenced
6875/// in the source code, and where that reference occurred. If this declaration
6876/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
6877/// C99 6.9p3), then the declaration will be marked as used.
6878///
6879/// \param Loc the location where the declaration was referenced.
6880///
6881/// \param D the declaration that has been referenced by the source code.
6882void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
6883 assert(D && "No declaration?");
Mike Stump1eb44332009-09-09 15:08:12 +00006884
Douglas Gregord7f37bf2009-06-22 23:06:13 +00006885 if (D->isUsed())
6886 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006887
Douglas Gregorb5352cf2009-10-08 21:35:42 +00006888 // Mark a parameter or variable declaration "used", regardless of whether we're in a
6889 // template or not. The reason for this is that unevaluated expressions
6890 // (e.g. (void)sizeof()) constitute a use for warning purposes (-Wunused-variables and
6891 // -Wunused-parameters)
6892 if (isa<ParmVarDecl>(D) ||
6893 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod()))
Douglas Gregore0762c92009-06-19 23:52:42 +00006894 D->setUsed(true);
Mike Stump1eb44332009-09-09 15:08:12 +00006895
Douglas Gregore0762c92009-06-19 23:52:42 +00006896 // Do not mark anything as "used" within a dependent context; wait for
6897 // an instantiation.
6898 if (CurContext->isDependentContext())
6899 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006900
Douglas Gregor2afce722009-11-26 00:44:06 +00006901 switch (ExprEvalContexts.back().Context) {
Douglas Gregorac7610d2009-06-22 20:57:11 +00006902 case Unevaluated:
6903 // We are in an expression that is not potentially evaluated; do nothing.
6904 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006905
Douglas Gregorac7610d2009-06-22 20:57:11 +00006906 case PotentiallyEvaluated:
6907 // We are in a potentially-evaluated expression, so this declaration is
6908 // "used"; handle this below.
6909 break;
Mike Stump1eb44332009-09-09 15:08:12 +00006910
Douglas Gregorac7610d2009-06-22 20:57:11 +00006911 case PotentiallyPotentiallyEvaluated:
6912 // We are in an expression that may be potentially evaluated; queue this
6913 // declaration reference until we know whether the expression is
6914 // potentially evaluated.
Douglas Gregor2afce722009-11-26 00:44:06 +00006915 ExprEvalContexts.back().addReferencedDecl(Loc, D);
Douglas Gregorac7610d2009-06-22 20:57:11 +00006916 return;
6917 }
Mike Stump1eb44332009-09-09 15:08:12 +00006918
Douglas Gregore0762c92009-06-19 23:52:42 +00006919 // Note that this declaration has been used.
Fariborz Jahanianb7f4cc02009-06-22 17:30:33 +00006920 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00006921 unsigned TypeQuals;
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00006922 if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) {
6923 if (!Constructor->isUsed())
6924 DefineImplicitDefaultConstructor(Loc, Constructor);
Mike Stump1eb44332009-09-09 15:08:12 +00006925 } else if (Constructor->isImplicit() &&
Mike Stumpac5fc7c2009-08-04 21:02:39 +00006926 Constructor->isCopyConstructor(Context, TypeQuals)) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00006927 if (!Constructor->isUsed())
6928 DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals);
6929 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00006930 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
6931 if (Destructor->isImplicit() && !Destructor->isUsed())
6932 DefineImplicitDestructor(Loc, Destructor);
Mike Stump1eb44332009-09-09 15:08:12 +00006933
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00006934 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
6935 if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
6936 MethodDecl->getOverloadedOperator() == OO_Equal) {
6937 if (!MethodDecl->isUsed())
6938 DefineImplicitOverloadedAssign(Loc, MethodDecl);
6939 }
6940 }
Fariborz Jahanianf5ed9e02009-06-24 22:09:44 +00006941 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Mike Stump1eb44332009-09-09 15:08:12 +00006942 // Implicit instantiation of function templates and member functions of
Douglas Gregor1637be72009-06-26 00:10:03 +00006943 // class templates.
Douglas Gregor3b846b62009-10-27 20:53:28 +00006944 if (!Function->getBody() && Function->isImplicitlyInstantiable()) {
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00006945 bool AlreadyInstantiated = false;
6946 if (FunctionTemplateSpecializationInfo *SpecInfo
6947 = Function->getTemplateSpecializationInfo()) {
6948 if (SpecInfo->getPointOfInstantiation().isInvalid())
6949 SpecInfo->setPointOfInstantiation(Loc);
Douglas Gregor3b846b62009-10-27 20:53:28 +00006950 else if (SpecInfo->getTemplateSpecializationKind()
6951 == TSK_ImplicitInstantiation)
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00006952 AlreadyInstantiated = true;
6953 } else if (MemberSpecializationInfo *MSInfo
6954 = Function->getMemberSpecializationInfo()) {
6955 if (MSInfo->getPointOfInstantiation().isInvalid())
6956 MSInfo->setPointOfInstantiation(Loc);
Douglas Gregor3b846b62009-10-27 20:53:28 +00006957 else if (MSInfo->getTemplateSpecializationKind()
6958 == TSK_ImplicitInstantiation)
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00006959 AlreadyInstantiated = true;
6960 }
6961
6962 if (!AlreadyInstantiated)
6963 PendingImplicitInstantiations.push_back(std::make_pair(Function, Loc));
6964 }
6965
Douglas Gregore0762c92009-06-19 23:52:42 +00006966 // FIXME: keep track of references to static functions
Douglas Gregore0762c92009-06-19 23:52:42 +00006967 Function->setUsed(true);
6968 return;
Douglas Gregord7f37bf2009-06-22 23:06:13 +00006969 }
Mike Stump1eb44332009-09-09 15:08:12 +00006970
Douglas Gregore0762c92009-06-19 23:52:42 +00006971 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00006972 // Implicit instantiation of static data members of class templates.
Mike Stump1eb44332009-09-09 15:08:12 +00006973 if (Var->isStaticDataMember() &&
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00006974 Var->getInstantiatedFromStaticDataMember()) {
6975 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
6976 assert(MSInfo && "Missing member specialization information?");
6977 if (MSInfo->getPointOfInstantiation().isInvalid() &&
6978 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
6979 MSInfo->setPointOfInstantiation(Loc);
6980 PendingImplicitInstantiations.push_back(std::make_pair(Var, Loc));
6981 }
6982 }
Mike Stump1eb44332009-09-09 15:08:12 +00006983
Douglas Gregore0762c92009-06-19 23:52:42 +00006984 // FIXME: keep track of references to static data?
Douglas Gregor7caa6822009-07-24 20:34:43 +00006985
Douglas Gregore0762c92009-06-19 23:52:42 +00006986 D->setUsed(true);
Douglas Gregor7caa6822009-07-24 20:34:43 +00006987 return;
Sam Weinigcce6ebc2009-09-11 03:29:30 +00006988 }
Douglas Gregore0762c92009-06-19 23:52:42 +00006989}
Anders Carlsson8c8d9192009-10-09 23:51:55 +00006990
6991bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
6992 CallExpr *CE, FunctionDecl *FD) {
6993 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
6994 return false;
6995
6996 PartialDiagnostic Note =
6997 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
6998 << FD->getDeclName() : PDiag();
6999 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
7000
7001 if (RequireCompleteType(Loc, ReturnType,
7002 FD ?
7003 PDiag(diag::err_call_function_incomplete_return)
7004 << CE->getSourceRange() << FD->getDeclName() :
7005 PDiag(diag::err_call_incomplete_return)
7006 << CE->getSourceRange(),
7007 std::make_pair(NoteLoc, Note)))
7008 return true;
7009
7010 return false;
7011}
7012
John McCall5a881bb2009-10-12 21:59:07 +00007013// Diagnose the common s/=/==/ typo. Note that adding parentheses
7014// will prevent this condition from triggering, which is what we want.
7015void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
7016 SourceLocation Loc;
7017
John McCalla52ef082009-11-11 02:41:58 +00007018 unsigned diagnostic = diag::warn_condition_is_assignment;
7019
John McCall5a881bb2009-10-12 21:59:07 +00007020 if (isa<BinaryOperator>(E)) {
7021 BinaryOperator *Op = cast<BinaryOperator>(E);
7022 if (Op->getOpcode() != BinaryOperator::Assign)
7023 return;
7024
John McCallc8d8ac52009-11-12 00:06:05 +00007025 // Greylist some idioms by putting them into a warning subcategory.
7026 if (ObjCMessageExpr *ME
7027 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
7028 Selector Sel = ME->getSelector();
7029
John McCallc8d8ac52009-11-12 00:06:05 +00007030 // self = [<foo> init...]
7031 if (isSelfExpr(Op->getLHS())
7032 && Sel.getIdentifierInfoForSlot(0)->getName().startswith("init"))
7033 diagnostic = diag::warn_condition_is_idiomatic_assignment;
7034
7035 // <foo> = [<bar> nextObject]
7036 else if (Sel.isUnarySelector() &&
7037 Sel.getIdentifierInfoForSlot(0)->getName() == "nextObject")
7038 diagnostic = diag::warn_condition_is_idiomatic_assignment;
7039 }
John McCalla52ef082009-11-11 02:41:58 +00007040
John McCall5a881bb2009-10-12 21:59:07 +00007041 Loc = Op->getOperatorLoc();
7042 } else if (isa<CXXOperatorCallExpr>(E)) {
7043 CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(E);
7044 if (Op->getOperator() != OO_Equal)
7045 return;
7046
7047 Loc = Op->getOperatorLoc();
7048 } else {
7049 // Not an assignment.
7050 return;
7051 }
7052
John McCall5a881bb2009-10-12 21:59:07 +00007053 SourceLocation Open = E->getSourceRange().getBegin();
John McCall2d152152009-10-12 22:25:59 +00007054 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
John McCall5a881bb2009-10-12 21:59:07 +00007055
John McCalla52ef082009-11-11 02:41:58 +00007056 Diag(Loc, diagnostic)
John McCall5a881bb2009-10-12 21:59:07 +00007057 << E->getSourceRange()
7058 << CodeModificationHint::CreateInsertion(Open, "(")
7059 << CodeModificationHint::CreateInsertion(Close, ")");
7060}
7061
7062bool Sema::CheckBooleanCondition(Expr *&E, SourceLocation Loc) {
7063 DiagnoseAssignmentAsCondition(E);
7064
7065 if (!E->isTypeDependent()) {
7066 DefaultFunctionArrayConversion(E);
7067
7068 QualType T = E->getType();
7069
7070 if (getLangOptions().CPlusPlus) {
7071 if (CheckCXXBooleanCondition(E)) // C++ 6.4p4
7072 return true;
7073 } else if (!T->isScalarType()) { // C99 6.8.4.1p1
7074 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
7075 << T << E->getSourceRange();
7076 return true;
7077 }
7078 }
7079
7080 return false;
7081}